Modified: 2016-05-10\n%\n% This file is part of the SPORCO library. Details of the copyright\n% and user license can be found in the 'License' file distributed with\n% the library.\n\n\nif nargin < 4,\n opt = [];\nend\ncheckopt(opt, defaultopts([]));\nopt = defaultopts(opt);\n\n% Set up status display for verbose operation\nhstr = 'Itn Fnc DFid l1 r s ';\nsfms = '%4d %9.2e %9.2e %9.2e %9.2e %9.2e';\nnsep = 54;\nif opt.AutoRho,\n hstr = [hstr ' rho '];\n sfms = [sfms ' %9.2e'];\n nsep = nsep + 10;\nend\nif opt.Verbose && opt.MaxMainIter > 0,\n disp(hstr);\n disp(char('-' * ones(1,nsep)));\nend\n\n\n% Start timer\ntstart = tic;\n\n% Insert impulse filter into dictionary\nimp = zeros(size(D,1), size(D,2), 1);\nimp(1,1,1) = 1.0;\nDi = cat(3, D, imp);\n\n% Collapsing of trailing singleton dimensions greatly complicates\n% handling of both SMV and MMV cases. The simplest approach would be\n% if s could always be reshaped to 4d, with dimensions consisting of\n% image rows, image cols, a single dimensional placeholder for number\n% of filters, and number of measurements, but in the single\n% measurement case the third dimension is collapsed so that the array\n% is only 3d.\nif size(S,3) > 1 && size(S,4) == 1,\n xsz = [size(S,1) size(S,2) size(Di,3) size(S,3)];\n % Insert singleton 3rd dimension (for number of filters) so that\n % 4th dimension is number of images in input s volume\n S = reshape(S, [size(S,1) size(S,2) 1 size(S,3)]);\n if ~isscalar(opt.W) & ndims(opt.W) > 2,\n opt.W = reshape(opt.W, [size(opt.W,1) size(opt.W,2) 1 size(opt.W,3)]);\n end\nelse\n xsz = [size(S,1) size(S,2) size(Di,3) size(S,4)];\nend\nIYW = 1.0 - opt.W;\n\n% Compute filters in DFT domain\nDf = fft2(Di, size(S,1), size(S,2));\n% Convolve-sum and its Hermitian transpose\nDop = @(x) sum(bsxfun(@times, Df, x), 3);\nDHop = @(x) bsxfun(@times, conj(Df), x);\n% Compute signal in DFT domain\nSf = fft2(S);\n% S convolved with all filters in DFT domain\nDSf = DHop(Sf);\n\n% Default lambda is 1/10 times the lambda value beyond which the\n% solution is a zero vector\nif nargin < 3 | isempty(lambda),\n b = ifft2(DHop(Sf), 'symmetric');\n lambda = 0.1*max(vec(abs(b)));\nend\n\n% Set up algorithm parameters and initialise variables\nrho = opt.rho;\nif isempty(rho), rho = 50*lambda+1; end;\nif isempty(opt.RhoRsdlTarget),\n if opt.StdResiduals,\n opt.RhoRsdlTarget = 1;\n else\n opt.RhoRsdlTarget = 1 + (18.3).^(log10(lambda) + 1);\n end\nend\nif opt.HighMemSolve,\n C = bsxfun(@rdivide, Df, sum(Df.*conj(Df), 3) + rho);\nelse\n C = [];\nend\nNx = prod(xsz);\noptinf = struct('itstat', [], 'opt', opt);\nr = Inf;\ns = Inf;\nepri = 0;\nedua = 0;\n\n% Initialise main working variables\nX = [];\nif isempty(opt.Y0),\n Y = zeros(xsz);\nelse\n Y = opt.Y0;\nend\nYprv = Y;\nif isempty(opt.U0),\n if isempty(opt.Y0),\n U = zeros(xsz);\n else\n U = (lambda/rho)*sign(Y);\n end\nelse\n U = opt.U0;\nend\n\n% Main loop\nk = 1;\nwhile k <= opt.MaxMainIter && (r > epri | s > edua),\n\n % Solve X subproblem\n Xf = solvedbi_sm(Df, rho, DSf + rho*fft2(Y - U), C);\n X = ifft2(Xf, 'symmetric');\n\n % See pg. 21 of boyd-2010-distributed\n if opt.RelaxParam == 1,\n Xr = X;\n else\n Xr = opt.RelaxParam*X + (1-opt.RelaxParam)*Y;\n end\n\n % Solve Y subproblem\n Y(:,:,1:(end-1),:) = shrink(Xr(:,:,1:(end-1),:) + U(:,:,1:(end-1),:), ...\n (lambda/rho)*opt.L1Weight);\n Y(:,:,end,:) = bsxfun(@times, IYW, Xr(:,:,end,:) + U(:,:,end,:));\n if opt.NoBndryCross,\n Y((end-size(D,1)+2):end,:,1:(end-1),:) = 0;\n Y(:,(end-size(D,2)+2):end,1:(end-1),:) = 0;\n end\n\n % Update dual variable\n U = U + Xr - Y;\n\n % Compute data fidelity term in Fourier domain (note normalisation)\n if opt.AuxVarObj,\n Yf = fft2(Y); % This represents unnecessary computational cost\n Jdf = sum(vec(abs(sum(bsxfun(@times,Df,Yf),3)-Sf).^2))/(2*xsz(1)*xsz(2));\n Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, Y(:,:,1:(end-1),:)))));\n else\n Jdf = sum(vec(abs(sum(bsxfun(@times,Df,Xf),3)-Sf).^2))/(2*xsz(1)*xsz(2));\n Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, X(:,:,1:(end-1),:)))));\n end\n Jfn = Jdf + lambda*Jl1;\n\n nX = norm(X(:)); nY = norm(Y(:)); nU = norm(U(:));\n if opt.StdResiduals,\n % See pp. 19-20 of boyd-2010-distributed\n r = norm(vec(X - Y));\n s = norm(vec(rho*(Yprv - Y)));\n epri = sqrt(Nx)*opt.AbsStopTol+max(nX,nY)*opt.RelStopTol;\n edua = sqrt(Nx)*opt.AbsStopTol+rho*nU*opt.RelStopTol;\n else\n % See wohlberg-2015-adaptive\n r = norm(vec(X - Y))/max(nX,nY);\n s = norm(vec(Yprv - Y))/nU;\n epri = sqrt(Nx)*opt.AbsStopTol/max(nX,nY)+opt.RelStopTol;\n edua = sqrt(Nx)*opt.AbsStopTol/(rho*nU)+opt.RelStopTol;\n end\n\n % Record and display iteration details\n tk = toc(tstart);\n optinf.itstat = [optinf.itstat; [k Jfn Jdf Jl1 r s epri edua rho tk]];\n if opt.Verbose,\n if opt.AutoRho,\n disp(sprintf(sfms, k, Jfn, Jdf, Jl1, r, s, rho));\n else\n disp(sprintf(sfms, k, Jfn, Jdf, Jl1, r, s));\n end\n end\n\n % See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed\n if opt.AutoRho,\n if k ~= 1 && mod(k, opt.AutoRhoPeriod) == 0,\n if opt.AutoRhoScaling,\n rhomlt = sqrt(r/(s*opt.RhoRsdlTarget));\n if rhomlt < 1, rhomlt = 1/rhomlt; end\n if rhomlt > opt.RhoScaling, rhomlt = opt.RhoScaling; end\n else\n rhomlt = opt.RhoScaling;\n end\n rsf = 1;\n if r > opt.RhoRsdlTarget*opt.RhoRsdlRatio*s, rsf = rhomlt; end\n if s > (opt.RhoRsdlRatio/opt.RhoRsdlTarget)*r, rsf = 1/rhomlt; end\n rho = rsf*rho;\n U = U/rsf;\n if opt.HighMemSolve && rsf ~= 1,\n C = bsxfun(@rdivide, Df, sum(Df.*conj(Df), 3) + rho);\n end\n end\n end\n\n Yprv = Y;\n k = k + 1;\n\nend\n\n% Record run time and working variables\noptinf.runtime = toc(tstart);\noptinf.X = X;\noptinf.Xf = Xf;\noptinf.Y = Y;\noptinf.U = U;\noptinf.lambda = lambda;\noptinf.rho = rho;\n\nif opt.Verbose && opt.MaxMainIter > 0,\n disp(char('-' * ones(1,nsep)));\nend\n\n% Remove coefficient map for impulse filter\nX = X(:,:,1:(end-1), :);\n\nreturn\n\n\nfunction u = vec(v)\n\n u = v(:);\n\nreturn\n\n\nfunction u = shrink(v, lambda)\n\n if isscalar(lambda),\n u = sign(v).*max(0, abs(v) - lambda);\n else\n u = sign(v).*max(0, bsxfun(@minus, abs(v), lambda));\n end\n\nreturn\n\n\n\nfunction opt = defaultopts(opt)\n\n if ~isfield(opt,'Verbose'),\n opt.Verbose = 0;\n end\n if ~isfield(opt,'MaxMainIter'),\n opt.MaxMainIter = 1000;\n end\n if ~isfield(opt,'AbsStopTol'),\n opt.AbsStopTol = 0;\n end\n if ~isfield(opt,'RelStopTol'),\n opt.RelStopTol = 1e-4;\n end\n if ~isfield(opt,'L1Weight'),\n opt.L1Weight = 1;\n end\n if ~isfield(opt,'Y0'),\n opt.Y0 = [];\n end\n if ~isfield(opt,'U0'),\n opt.U0 = [];\n end\n if ~isfield(opt,'rho'),\n opt.rho = [];\n end\n if ~isfield(opt,'AutoRho'),\n opt.AutoRho = 1;\n end\n if ~isfield(opt,'AutoRhoPeriod'),\n opt.AutoRhoPeriod = 1;\n end\n if ~isfield(opt,'RhoRsdlRatio'),\n opt.RhoRsdlRatio = 1.2;\n end\n if ~isfield(opt,'RhoScaling'),\n opt.RhoScaling = 100;\n end\n if ~isfield(opt,'AutoRhoScaling'),\n opt.AutoRhoScaling = 1;\n end\n if ~isfield(opt,'RhoRsdlTarget'),\n opt.RhoRsdlTarget = [];\n end\n if ~isfield(opt,'StdResiduals'),\n opt.StdResiduals = 1;\n end\n if ~isfield(opt,'RelaxParam'),\n opt.RelaxParam = 1.8;\n end\n if ~isfield(opt,'NoBndryCross'),\n opt.NoBndryCross = 0;\n end\n if ~isfield(opt,'AuxVarObj'),\n opt.AuxVarObj = 0;\n end\n if ~isfield(opt,'HighMemSolve'),\n opt.HighMemSolve = 0;\n end\n if ~isfield(opt,'W'),\n opt.W = 1.0;\n end\n\nreturn\n", "meta": {"author": "thfylsty", "repo": "Classic-and-state-of-the-art-image-fusion-methods", "sha": "5d9457df396f1ea6921e1b9b3703995205940862", "save_path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods", "path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods/Classic-and-state-of-the-art-image-fusion-methods-5d9457df396f1ea6921e1b9b3703995205940862/ConvSR_Image_Fusion_Codes/sporco/SparseCode/cbpdnms.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.47523759284547973}}
{"text": "function [model, varargout] = grlvq_core(trainSet, trainLab, varargin)\n%grlvq_core.m - trains the Generalized Relevance LVQ algorithm\n%NOTE: minimal requirement version 7.4.0.336 (R2007a) \n% \n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %% Use the wrapper GRLVQ.M to access the functionality in style of %%\n% %% the SOM Toolbox (i.e. with data structs). %%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% example for usage:\n% trainSet = [1,2,3;4,5,6;7,8,9];\n% trainLab = [1;1;2];\n% GRLVQ_model=GRLVQ_train(trainSet,trainLab); % minimal parameters required\n% estimatedTrainLabels = GRLVQ_classify(trainSet, GRLVQ_model);\n% trainError = mean( trainLab ~= estimatedTrainLabels );\n%\n% input: \n% trainSet : matrix with training samples in its rows\n% trainLab : vector with the labels of the training set\n% optional parameters:\n% PrototypesPerClass: (default=1) the number of prototypes per class used. This could\n% be a number or a vector with the number for each class\n% initialPrototypes : (default=[]) a set of prototypes to start with. If not given initialization near the class means\n% initialRelevances : the relevances to start with. If not given all\n% relevances are equal at start\n% regularization : (default=0) values usually between 0 and 1 treat with care. \n% Regularizes the relevances to be more homogeneous\n% testSet : (default=[]) an optional test set used to compute\n% the test error. The last column is expected to be a label vector\n% comparable : (default=0) a flag which resets the random generator\n% to produce comparable results if set to 1\n% optimization : (default=fminlbfgs) indicates which optimization is used: sgd or fminlbfgs\n% parameter for the stochastic gradient descent sgd\n% nb_epochs : (default=100) the number of epochs for sgd\n% learningRatePrototypes: (default=[]) the learning rate for the prototypes. \n% Could be the start and end value used for a sigmoidal spectrum or a vector of length nb_epochs\n% learningRateRelevances: (default=[]) the learning rate for the matrix.\n% Could be the start and end value used for a sigmoidal spectrum or a vector of length nb_epochs\n% relevanceStart : (default=1) the epoch to start the matrix training\n% parameter for the build-in function fminlbfgs\n% threshstop : (default=0) the training error for early stopping\n% useEarlyStopping : (default=1) use early stopping based on threshstop\n% Display : (default='off') the optimization output 'iter' or 'off'\n% GradObj : (default=on) use the gradient information or not\n% HessUpdate : (default=lbfgs) the update can be 'lbfgs', 'bfgs' or 'steepdesc'\n% TolFun : (default=1e-6) the tolerance\n% MaxIter : (default=2500) the maximal number of iterations\n% MaxFunEvals : (default=1000000) the maximal number of function evaluations\n% TolX : (default=1e-10) tolerance\n% DiffMinChange : (default=1e-10) minimal change\n%\n% output: the GRLVQ model with prototypes w their labels c_w and the relevances lamda\n% optional output:\n% initialization : a struct containing the settings\n% trainError : error in the training set\n% testError : error in the training set (only computed if 'testSet' is given)\n% costs : the output of the cost function\n% \n% Citation information:\n% B. Hammer and T. Villmann, Generalized relevance learning vector quantization, Neural Networks 15, 1059-1068, 2002. \n% \n% P. Schneider, K. Bunte, B. Hammer and M. Biehl, Regularization in Matrix Relevance Learning, \n% IEEE Transactions on Neural Networks, vol. 21, nb. 5, pp. 831-840, 2010.\n% \n% Kerstin Bunte\n% uses the Fast Limited Memory Optimizer fminlbfgs.m written by Dirk-Jan Kroon available at the MATLAB central\n% kerstin.bunte@googlemail.com\n% Fri Nov 09 14:13:52 CEST 2012\n%\n% Conditions of GNU General Public License, version 2 and BSD License apply.\n% See file 'license-gpl2.txt' and 'BSD_license.txt' enclosed in this package.\n% Programs are not for use in critical applications!\n%\n\n% Contributed to SOM Toolbox vs2, December 3rd, 2012 by Alexander Schulz\n% Copyright (c) Kerstin Bunte\n% http://www.cis.hut.fi/projects/somtoolbox/\n\nnout = max(nargout,1)-1;\np = inputParser; % Create an instance of the class.\np.addRequired('trainSet', @isfloat);\np.addRequired('trainLab', @(x) length(x)==size(trainSet,1) & isnumeric(x));\n\np.addOptional('testSet', [], @(x)(size(x,2)-1)==size(trainSet,2) & isfloat(x));\np.addParamValue('PrototypesPerClass', ones(1,length(unique(trainLab))), @(x)(sum(~(x-floor(x)))/length(x)==1 && (length(x)==length(unique(trainLab)) || length(x)==1)));\np.addParamValue('initialPrototypes',[], @(x)(size(x,2)-1==size(trainSet,2) && isfloat(x)));\np.addParamValue('initialRelevances',[], @(x)(numel(x)==size(trainSet,2) && isfloat(x)));\np.addOptional('comparable', 0, @(x)(~(x-floor(x))));\np.addParamValue('regularization',0, @(x)(isfloat(x) && x>=0));\np.addOptional('optimization', 'fminlbfgs', @(x)any(strcmpi(x,{'sgd','fminlbfgs'})));\n% parameter for the stochastic gradient descent\np.addOptional('nb_epochs', 100, @(x)(~(x-floor(x))));\np.addParamValue('learningRatePrototypes', [], @(x)(isfloat(x) || isa(x,'function_handle')));\np.addParamValue('learningRateRelevances', [], @(x)(isfloat(x) || isa(x,'function_handle')));\np.addOptional('relevanceStart', 1, @(x)(~(x-floor(x))));\n% parameter for the build-in function\np.addOptional('threshstop',0,@(x) isfloat(x));\np.addOptional('useEarlyStopping',1,@(x)(~(x-floor(x))));\np.addOptional('Display', 'off', @(x)any(strcmpi(x,{'iter','off'})));\np.addOptional('GradObj', 'on', @(x)any(strcmpi(x,{'on','off'})));\np.addOptional('HessUpdate', 'lbfgs', @(x)any(strcmpi(x,{'lbfgs', 'bfgs', 'steepdesc'})));\np.addOptional('TolFun',1e-6,@(x) isfloat(x));\np.addOptional('MaxIter', 2500, @(x)(~(x-floor(x))));\np.addOptional('MaxFunEvals', 1000000, @(x)(~(x-floor(x))));\np.addOptional('TolX',1e-10,@(x) isfloat(x));\np.addOptional('DiffMinChange',1e-10,@(x)isfloat(x));\np.CaseSensitive = true;\np.FunctionName = 'GRLVQ';\n% Parse and validate all input arguments.\np.parse(trainSet, trainLab, varargin{:});\n\n%%% check if results should be comparable\nif p.Results.comparable,\n rng('default');\nend\n%%% set useful variables\nnb_samples = size(trainSet,1);\nnb_features = size(trainSet,2);\nif size(trainLab,1)~=nb_samples, trainLab = trainLab';end\n\nclasses = unique(trainLab);\nnb_classes = length(classes);\ntestSet = p.Results.testSet;\n\n% global regularization;\nregularization = p.Results.regularization;\nif regularization, disp(['Regularize the relevances with ',num2str(regularization)]);end\n\ninitialization = rmfield(p.Results, 'trainSet');\ninitialization.trainSet = [num2str(nb_samples),'x',num2str(nb_features),' matrix'];\ninitialization = rmfield(initialization, 'trainLab');\ninitialization.trainLab = ['vector of length ',num2str(length(trainLab))];\nif ~isempty(testSet)\n initialization = rmfield(initialization, 'testSet');\n initialization.testSet = [num2str(size(testSet,1)),'x',num2str(size(testSet,2)),' matrix'];\nend\nswitch(p.Results.optimization)\ncase{'sgd'}\n initialization = rmfield(initialization, 'useEarlyStopping');\n initialization = rmfield(initialization, 'Display');\n initialization = rmfield(initialization, 'GradObj');\n initialization = rmfield(initialization, 'HessUpdate');\n initialization = rmfield(initialization, 'TolFun');\n initialization = rmfield(initialization, 'MaxIter');\n initialization = rmfield(initialization, 'MaxFunEvals');\n initialization = rmfield(initialization, 'TolX');\n initialization = rmfield(initialization, 'DiffMinChange');\ncase{'fminlbfgs'}\n disp('The fminlbfgs optimization uses some global variables:');\n disp('threshstop earlystopped useEarlyStopping');\n initialization = rmfield(initialization, 'nb_epochs');\n initialization = rmfield(initialization, 'learningRatePrototypes');\n initialization = rmfield(initialization, 'learningRateRelevances');\n initialization = rmfield(initialization, 'relevanceStart');\nend\n% Display all arguments.\n%disp 'Settings for GRLVQ:'\n%disp(initialization);\n\n%%% check the number of prototypes per class if one integer is given and turn\n%%% it into a vector\nnb_ppc = p.Results.PrototypesPerClass;\nif length(nb_ppc)~=nb_classes,\n nb_ppc = ones(1,nb_classes)*nb_ppc;\nend\n\n%%% initialize the prototypes\nif isempty(p.Results.initialPrototypes)\n % initialize near the class centers\n w = zeros(sum(nb_ppc),nb_features);\n c_w = zeros(sum(nb_ppc),1);\n actPos = 1;\n for actClass=1:nb_classes\n nb_prot_c = nb_ppc(actClass);\n classMean = mean(trainSet(trainLab==classes(actClass),:));\n % set the prototypes to the class mean and add a random variation\n % between -0.1 and 0.1\n w(actPos:actPos+nb_prot_c-1,:) = classMean(ones(nb_prot_c,1),:)+(rand(nb_prot_c,nb_features)*2-ones(nb_prot_c,nb_features))/10;\n c_w(actPos:actPos+nb_prot_c-1) = classes(actClass);\n actPos = actPos+nb_prot_c;\n end\nelse\n % initialize with given w\n w = p.Results.initialPrototypes(:,1:end-1);\n c_w = p.Results.initialPrototypes(:,end);\nend\n%%% initialize the matrix\nif isempty(p.Results.initialRelevances) \n lambda = ones(1,nb_features); \nelse\n% if isvector(p.Results.initialRelevances)\n% omega = diag(p.Results.initialRelevances);\n% else\n lambda = p.Results.initialRelevances;\n% end \nend\n% normalize the relevances\nlambda = lambda / sum(lambda);\nmodel = struct('w',w,'c_w',c_w,'lambda',lambda);\nclear w c_w lambda;\n\ndim = length(model.lambda);\n\nswitch(p.Results.optimization)\ncase{'sgd'}\n %%% gradient descent variables\n nb_epochs = p.Results.nb_epochs;\n relevanceStart = p.Results.relevanceStart;\n % compute the vector of nb_epochs learning rates alpha for the prototype learning\n if isa(p.Results.learningRatePrototypes,'function_handle')\n % with a given function specified from the user\n alphas = arrayfun(p.Results.learningRatePrototypes, 1:nb_epochs);\n elseif length(p.Results.learningRatePrototypes)>2\n if length(p.Results.learningRatePrototypes)==nb_epochs\n alphas = p.Results.learningRatePrototypes;\n else\n disp('The learning rate vector for the prototypes does not fit the nb of epochs');\n return;\n end\n else\n % or use an decay with a start and a decay value\n if isempty(p.Results.learningRatePrototypes)\n initialization.learningRatePrototypes = [nb_features/100, nb_features/10000];\n end\n alpha_start = initialization.learningRatePrototypes(1);\n alpha_end = initialization.learningRatePrototypes(2);\n alphas = arrayfun(@(x) alpha_start * (alpha_end/alpha_start)^(x/nb_epochs), 1:nb_epochs);\n % alphas = arrayfun(@(x) alpha_start / (1+(x-1)*alpha_end), 1:nb_epochs);\n end\n % compute the vector of nb_epochs learning rates epsilon for the Matrix learning\n epsilons = zeros(1,nb_epochs);\n if isa(p.Results.learningRateRelevances,'function_handle')\n % with a given function specified from the user\n % \tepsilons = arrayfun(p.Results.learningRateRelevances, 1:nb_epochs);\n epsilons(relevanceStart:nb_epochs) = arrayfun(p.Results.learningRateRelevances, relevanceStart:nb_epochs);\n elseif length(p.Results.learningRateRelevances)>2\n if length(p.Results.learningRateRelevances)==nb_epochs\n epsilons = p.Results.learningRateRelevances;\n else\n disp('The learning rate vector for the Matrix does not fit the nb of epochs');\n return;\n end\n else\n % or use an decay with a start and a decay value\n if isempty(p.Results.learningRateRelevances)\n initialization.learningRateRelevances = [nb_features/1000, nb_features/100000];\n end\n eps_start = initialization.learningRateRelevances(1);\n eps_end = initialization.learningRateRelevances(2);\n % epsilons = arrayfun(@(x) eps_start * (eps_end/eps_start)^(x/nb_epochs), 1:nb_epochs);\n epsilons(relevanceStart:nb_epochs) = arrayfun(@(x) eps_start * (eps_end/eps_start)^((x-relevanceStart)/(nb_epochs-relevanceStart)), relevanceStart:nb_epochs);\n end\n\n %%% initialize requested outputs\n trainError = [];\n costs = [];\n testError = [];\n if nout>=2,\n % train error requested\n trainError = ones(1,nb_epochs+1);\n estimatedLabels = GRLVQ_classify(trainSet, model); % error after initialization\n trainError(1) = sum( trainLab ~= estimatedLabels )/nb_samples;\n if nout>=3,\n % test error requested\n if isempty(testSet)\n testError = [];\n disp('The test error is requested, but no labeled test set given. Omitting the computation.');\n else\n testError = ones(1,nb_epochs+1);\n estimatedLabels = GRLVQ_classify(testSet(:,1:end-1), model); % error after initialization\n testError(1) = sum( testSet(:,end) ~= estimatedLabels )/length(estimatedLabels);\n end \n if nout>=4,\n % costs requested\n disp('The computation of the costs is an expensive operation, do it only if you really need it!');\n costs(1) = GRLVQ_costfun(trainSet, trainLab, model, regularization);\n end\n end\n end\n \n %%% optimize with stochastic gradient descent\n for epoch=1:nb_epochs\n if mod(epoch,100)==0, disp(epoch); end\n % generate order to sweep through the trainingset\n order = randperm(nb_samples);\t\n \n % perform one sweep through trainingset\n for i=1:nb_samples\n % select one training sample randomly\n xi = trainSet(order(i),:);\n c_xi = trainLab(order(i));\n% dist = ((xi(ones(size(model.w,1),1),:))-model.w)*model.omega'*(model.omega*((xi(ones(size(model.w,1),1),:))-model.w)');\n% dist = diag(dist);\n dist = sum(bsxfun(@times,bsxfun(@minus,xi,model.w).^2,model.lambda), 2);\n % determine the two winning prototypes\n % nearest prototype with the same class\n [sortDist,sortIdx] = sort(dist);\n count = 1;\n J = sortIdx(count);\n while model.c_w(sortIdx(count)) ~= c_xi, \n count = count+1;\n J = sortIdx(count);\n end\n dJ = sortDist(count);\n count = 1;\n K = sortIdx(count);\n while model.c_w(sortIdx(count)) == c_xi, \n count = count+1;\n K = sortIdx(count);\n end\n dK = sortDist(count);\n \n wJ = model.w(J,:);\n wK = model.w(K,:);\n % prototype update\n norm_factor = (dJ + dK)^2;\n DJ = (xi-wJ);\n DK = (xi-wK);\n\n dwJ = (2*dK/norm_factor)*2*model.lambda.*DJ;\n dwK = (2*dJ/norm_factor)*2*model.lambda.*DK;\n\n model.w(J,:) = wJ + alphas(epoch) * dwJ;\n model.w(K,:) = wK - alphas(epoch) * dwK;\n\n % update relevances\n if epsilons(epoch)>0, % epoch >= RelevanceStart\n% f1 = (2*dK/norm_factor)*2*(model.omega*DJ')*DJ;\n% f2 = (2*dJ/norm_factor)*2*(model.omega*DK')*DK;\n f1 = (2*dK/norm_factor)*DJ.^2;\n f2 = (2*dJ/norm_factor)*DK.^2;\n % update lambda\n if regularization,\n f3 = diag(pinv(sqrt(diag(model.lambda))))';\n% test = bsxfun(@times,model.lambda,ones(1,length(model.lambda))');\n% test(1:nb_features+1:nb_features*nb_features) = 1;\n% f3 = 1/(prod(model.lambda)+eps)*prod(test,2)';\n else\n f3 = 0;\n end\n model.lambda = model.lambda-epsilons(epoch) * (f1-f2 - regularization * f3);\n % normalization\n model.lambda (model.lambda < 0) = 0;\n model.lambda = model.lambda / sum(model.lambda);\n end\n end\n if nout>=2,\n % train error requested\n estimatedLabels = GRLVQ_classify(trainSet, model); % error after epoch\n trainError(epoch+1) = sum( trainLab ~= estimatedLabels )/nb_samples;\n if nout>=3,\n % test error requested\n if ~isempty(testSet)\n estimatedLabels = GRLVQ_classify(testSet(:,1:end-1), model); % error after initialization\n testError(epoch+1) = sum( testSet(:,end) ~= estimatedLabels )/length(estimatedLabels);\n end \n if nout>=4,\n % costs requested\n% dist = computeDistance(trainSet, model.w, model);\n% if regularization,\n% regTerm = regularization * log(det(model.omega*model.omega'));\n% else\n% regTerm = 0;\n% end\n% costs(epoch+1) = sum(arrayfun(@(idx) GLVQ_costfun(min(dist(idx,model.c_w == trainLab(idx))),...\n% min(dist(idx,model.c_w ~= trainLab(idx)))), 1:size(dist,1)))-regTerm;\n costs(epoch+1) = GRLVQ_costfun(trainSet, trainLab, model, regularization);\n end\n end\n end\n end\ncase{'fminlbfgs'}\n %%% optimization options\n options = struct( ...\n 'Display',p.Results.Display, ...\n 'GradObj',p.Results.GradObj, ...\n 'GradConstr',false, ...\n 'GoalsExactAchieve',0, ...\n 'TolFun',p.Results.TolFun, ...\n 'MaxIter',p.Results.MaxIter, ...\n 'MaxFunEvals', p.Results.MaxFunEvals, ...\n 'TolX',p.Results.TolX, ...\n 'DiffMinChange',p.Results.DiffMinChange, ...\n 'OutputFcn','LVQ_progresser', ...\n 'HessUpdate',p.Results.HessUpdate ...\n );\n clear('progresser'); % memory therein might need reset \n global threshstop earlystopped useEarlyStopping % for LVQ_progresser.m datval labval n_vec\n useEarlyStopping = p.Results.useEarlyStopping; % use early stopping\n% useEarlyStopping = []; % if empty, no validation set given/used for early stopping\n earlystopped = false;\n threshstop = p.Results.threshstop; % stop if classification below this threshold for early stopping\n% global training_data training_label LabelEqualsPrototype LRrelevances LRprototypes prototypeLabel; \n% training_data = trainSet;\n% training_label = trainLab;\n% prototypeLabel = model.c_w;\n nb_prototypes = numel(model.c_w);\n% nb_samples = size(training_data,1);\n% LabelEqualsPrototype = trainLab*ones(1,nb_prototypes) == (model.c_w*ones(1,nb_samples))'; \n LabelEqualsPrototype = bsxfun(@eq,trainLab,model.c_w');\n earlystopped = false; % don't change, assigned in progresser.m\n clear('progresser'); % memory therein might need reset\n newfval = realmax('single');\n % fminlbfgs optimizer courtesy of Dirk-Jan Kroon: \n % http://www.mathworks.de/matlabcentral/fileexchange/23245\n % early stopping to be implemented in progresser function \n variables = zeros(nb_prototypes+nb_features,size(trainSet,2));\n variables(1:nb_prototypes,:) = model.w;\n variables(nb_prototypes+1:end,:) = diag(sqrt(model.lambda));\n LRprototypes = 1; % learn prototype locations\n LRrelevances = 0; % don't learn metric\n% [variables,fval] = fminlbfgs(@GRLVQ_optfun,variables,options);\n [variables,fval] = fminlbfgs(@(variables) GMLVQ_optfun(variables,trainSet,LabelEqualsPrototype,LRrelevances,LRprototypes,model.c_w,regularization),variables,options);\n if not(isempty(fval))\n newfval = fval;\n end\n LRprototypes = 0; % don't learn prototype locations\n LRrelevances = 1; % learn metric\n% [variables,fval] = fminlbfgs(@GRLVQ_optfun,variables,options); \n [variables,fval] = fminlbfgs(@(variables) GMLVQ_optfun(variables,trainSet,LabelEqualsPrototype,LRrelevances,LRprototypes,model.c_w,regularization),variables,options);\n if not(isempty(fval))\n newfval = fval;\n end\n if not(isempty(fval))\n clear('progresser'); % memory therein might need reset\n LRprototypes = 1; \n for i = 1:100 % depending on data, re-iterations might further improve\n% [variables,fval] = fminlbfgs(@GRLVQ_optfun,variables,options);\n [variables,fval] = fminlbfgs(@(variables) GMLVQ_optfun(variables,trainSet,LabelEqualsPrototype,LRrelevances,LRprototypes,model.c_w,regularization),variables,options);\n if not(isempty(fval))\n if abs(fval - newfval) < 1e-3 \n newfval = fval;\n break\n end\n newfval = fval;\n end\n if isempty(fval) || earlystopped\n break\n end\n end\n end\n model.w = variables(1:nb_prototypes,:);\n model.lambda = diag(variables(nb_prototypes+1:end,:)'*variables(nb_prototypes+1:end,:))';\n% model.lambda = model.lambda/sum(model.lambda);\n if nout>=2,\n % train error requested\n estimatedLabels = GRLVQ_classify(trainSet, model); % error after initialization\n trainError = mean( trainLab ~= estimatedLabels );\n if nout>=3,\n % test error requested\n if isempty(testSet)\n testError = [];\n disp('The test error is requested, but no labeled test set given. Omitting the computation.');\n else\n estimatedLabels = GRLVQ_classify(testSet(:,1:end-1), model); % error after initialization\n testError = mean( testSet(:,end) ~= estimatedLabels );\n end \n if nout>=4,\n % costs requested \n% dist = computeDistance(trainSet, model.w, model);\n% if regularization,\n% regTerm = regularization * log(det(model.omega*model.omega'));\n% else\n% regTerm = 0;\n% end\n% costs = sum(arrayfun(@(idx) GLVQ_costfun(min(dist(idx,model.c_w == trainLab(idx))),...\n% min(dist(idx,model.c_w ~= trainLab(idx)))), 1:size(dist,1)))-regTerm; \n costs = GRLVQ_costfun(trainSet, trainLab, model, regularization);\n end\n end\n end\nend\n\n%%% output of the training\nvarargout = cell(nout);\nfor k=1:nout\n\tswitch(k)\n\t\tcase(1)\n\t\t\tvarargout(k) = {initialization};\n\t\tcase(2)\n\t\t\tvarargout(k) = {trainError};\n\t\tcase(3)\n\t\t\tvarargout(k) = {testError};\n\t\tcase(4)\n varargout(k) = {costs};\n\tend\nend\n\n\n\n\n\n\n\n\n\n\nfunction cost = GRLVQ_costfun(trainSet, trainLab, model, regularization)\n%GRLVQ_costfun.m - computes the costs for a given training set and GRLVQ\n%model with or without regularization\n% example for usage:\n% trainSet = [1,2,3;4,5,6;7,8,9];\n% trainLab = [1;1;2];\n% GMLVQ_model=GMLVQ_train(trainSet,trainLab); % minimal parameters required\n% costs = GMLVQ_costfun(trainSet, trainLab, GMLVQ_model, 0);\n%\n% input: \n% trainSet : matrix with training samples in its rows\n% trainLab : a vector of training labels\n% model : GMLVQ model with prototypes w their labels c_w and the matrix omega\n% regularization: the factor>=0 for the regularization\n% \n% output : cost function value\n% \n% Kerstin Bunte (based on the code from Marc Strickert)\n% kerstin.bunte@googlemail.com\n% Mon Nov 05 09:05:52 CEST 2012\n%\n% Conditions of GNU General Public License, version 2 apply.\n% See file 'license-gpl2.txt' enclosed in this package.\n% Programs are not for use in critical applications!\n%\nnb_samples = length(trainLab);\n% labels should be a row vector\nif size(trainLab,1)~=nb_samples, trainLab = trainLab';end\n\n% LabelEqPrototype = trainLab*ones(1,numel(model.c_w)) == (model.c_w*ones(1,nb_samples))';\nLabelEqPrototype = bsxfun(@eq,trainLab,model.c_w');\ndists = computeDistance(trainSet, model.w, model);\nif regularization,\n regTerm = regularization * log(prod(model.lambda));\n% if strcmp(p.Results.optimization,'sgd') \nelse\n regTerm = 0;\nend\nDwrong = dists;\nDwrong(LabelEqPrototype) = realmax(class(Dwrong)); % set correct labels impossible\ndistwrong = min(Dwrong.'); % closest wrong\nclear Dwrong;\n\nDcorrect = dists;\nDcorrect(~LabelEqPrototype) = realmax(class(Dcorrect)); % set wrong labels impossible\ndistcorrect = min(Dcorrect.'); % closest correct\nclear Dcorrect;\nclear dists;\ndistcorrectpluswrong = distcorrect + distwrong;\ndistcorrectminuswrong = distcorrect - distwrong;\nmu = distcorrectminuswrong ./ distcorrectpluswrong;\nif regularization,\n regTerm = regularization * log(prod(model.lambda));\nelse\n regTerm = 0;\nend\ncost = sum(mu)-regTerm;\n\n\n\n\nfunction [f G] = GMLVQ_optfun(variables,training_data,LabelEqualsPrototype,LRrelevances,LRprototypes,prototypeLabel,regularization)\n% [f G] = GMLVQ_optfun(variables) \n% function to be optimzed by matrix relevance learning vector quantization\n% variables = [prototype matrix;omega matrix]\n% global variables are\n% training_data : data vectors as row vectors, i.e. attributes in columns\n% LabelEqualsPrototype : binary matrix indicating coocurrences of\n% training labels and prototype labels\n% prototypeLabel : label vector for the prototypes\n% regularization : the regularization parameter\n% LRrelevances : learning rate for the relevance matrix\n% LRprototypes : learning rate for the prototypes\n%\n% Kerstin Bunte (modified based on the code of Marc Strickert http://www.mloss.org/software/view/323/)\n% kerstin.bunte@googlemail.com\n% Fri Nov 09 14:13:52 CEST 2012\n%\n% Conditions of GNU General Public License, version 2 apply.\n% See file 'license-gpl2.txt' enclosed in this package.\n% Programs are not for use in critical applications!\n% \nif isempty(LRprototypes) % values between 1e-2,1e-3,... 1e-8 seem pragmatic\n LRprototypes = 1; % no relevance learning by default\nend\nif isempty(LRrelevances) % values between 1e-2,1e-3,... 1e-8 seem pragmatic\n LRrelevances = 0; % no relevance learning by default\nend\n[n_data, n_dim] = size(training_data);\nnb_prototypes = numel(prototypeLabel);\nomegaT = variables(nb_prototypes+1:end,:)';\nn_vec = size(variables,1) - nb_prototypes;\n\ndists = squaredEuclidean(training_data*omegaT, variables(1:nb_prototypes,:)*omegaT);\n\nDwrong = dists;\nDwrong(LabelEqualsPrototype) = realmax(class(Dwrong)); % set correct labels impossible\n[distwrong pidxwrong] = min(Dwrong.'); % closest wrong\nclear Dwrong;\n\nDcorrect = dists;\nDcorrect(~LabelEqualsPrototype) = realmax(class(Dcorrect)); % set wrong labels impossible\n[distcorrect pidxcorrect] = min(Dcorrect.'); % closest correct\nclear Dcorrect;\n\ndistcorrectpluswrong = distcorrect + distwrong;\ndistcorrectminuswrong = distcorrect - distwrong;\nmu = distcorrectminuswrong ./ distcorrectpluswrong;\n% callitq = 1./(1 + exp(-squashsigmoid * mu)); % apply sigmoidal\n\nif regularization,\n regTerm = regularization * log(det(omegaT'*omegaT));\nelse\n regTerm = 0;\nend\nf = sum(mu)-regTerm;\n% f = mean(callitq);\n\nif nargout > 1 % gradient needed not just function eval\n G = zeros(size(variables)); % initially no gradient\n % callitq = squashsigmoid * callitq .* (1-callitq); % derivative of sigmoid\n % distcorrectpluswrong = 2 * callitq ./ distcorrectpluswrong.^2; % degeneration?\n distcorrectpluswrong = 4 ./ distcorrectpluswrong.^2; % norm_factor for derivative for every data sample\n if LRrelevances > 0\n Gw = zeros(n_vec,n_dim);\n end\n for k=1:nb_prototypes%(n_vec+1):size(lambda,1) % update all prototypes \n idxc = (k == pidxcorrect); % Js: idxs where actual prototype is nearest correct\n idxw = (k == pidxwrong); % Ks: idxs where actual prototype is nearest wrong\n\n dcd = distcorrect(idxw) .* distcorrectpluswrong(idxw);\n dwd = distwrong(idxc) .* distcorrectpluswrong(idxc);\n if LRrelevances > 0\n % part of derivative of distance\n difc = bsxfun(@minus,training_data(idxc,:),variables(k,:)); % DJs\n difw = bsxfun(@minus,training_data(idxw,:),variables(k,:)); % DKs\n % update omega \n Gw = Gw - (bsxfun(@times,difw,dcd.') * omegaT).' * difw + ...\n (bsxfun(@times,difc,dwd.') * omegaT).' * difc;\n if LRprototypes > 0\n G(k,:) = dcd * difw - dwd * difc;\n end\n else\n if LRprototypes > 0\n G(k,:) = dcd * training_data(idxw,:) - dwd * training_data(idxc,:) + (sum(dwd)-sum(dcd)) * variables(k,:);\n end\n end\n end\nif regularization,\n f3 = (pinv(omegaT'))'; \nelse\n f3 = 0;\nend \n % some rescalings needed\n if LRrelevances > 0\n G(nb_prototypes+1:nb_prototypes+n_vec,:) = 2/n_data * LRrelevances * Gw - regularization*f3;\n end\n if LRprototypes > 0\n G(1:nb_prototypes,:) = 1./n_data * LRprototypes * G(1:nb_prototypes,:) * omegaT * omegaT.';\n end\n G = G .* (1 + .0001 * (rand(size(G))-.5)); % help break symmetries\nend\n% if 0,\n% w = variables(1:nb_prototypes,:);\n% dJs = zeros(1,nb_samples);\n% dKs = zeros(1,nb_samples);\n% Js = zeros(1,nb_samples);\n% Ks = zeros(1,nb_samples);\n% norm_factors = zeros(1,nb_samples);\n% DJs = zeros(nb_samples,size(training_data,2));\n% DKs = zeros(nb_samples,size(training_data,2));\n% for i=1:nb_samples\n% % select one training sample randomly\n% xi = training_data(i,:);\n% c_xi = trainLab(i);\n% \n% dist = ((xi(ones(size(w,1),1),:))-w)*omegaT*(omegaT'*((xi(ones(size(w,1),1),:))-w)');\n% dist = diag(dist);\n% % determine the two winning prototypes\n% % nearest prototype with the same class\n% [sortDist,sortIdx] = sort(dist);\n% count = 1;\n% J = sortIdx(count);\n% while prototypeLabel(sortIdx(count)) ~= c_xi, \n% count = count+1;\n% J = sortIdx(count);\n% end\n% dJ = sortDist(count);\n% dJs(i) = dJ;\n% Js(i) = J;\n% count = 1;\n% K = sortIdx(count);\n% while prototypeLabel(sortIdx(count)) == c_xi, \n% count = count+1;\n% K = sortIdx(count);\n% end\n% dK = sortDist(count);\n% dKs(i) = dK;\n% Ks(i) = K;\n% \n% wJ = w(J,:);\n% wK = w(K,:);\n% % prototype update\n% norm_factors(i) = 4/((dJ + dK)^2);\n% DJ = (xi-wJ);\n% DK = (xi-wK);\n% DJs(i,:) = DJ;\n% DKs(i,:) = DK;\n% end\n% end\n\n\n\n\n\nfunction D = squaredEuclidean(A, B)\n% computes the sqared Euclidean distance\n%\n% D = squaredEuclidean(X) returns the squared Euclidean distance matrix of data in rows of X \n% D = squaredEuclidean(X, Y) returns the distance matrix with all distances between the points in X and Y.\n%\nif nargin == 1 % means that one matrix\n D = bsxfun(@plus, sumsquared(A,2), bsxfun(@minus, sumsquared(A,2).', 2*A*A.')); % 2*(Y*Y.')\nelse \n D = bsxfun(@plus, sumsquared(A,2), bsxfun(@minus, sumsquared(B,2).', 2*A*B.'));\nend\nD = max(D,0);\n\n\n\n\nfunction sq = sumsquared(x,dim) \n% sq = sumsquared(x,dim) \n% sum of all squared element of matrix x along dimension dim\n\npersistent isoctave\n\nif isempty(isoctave)\n isoctave = exist('OCTAVE_VERSION','builtin');\nend\n\nif nargin == 1\n dim = 1;\nend\n\nif isoctave\n sq = sumsq(x,dim);\nelse\n sq = sum(x.^2, dim);\nend\n\n\n", "meta": {"author": "ilarinieminen", "repo": "SOM-Toolbox", "sha": "f2597abc1ae33c2060e0443d49e854011ff21831", "save_path": "github-repos/MATLAB/ilarinieminen-SOM-Toolbox", "path": "github-repos/MATLAB/ilarinieminen-SOM-Toolbox/SOM-Toolbox-f2597abc1ae33c2060e0443d49e854011ff21831/contrib/gmlvq/grlvq_core.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.47523759284547973}}
{"text": "function DEM = reclassify(DEM,varargin)\n\n%RECLASSIFY generate univariate class intervals for an instance of GRIDobj\n%\n% Syntax\n%\n% C = reclassify(DEM);\n% C = reclassify(DEM,'method',value)\n%\n% Description\n%\n% reclassify bins continous values of an instance of GRIDobj by setting\n% class intervals based on different classification methods. The\n% default method is equal interval classification with 10 classes.\n%\n% Input Arguments\n%\n% DEM Grid (class = GRIDobj)\n% \n% 'Methods' and [values]\n%\n% 'equalintervals' [number of classes]\n% 'definedintervals' [vector of class breaks]\n% 'equalquantiles' [number of classes]\n% 'definedquantiles' [vector of quantiles] \n% e.g. [0.1 0.9] results in three classes \n% 'kmeans' [number of classes]\n% uses the k_means algorithm of Yi Cao\n% FEX submission 19344 included in this function\n% ! may take a while for large grids !\n% 'std' [s = scale of standard deviation, e.g. 2]\n% equal intervals with a width of std/s. Bins are\n% centered around sample mean\n% 'otsu' [number of classes, must be (2 4 8 16 etc)] \n% recursive Otsu thresholding (see function \n% graythresh)\n%\n% Output argument\n%\n% C Classified grid (class = GRIDobj)\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% C = reclassify(DEM,'equalquantiles',10);\n% imageschs(DEM,C)\n%\n% See also: k_means, graythresh\n% \n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 18. January, 2013\n\nnarginchk(1,3)\n\nallowedmethods = {'equalintervals',...\n 'definedintervals',...\n 'definedquantiles',...\n 'equalquantiles',...\n 'kmeans',...\n 'standarddeviation',...\n 'std',...\n 'otsu'...\n };\n% nr of classes\nif nargin == 1;\n method = 'equalinterval';\n num = 10;\nelse\n method = validatestring(varargin{1},allowedmethods);\n \n if nargin==3\n num = varargin{2};\n end\nend\n\nINAN = isnan(DEM.Z) | isinf(DEM.Z);\nDEM.Z(INAN) = nan;\ninan = any(INAN(:));\n\nswitch method\n case 'equalintervals'\n validateattributes(num,{'numeric'},{'scalar'});\n \n if inan\n DEM.Z(~INAN) = mat2gray(DEM.Z(~INAN));\n DEM.Z = grayslice(DEM.Z,num);\n if num == 256;\n DEM.Z = double(DEM.Z) + 1;\n DEM.Z(INAN) = nan;\n elseif num < 256;\n DEM.Z = DEM.Z + 1;\n DEM.Z(INAN) = 0;\n else\n DEM.Z(INAN) = nan;\n end\n \n else\n DEM.Z = mat2gray(DEM.Z);\n DEM.Z = grayslice(DEM.Z,num);\n \n if num <= 255\n DEM.Z = DEM.Z + 1;\n elseif num == 256\n DEM.Z = double(DEM.Z) + 1;\n end\n end\n case 'definedintervals'\n validateattributes(num,{'numeric'},{'vector'});\n num(end+1) = inf;\n num = [-inf; num(:)];\n siz = size(DEM.Z);\n [~,DEM.Z] = histc(DEM.Z(:),num);\n DEM.Z = reshape(DEM.Z,siz);\n case 'equalquantiles'\n validateattributes(num,{'numeric'},{'scalar','integer','>',1});\n z = DEM.Z(~INAN);\n z = z(:);\n z = sort(z,'ascend');\n q = (1:num)/num;\n q = ceil(q*numel(z));\n edges = z(q);\n edges(end) = inf;\n [~,DEM.Z] = histc(DEM.Z(:),[-inf; edges]);\n DEM.Z = reshape(DEM.Z,DEM.size);\n DEM.Z(INAN) = nan;\n case 'definedquantiles'\n validateattributes(num,{'numeric'},{'vector','>',0,'<=',1});\n p = num(:);\n if p(end) < 1;\n p(end+1) = 1;\n end\n \n z = DEM.Z(~INAN);\n z = z(:);\n n = numel(z);\n edges = interp1((0:n-1).'/(n-1), sort(z), p);\n \n edges(end) = inf;\n [~,DEM.Z] = histc(DEM.Z(:),[-inf; edges]);\n DEM.Z = reshape(DEM.Z,DEM.size);\n DEM.Z(INAN) = nan;\n \n case {'standarddeviation','std'}\n validateattributes(num,{'numeric'},{'vector','>',0,'<=',1});\n z = DEM.Z(~INAN);\n z = z(:);\n s = std(z(:));\n s = s*num;\n mz = mean(z);\n minz = min(z);\n maxz = max(z);\n \n edges1 = [mz-s/2 :-s: minz];\n if edges1(end) > minz\n edges1(end+1) = -inf;\n else\n edges1(end) = -inf;\n end\n edges2 = mz+s/2 :s: maxz;\n \n edges2(end) = inf;\n \n [~,DEM.Z] = histc(DEM.Z(:),[edges1(end:-1:1) edges2]);\n DEM.Z = reshape(DEM.Z,DEM.size);\n DEM.Z(INAN) = nan;\n \n case 'kmeans';\n \n validateattributes(num,{'numeric'},{'scalar','integer','>',1});\n z = DEM.Z(~INAN);\n z = z(:);\n \n IX = k_means(z,num);\n \n DEM.Z(:,:) = nan;\n DEM.Z(~INAN) = IX;\n case 'otsu'; \n validateattributes(num,{'numeric'},{'scalar','integer','>',1});\n if ceil(log2(num)) ~= log2(num);\n error('TopToolbox:GRIDobj','log2(value) must be an integer')\n end\n \n INAN = ~INAN;\n z = mat2gray(DEM.Z(INAN));\n DEM.Z(INAN) = cast(otsu(z,num),class(DEM.Z));\nend\n\nend\n\n\n\n\n% subfunctions\n\nfunction [gIdx,c]=k_means(X,k)\n% K_MEANS k-means clustring\n% IDX = k_means(X, K) partititions the N x P data matrix X into K\n% clusters through a fully vectorized algorithm, where N is the number of\n% data points and P is the number of dimensions (variables). The\n% partition minimizes the sum of point-to-cluster-centroid Euclidean\n% distances of all clusters. The returned N x 1 vector IDX contains the\n% cluster indices of each point.\n%\n% IDX = k_means(X, C) works with the initial centroids, C, (K x P).\n%\n% [IDX, C] = k_means(X, K) also returns the K cluster centroid locations\n% in the K x P matrix, C.\n%\n% See also kmeans\n\n% Version 2.0, by Yi Cao at Cranfield University on 27 March 2008.\n\n% Example 1: small data set\n%{\nN=200;\nX = [randn(N,2)+ones(N,2); randn(N,2)-ones(N,2)];\n[cidx, ctrs] = k_means(X, 2);\nplot(X(cidx==1,1),X(cidx==1,2),'r.',X(cidx==2,1),X(cidx==2,2),'b.', ctrs(:,1),ctrs(:,2),'kx');\n%}\n\n% Example 2: large data set\n%{\nN=20000;\nX = [randn(N,2)+ones(N,2); randn(N,2)-ones(N,2)];\ntic\n[cidx, ctrs] = k_means(X, 2);\ntoc\nplot(X(cidx==1,1),X(cidx==1,2),'r.',X(cidx==2,1),X(cidx==2,2),'b.', ctrs(:,1),ctrs(:,2),'kx');\n%}\n\n% Example 3: large data set with 5 centroids \n%{\nN=20000;\nX = [randn(N,2)+ones(N,2); randn(N,2)-ones(N,2)];\ntic\n[cidx, ctrs] = k_means(X, 5);\ntoc\nplot(X(cidx==1,1),X(cidx==1,2),'.',...\nX(cidx==2,1),X(cidx==2,2),'.',...\nX(cidx==3,1),X(cidx==3,2),'.',...\nX(cidx==4,1),X(cidx==4,2),'.',...\nX(cidx==5,1),X(cidx==5,2),'.',...\nctrs(:,1),ctrs(:,2),'+','linewidth',2)\n%}\n\n% Example 4: Comparison with kmeans in Statistics Toolbox\n%{\nN=20000;\nX = [randn(N,2)+ones(N,2); randn(N,2)-ones(N,2)];\nrand('state',0);\ntic\ncidx = k_means(X, 20);\ntoc\n% Compare with kmeans in Statistis Toolbox\nrand('state',0);\ntic,\ncidx1 = kmeans(X, 20, 'Option', statset('MaxIter',200));\ntoc\n%}\n\n% Check input and output\nnarginchk(2,2);\n\n[n,m]=size(X);\n\n% Check if second input is centroids\nif ~isscalar(k)\n c=k;\n k=size(c,1);\nelse\n c=X(ceil(rand(k,1)*n),:);\nend\n\n% allocating variables\ng0=ones(n,1);\ngIdx=zeros(n,1);\nD=zeros(n,k);\n\n% Main loop converge if previous partition is the same as current\nwhile any(g0~=gIdx)\n% disp(sum(g0~=gIdx))\n g0=gIdx;\n % Loop for each centroid\n for t=1:k\n d=zeros(n,1);\n % Loop for each dimension\n for s=1:m\n d=d+(X(:,s)-c(t,s)).^2;\n end\n D(:,t)=d;\n end\n % Partition data to closest centroids\n [~,gIdx]=min(D,[],2);\n % Update centroids using means of partitions\n for t=1:k\n c(t,:)=mean(X(gIdx==t,:));\n end\n% for t=1:m\n% c(:,t)=accumarray(gIdx,X(:,t),[],@mean);\n% end\nend\n\nend\n\n\nfunction ix = otsu(x,n)\n\nif mod(n,2)~=0\n error('number of classes is odd');\nend\n\nI = x >= graythresh(x);\nix = I*n/2;% + 1;\n% do until all classes are \nif n > 2\nix(I) = otsu(x(I),n/2) + ix(I); \nix(~I) = otsu(x(~I),n/2) + ix(~I);\nelse\n ix = ix+1;\n \nend\n\nend\n\n\n\n\n", "meta": {"author": "GERSL", "repo": "CCDC", "sha": "11b47273a9599b6943040f068d7a0af0db96c885", "save_path": "github-repos/MATLAB/GERSL-CCDC", "path": "github-repos/MATLAB/GERSL-CCDC/CCDC-11b47273a9599b6943040f068d7a0af0db96c885/GRIDobj/reclassify.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.4749187126281322}}
{"text": "function C = minus(A,B)\n%MINUS Binary subtraction for sparse tensors. \n%\n% MINUS(A,B) is called for the syntax 'A - B' when A or B is a sparse\n% tensor. A and B must have the same size, unless one is a scalar. A\n% scalar can be subtracted from a sparse tensor of any size.\n%\n% Examples\n% A = sptenrand([4 3 2],5); B = sptenrand([4 3 2],3);\n% A - B %<-- sparse\n% A - 5 %<-- dense\n% A - 0 %<-- dense\n% A - full(A) %<-- dense\n%\n% See also SPTENSOR.\n%\n%MATLAB Tensor Toolbox.\n%Copyright 2015, Sandia Corporation.\n\n% This is the MATLAB Tensor Toolbox by T. Kolda, B. Bader, and others.\n% http://www.sandia.gov/~tgkolda/TensorToolbox.\n% Copyright (2015) Sandia Corporation. Under the terms of Contract\n% DE-AC04-94AL85000, there is a non-exclusive license for use of this\n% work by or on behalf of the U.S. Government. Export of this data may\n% require a license from the United States Government.\n% The full license terms can be found in the file LICENSE.txt\n\n\n%% Observations for sparse matrix case.\n% The result of a - 5 is dense!\n% The result of a - 0 is dense!\n% The result of a - full(a) is dense!\n% The result of a - b (two sparse matrices) is sparse.\n\n%% Case 1: One argument is a scalar\n% Emulating the sparse matrix case here, which creates and returns\n% a dense result, even if the scalar is zero.\n\n% Case 1a: Second argument is a scalar or a dense tensor\nif isscalar(B) || isa(B,'tensor')\n C = full(A) - B;\n return;\nend\n\n% Case 1b: First argument is a scalar or a dense tensor\nif isscalar(A) || isa(A,'tensor')\n C = A - full(B);\n return;\nend\n\n%% Case 2: Both are sparse tensors\nif ~isa(A,'sptensor') || ~isa(B,'sptensor') || ~isequal(size(A),size(B))\n error('Must be two sparse tensors of the same size');\nend\n\nC = sptensor([A.subs; B.subs], [A.vals; -B.vals], size(A));\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/åē±»ē®ę³/DEEP-TENSOR-FACTORIZATION-FOR-HYPERSPECTRAL-IMAGE-CLASSIFICATION-master/code/tensor_toolbox_2.6/@sptensor/minus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.47491870383067325}}
{"text": "%go_calib_optim_iter\n%\n%Main calibration function. Computes the intrinsic andextrinsic parameters.\n%Runs as a script.\n%\n%INPUT: x_1,x_2,x_3,...: Feature locations on the images\n% X_1,X_2,X_3,...: Corresponding grid coordinates\n%\n%OUTPUT: fc: Camera focal length\n% cc: Principal point coordinates\n% alpha_c: Skew coefficient\n% kc: Distortion coefficients\n% KK: The camera matrix (containing fc and cc)\n% omc_1,omc_2,omc_3,...: 3D rotation vectors attached to the grid positions in space\n% Tc_1,Tc_2,Tc_3,...: 3D translation vectors attached to the grid positions in space\n% Rc_1,Rc_2,Rc_3,...: 3D rotation matrices corresponding to the omc vectors\n%\n%Method: Minimizes the pixel reprojection error in the least squares sense over the intrinsic\n% camera parameters, and the extrinsic parameters (3D locations of the grids in space)\n%\n%Note: If the intrinsic camera parameters (fc, cc, kc) do not exist before, they are initialized through\n% the function init_intrinsic_param.m. Otherwise, the variables in memory are used as initial guesses.\n%\n%Note: The row vector active_images consists of zeros and ones. To deactivate an image, set the\n% corresponding entry in the active_images vector to zero.\n%\n%VERY IMPORTANT: This function works for 2D and 3D calibration rigs, except for init_intrinsic_param.m\n%that is so far implemented to work only with 2D rigs.\n%In the future, a more general function will be there.\n%For now, if using a 3D calibration rig, quick_init is set to 1 for an easy initialization of the focal length\n\nif ~exist('desactivated_images'),\n desactivated_images = [];\nend;\n\n\n\nif ~exist('est_aspect_ratio'),\n est_aspect_ratio = 1;\nend;\n\nif ~exist('est_fc');\n est_fc = [1;1]; % Set to zero if you do not want to estimate the focal length (it may be useful! believe it or not!)\nend;\n\nif ~exist('recompute_extrinsic'),\n recompute_extrinsic = 1; % Set this variable to 0 in case you do not want to recompute the extrinsic parameters\n % at each iterstion.\nend;\n\nif ~exist('MaxIter'),\n MaxIter = 30; % Maximum number of iterations in the gradient descent\nend;\n\nif ~exist('check_cond'),\n check_cond = 1; % Set this variable to 0 in case you don't want to extract view dynamically\nend;\n\nif ~exist('center_optim'),\n center_optim = 1; %%% Set this variable to 0 if your do not want to estimate the principal point\nend;\n\nif exist('est_dist'),\n if length(est_dist) == 4,\n est_dist = [est_dist ; 0];\n end;\nend;\n\nif ~exist('est_dist'),\n est_dist = [1;1;1;1;0];\nend;\n\nif ~exist('est_alpha'),\n est_alpha = 0; % by default, do not estimate skew\nend;\n\n\n% Little fix in case of stupid values in the binary variables:\ncenter_optim = double(~~center_optim);\nest_alpha = double(~~est_alpha);\nest_dist = double(~~est_dist);\nest_fc = double(~~est_fc);\nest_aspect_ratio = double(~~est_aspect_ratio);\n\n\n\nfprintf(1,'\\n');\n\nif ~exist('nx')&~exist('ny'),\n fprintf(1,'WARNING: No image size (nx,ny) available. Setting nx=640 and ny=480. If these are not the right values, change values manually.\\n');\n nx = 640;\n ny = 480;\nend;\n\n\ncheck_active_images;\n\n\nquick_init = 0; % Set to 1 for using a quick init (necessary when using 3D rigs)\n\n\n% Check 3D-ness of the calibration rig:\nrig3D = 0;\nfor kk = ind_active,\n eval(['X_kk = X_' num2str(kk) ';']);\n if is3D(X_kk),\n rig3D = 1;\n end;\nend;\n\n\nif center_optim & (length(ind_active) < 2) & ~rig3D,\n fprintf(1,'WARNING: Principal point rejected from the optimization when using one image and planar rig (center_optim = 1).\\n');\n center_optim = 0; %%% when using a single image, please, no principal point estimation!!!\n est_alpha = 0;\nend;\n\nif ~exist('dont_ask'),\n dont_ask = 0;\nend;\n\nif center_optim & (length(ind_active) < 5) & ~rig3D,\n fprintf(1,'WARNING: The principal point estimation may be unreliable (using less than 5 images for calibration).\\n');\n %if ~dont_ask,\n % quest = input('Are you sure you want to keep the principal point in the optimization process? ([]=yes, other=no) ');\n % center_optim = isempty(quest);\n %end;\nend;\n\n\n% A quick fix for solving conflict\nif ~isequal(est_fc,[1;1]),\n est_aspect_ratio=1;\nend;\nif ~est_aspect_ratio,\n est_fc=[1;1];\nend;\n\n\nif ~est_aspect_ratio,\n fprintf(1,'Aspect ratio not optimized (est_aspect_ratio = 0) -> fc(1)=fc(2). Set est_aspect_ratio to 1 for estimating aspect ratio.\\n');\nelse\n if isequal(est_fc,[1;1]),\n fprintf(1,'Aspect ratio optimized (est_aspect_ratio = 1) -> both components of fc are estimated (DEFAULT).\\n');\n end;\nend;\n\nif ~isequal(est_fc,[1;1]),\n if isequal(est_fc,[1;0]),\n fprintf(1,'The first component of focal (fc(1)) is estimated, but not the second one (est_fc=[1;0])\\n');\n else\n if isequal(est_fc,[0;1]),\n fprintf(1,'The second component of focal (fc(1)) is estimated, but not the first one (est_fc=[0;1])\\n');\n else\n fprintf(1,'The focal vector fc is not optimized (est_fc=[0;0])\\n');\n end;\n end;\nend;\n\n\nif ~center_optim, % In the case where the principal point is not estimated, keep it at the center of the image\n fprintf(1,'Principal point not optimized (center_optim=0). ');\n if ~exist('cc'),\n fprintf(1,'It is kept at the center of the image.\\n');\n cc = [(nx-1)/2;(ny-1)/2];\n else\n fprintf(1,'Note: to set it in the middle of the image, clear variable cc, and run calibration again.\\n');\n end;\nelse\n fprintf(1,'Principal point optimized (center_optim=1) - (DEFAULT). To reject principal point, set center_optim=0\\n');\nend;\n\n\nif ~center_optim & (est_alpha),\n fprintf(1,'WARNING: Since there is no principal point estimation (center_optim=0), no skew estimation (est_alpha = 0)\\n');\n est_alpha = 0; \nend;\n\nif ~est_alpha,\n fprintf(1,'Skew not optimized (est_alpha=0) - (DEFAULT)\\n');\n alpha_c = 0;\nelse\n fprintf(1,'Skew optimized (est_alpha=1). To disable skew estimation, set est_alpha=0.\\n');\nend;\n\n\nif ~prod(double(est_dist)),\n fprintf(1,'Distortion not fully estimated (defined by the variable est_dist):\\n');\n if ~est_dist(1),\n fprintf(1,' Second order distortion not estimated (est_dist(1)=0).\\n');\n end;\n if ~est_dist(2),\n fprintf(1,' Fourth order distortion not estimated (est_dist(2)=0).\\n');\n end;\n if ~est_dist(5),\n fprintf(1,' Sixth order distortion not estimated (est_dist(5)=0) - (DEFAULT) .\\n');\n end;\n if ~prod(double(est_dist(3:4))),\n fprintf(1,' Tangential distortion not estimated (est_dist(3:4)~=[1;1]).\\n');\n end;\nend;\n\n\n% Check 3D-ness of the calibration rig:\nrig3D = 0;\nfor kk = ind_active,\n eval(['X_kk = X_' num2str(kk) ';']);\n if is3D(X_kk),\n rig3D = 1;\n end;\nend;\n\n% If the rig is 3D, then no choice: the only valid initialization is manual!\nif rig3D,\n quick_init = 1;\nend;\n\n\n\nalpha_smooth = 0.1; % set alpha_smooth = 1; for steepest gradient descent\n\n\n% Conditioning threshold for view rejection\nthresh_cond = 1e6;\n\n\n\n% Initialization of the intrinsic parameters (if necessary)\n\nif ~exist('cc'),\n fprintf(1,'Initialization of the principal point at the center of the image.\\n');\n cc = [(nx-1)/2;(ny-1)/2];\n alpha_smooth = 0.1; % slow convergence\nend;\n\n\nif exist('kc'),\n if length(kc) == 4;\n fprintf(1,'Adding a new distortion coefficient to kc -> radial distortion model up to the 6th degree');\n kc = [kc;0];\n end;\nend;\n\nif ~exist('alpha_c'),\n fprintf(1,'Initialization of the image skew to zero.\\n');\n alpha_c = 0;\n alpha_smooth = 0.1; % slow convergence\nend;\n\nif ~exist('fc') && quick_init,\n FOV_angle = 35; % Initial camera field of view in degrees\n fprintf(1,['Initialization of the focal length to a FOV of ' num2str(FOV_angle) ' degrees.\\n']);\n fc = (nx/2)/tan(pi*FOV_angle/360) * ones(2,1);\n est_fc = [1;1];\n alpha_smooth = 0.1; % slow \nend;\n\n\nif ~exist('fc'),\n % Initialization of the intrinsic parameters:\n fprintf(1,'Initialization of the intrinsic parameters using the vanishing points of planar patterns.\\n')\n init_intrinsic_param; % The right way to go (if quick_init is not active)!\n alpha_smooth = 0.1; % slow convergence\n est_fc = [1;1];\nend;\n\n\nif ~exist('kc'),\n fprintf(1,'Initialization of the image distortion to zero.\\n');\n kc = zeros(5,1);\n alpha_smooth = 0.1; % slow convergence\nend;\n\nif ~est_aspect_ratio,\n fc(1) = (fc(1)+fc(2))/2;\n fc(2) = fc(1);\nend;\n\nif ~prod(double(est_dist)),\n % If no distortion estimated, set to zero the variables that are not estimated\n kc = kc .* est_dist;\nend;\n\n\nif ~prod(double(est_fc)),\n fprintf(1,'Warning: The focal length is not fully estimated (est_fc ~= [1;1])\\n');\nend;\n\n\n%%% Initialization of the extrinsic parameters for global minimization:\ncomp_ext_calib;\n\n\n\n%%% Initialization of the global parameter vector:\n\ninit_param = [fc;cc;alpha_c;kc;zeros(5,1)]; \n\nfor kk = 1:n_ima,\n eval(['omckk = omc_' num2str(kk) ';']);\n eval(['Tckk = Tc_' num2str(kk) ';']);\n init_param = [init_param; omckk ; Tckk]; \nend;\n\n\n\n%-------------------- Main Optimization:\n\nfprintf(1,'\\nMain calibration optimization procedure - Number of images: %d\\n',length(ind_active));\n\n\nparam = init_param;\nchange = 1;\n\niter = 0;\n\nfprintf(1,'Gradient descent iterations: ');\n\nparam_list = param;\n\n\nwhile (change > 1e-9) && (iter < MaxIter),\n \n fprintf(1,'%d...',iter+1);\n \n % To speed up: pre-allocate the memory for the Jacobian JJ3.\n % For that, need to compute the total number of points.\n \n %% The first step consists of updating the whole vector of knowns (intrinsic + extrinsic of active\n %% images) through a one step steepest gradient descent.\n \n \n f = param(1:2);\n c = param(3:4);\n alpha = param(5);\n k = param(6:10);\n \n \n % Compute the size of the Jacobian matrix:\n N_points_views_active = N_points_views(ind_active);\n \n JJ3 = sparse([],[],[],15 + 6*n_ima,15 + 6*n_ima,126*n_ima + 225);\n ex3 = zeros(15 + 6*n_ima,1);\n \n \n for kk = ind_active, %1:n_ima,\n %if active_images(kk),\n \n omckk = param(15+6*(kk-1) + 1:15+6*(kk-1) + 3); \n \n Tckk = param(15+6*(kk-1) + 4:15+6*(kk-1) + 6); \n \n if isnan(omckk(1)),\n fprintf(1,'Intrinsic parameters at frame %d do not exist\\n',kk);\n return;\n end;\n \n eval(['X_kk = X_' num2str(kk) ';']);\n eval(['x_kk = x_' num2str(kk) ';']);\n \n Np = N_points_views(kk);\n \n if ~est_aspect_ratio,\n [x,dxdom,dxdT,dxdf,dxdc,dxdk,dxdalpha] = project_points2(X_kk,omckk,Tckk,f(1),c,k,alpha);\n dxdf = repmat(dxdf,[1 2]);\n else\n [x,dxdom,dxdT,dxdf,dxdc,dxdk,dxdalpha] = project_points2(X_kk,omckk,Tckk,f,c,k,alpha);\n end;\n \n exkk = x_kk - x;\n \n A = [dxdf dxdc dxdalpha dxdk]';\n B = [dxdom dxdT]';\n \n JJ3(1:10,1:10) = JJ3(1:10,1:10) + sparse(A*A');\n JJ3(15+6*(kk-1) + 1:15+6*(kk-1) + 6,15+6*(kk-1) + 1:15+6*(kk-1) + 6) = sparse(B*B');\n \n AB = sparse(A*B');\n JJ3(1:10,15+6*(kk-1) + 1:15+6*(kk-1) + 6) = AB;\n JJ3(15+6*(kk-1) + 1:15+6*(kk-1) + 6,1:10) = (AB)';\n \n ex3(1:10) = ex3(1:10) + A*exkk(:);\n ex3(15+6*(kk-1) + 1:15+6*(kk-1) + 6) = B*exkk(:);\n \n % Check if this view is ill-conditioned:\n if check_cond,\n JJ_kk = B'; %[dxdom dxdT];\n if (cond(JJ_kk)> thresh_cond),\n active_images(kk) = 0;\n fprintf(1,'\\nWarning: View #%d ill-conditioned. This image is now set inactive. (note: to disactivate this option, set check_cond=0)\\n',kk)\n desactivated_images = [desactivated_images kk];\n param(15+6*(kk-1) + 1:15+6*(kk-1) + 6) = NaN*ones(6,1); \n end;\n end;\n \n %end;\n \n end;\n \n \n % List of active images (necessary if changed):\n check_active_images;\n \n \n % The following vector helps to select the variables to update (for only active images):\n selected_variables = [est_fc;center_optim*ones(2,1);est_alpha;est_dist;zeros(5,1);reshape(ones(6,1)*active_images,6*n_ima,1)];\n if ~est_aspect_ratio,\n if isequal(est_fc,[1;1]) | isequal(est_fc,[1;0]),\n selected_variables(2) = 0;\n end;\n end;\n ind_Jac = find(selected_variables)';\n \n JJ3 = JJ3(ind_Jac,ind_Jac);\n ex3 = ex3(ind_Jac);\n \n JJ2_inv = inv(JJ3); % not bad for sparse matrices!!\n \n \n % Smoothing coefficient:\n \n alpha_smooth2 = 1-(1-alpha_smooth)^(iter+1); %set to 1 to undo any smoothing!\n \n param_innov = alpha_smooth2*JJ2_inv*ex3;\n \n \n param_up = param(ind_Jac) + param_innov;\n param(ind_Jac) = param_up;\n \n \n % New intrinsic parameters:\n \n fc_current = param(1:2);\n cc_current = param(3:4);\n\n if center_optim & ((param(3)<0)|(param(3)>nx)|(param(4)<0)|(param(4)>ny)),\n fprintf(1,'Warning: it appears that the principal point cannot be estimated. Setting center_optim = 0\\n');\n center_optim = 0;\n cc_current = c;\n else\n cc_current = param(3:4);\n end;\n \n alpha_current = param(5);\n kc_current = param(6:10);\n \n if ~est_aspect_ratio & isequal(est_fc,[1;1]),\n fc_current(2) = fc_current(1);\n param(2) = param(1);\n end;\n \n % Change on the intrinsic parameters:\n change = norm([fc_current;cc_current] - [f;c])/norm([fc_current;cc_current]);\n \n \n %% Second step: (optional) - It makes convergence faster, and the region of convergence LARGER!!!\n %% Recompute the extrinsic parameters only using compute_extrinsic.m (this may be useful sometimes)\n %% The complete gradient descent method is useful to precisely update the intrinsic parameters.\n \n \n if recompute_extrinsic,\n MaxIter2 = 20;\n for kk =ind_active, %1:n_ima,\n %if active_images(kk),\n omc_current = param(15+6*(kk-1) + 1:15+6*(kk-1) + 3);\n Tc_current = param(15+6*(kk-1) + 4:15+6*(kk-1) + 6);\n eval(['X_kk = X_' num2str(kk) ';']);\n eval(['x_kk = x_' num2str(kk) ';']);\n [omc_current,Tc_current] = compute_extrinsic_init(x_kk,X_kk,fc_current,cc_current,kc_current,alpha_current);\n [omckk,Tckk,Rckk,JJ_kk] = compute_extrinsic_refine(omc_current,Tc_current,x_kk,X_kk,fc_current,cc_current,kc_current,alpha_current,MaxIter2,thresh_cond);\n if check_cond,\n if (cond(JJ_kk)> thresh_cond),\n active_images(kk) = 0;\n fprintf(1,'\\nWarning: View #%d ill-conditioned. This image is now set inactive. (note: to disactivate this option, set check_cond=0)\\n',kk);\n desactivated_images = [desactivated_images kk];\n omckk = NaN*ones(3,1);\n Tckk = NaN*ones(3,1);\n end;\n end;\n param(15+6*(kk-1) + 1:15+6*(kk-1) + 3) = omckk;\n param(15+6*(kk-1) + 4:15+6*(kk-1) + 6) = Tckk;\n %end;\n end;\n end;\n \n param_list = [param_list param];\n iter = iter + 1;\n \nend;\n\nfprintf(1,'done\\n');\n\n\n\n%%%--------------------------- Computation of the error of estimation:\n\nfprintf(1,'Estimation of uncertainties...');\n\n\ncheck_active_images;\n\nsolution = param;\n\n\n% Extraction of the paramters for computing the right reprojection error:\n\nfc = solution(1:2);\ncc = solution(3:4);\nalpha_c = solution(5);\nkc = solution(6:10);\n\nfor kk = 1:n_ima,\n \n if active_images(kk), \n \n omckk = solution(15+6*(kk-1) + 1:15+6*(kk-1) + 3);%*** \n Tckk = solution(15+6*(kk-1) + 4:15+6*(kk-1) + 6);%*** \n Rckk = rodrigues(omckk);\n \n else\n \n omckk = NaN*ones(3,1); \n Tckk = NaN*ones(3,1);\n Rckk = NaN*ones(3,3);\n \n end;\n \n eval(['omc_' num2str(kk) ' = omckk;']);\n eval(['Rc_' num2str(kk) ' = Rckk;']);\n eval(['Tc_' num2str(kk) ' = Tckk;']);\n \nend;\n\n\n% Recompute the error (in the vector ex):\ncomp_error_calib;\n\nsigma_x = std(ex(:));\n\n% Compute the size of the Jacobian matrix:\nN_points_views_active = N_points_views(ind_active);\n\nJJ3 = sparse([],[],[],15 + 6*n_ima,15 + 6*n_ima,126*n_ima + 225);\n\nfor kk = ind_active,\n \n omckk = param(15+6*(kk-1) + 1:15+6*(kk-1) + 3); \n Tckk = param(15+6*(kk-1) + 4:15+6*(kk-1) + 6); \n \n eval(['X_kk = X_' num2str(kk) ';']);\n \n Np = N_points_views(kk);\n \n %[x,dxdom,dxdT,dxdf,dxdc,dxdk,dxdalpha] = project_points2(X_kk,omckk,Tckk,fc,cc,kc,alpha_c);\n \n if ~est_aspect_ratio,\n [x,dxdom,dxdT,dxdf,dxdc,dxdk,dxdalpha] = project_points2(X_kk,omckk,Tckk,fc(1),cc,kc,alpha_c);\n dxdf = repmat(dxdf,[1 2]);\n else\n [x,dxdom,dxdT,dxdf,dxdc,dxdk,dxdalpha] = project_points2(X_kk,omckk,Tckk,fc,cc,kc,alpha_c);\n end;\n \n A = [dxdf dxdc dxdalpha dxdk]';\n B = [dxdom dxdT]';\n \n JJ3(1:10,1:10) = JJ3(1:10,1:10) + sparse(A*A');\n JJ3(15+6*(kk-1) + 1:15+6*(kk-1) + 6,15+6*(kk-1) + 1:15+6*(kk-1) + 6) = sparse(B*B');\n \n AB = sparse(A*B');\n JJ3(1:10,15+6*(kk-1) + 1:15+6*(kk-1) + 6) = AB;\n JJ3(15+6*(kk-1) + 1:15+6*(kk-1) + 6,1:10) = (AB)';\n \nend;\n\nJJ3 = JJ3(ind_Jac,ind_Jac);\n\nJJ2_inv = inv(JJ3); % not bad for sparse matrices!!\n\nparam_error = zeros(6*n_ima+15,1);\nparam_error(ind_Jac) = 3*sqrt(full(diag(JJ2_inv)))*sigma_x;\n\nsolution_error = param_error;\n\nif ~est_aspect_ratio && isequal(est_fc,[1;1]),\n solution_error(2) = solution_error(1);\nend;\n\n\n%%% Extraction of the final intrinsic and extrinsic paramaters:\n\nextract_parameters;\n\nfprintf(1,'done\\n');\n\n\nfprintf(1,'\\n\\nCalibration results after optimization (with uncertainties):\\n\\n');\nfprintf(1,'Focal Length: fc = [ %3.5f %3.5f ] +/- [ %3.5f %3.5f ]\\n',[fc;fc_error]);\nfprintf(1,'Principal point: cc = [ %3.5f %3.5f ] +/- [ %3.5f %3.5f ]\\n',[cc;cc_error]);\nfprintf(1,'Skew: alpha_c = [ %3.5f ] +/- [ %3.5f ] => angle of pixel axes = %3.5f +/- %3.5f degrees\\n',[alpha_c;alpha_c_error],90 - atan(alpha_c)*180/pi,atan(alpha_c_error)*180/pi);\nfprintf(1,'Distortion: kc = [ %3.5f %3.5f %3.5f %3.5f %5.5f ] +/- [ %3.5f %3.5f %3.5f %3.5f %5.5f ]\\n',[kc;kc_error]); \nfprintf(1,'Pixel error: err = [ %3.5f %3.5f ]\\n\\n',err_std); \nfprintf(1,'Note: The numerical errors are approximately three times the standard deviations (for reference).\\n\\n\\n')\n%fprintf(1,' For accurate (and stable) error estimates, it is recommended to run Calibration once again.\\n\\n\\n')\n\n\n\n%%% Some recommendations to the user to reject some of the difficult unkowns... Still in debug mode.\n\nalpha_c_min = alpha_c - alpha_c_error/2;\nalpha_c_max = alpha_c + alpha_c_error/2;\n\nif (alpha_c_min < 0) && (alpha_c_max > 0),\n fprintf(1,'Recommendation: The skew coefficient alpha_c is found to be equal to zero (within its uncertainty).\\n');\n fprintf(1,' You may want to reject it from the optimization by setting est_alpha=0 and run Calibration\\n\\n');\nend;\n\nkc_min = kc - kc_error/2;\nkc_max = kc + kc_error/2;\n\nprob_kc = (kc_min < 0) & (kc_max > 0);\n\nif ~(prob_kc(3) && prob_kc(4))\n prob_kc(3:4) = [0;0];\nend;\n\n\nif sum(prob_kc),\n fprintf(1,'Recommendation: Some distortion coefficients are found equal to zero (within their uncertainties).\\n');\n fprintf(1,' To reject them from the optimization set est_dist=[%d;%d;%d;%d;%d] and run Calibration\\n\\n',est_dist & ~prob_kc);\nend;\n\n\nreturn;", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/toolbox_calib/go_calib_optim_iter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.47491869503321427}}
{"text": "function [traj, infStates] = tapas_hgf_ar1_mab(r, p, varargin)\n% Calculates the trajectories of the agent's representations under the AR(1)-HGF in a multi-armed\n% bandit task\n%\n% This function can be called in two ways:\n% \n% (1) tapas_hgf_ar1_mab(r, p)\n% \n% where r is the structure generated by tapas_fitModel and p is the parameter vector in native space;\n%\n% (2) tapas_hgf_ar1_mab(r, ptrans, 'trans')\n% \n% where r is the structure generated by tapas_fitModel, ptrans is the parameter vector in\n% transformed space, and 'trans' is a flag indicating this.\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2013 Christoph Mathys, TNU, UZH & ETHZ\n%\n% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or .\n\n\n% Transform paramaters back to their native space if needed\nif ~isempty(varargin) && strcmp(varargin{1},'trans');\n p = tapas_hgf_ar1_mab_transp(r, p);\nend\n\n% Number of levels\ntry\n l = r.c_prc.n_levels;\ncatch\n l = length(p)/6;\n \n if l ~= floor(l)\n error('tapas:hgf:UndetNumLevels', 'Cannot determine number of levels');\n end\nend\n\n% Number of bandits\ntry\n b = r.c_prc.n_bandits;\ncatch\n error('tapas:hgf:NumOfBanditsConfig', 'Number of bandits has to be configured in r.c_prc.n_bandits.');\nend\n\n% Unpack parameters\nmu_0 = p(1:l);\nsa_0 = p(l+1:2*l);\nphi = p(2*l+1:3*l);\nm = p(3*l+1:4*l);\nka = p(4*l+1:5*l-1);\nom = p(5*l:6*l-2);\nth = exp(p(6*l-1));\nal = p(6*l);\n\n% Add dummy \"zeroth\" trial\nu = [0; r.u(:,1)];\ny = [0; r.u(:,2)];\n\n% Number of trials (including prior)\nn = size(u,1);\n\n% Construct time axis\nif r.c_prc.irregular_intervals\n if size(u,2) > 1\n t = [0; r.u(:,end)];\n else\n error('tapas:hgf:InputSingleColumn', 'Input matrix must contain more than one column if irregular_intervals is set to true.');\n end\nelse\n t = ones(n,1);\nend\n\n% Initialize updated quantities\n\n% Representations\nmu = NaN(n,l,b);\npi = NaN(n,l,b);\n\n% Other quantities\nmuhat = NaN(n,l,b);\npihat = NaN(n,l,b);\nv = NaN(n,l);\nw = NaN(n,l-1);\nda = NaN(n,l);\ndau = NaN(n,1);\n\n% Representation priors\n% Note: first entries of the other quantities remain\n% NaN because they are undefined and are thrown away\n% at the end; their presence simply leads to consistent\n% trial indices.\nmu(1,:,:) = repmat(mu_0,[1 1 b]);\npi(1,:,:) = repmat(1./sa_0,[1 1 b]);\n\n% Representation update loop\n% Pass through trials \nfor k = 2:1:n\n if not(ismember(k-1, r.ign))\n \n %%%%%%%%%%%%%%%%%%%%%%\n % Effect of input u(k)\n %%%%%%%%%%%%%%%%%%%%%%\n \n % 1st level\n % ~~~~~~~~~\n % Prediction\n muhat(k,1,:) = mu(k-1,1,:) +t(k) *phi(1) *(m(1) -mu(k-1,1,:));\n \n % Precision of prediction\n pihat(k,1,:) = 1/(1/pi(k-1,1,:) +t(k) *exp(ka(1) *mu(k-1,2,:) +om(1)));\n \n % Input prediction error\n dau(k) = u(k) -muhat(k,1,y(k));\n \n % Updates\n pi(k,1,:) = pihat(k,1,:);\n pi(k,1,y(k)) = pi(k,1,y(k)) +1/al;\n \n mu(k,1,:) = muhat(k,1,:);\n mu(k,1,y(k)) = mu(k,1,y(k)) +1/pihat(k,1,y(k)) *1/(1/pihat(k,1,y(k)) +al) *dau(k);\n\n % Volatility prediction error\n da(k,1) = (1/pi(k,1,y(k)) +(mu(k,1,y(k)) -muhat(k,1,y(k)))^2) *pihat(k,1,y(k)) -1;\n \n if l > 2\n % Pass through higher levels\n % ~~~~~~~~~~~~~~~~~~~~~~~~~~\n for j = 2:l-1\n % Prediction\n muhat(k,j,:) = mu(k-1,j,:) +t(k) *phi(j) *(m(j) -mu(k-1,j,:));\n \n % Precision of prediction\n pihat(k,j,:) = 1/(1/pi(k-1,j,:) +t(k) *exp(ka(j) *mu(k-1,j+1,:) +om(j)));\n\n % Weighting factor\n v(k,j-1) = t(k) *exp(ka(j-1) *mu(k-1,j,y(k)) +om(j-1));\n w(k,j-1) = v(k,j-1) *pihat(k,j-1,y(k));\n\n % Updates\n pi(k,j,:) = pihat(k,j,:) +1/2 *ka(j-1)^2 *w(k,j-1) *(w(k,j-1) +(2 *w(k,j-1) -1) *da(k,j-1));\n\n if pi(k,j,1) <= 0\n error('tapas:hgf:NegPostPrec', 'Negative posterior precision. Parameters are in a region where model assumptions are violated.');\n end\n\n mu(k,j,:) = muhat(k,j,:) +1/2 *1/pi(k,j,:) *ka(j-1) *w(k,j-1) *da(k,j-1);\n \n % Volatility prediction error\n da(k,j) = (1/pi(k,j,y(k)) +(mu(k,j,y(k)) -muhat(k,j,y(k)))^2) *pihat(k,j,y(k)) -1;\n end\n end\n\n % Last level\n % ~~~~~~~~~~\n % Prediction\n muhat(k,l,:) = mu(k-1,l,:) +t(k) *phi(l) *(m(l) -mu(k-1,l,:));\n \n % Precision of prediction\n pihat(k,l,:) = 1/(1/pi(k-1,l,:) +t(k) *th);\n\n % Weighting factor\n v(k,l) = t(k) *th;\n v(k,l-1) = t(k) *exp(ka(l-1) *mu(k-1,l,y(k)) +om(l-1));\n w(k,l-1) = v(k,l-1) *pihat(k,l-1,y(k));\n \n % Updates\n pi(k,l,:) = pihat(k,l,:) +1/2 *ka(l-1)^2 *w(k,l-1) *(w(k,l-1) +(2 *w(k,l-1) -1) *da(k,l-1));\n\n if pi(k,l,1) <= 0\n error('tapas:hgf:NegPostPrec', 'Negative posterior precision. Parameters are in a region where model assumptions are violated.');\n end\n\n mu(k,l,:) = muhat(k,l,:) +1/2 *1/pi(k,l,:) *ka(l-1) *w(k,l-1) *da(k,l-1);\n \n % Volatility prediction error\n da(k,l) = (1/pi(k,l,y(k)) +(mu(k,l,y(k)) -muhat(k,l,y(k)))^2) *pihat(k,l,y(k)) -1;\n else\n\n mu(k,:,:) = mu(k-1,:,:);\n pi(k,:,:) = pi(k-1,:,:);\n\n muhat(k,:,:) = muhat(k-1,:,:);\n pihat(k,:,:) = pihat(k-1,:,:);\n \n v(k,:) = v(k-1,:);\n w(k,:) = w(k-1,:);\n da(k,:) = da(k-1,:);\n \n end\nend\n\n% Remove representation priors\nmu(1,:,:) = [];\npi(1,:,:) = [];\n\n% Check validity of trajectories\nif any(isnan(mu(:))) || any(isnan(pi(:)))\n error('tapas:hgf:VarApproxInvalid', 'Variational approximation invalid. Parameters are in a region where model assumptions are violated.');\nelse\n % Check for implausible jumps in trajectories\n dmu = diff(mu);\n dpi = diff(pi);\n rmdmu = repmat(sqrt(mean(dmu.^2)),length(dmu),1);\n rmdpi = repmat(sqrt(mean(dpi.^2)),length(dpi),1);\n\n jumpTol = 256;\n if any(abs(dmu(:)) > jumpTol*rmdmu(:)) || any(abs(dpi(:)) > jumpTol*rmdpi(:))\n error('tapas:hgf:VarApproxInvalid', 'Variational approximation invalid. Parameters are in a region where model assumptions are violated.');\n end\nend\n\n% Remove other dummy initial values\nmuhat(1,:,:) = [];\npihat(1,:,:) = [];\nv(1,:) = [];\nw(1,:) = [];\nda(1,:) = [];\ndau(1) = [];\n\n% Create result data structure\ntraj = struct;\n\ntraj.mu = mu;\ntraj.sa = 1./pi;\n\ntraj.muhat = muhat;\ntraj.sahat = 1./pihat;\n\ntraj.v = v;\ntraj.w = w;\ntraj.da = da;\ntraj.dau = dau;\n\n% Updates with respect to prediction\ntraj.ud = mu -muhat;\n\n% Psi (precision weights on prediction errors)\npsi = NaN(n-1,l);\npi1 = squeeze(pi(:,1,:));\npi1obs = pi1(sub2ind(size(pi1), (1:size(pi1,1))', y));\npsi(:,1) = 1./(al*pi1obs);\nfor i=2:l\n pihati = squeeze(pihat(:,i-1,:));\n pihatiobs = pihati(sub2ind(size(pihati), (1:size(pihati,1))', y));\n pii = squeeze(pi(:,i,:));\n piiobs = pii(sub2ind(size(pii), (1:size(pii,1))', y));\n psi(:,i) = pihatiobs./piiobs;\nend\ntraj.psi = psi;\n\n% Epsilons (precision-weighted prediction errors)\nepsi = NaN(n-1,l);\nepsi(:,1) = psi(:,1) .*dau;\nepsi(:,2:l) = psi(:,2:l) .*da(:,1:l-1);\ntraj.epsi = epsi;\n\n% Full learning rate (full weights on prediction errors)\nwt = NaN(n-1,l);\nwt(:,1) = psi(:,1);\nwt(:,2:l) = 1/2 *(v(:,1:l-1) *diag(ka(1:l-1))) .*psi(:,2:l);\ntraj.wt = wt;\n\n% Create matrices for use by the observation model\ninfStates = NaN(n-1,l,b,4);\ninfStates(:,:,:,1) = traj.muhat;\ninfStates(:,:,:,2) = traj.sahat;\ninfStates(:,:,:,3) = traj.mu;\ninfStates(:,:,:,4) = traj.sa;\n\nreturn;\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/HGF/tapas_hgf_ar1_mab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.47456185602032713}}
{"text": "function [MDP] = spm_MDP_game_KL(MDP,varargin)\n% action selection using active inference (KL formulation)\n% FORMAT [MDP] = spm_MDP_game_KL(MDP,[EU])\n%\n% EU - optional flag to invoke expected utility only\n%\n% MDP.T - process depth (the horizon)\n% MDP.N - number of variational iterations (default 4)\n% MDP.S(N,1) - true initial state\n%\n% MDP.A(O,N) - Likelihood of O outcomes given N hidden states\n% MDP.B{M}(N,N) - transition probabilities among hidden states (priors)\n% MDP.C(N,1) - terminal cost probabilities (prior over hidden states)\n% MDP.D(N,1) - initial prior probabilities (prior over hidden states)\n%\n% MDP.V(T,P) - P allowable policies (control sequences over T times)\n%\n% optional:\n% MDP.s(1 x T) - vector of true states - for deterministic solutions\n% MDP.o(1 x T) - vector of observations - for deterministic solutions\n% MDP.a(1 x T) - vector of action - for deterministic solutions\n% MDP.w(1 x T) - vector of precisions - for deterministic solutions\n%\n% MDP.B{T,M}(N,N) - model transition probabilities for each time point\n% MDP.G{T,M}(N,N) - true transition probabilities for each time point\n% (default: MDP.G{T,M} = MDP.G{M} = MDP.B{M})\n%\n% MDP.plot - switch to suppress graphics: (default: [0])\n% MDP.alpha - upper bound on precision (Gamma hyperprior - shape [8])\n% MDP.beta - precision over precision (Gamma hyperprior - rate [1])\n%\n% produces:\n%\n% MDP.P(M,T) - probability of emitting an action 1,...,M at time 1,...,T\n% MDP.Q(N,T) - an array of conditional (posterior) expectations over\n% N hidden states and time 1,...,T\n% MDP.O(O,T) - a sparse matrix of ones encoding outcomes at time 1,...,T\n% MDP.S(N,T) - a sparse matrix of ones encoding states at time 1,...,T\n% MDP.U(M,T) - a sparse matrix of ones encoding action at time 1,...,T\n% MDP.W(1,T) - posterior expectations of precision\n% MDP.d - simulated dopamine responses\n%\n% This routine provides solutions of active inference (minimisation of\n% variational free energy) using a generative model based upon a Markov\n% decision process. This model and inference scheme is formulated\n% in discrete space and time. This means that the generative model (and\n% process) are finite state machines or hidden Markov models whose\n% dynamics are given by transition probabilities among states and the \n% likelihood corresponds to a particular outcome conditioned upon\n% hidden states. For simplicity, this routine assumes that action\n% and hidden controls are isomorphic. If the dynamics of transition\n% probabilities of the true process are not provided, this routine will use\n% the equivalent probabilities from the generative model.\n%\n% This particular scheme is designed for any allowable policies or control \n% sequences specified in MDP.V. Constraints on allowable policies can limit \n% the numerics or combinatorics considerable. For example, situations in \n% which one action can be selected at one time can be reduced to T polices\n% - with one (shift) control being emitted at all possible time points.\n% This specification of polices simplifies the generative model, allowing a\n% fairly exhaustive model of potential outcomes - eschewing a mean field \n% approximation over successive control states. In brief, the agent simply\n% represents the current state and states in the immediate and distant \n% future.\n%\n% The transition probabilities are a cell array of probability transition\n% matrices corresponding to each (discrete) the level of the control state.\n%\n% Mote that the conditional expectations are functions of time but also\n% contain expectations about fictive states over time at each time point.\n% To create time dependent transition probabilities, one can specify a\n% function in place of the transition probabilities under different levels\n% of control.\n%\n% Partially observed Markov decision processes can be modelled by\n% specifying a likelihood (as part of a generative model) and absorbing any\n% probabilistic mapping between (isomorphic) hidden states and outcomes\n% into the transition probabilities G.\n%\n% See also: spm_MDP, which uses multiple future states and a mean field \n% approximation for control states - but allows for different actions\n% at all times (as in control problems).\n%\n% See also: spm_MDP_game, which generalises this scheme and replaces prior\n% beliefs about KL control with minimisation of expected free energy.\n%__________________________________________________________________________\n% Copyright (C) 2005 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: spm_MDP_game_KL.m 7679 2019-10-24 15:54:07Z spm $\n\n% set up and preliminaries\n%==========================================================================\n\n% options and precision defaults\n%--------------------------------------------------------------------------\ntry, PLOT = MDP.plot; catch, PLOT = 0; end\ntry, alpha = MDP.alpha; catch, alpha = 8; end\ntry, beta = MDP.beta; catch, beta = 1; end\ntry, N = MDP.N; catch, N = 4; end\n\n\n% set up figure if necessary\n%--------------------------------------------------------------------------\nif PLOT\n if ishandle(PLOT)\n figure(PLOT); clf\n PLOT = 2;\n else\n spm_figure('GetWin','MDP'); clf\n end\nend\n\n% generative model and initial states\n%--------------------------------------------------------------------------\nT = MDP.T; % process depth (the horizon)\nNs = size(MDP.B{1},1); % number of hidden states\nNb = size(MDP.B,1); % number of time-dependent probabilities\nNu = size(MDP.B,2); % number of hidden controls\np0 = eps; % smallest probability\n\n% likelihood model (for a partially observed MDP implicit in G)\n%--------------------------------------------------------------------------\ntry\n A = MDP.A + p0;\n No = size(MDP.A,1); % number of outcomes\ncatch\n A = speye(Ns,Ns) + p0;\n No = Ns;\nend\nA = A*diag(1./sum(A));\nlnA = log(A);\n\n\n% transition probabilities (priors)\n%--------------------------------------------------------------------------\nfor i = 1:T\n for j = 1:Nu\n if i == 1 || Nb == T\n B{i,j} = MDP.B{i,j} + p0;\n B{i,j} = B{i,j}*diag(1./sum(B{i,j}));\n else\n B{i,j} = B{1,j};\n end\n end\nend\n\n% terminal probabilities (priors)\n%--------------------------------------------------------------------------\ntry\n C = spm_vec(MDP.C) + p0;\ncatch\n C = ones(Ns,1);\nend\nC = C/sum(C);\nlnC = log(C);\n\n% intital probabilities (priors)\n%--------------------------------------------------------------------------\ntry\n D = spm_vec(MDP.D) + p0;\ncatch\n D = ones(Ns,1);\nend\nD = D/sum(D);\nlnD = log(D);\n\n% generative process (assume the true process is the same as the model)\n%--------------------------------------------------------------------------\ntry\n G = MDP.G;\ncatch\n G = MDP.B;\nend\nNg = size(G,1);\nfor i = 1:T\n for j = 1:Nu\n if i == 1 || Ng == T\n G{i,j} = G{i,j} + p0;\n G{i,j} = G{i,j}*diag(1./sum(G{i,j}));\n else\n G{i,j} = G{1,j};\n end\n end\nend\n\n% policies and their expectations\n%--------------------------------------------------------------------------\nV = MDP.V;\nu = zeros(size(V,2),1);\nNp = size(V,2); % number of allowable policies\nw = 1:Np; % indices of allowable policies\n\n\n% initial states and outcomes\n%--------------------------------------------------------------------------\n[p q] = max(A*MDP.S(:,1)); % initial outcome (index)\ns = find( MDP.S(:,1)); % initial state (index)\no = sparse(1,1,q,1,T); % observations (index)\nS = sparse(s,1,1,Ns,T); % states sampled (1 in K vector)\nO = sparse(q,1,1,No,T); % states observed (1 in K vector)\na = sparse(1, T); % action (index)\nU = sparse(Nu,T); % action selected (1 in K vector)\nP = sparse(Nu,T); % posterior beliefs about control\nE = sparse(T,Np); % posterior beliefs about policies\nW = sparse(1,T); % posterior precision\n\n\n% sufficient statistics of hidden states (past, current and last)\n%--------------------------------------------------------------------------\ngamma = []; % simulated dopamine responses\nx = zeros(Ns,T);\n\n% solve\n%==========================================================================\nfor t = 1:T\n \n \n % allowable policies\n %----------------------------------------------------------------------\n if t > 1\n \n % record posterior expectations over policies\n %------------------------------------------------------------------\n E(t - 1,w) = u;\n \n % retain allowable policies (that are consistent with last action)\n %------------------------------------------------------------------\n j = ismember(V(t - 1,:),a(t - 1));\n V = V(:,j);\n u = u(j);\n w = w(j);\n \n \n end\n \n % conditional KL divergence (under allowable policies)\n %======================================================================\n Np = size(V,2); % number of allowable policies\n Q = zeros(Np,Ns); % value of policies x current state\n for k = 1:Np\n \n % compositon of future states\n %------------------------------------------------------------------\n Bj = 1;\n for j = t:T\n Bj = B{j,V(j,k)}*Bj;\n end\n \n % divergence or information gain\n %------------------------------------------------------------------\n if nargin > 1\n Q(k,:) = lnC'*Bj;\n else\n Q(k,:) = lnC'*Bj - sum(Bj.*log(Bj));\n end\n \n end\n \n \n % Variational iterations (assuming precise inference about past action)\n %======================================================================\n for i = 1:N\n \n \n % present state (x)\n %------------------------------------------------------------------\n if t == 1\n v = lnD;\n else\n v = log(B{t - 1,a(t - 1)}*x(:,t - 1));\n end\n v = v + lnA(o(t),:)' + W(t)*Q'*u;\n x(:,t) = spm_softmax(v);\n \n % precision (W)\n %------------------------------------------------------------------\n if isfield(MDP,'w')\n W(t) = MDP.w(t);\n else\n v = beta - u'*Q*x(:,t);\n W(t) = alpha/v;\n end\n \n % policy (u)\n %------------------------------------------------------------------\n v = W(t)*Q*x(:,t);\n u = spm_softmax(v);\n E(t,w) = u;\n \n \n % re-compute precision for first iteration\n %------------------------------------------------------------------\n if t == 1\n v = beta - u'*Q*x(:,t);\n W(t) = alpha/v;\n end\n \n \n % simulated dopamine responses (precision as each iteration)\n %------------------------------------------------------------------\n gamma(end + 1,1) = W(t);\n \n end\n \n % posterior expectations (control)\n %======================================================================\n for j = 1:Nu\n for k = t:T\n P(j,k) = sum(u(ismember(V(k,:),j)));\n end\n end\n \n % next action (the action that minimises expected free energy)\n %------------------------------------------------------------------\n try\n a(t) = MDP.a(t);\n catch\n try\n a(t) = find(rand < cumsum(P(:,t)),1);\n catch\n error('there are no more allowable policies')\n end\n end\n \n % save action\n %------------------------------------------------------------------\n U(a(t),t) = 1;\n \n \n % sampling of next state (outcome)\n %====================================================================== \n if t < T\n \n % next sampled state\n %------------------------------------------------------------------\n try\n s(t + 1) = MDP.s(t + 1);\n catch\n s(t + 1) = find(rand < cumsum(G{t,a(t)}(:,s(t))),1);\n end\n \n % next obsverved state\n %------------------------------------------------------------------\n try\n o(t + 1) = MDP.o(t + 1);\n catch\n o(t + 1) = find(rand < cumsum(A(:,s(t + 1))),1);\n end\n \n % save outcome and state sampled\n %------------------------------------------------------------------\n W(1,t + 1) = W(t);\n O(o(t + 1),t + 1) = 1;\n S(s(t + 1),t + 1) = 1;\n \n end\n \n \n % plot\n %======================================================================\n if PLOT > 0\n \n % posterior beliefs about hidden states\n %------------------------------------------------------------------\n subplot(4,2,1)\n imagesc(1 - [x C*max(max(x))/max(C)])\n if size(x,1) > 128\n hold on, spm_spy(x,16,1), hold off\n end\n title('Inferred states (and utility)','FontSize',14)\n xlabel('Time','FontSize',12)\n ylabel('Hidden state','FontSize',12)\n \n \n % posterior beliefs about control states\n %==================================================================\n subplot(4,2,2)\n \n % make previous plots dotted lines\n %------------------------------------------------------------------\n if T > 2\n h = get(gca,'Children'); hold on\n for i = 1:length(h)\n set(h(i),'LineStyle',':');\n end\n plot(P')\n title('Inferred policy','FontSize',14)\n xlabel('Time','FontSize',12)\n ylabel('Control state','FontSize',12)\n spm_axis tight\n else\n bar(P)\n title('Inferred policy','FontSize',14)\n xlabel('Contol state','FontSize',12)\n ylabel('Posterior expectation','FontSize',12)\n end\n \n \n % policies\n %------------------------------------------------------------------\n subplot(4,2,3)\n imagesc(MDP.V')\n title('Allowable policies','FontSize',14)\n ylabel('Policy','FontSize',12)\n xlabel('Time','FontSize',12)\n \n % expectations over policies\n %------------------------------------------------------------------\n subplot(4,2,4)\n imagesc(E')\n title('Posterior probability','FontSize',14)\n ylabel('Policy','FontSize',12)\n xlabel('Time','FontSize',12)\n \n % true state (outcome)\n %------------------------------------------------------------------\n subplot(4,2,5)\n if size(S,1) > 128\n spm_spy(S,16)\n else\n imagesc(1 - S)\n end\n title('True states','FontSize',14)\n ylabel('State','FontSize',12)\n \n % sample (observation)\n %------------------------------------------------------------------\n subplot(4,2,7)\n if size(O,1) > 128\n spm_spy(O,16,1)\n else\n imagesc(1 - O)\n end\n title('Observed states','FontSize',14)\n xlabel('Time','FontSize',12)\n ylabel('State','FontSize',12)\n \n \n % action sampled (selected)\n %------------------------------------------------------------------\n subplot(4,2,6)\n if size(U,1) > 128\n spm_spy(U,16,1)\n else\n imagesc(1 - U)\n end\n title('Selected action','FontSize',14)\n ylabel('Action','FontSize',12)\n \n % expected action\n %------------------------------------------------------------------\n subplot(4,2,8)\n plot((1:length(gamma))/N,gamma)\n title('Expected precision (confidence)','FontSize',14)\n xlabel('Time','FontSize',12)\n ylabel('Precision','FontSize',12)\n spm_axis tight\n drawnow\n \n end\n \nend\n\n% deconvolve to simulate dopamine responses\n%--------------------------------------------------------------------------\nda = pinv( tril(toeplitz(exp(-((1:length(gamma)) - 1)'/8))) )*gamma;\n\n% assemble results and place in NDP structure\n%--------------------------------------------------------------------------\nMDP.P = P; % probability of action at time 1,...,T - 1\nMDP.Q = x; % conditional expectations over N hidden states\nMDP.O = O; % a sparse matrix, encoding outcomes at 1,...,T\nMDP.S = S; % a sparse matrix, encoding the states\nMDP.U = U; % a sparse matrix, encoding the action\nMDP.W = W; % posterior expectations of precision\nMDP.d = gamma; % simulated dopamine responses\nMDP.da = da; % simulated dopamine responses (deconvolved)\n\n\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/DEM/spm_MDP_game_KL.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.47456185602032713}}
{"text": "function [perimeterEdges,eulerCondition] = findLegalPerimeters2(mesh,perimDist)\n% \n% [perimeterEdges,eulerCondition] = findLegalPerimeters2(mesh,perimDist)\n% \n% Given a mesh structure (nodes, edges, distances from start point) and a\n% threshold distance this routine will return a list of edges that\n% constitute separate perimeters at a distance of perimDist from the start\n% point.\n%\n% Note that because of intrinsic curvature, there can be more than one\n% perimeter at the required distance. This routine makes sure that it\n% returns separate perimeters (ones with no common nodes).\n\n% Find perims with simple thold\ninsideNodes=find(mesh.dist<=perimDist);\ninsideNodes=insideNodes(:);\n\ninsideNodes = removeHangingNodes(mesh,insideNodes); % Cleans up the mesh\n[perimeterEdges,eulerCondition]=findGroupPerimeter(mesh,insideNodes); % Find perimeter(s) - there may be more than 1\nbadPerimNodes = findBadPerimNodes(mesh,perimeterEdges); % See if some perimeters are joined up.\n\nnumBadNodes=9999999; % Hope we don't get more than this...\n\nwhile (numBadNodes>0)\n [perimeterEdges,eulerCondition]=findGroupPerimeter(mesh,insideNodes);\n\tlength(perimeterEdges);\n\tlength(unique(perimeterEdges,'rows'));\n fprintf('Euler number=%d\\n',eulerCondition);\n \n badPerimNodes=findBadPerimNodes(mesh,perimeterEdges);\n numBadNodes=length(badPerimNodes);\n fprintf('There are %d bad perim nodes.\\n',numBadNodes);\n\t\n if(numBadNodes)\n\t\t[insideNodes]=correctBadNodes(mesh,insideNodes,badPerimNodes); % Splits up joined perimeters\n\t\tinsideNodes=removeHangingNodes(mesh,insideNodes); % Cleans up mesh again\n end\nend\n\nreturn;\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAnatomy/mrFlatMesh/meshOperations/findLegalPerimeters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.4744733666490599}}
{"text": "function [M q]=modularity_probtune_und_sign(W,qtype,M,p)\n%MODULARITY_PROBTUNE_UND_SIGN Optimal community structure, modularity and degeneracy\n%\n% Ci = modularity_probtune_und_sign(W, [],Ci0,0.01);\n% Ci = modularity_probtune_und_sign(W,'sta',Ci0,0.01);\n% [Ci Q] = modularity_probtune_und_sign(W,'sta',Ci0,0.01);\n%\n% The optimal community structure is a subdivision of the network into\n% nonoverlapping groups of nodes in a way that maximizes the number of\n% within-group edges, and minimizes the number of between-group edges. \n% The modularity is a statistic that quantifies the degree to which the\n% network may be subdivided into such clearly delineated groups.\n% High-modularity degeneracy is the presence of many topologically\n% distinct high-modularity partitions of the network.\n%\n% This algorithm is inspired by the Kernighan-Lin fine-tuning algorithm\n% and is designed to probabilistically refine a previously detected\n% community by incorporating random node moves into a finetuning\n% algorithm.\n%\n% Input: W, undirected (weighted or binary) connection matrix\n% with positive and negative weights\n%\n% qtype, modularity type (see Rubinov and Sporns, 2011)\n% 'sta', Q_* (default if qtype is not specified)\n% 'pos', Q_+\n% 'smp', Q_simple\n% 'gja', Q_GJA\n% 'neg', Q_-\n%\n% Ci0, initial community affiliation vector (optional)\n%\n% p, probability of random node moves\n%\n%\n% Output: Ci, refined community affiliation vector\n% Q, modularity (qtype dependent)\n%\n% Note: Ci and Q may vary from run to run, due to heuristics in the\n% algorithm. Consequently, it may be worth to compare multiple runs.\n%\n% References:\n% Rubinov and Sporns (2011) NeuroImage.\n% Sun et al. (2008) Europhysics Lett 86, 28004.\n%\n%\n% Mika Rubinov, UNSW, 2011\n\n% Modification History:\n% Mar 2011: Original\n\n\nn=length(W); %number of nodes/modules\nif ~exist('qtype','var') || isempty(qtype);\n qtype = 'sta';\nend\nif isempty(M);\n M = 1:n;\nelse\n [dum dum M] = unique(M(:).'); %align module indices\nend\n\nW0= W.*(W>0); %positive weights matrix\nW1=-W.*(W<0); %negative weights matrix\ns0=sum(W0(:)); %positive sum of weights\ns1=sum(W1(:)); %negative sum of weights\nKnm0=zeros(n,n); %positive node-to-module degree\nKnm1=zeros(n,n); %negative node-to-module degree\nfor m=1:max(M) %loop over modules\n Knm0(:,m)=sum(W0(:,M==m),2);\n Knm1(:,m)=sum(W1(:,M==m),2);\nend\nKn0=sum(Knm0,2); %positive node degree\nKn1=sum(Knm1,2); %negative node degree\nKm0=sum(Knm0,1); %positive module degree\nKm1=sum(Knm1,1); %negative module degree\n\nswitch qtype\n case 'smp'; d0 = 1/s0; d1 = 1/s1; %dQ = dQ0/s0 - dQ1/s1;\n case 'gja'; d0 = 1/(s0+s1); d1 = 1/(s0+s1); %dQ = (dQ0 - dQ1)/(s0+s1);\n case 'sta'; d0 = 1/s0; d1 = 1/(s0+s1); %dQ = dQ0/s0 - dQ1/(s0+s1);\n case 'pos'; d0 = 1/s0; d1 = 0; %dQ = dQ0/s0;\n case 'neg'; d0 = 0; d1 = 1/s1; %dQ = -dQ1/s1;\n otherwise; error('qtype unknown');\nend\nif ~s0 %adjust for absent positive weights\n s0=1;\n d0=0;\nend\nif ~s1 %adjust for absent negative weights\n s1=1;\n d1=0;\nend\n\nfor u=randperm(n); %loop over all nodes in random order\n ma = M(u); %current module of u\n r=rand1e-10) %if maximal increase is positive (equiv. dQ(mb)>dQ(ma))\n M(u) = mb; %reassign module\n\n Knm0(:,mb)=Knm0(:,mb)+W0(:,u);\n Knm1(:,mb)=Knm1(:,mb)+W1(:,u);\n Knm0(:,ma)=Knm0(:,ma)-W0(:,u);\n Knm1(:,ma)=Knm1(:,ma)-W1(:,u);\n Km0(mb)=Km0(mb)+Kn0(u);\n Km1(mb)=Km1(mb)+Kn1(u);\n Km0(ma)=Km0(ma)-Kn0(u);\n Km1(ma)=Km1(ma)-Kn1(u);\n end\nend\n\n[dum dum M]=unique(M(:).'); %realign module indices\nif nargout==2 %compute modularity\n m = M(ones(1,n),:);\n Q0 = (W0-(Kn0*Kn0.')/s0).*(m==m.');\n Q1 = (W1-(Kn1*Kn1.')/s1).*(m==m.');\n q = d0*sum(Q0(:)) - d1*sum(Q1(:));\nend", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/bct/modularity_probtune_und_sign.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4744670949077991}}
{"text": "% WAVELET_LAYER_1D Compute the one-dimensional wavelet transform from\n% the modulus wavelet coefficients of the previous layer.\n%\n% Usages\n% [U_phi , U_psi] = wavelet_layer_1d(U, filters)\n%\n% [U_phi , U_psi] = wavelet_layer_1d(U, filters, scat_opt)\n%\n% [U_phi , U_psi] = wavelet_layer_1d(U, filters, scat_opt, wavelet)\n%\n% Input\n% U (struct): The input layer to be transformed.\n% filters (cell): The filters of the wavelet transform.\n% scat_opt (struct): The options that are transferred to the wavelet\n% function handle.\n% wavelet (function handle): the wavelet transform function (default is\n% @wavelet_1d). \n%\n% Output\n% U_phi The coefficients of in, lowpass-filtered (scattering\n% coefficients).\n% U_psi: The wavelet transform coefficients.\n%\n% Description\n% This function has a pivotal role between WAVELET_1D (which computes a\n% single wavelet transform), and WAVELET_FACTORY_1D (which creates the\n% whole cascade). Given inputs modulus wavelet coefficients\n% corresponding to a layer, WAVELET_LAYER_1D computes the wavelet\n% transform coefficients of the next layer using WAVELET_1D. \n% See also\n% WAVELET_1D, WAVELET_FACTORY_1D, WAVELET_LAYER_2D\n\nfunction [U_phi, U_psi] = wavelet_layer_1dave(U, filters, scat_opt, wavelet)\n\tif nargin < 3\n\t\tscat_opt = struct();\n\tend\n\t\n\tif nargin < 4\n\t\twavelet = @wavelet_1d;\n\tend\n\t\n\tcalc_U = (nargout>=2);\n\n\t[psi_xi,psi_bw,phi_bw] = filter_freq(filters.meta);\n\t\n\tif ~isfield(U.meta, 'bandwidth'), U.meta.bandwidth = 2*pi; end\n\tif ~isfield(U.meta, 'resolution'), U.meta.resolution = 0; end\n\t\n\tU_phi.signal = {};\n\tU_phi.meta.bandwidth = [];\n\tU_phi.meta.resolution = [];\n\tU_phi.meta.j = zeros(size(U.meta.j,1),0);\n\t\n\tU_psi.signal = {};\n\tU_psi.meta.bandwidth = [];\n\tU_psi.meta.resolution = [];\n\tU_psi.meta.j = zeros(size(U.meta.j,1)+1,0);\n\t\n\tr = 1;\n\tfor p1 = 1:length(U.signal)\n\t\tpsi_mask = calc_U&(U.meta.bandwidth(p1)>psi_xi);\n\t\t\n\t\tscat_opt.x_resolution = U.meta.resolution(p1);\n\t\tscat_opt.psi_mask = psi_mask;\n\t\t[x_phi, x_psi, meta_phi, meta_psi] = ...\n\t\t\twavelet(U.signal{p1}, filters, scat_opt);\n\t\t\n\t\tU_phi.signal{1,p1} = mean(U.signal{p1}(:));\n\t\tU_phi.meta = map_meta(U.meta,p1,U_phi.meta,p1);\n\t\tU_phi.meta.bandwidth(1,p1) = meta_phi.bandwidth;\n\t\tU_phi.meta.resolution(1,p1) = meta_phi.resolution;\n\t\t\n\t\tind = r:r+sum(psi_mask)-1;\n\t\tU_psi.signal(1,ind) = x_psi(1,psi_mask);\n\t\tU_psi.meta = map_meta(U.meta,p1,U_psi.meta,ind,{'j'});\n\t\tU_psi.meta.bandwidth(1,ind) = meta_psi.bandwidth(1,psi_mask);\n\t\tU_psi.meta.resolution(1,ind) = meta_psi.resolution(1,psi_mask);\n\t\tU_psi.meta.j(:,ind) = [U.meta.j(:,p1)*ones(1,length(ind)); ...\n\t\t\tmeta_psi.j(1,psi_mask)];\n\t\t\t\n\t\tr = r+length(ind);\n\tend\nend\n", "meta": {"author": "scatnet", "repo": "scatnet", "sha": "59d935afa20359845282a3518134e24244862c1f", "save_path": "github-repos/MATLAB/scatnet-scatnet", "path": "github-repos/MATLAB/scatnet-scatnet/scatnet-59d935afa20359845282a3518134e24244862c1f/papers/IPASM/wavelet_layer_1dave.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4744280339914018}}
{"text": "function [M,scal] = spm_affreg(VG,VF,flags,M,scal)\n% Affine registration using least squares.\n% FORMAT [M,scal] = spm_affreg(VG,VF,flags,M0,scal0)\n%\n% VG - Vector of template volumes.\n% VF - Source volume.\n% flags - a structure containing various options. The fields are:\n% WG - Weighting volume for template image(s).\n% WF - Weighting volume for source image\n% Default to [].\n% sep - Approximate spacing between sampled points (mm).\n% Defaults to 5.\n% regtype - regularisation type. Options are:\n% 'none' - no regularisation\n% 'rigid' - almost rigid body\n% 'subj' - inter-subject registration (default).\n% 'mni' - registration to ICBM templates\n% globnorm - Global normalisation flag (1)\n% M0 - (optional) starting estimate. Defaults to eye(4).\n% scal0 - (optional) starting estimate.\n%\n% M - affine transform, such that voxels in VF map to those in\n% VG by VG.mat\\M*VF.mat\n% scal - scaling factors for VG\n%\n% When only one template is used, then the cost function is approximately\n% symmetric, although a linear combination of templates can be used.\n% Regularisation is based on assuming a multi-normal distribution for the\n% elements of the Henckey Tensor. See:\n% \"Non-linear Elastic Deformations\". R. W. Ogden (Dover), 1984.\n% Weighting for the regularisation is determined approximately according\n% to:\n% \"Incorporating Prior Knowledge into Image Registration\"\n% J. Ashburner, P. Neelin, D. L. Collins, A. C. Evans & K. J. Friston.\n% NeuroImage 6:344-352 (1997).\n%\n%_______________________________________________________________________\n% @(#)spm_affreg.m\t2.3 John Ashburner 03/02/18\n\nif nargin<5, scal = ones(length(VG),1); end;\nif nargin<4, M = eye(4); end;\n\ndef_flags = struct('sep',5, 'regtype','subj','WG',[],'WF',[],'globnorm',1,'debug',0);\nif nargin < 2 | ~isstruct(flags),\n\tflags = def_flags;\nelse,\n\tfnms = fieldnames(def_flags);\n\tfor i=1:length(fnms),\n\t\tif ~isfield(flags,fnms{i}),\n\t\t\tflags = setfield(flags,fnms{i},getfield(def_flags,fnms{i}));\n\t\tend;\n\tend;\nend;\n\n% Check to ensure inputs are valid...\n% ---------------------------------------------------------------\nif length(VF)>1, error('Can not use more than one source image'); end;\nif ~isempty(flags.WF),\n\tif length(flags.WF)>1,\n\t\terror('Can only use one source weighting image');\n\tend;\n\tif any(any(VF.mat-flags.WF.mat)),\n\t\terror('Source and its weighting image must have same orientation');\n\tend;\n\tif any(any(VF.dim(1:3)-flags.WF.dim(1:3))),\n\t\terror('Source and its weighting image must have same dimensions');\n\tend;\nend;\nif ~isempty(flags.WG),\n\tif length(flags.WG)>1,\n\t\terror('Can only use one template weighting image');\n\tend;\n\ttmp = reshape(cat(3,VG(:).mat,flags.WG.mat),16,length(VG)+length(flags.WG));\nelse,\n\ttmp = reshape(cat(3,VG(:).mat),16,length(VG));\nend;\nif any(any(diff(tmp,1,2))),\n\terror('Reference images must all have the same orientation');\nend;\nif ~isempty(flags.WG),\n\ttmp = cat(1,VG(:).dim,flags.WG.dim);\nelse,\n\ttmp = cat(1,VG(:).dim);\nend;\nif any(any(diff(tmp(:,1:3),1,1))),\n\terror('Reference images must all have the same dimensions');\nend;\n% ---------------------------------------------------------------\n\n% Generate points to sample from, adding some jitter in order to\n% make the cost function smoother.\n% ---------------------------------------------------------------\nrand('state',0); % want the results to be consistant.\ndg = VG(1).dim(1:3);\ndf = VF(1).dim(1:3);\n\nif length(VG)==1,\n\tskip = sqrt(sum(VG(1).mat(1:3,1:3).^2)).^(-1)*flags.sep;\n\t[x1,x2,x3]=ndgrid(1:skip(1):dg(1)-.5, 1:skip(2):dg(2)-.5, 1:skip(3):dg(3)-.5);\n\tx1 = x1 + rand(size(x1))*0.5; x1 = x1(:);\n\tx2 = x2 + rand(size(x2))*0.5; x2 = x2(:);\n\tx3 = x3 + rand(size(x3))*0.5; x3 = x3(:);\nend;\n\nskip = sqrt(sum(VF(1).mat(1:3,1:3).^2)).^(-1)*flags.sep;\n[y1,y2,y3]=ndgrid(1:skip(1):df(1)-.5, 1:skip(2):df(2)-.5, 1:skip(3):df(3)-.5);\ny1 = y1 + rand(size(y1))*0.5; y1 = y1(:);\ny2 = y2 + rand(size(y2))*0.5; y2 = y2(:);\ny3 = y3 + rand(size(y3))*0.5; y3 = y3(:);\n% ---------------------------------------------------------------\n\nif flags.globnorm,\n\t% Scale all images approximately equally\n\t% ---------------------------------------------------------------\n\tfor i=1:length(VG),\n\t\tVG(i).pinfo(1:2,:) = VG(i).pinfo(1:2,:)/spm_global(VG(i));\n\tend;\n\tVF(1).pinfo(1:2,:) = VF(1).pinfo(1:2,:)/spm_global(VF(1));\nend;\n% ---------------------------------------------------------------\n\nif length(VG)==1,\n\t[G,dG1,dG2,dG3] = spm_sample_vol(VG(1),x1,x2,x3,1);\n\tif ~isempty(flags.WG),\n\t\tWG = abs(spm_sample_vol(flags.WG,x1,x2,x3,1))+eps;\n\tend;\nend;\n\n[F,dF1,dF2,dF3] = spm_sample_vol(VF(1),y1,y2,y3,1);\nif ~isempty(flags.WF),\n\tWF = abs(spm_sample_vol(flags.WF,y1,y2,y3,1))+eps;\nend;\n% ---------------------------------------------------------------\nn_main_its = 0;\nss = Inf;\nW = [Inf Inf Inf];\nest_smo = 1;\n% ---------------------------------------------------------------\n\nfor iter=1:256,\n\tpss = ss;\n\tp0 = [0 0 0 0 0 0 1 1 1 0 0 0];\n\n\t% Initialise the cost function and its 1st and second derivatives\n\t% ---------------------------------------------------------------\n\tn = 0;\n\tss = 0;\n\tBeta = zeros(12+length(VG),1);\n\tAlpha = zeros(12+length(VG));\n\n\tif length(VG)==1,\n\t\t% Make the cost function symmetric\n\t\t% ---------------------------------------------------------------\n\n\t\t% Build a matrix to rotate the derivatives by, converting from\n\t\t% derivatives w.r.t. changes in the overall affine transformation\n\t\t% matrix, to derivatives w.r.t. the parameters p.\n\t\t% ---------------------------------------------------------------\n\t\tdt = 0.0001;\n\t\tR = eye(13);\n\t\tMM0 = inv(VG.mat)*inv(spm_matrix(p0))*VG.mat;\n\t\tfor i1=1:12,\n\t\t\tp1 = p0;\n\t\t\tp1(i1) = p1(i1)+dt;\n\t\t\tMM1 = (inv(VG.mat)*inv(spm_matrix(p1))*(VG.mat));\n\t\t\tR(1:12,i1) = reshape((MM1(1:3,:)-MM0(1:3,:))/dt,12,1);\n\t\tend;\n\t\t% ---------------------------------------------------------------\n\t\t[t1,t2,t3] = coords((M*VF(1).mat)\\VG(1).mat,x1,x2,x3);\n\t\tmsk = find((t1>=1 & t1<=df(1) & t2>=1 & t2<=df(2) & t3>=1 & t3<=df(3)));\n\t\tif length(msk)<32, error_message; end;\n\t\tt1 = t1(msk);\n\t\tt2 = t2(msk);\n\t\tt3 = t3(msk);\n\t\tt = spm_sample_vol(VF(1), t1,t2,t3,1);\n\n\t\t% Get weights\n\t\t% ---------------------------------------------------------------\n\t\tif ~isempty(flags.WF) | ~isempty(flags.WG),\n\t\t\tif isempty(flags.WF),\n\t\t\t\twt = WG(msk);\n\t\t\telse,\n\t\t\t\twt = spm_sample_vol(flags.WF(1), t1,t2,t3,1)+eps;\n\t\t\t\tif ~isempty(flags.WG), wt = 1./(1./wt + 1./WG(msk)); end;\n\t\t\tend;\n\t\t\twt = sparse(1:length(wt),1:length(wt),wt);\n\t\telse,\n\t\t\twt = speye(length(msk));\n\t\t\twt = [];\n\t\tend;\n\t\t% ---------------------------------------------------------------\n\t\tclear t1 t2 t3\n\n\t\t% Update the cost function and its 1st and second derivatives.\n\t\t% ---------------------------------------------------------------\n\t\t[AA,Ab,ss1,n1] = costfun(x1,x2,x3,dG1,dG2,dG3,msk,scal^(-2)*t,G(msk)-(1/scal)*t,wt);\n\t\tAlpha = Alpha + R'*AA*R;\n\t\tBeta = Beta + R'*Ab;\n\t\tss = ss + ss1;\n\t\tn = n + n1;\n\t\tt = G(msk) - (1/scal)*t;\n\tend;\n\n\tif 1,\n\t\t% Build a matrix to rotate the derivatives by, converting from\n\t\t% derivatives w.r.t. changes in the overall affine transformation\n\t\t% matrix, to derivatives w.r.t. the parameters p.\n\t\t% ---------------------------------------------------------------\n\t\tdt = 0.0001;\n\t\tR = eye(12+length(VG));\n\t\tMM0 = inv(M*VF.mat)*spm_matrix(p0)*M*VF.mat;\n\t\tfor i1=1:12,\n\t\t\tp1 = p0;\n\t\t\tp1(i1) = p1(i1)+dt;\n\t\t\tMM1 = (inv(M*VF.mat)*spm_matrix(p1)*M*VF.mat);\n\t\t\tR(1:12,i1) = reshape((MM1(1:3,:)-MM0(1:3,:))/dt,12,1);\n\t\tend;\n\t\t% ---------------------------------------------------------------\n\t\t[t1,t2,t3] = coords(VG(1).mat\\M*VF(1).mat,y1,y2,y3);\n\t\tmsk = find((t1>=1 & t1<=dg(1) & t2>=1 & t2<=dg(2) & t3>=1 & t3<=dg(3)));\n\t\tif length(msk)<32, error_message; end;\n\n\t\tif length(msk)<32, error_message; end;\n\t\tt1 = t1(msk);\n\t\tt2 = t2(msk);\n\t\tt3 = t3(msk);\n\t\tt = zeros(length(t1),length(VG));\n\n\t\t% Get weights\n\t\t% ---------------------------------------------------------------\n\t\tif ~isempty(flags.WF) | ~isempty(flags.WG),\n\t\t\tif isempty(flags.WG),\n\t\t\t\twt = WF(msk);\n\t\t\telse,\n\t\t\t\twt = spm_sample_vol(flags.WG(1), t1,t2,t3,1)+eps;\n\t\t\t\tif ~isempty(flags.WF), wt = 1./(1./wt + 1./WF(msk)); end;\n\t\t\tend;\n\t\t\twt = sparse(1:length(wt),1:length(wt),wt);\n\t\telse,\n\t\t\twt = speye(length(msk));\n\t\tend;\n\t\t% ---------------------------------------------------------------\n\n\t\tif est_smo,\n\t\t\t% Compute derivatives of residuals in the space of F\n\t\t\t% ---------------------------------------------------------------\n\t\t\t[ds1,ds2,ds3] = transform_derivs(VG(1).mat\\M*VF(1).mat,dF1(msk),dF2(msk),dF3(msk));\n\t\t\tfor i=1:length(VG),\n\t\t\t\t[t(:,i),dt1,dt2,dt3] = spm_sample_vol(VG(i), t1,t2,t3,1);\n\t\t\t\tds1 = ds1 - dt1*scal(i); clear dt1\n\t\t\t\tds2 = ds2 - dt2*scal(i); clear dt2\n\t\t\t\tds3 = ds3 - dt3*scal(i); clear dt3\n\t\t\tend;\n\t\t\tdss = [ds1'*wt*ds1 ds2'*wt*ds2 ds3'*wt*ds3];\n\t\t\tclear ds1 ds2 ds3\n\t\telse,\n\t\t\tfor i=1:length(VG),\n\t\t\t\tt(:,i)= spm_sample_vol(VG(i), t1,t2,t3,1);\n\t\t\tend;\n\t\tend;\n\n\t\tclear t1 t2 t3\n\n\t\t% Update the cost function and its 1st and second derivatives.\n\t\t% ---------------------------------------------------------------\n\t\t[AA,Ab,ss2,n2] = costfun(y1,y2,y3,dF1,dF2,dF3,msk,-t,F(msk)-t*scal,wt);\n\t\tAlpha = Alpha + R'*AA*R;\n\t\tBeta = Beta + R'*Ab;\n\t\tss = ss + ss2;\n\t\tn = n + n2;\n\tend;\n\n\tif est_smo,\n\t\t% Compute a smoothness correction from the residuals and their\n\t\t% derivatives. This is analagous to the one used in:\n\t\t% \t\"Analysis of fMRI Time Series Revisited\"\n\t\t% \tFriston KJ, Holmes AP, Poline JB, Grasby PJ, Williams SCR,\n\t\t% \tFrackowiak RSJ, Turner R. Neuroimage 2:45-53 (1995).\n\t\t% ---------------------------------------------------------------\n\t\tvx = sqrt(sum(VG(1).mat(1:3,1:3).^2));\n\t\tpW = W;\n\t\tW = (2*dss/ss2).^(-.5).*vx;\n\t\tW = min(pW,W);\n\t\tif flags.debug, fprintf('\\nSmoothness FWHM: %.3g x %.3g x %.3g mm\\n', W*sqrt(8*log(2))); end;\n\t\tif length(VG)==1, dens=2; else, dens=1; end;\n\t\tsmo = prod(min(dens*flags.sep/sqrt(2*pi)./W,[1 1 1]));\n\t\test_smo=0;\n\t\tn_main_its = n_main_its + 1;\n\tend;\n\n\t% Update the parameter estimates\n\t% ---------------------------------------------------------------\n\tnu = n*smo;\n\tsig2 = ss/nu;\n\t[d1,d2] = reg(M,12+length(VG),flags.regtype);\n\n\tsoln = (Alpha/sig2+d2)\\(Beta/sig2-d1);\n\tscal = scal - soln(13:end);\n\tM = spm_matrix(p0 + soln(1:12)')*M;\n\n\tif flags.debug,\n\t\tfprintf('%d\\t%g\\n', iter, ss/n);\n\t\tpiccies(VF,VG,M,scal,b)\n\tend;\n\n\t% If cost function stops decreasing, then re-estimate smoothness\n\t% and try again. Repeat a few times.\n\t% ---------------------------------------------------------------\n\tss = ss/n;\n\tif iter>1, spm_chi2_plot('Set',ss); end;\n\tif (pss-ss)/pss < 1e-6,\n\t\test_smo = 1;\n\tend;\n\tif n_main_its>3, break; end;\n\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [X1,Y1,Z1] = transform_derivs(Mat,X,Y,Z)\n% Given the derivatives of a scalar function, return those of the\n% affine transformed function\n%_______________________________________________________________________\n\nt1 = Mat(1:3,1:3);\nt2 = eye(3);\nif sum((t1(:)-t2(:)).^2) < 1e-12,\n X1 = X;Y1 = Y; Z1 = Z;\nelse,\n X1 = Mat(1,1)*X + Mat(1,2)*Y + Mat(1,3)*Z;\n Y1 = Mat(2,1)*X + Mat(2,2)*Y + Mat(2,3)*Z;\n Z1 = Mat(3,1)*X + Mat(3,2)*Y + Mat(3,3)*Z;\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [d1,d2] = reg(M,n,typ)\n% Analytically compute the first and second derivatives of a penalty\n% function w.r.t. changes in parameters.\n\nif nargin<3, typ = 'subj'; end;\nif nargin<2, n = 13; end;\n\n[mu,isig] = priors(typ);\nds = 0.000001;\nd1 = zeros(n,1);\nd2 = zeros(n);\np0 = [0 0 0 0 0 0 1 1 1 0 0 0];\nh0 = penalty(p0,M,mu,isig);\nfor i=7:12, % derivatives are zero w.r.t. rotations and translations\n\tp1 = p0;\n\tp1(i) = p1(i)+ds;\n\th1 = penalty(p1,M,mu,isig);\n\td1(i) = (h1-h0)/ds; % First derivative\n\tfor j=7:12,\n\t\tp2 = p0;\n\t\tp2(j) = p2(j)+ds;\n\t\th2 = penalty(p2,M,mu,isig);\n\t\tp3 = p1;\n\t\tp3(j) = p3(j)+ds;\n\t\th3 = penalty(p3,M,mu,isig);\n\t\td2(i,j) = ((h3-h2)/ds-(h1-h0)/ds)/ds; % Second derivative\n\tend;\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction h = penalty(p,M,mu,isig)\n% Return a penalty based on the elements of an affine transformation,\n% which is given by:\n% \tspm_matrix(p)*M\n%\n% The penalty is based on the 6 unique elements of the Hencky tensor\n% elements being multinormally distributed.\n%_______________________________________________________________________\n\n% Unique elements of symmetric 3x3 matrix.\nels = [1 2 3 5 6 9];\n\nT = spm_matrix(p)*M;\nT = T(1:3,1:3);\nT = 0.5*logm(T'*T);\nT = T(els)' - mu;\nh = T'*isig*T;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [mu,isig] = priors(typ)\n% The parameters for this distribution were derived empirically from 227\n% scans, that were matched to the ICBM space.\n%_______________________________________________________________________\n\nmu = zeros(6,1);\nisig = zeros(6);\nswitch deblank(lower(typ)),\n\ncase 'mni', % For registering with MNI templates...\n\tmu = [0.0667 0.0039 0.0008 0.0333 0.0071 0.1071]';\n\tisig = 1e4 * [\n\t 0.0902 -0.0345 -0.0106 -0.0025 -0.0005 -0.0163\n\t -0.0345 0.7901 0.3883 0.0041 -0.0103 -0.0116\n\t -0.0106 0.3883 2.2599 0.0113 0.0396 -0.0060\n\t -0.0025 0.0041 0.0113 0.0925 0.0471 -0.0440\n\t -0.0005 -0.0103 0.0396 0.0471 0.2964 -0.0062\n\t -0.0163 -0.0116 -0.0060 -0.0440 -0.0062 0.1144];\n\ncase 'rigid', % Constrained to be almost rigid...\n\tmu = zeros(6,1);\n\tisig = eye(6)*1e9;\n\ncase 'isochoric', % Volume preserving...\n\terror('Not implemented');\n\ncase 'isotropic', % Isotropic zoom in all directions...\n\terror('Not implemented');\n\ncase 'subj', % For inter-subject registration...\n\tmu = zeros(6,1);\n\tisig = 1e3 * [\n\t 0.8876 0.0784 0.0784 -0.1749 0.0784 -0.1749\n\t 0.0784 5.3894 0.2655 0.0784 0.2655 0.0784\n\t 0.0784 0.2655 5.3894 0.0784 0.2655 0.0784\n\t -0.1749 0.0784 0.0784 0.8876 0.0784 -0.1749\n\t 0.0784 0.2655 0.2655 0.0784 5.3894 0.0784\n\t -0.1749 0.0784 0.0784 -0.1749 0.0784 0.8876];\n\ncase 'none', % No regularisation...\n\tmu = zeros(6,1);\n\tisig = zeros(6);\n\notherwise,\n\terror(['\"' typ '\" not recognised as type of regularisation.']);\nend;\nreturn;\n\n%_______________________________________________________________________\nfunction [y1,y2,y3]=coords(M,x1,x2,x3)\n% Affine transformation of a set of coordinates.\n%_______________________________________________________________________\n\ny1 = M(1,1)*x1 + M(1,2)*x2 + M(1,3)*x3 + M(1,4);\ny2 = M(2,1)*x1 + M(2,2)*x2 + M(2,3)*x3 + M(2,4);\ny3 = M(3,1)*x1 + M(3,2)*x2 + M(3,3)*x3 + M(3,4);\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction A = make_A(x1,x2,x3,dG1,dG2,dG3,t)\n% Generate part of a design matrix using the chain rule...\n% df/dm = df/dy * dy/dm\n% where\n% \tdf/dm is the rate of change of intensity w.r.t. affine parameters\n% \tdf/dy is the gradient of the image f\n% \tdy/dm crange of position w.r.t. change of parameters\n%_______________________________________________________________________\n\nA = [x1.*dG1 x1.*dG2 x1.*dG3 ...\n\t x2.*dG1 x2.*dG2 x2.*dG3 ...\n\t x3.*dG1 x3.*dG2 x3.*dG3 ...\n\t dG1 dG2 dG3 t];\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [AA,Ab,ss,n] = costfun(x1,x2,x3,dG1,dG2,dG3,msk,lastcols,b,wt)\nchunk = 10240;\nlm = length(msk);\nAA = zeros(12+size(lastcols,2));\nAb = zeros(12+size(lastcols,2),1);\nss = 0;\nn = 0;\n\nfor i=1:ceil(lm/chunk),\n\tind = (((i-1)*chunk+1):min(i*chunk,lm))';\n\tmsk1 = msk(ind);\n\n\tA1 = make_A(x1(msk1),x2(msk1),x3(msk1),dG1(msk1),dG2(msk1),dG3(msk1),lastcols(ind,:));\n\tb1 = b(ind);\n\tif ~isempty(wt),\n\t\twt1 = wt(ind,ind);\n\t\tAA = AA + A1'*wt1*A1;\n\t\t%Ab = Ab + A1'*wt1*b1;\n\t\tAb = Ab + (b1'*wt1*A1)';\n\t\tss = ss + b1'*wt1*b1;\n\t\tn = n + trace(wt1);\n\t\tclear wt1\n\telse,\n\t\tAA = AA + spm_atranspa(A1);\n\t\t%Ab = Ab + A1'*b1;\n\t\tAb = Ab + (b1'*A1)';\n\t\tss = ss + b1'*b1;\n\t\tn = n + length(msk1);\n\tend;\n\tclear A1 b1 msk1 ind\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction error_message\n% Display an error message for when things go wrong.\nstr = {\t'There is not enough overlap in the images',...\n\t'to obtain a solution.',...\n\t' ',...\n\t'Please check that your header information is OK.'};\nspm('alert*',str,mfilename,sqrt(-1));\nerror('insufficient image overlap')\nreturn\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction piccies(VF,VG,M,scal,b)\n% This is for debugging purposes.\n% It shows the linear combination of template images, the affine\n% transformed source image, the residual image and a histogram of the\n% residuals.\n%_______________________________________________________________________\n\nfigure(2);\nMt = spm_matrix([0 0 (VG(1).dim(3)+1)/2]);\nM = (M*VF(1).mat)\\VG(1).mat;\nt = zeros(VG(1).dim(1:2));\nfor i=1:length(VG);\n\tt = t + spm_slice_vol(VG(i), Mt,VG(1).dim(1:2),1)*scal(i);\nend;\nu = spm_slice_vol(VF(1),M*Mt,VG(1).dim(1:2),1);\nsubplot(2,2,1);imagesc(t');axis image xy off\nsubplot(2,2,2);imagesc(u');axis image xy off\nsubplot(2,2,3);imagesc(u'-t');axis image xy off\nsubplot(2,2,4);hist(b,50); % Entropy of residuals may be a nice cost function?\ndrawnow;\nreturn;\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/spm2/spm_affreg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4744280339914018}}
{"text": "function outputImage = rms(this, varargin)\n% Computes root mean square along specified dimension, i.e. sqrt(mean(Y.^2))\n%\n%\n% Y = MrImage()\n% Y.rms(applicationDimension)\n%\n% This is a method of class MrImage.\n%\n% IN\n% applicationDimension image dimension along which operation is\n% performed (e.g. 4 = time, 3 = slices)\n% default: The last dimension with more than one\n% value is chosen \n% (i.e. 3 for 3D image, 4 for 4D image)\n%\n% OUT\n% outputImage rms of all images along application dimension\n%\n% EXAMPLE\n% rms\n%\n% See also MrImage MrImage.perform_unary_operation\n\n% Author: Saskia Klein & Lars Kasper\n% Created: 2014-12-23\n% Copyright (C) 2014 Institute for Biomedical Engineering\n% University of Zurich and ETH Zurich\n%\n% This file is part of the TAPAS UniQC Toolbox, which is released\n% under the terms of the GNU General Public Licence (GPL), version 3. \n% You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version).\n% For further details, see the file COPYING or\n% .\n\n\nif nargin > 1\n applicationDimension = varargin{1};\n outputImage = mean(this.^2, applicationDimension).^(1/2);\nelse\n outputImage = mean(this.^2).^(1/2);\nend", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/UniQC/code/classes/@MrDataNd/rms.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.47427285129627383}}
{"text": "function bc = specific_bc(xbd,ybd)\n%quad_bc channel flow boundary condition for 4:1 quadrilateral domain \n% bc = specific_bc(xbd,ybd);\n% input\n% xbd x boundary coordinate vector\n% ybd y boundary coordinate vector \n%\n% specifies streamfunction associated with Poiseuille flow\n% needs editing for general aspect ratios\n% IFISS function: DJS; 6 March 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \naspect=4; deform=4;\nbc=0*xbd; \nk=find(xbd==0); bc(k)=2*ybd(k).*ybd(k) -(4/3)*ybd(k).*ybd(k).*ybd(k);\nslope=(1/aspect)*(1/deform-1);\nk3=find(ybd==slope*xbd +1); bc(k3)=2/3;\nreturn\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms866/stokes_flow/test_problems/quad_bc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4741675128438852}}
{"text": " function st = nufft_init(om, Nd, Jd, Kd, varargin)\n%function st = nufft_init(om, Nd, Jd, Kd, [n_shift,] ...)\n%\n% Initialize structure for d-dimension NUFFT using KB interpolator,\n% particularly the interpolation matrix in sparse format.\n% caution: this routine can require a lot of memory!\n% in\n%\tom [M,d]\t\"digital\" frequencies in radians\n%\tNd [d]\t\timage dimensions (N1,N2,...,Nd)\n%\tJd [d]\t\t# of neighbors used (in each direction)\n%\tKd [d]\t\tFFT sizes (should be >= N1,N2,...)\n% optional arguments\n%\tn_shift [d]\tn = 0-n_shift to N-1-n_shift (must be first)\n%\t'minmax:kb'\tminmax interpolator with excellent KB scaling!\n%\t\t\t\t(minmax:kb is recommended, and used by default)\n%\t'minmax:tuned'\tminmax interpolator, somewhat numerically tuned\n%\t'minmax:user'\tminmax interpolator with user ({alpha}, {beta})\n%\t'uniform'\tuniform scaling factors (not recommended)\n%\t'kaiser'\tkaiser-bessel (KB) interpolator (minmax best alpha, m)\n%\t\t\tor 'kaiser', alpha, m to specify parameter (vectors)\n%\t'linear'\tlinear interpolator (a terrible straw man)\n%\tkernel\t\tuser-provided inline interpolation kernel(k,J)\n%\t\t\t(or a cell array of kernels, one for each dimension)\n%\t'table'\t\tuse table-based interpolation rather than sparse matrix.\n%\t\t\tthis can save a lot of memory for large problems.\n%\t\t\texample ..., 'table', 2^11, 'minmax:kb'\n%\t\t\twhere 2^11 is the table over-sampling factor.\n% out\n%\tst.p\t\t[M, *Nd]\tsparse interpolation matrix\n%\t\t\t\t\t(or empty if table-based) \n%\tst.sn\t\t[(Nd)]\t\tscaling factors\n%\tst.Nd,Jd,Kd,om\tcopies of inputs\n%\n% *Nd is shorthand for prod(Nd).\n% (Nd) is shorthand for (N1,N2,...,Nd)\n%\n% Like fft(), the NUFFT expects the signals to be x(0,0), ...\n% Use n_shift = [N1/2, N2/2, ...] for x(-N1/2,-N2/2,...), ...\n%\n% Copyright 2002-5-30\tJeff Fessler\tThe University of Michigan\n\nif nargin < 4, help(mfilename), error args, end\n\n% dimensionality of input space (usually 2 or 3)\ndd = length(Nd);\nif dd ~= length(Jd) | dd ~= length(Kd)\n\terror 'inconsistent dim'\nend\nif dd ~= size(om,2), error(sprintf('omega needs %d columns', dd)), end\n\n%\n% process optional arguments\n%\n\n% n_shift argument? (must be first)\nif length(varargin) > 0 & isnumeric(varargin{1})\n\tn_shift = varargin{1};\n\tif dd ~= length(n_shift)\n\t\terror(sprintf('n_shift needs %d columns', dd))\n\tend\n\tvarargin = {varargin{2:end}};\nelse\n\tn_shift = zeros(size(Nd));\nend\nst.n_shift = n_shift;\n\n% default/recommended interpolator is minmax with KB scaling factors\nif length(varargin) == 0\n\tvarargin = {'minmax:kb'};\nend\n\nst.alpha = {};\nst.beta = {};\nis_kaiser_scale = logical(0);\n\n% table based?\nif ischar(varargin{1}) & streq(varargin{1}, 'table')\n\tst = nufft_table_init(om, Nd, Jd, Kd, n_shift, varargin{2:end});\n\treturn\nend\n\nktype = varargin{1};\n\n% cell array of kernel functions: {kernel1, kernel2, ..., kernelD}\nif isa(ktype, 'cell')\n\tif isa(ktype{1}, 'inline') | isa(ktype{1}, 'function_handle')\n\t\tktype = 'inline';\n\t\tif length(varargin) > 1, error 'excess arguments?', end\n\t\tif length(varargin{1}) ~= dd, error 'wrong # of kernels', end\n\t\tst.kernel = varargin{1};\n\telse\n\t\terror 'cell array should be inline kernels!?'\n\tend\n\n% or a single inline kernel for all dimension\nelseif isa(ktype, 'inline') | isa(ktype, 'function_handle')\n\tktype = 'inline';\n\tif length(varargin) > 1, error 'excess arguments?', end\n\tfor id = 1:dd\n\t\tst.kernel{id} = varargin{1};\t% all same\n\tend\n\n% or a string that describes the type of interpolator\nelseif ~ischar(ktype)\n\terror 'non-string kernel type?'\n\nend\n\nst.ktype = ktype;\n\n%\n% set up whatever is needed for each interpolator\n%\nif streq(ktype, 'inline')\n\t% already did it above\n\n% linear interpolator straw man\nelseif streq(ktype, 'linear')\n\tktype = 'inline';\n\tkernel = inline('(1 - abs(k/(J/2))) .* (abs(k) < J/2)', 'k', 'J');\n\tfor id = 1:dd\n\t\tst.kernel{id} = kernel;\n\tend\n\n% KB interpolator\nelseif streq(ktype, 'kaiser')\n\tis_kaiser_scale = logical(1);\n\n\t% with minmax-optimized parameters\n\tif length(varargin) == 1\n\t\tfor id = 1:dd\n\t\t\t[st.kernel{id} st.kb_alf(id) st.kb_m(id)] = ...\n\t\t\t\tkaiser_bessel('inline', Jd(id));\n\t\tend\n\n\t% with user-defined parameters\n\telseif length(varargin) == 3\n\t\talpha_list = varargin{2};\n\t\tm_list = varargin{3};\n\t\tif (length(alpha_list) ~= dd) | (length(m_list) ~= dd)\n\t\t\terror 'need #dim alpha and m'\n\t\tend\n\t\tfor id = 1:dd\n\t\t\t[st.kernel{id} st.kb_alf(id) st.kb_m(id)] = ...\n\t\t\t\tkaiser_bessel('inline', Jd(id), ...\n\t\t\t\t\talpha_list(id), m_list(id));\n\t\tend\n\telse\n\t\terror 'kaiser should have no arguments, or both alpha and m'\n\tend\n\n% minmax interpolator with KB scaling factors (recommended default)\nelseif streq(ktype, 'minmax:kb')\n\tfor id = 1:dd\n\t\t[st.alpha{id}, st.beta{id}] = ...\n\t\t\tnufft_alpha_kb_fit(Nd(id), Jd(id), Kd(id));\n\tend\n\n% minmax interpolator with numerically \"tuned\" scaling factors\nelseif streq(ktype, 'minmax:tuned')\n\tfor id = 1:dd\n\t\t[st.alpha{id}, st.beta{id}, ok] = ...\n\t\t\tnufft_best_alpha(Jd(id), 0, Kd(id)/Nd(id));\n\t\tif ~ok, error 'unknown J,K/N', end\n\tend\n\n% minmax interpolator with user-provided scaling factors\nelseif streq(ktype, 'minmax:user')\n\tif length(varargin) ~= 3, error 'user must provide alpha/beta', end\n\tst.alpha = varargin{2};\n\tst.beta = varargin{3};\n\tif length(st.alpha) ~= dd | length(st.beta) ~= dd\n\t\terror 'alpha/beta size mismatch'\n\tend\n\nelseif streq(ktype, 'uniform')\n\tfor id = 1:dd\n\t\tst.alpha{id} = 1;\n\t\tst.beta{id} = 0;\n\tend\n\nelse\n\terror 'unknown kernel type'\nend\n\nst.tol\t= 0;\n\nst.Jd\t= Jd;\nst.Nd\t= Nd;\nst.Kd\t= Kd;\n\nM = size(om,1);\nst.M\t= M;\nst.om\t= om;\n\n%\n% scaling factors: \"outer product\" of 1D vectors\n%\nst.sn = 1;\nfor id=1:dd\n\tif is_kaiser_scale\n\t\tnc = [0:Nd(id)-1]'-(Nd(id)-1)/2;\n\t\ttmp = 1 ./ kaiser_bessel_ft(...\n\t\t\tnc/Kd(id), Jd(id), st.kb_alf(id), st.kb_m(id), 1);\n\telseif streq(ktype, 'inline')\n\t\ttmp = 1 ./ nufft_interp_zn(0, Nd(id), Jd(id), Kd(id), st.kernel{id});\n\telse\n\t\ttmp = nufft_scale(Nd(id), Kd(id), st.alpha{id}, st.beta{id});\n\tend\n\tst.sn = st.sn(:) * tmp';\nend\nif length(Nd) > 1\n\tst.sn = reshape(st.sn, Nd);\t% [(Nd)]\nelse\n\tst.sn = st.sn(:);\t% [(Nd)]\nend\n\n%\n% [J?,M] interpolation coefficient vectors. will need kron of these later\n%\nfor id=1:dd\n\tN = Nd(id);\n\tJ = Jd(id);\n\tK = Kd(id);\n\tif isvar('st.kernel')\n\t\t[c, arg] = ...\n\t\tnufft_coef(om(:,id), J, K, st.kernel{id});\t% [J?,M]\n\telse\n\t\talpha = st.alpha{id};\n\t\tbeta = st.beta{id};\n\t\tT = nufft_T(N, J, K, st.tol, alpha, beta);\t% [J?,J?]\n\t\t[r, arg] = ...\n\t\tnufft_r(om(:,id), N, J, K, alpha, beta);\t% [J?,M]\n\t\tc = T * r;\tclear T r\n\tend\n\n\tgam = 2*pi/K;\n\tphase_scale = 1i * gam * (N-1)/2;\n\n\tphase = exp(phase_scale * arg);\t% [J?,M] linear phase\n\tud{id} = phase .* c;\t\t% [J?,M]\n\n\t%\n\t% indices into oversampled FFT components\n\t%\n\tkoff = nufft_offset(om(:,id), J, K);\t% [M,1] to leftmost near nbr\n\tkd{id} = mod(outer_sum([1:J]', koff'), K) + 1;\t% [J?,M] {1,...,K?}\n\tif id > 1\t% trick: pre-convert these indices into offsets!\n\t\tkd{id} = (kd{id}-1) * prod(Kd(1:(id-1)));\n\tend\n\nend, clear c arg gam phase phase_scale koff N J K\n\n%\n% build sparse matrix that is [M,*Kd]\n% with *Jd nonzero entries per frequency point\n%\nif dd >= 3, printf('Needs at least %g Gbyte RAM', prod(Jd)*M*8/10^9*2), end\n\nkk = kd{1};\t% [J1,M]\nuu = ud{1};\t% [J1,M]\nfor id = 2:dd\n\tJprod = prod(Jd(1:id));\n\tkk = block_outer_sum(kk, kd{id});\t% outer sum of indices\n\tkk = reshape(kk, Jprod, M);\n\tuu = block_outer_prod(uu, ud{id});\t% outer product of coefficients\n\tuu = reshape(uu, Jprod, M);\nend\t% now kk and uu are [*Jd, M]\n\n%\n% apply phase shift\n% pre-do Hermitian transpose of interpolation coefficients\n%\nphase = exp(1i * (om * n_shift(:))).';\t\t\t% [1,M]\nuu = conj(uu) .* phase(ones(1,prod(Jd)),:);\t\t% [*Jd,M]\n\nmm = [1:M]; mm = mm(ones(prod(Jd),1),:);\t\t% [*Jd,M]\nst.p = sparse(mm(:), kk(:), uu(:), M, prod(Kd));\t% sparse matrix\n\n\n%\n% in\n%\tx1\t[J1,M]\n%\tx2\t[J2,M]\n% out\n%\ty\t[J1,J2,M]\ty(i1,i2,m) = x1(i1,m) + x2(i2,m)\n%\nfunction y = block_outer_sum(x1, x2)\n[J1 M] = size(x1);\n[J2 M] = size(x2);\nxx1 = reshape(x1, [J1 1 M]);\t% [J1,1,M] from [J1,M]\nxx1 = xx1(:,ones(J2,1),:);\t% [J1,J2,M], emulating ndgrid\nxx2 = reshape(x2, [1 J2 M]);\t% [1,J2,M] from [J2,M]\nxx2 = xx2(ones(J1,1),:,:);\t% [J1,J2,M], emulating ndgrid\ny = xx1 + xx2;\t\t\t% [J1,J2,M]\n\nfunction y = block_outer_prod(x1, x2)\n[J1 M] = size(x1);\n[J2 M] = size(x2);\nxx1 = reshape(x1, [J1 1 M]);\t% [J1,1,M] from [J1,M]\nxx1 = xx1(:,ones(J2,1),:);\t% [J1,J2,M], emulating ndgrid\nxx2 = reshape(x2, [1 J2 M]);\t% [1,J2,M] from [J2,M]\nxx2 = xx2(ones(J1,1),:,:);\t% [J1,J2,M], emulating ndgrid\ny = xx1 .* xx2;\t\t\t% [J1,J2,M]\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/@NUFFT/private/nufft_init.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4741084201082126}}
{"text": "function plot_llkstest(a,time,timef,bootloops,maepi)\n % function plot_llkstes(a,time,timef,bootloops,maepi);\n % --------------------------------------------------\n % Plots Ncum observed vs. Ncum modeled for specified time windows\n % with choosing the model for the learning period and performs a KS-Test\n %\n % Input variables:\n % a : earthquake catalog\n % time : learning period fo fit Omori parameters\n % timef : forecast period\n % bootloops : Number of bootstraps\n % maepi : mainshock\n %\n % J.Woessner\n % last update: 20.07.04\n\n % Surpress warnings from fmincon\n warning off;\n\n %[m_main, main] = max(a.Magnitude);\n date_matlab = datenum(a.Date.Year,a.Date.Month,a.Date.Day,a.Date.Hour,a.Date.Minute,zeros(size(a,1),1));\n date_main = datenum(floor(maepi(3)),maepi(4),maepi(5),maepi(8),maepi(9),0);\n time_aftershock = date_matlab-date_main;\n\n % Aftershock catalog\n vSel1 = time_aftershock(:) > 0;\n tas = time_aftershock(vSel1);\n eqcatalogue = a.subset(vSel1);\n\n % Estimation of Omori parameters from learning period\n l = tas <= time;\n time_as=tas(l);\n % Times up to the forecast time\n lf = tas <= time+timef ;\n time_asf= [tas(lf) ];\n time_asf=sort(time_asf);\n\n % Select biggest aftershock earliest in time, but more than 1 day after\n % mainshock and in learning period\n mAfLearnCat = eqcatalogue(l,:);\n fDay = 1;\n ft_c=fDay/365; % Time not considered to find biggest aftershock\n vSel = (mAfLearnCat(:,3) > maepi(:,3)+ft_c & mAfLearnCat(:,3)<= maepi(:,3)+time/365);\n mCat = mAfLearnCat(vSel,:);\n vSel = mCat(:,6) == max(mCat(:,6));\n vBigAf = mCat(vSel,:);\n if length(mCat(:,1)) > 1\n vSel = vBigAf(:,3) == min(vBigAf(:,3));\n vBigAf = vBigAf(vSel,:);\n end\n\n date_biga = datenum(floor(vBigAf(3)),vBigAf(4),vBigAf(5),vBigAf(8),vBigAf(9),0);\n fT1 = date_biga - date_main; % Time of big aftershock\n\n\n % Calculate p,c,k for dataset\n prompt = {'Enter model number (1:pck, 2:pckk, 3:ppckk, 4:ppcckk:'};\n title = 'Model selection for fitting aftershock sequence';\n lines= 1;\n def = {'1'};\n answer = inputdlg(prompt,title,lines,def);\n nMod = str2double(answer{1});\n\n % Calculate uncertainty and mean values of p,c,and k\n [mMedModF, mStdL, loopout] = brutebootloglike_a2(time_as, time_asf, bootloops,fT1,nMod);\n pmed1 = mMedModF(1,1);\n pmed2 = mMedModF(1,3);\n cmed1 = mMedModF(1,5);\n cmed2 = mMedModF(1,7);\n kmed1 = mMedModF(1,9);\n kmed2 = mMedModF(1,11);\n\n\n % Compute model according to model choice\n if nMod == 1\n [pval1, pval2, cval1, cval2, kval1, kval2, fAIC, fL] = bruteforceloglike_a2(time_as,fT1,nMod);\n elseif nMod == 2\n [pval1, pval2, cval1, cval2, kval1, kval2, fAIC, fL] = bruteforceloglike_a2(time_as,fT1,nMod);\n elseif nMod == 3\n [pval1, pval2, cval1, cval2, kval1, kval2 , fAIC, fL] = bruteforceloglike_a2(time_as,fT1,nMod);\n else\n [pval1, pval2, cval1, cval2, kval1, kval2, fAIC, fL] = bruteforceloglike_a2(time_as,fT1,nMod);\n end\n\n % Start plotting\n figure_w_normalized_uicontrolunits('Numbertitle','off','Name','Aftershock modelling fit')\n\n % Plot the forecast ...\n cumnrf = (1:length(time_as))';\n cumnr_modelf = [];\n if nMod == 1\n for i=1:length(time_as)\n if pval1 ~= 1\n cm = kval1/(pval1-1)*(cval1^(1-pval1)-(time_as(i)+cval1)^(1-pval1));\n else\n cm = kval1*log(time_as(i)/cval1+1);\n end\n cumnr_modelf = [cumnr_modelf; cm];\n end % END of FOR on length(time_as)\n else\n for i=1:length(time_as)\n if time_as(i) <= fT1\n if pval1 ~= 1\n cm = kval1/(pval1-1)*(cval1^(1-pval1)-(time_as(i)+cval1)^(1-pval1));\n else\n cm = kval1*log(time_as(i)/cval1+1);\n end\n cumnr_modelf = [cumnr_modelf; cm];\n else\n if (pval1 ~= 1 & pval2 ~= 1)\n cm = kval1/(pval1-1)*(cval1^(1-pval1)-(time_as(i)+cval1)^(1-pval1))+ kval2/(pval2-1)*(cval2^(1-pval2)-(time_as(i)-fT1+cval2)^(1-pval2));\n else\n cm = kval1*log(time_as(i)/cval1+1) + kval2*log((time_as(i)-fT1)/cval2+1);\n end\n cumnr_modelf = [cumnr_modelf; cm];\n end %END of IF on fT1\n end % End of FOR length(time_as)\n end % End of if on nMod\n time_as=sort(time_as);\n cumnr_modelf=sort(cumnr_modelf);\n\n pf1 = plot(time_as,cumnr_modelf,'g-.','Linewidth',2);\n hold on\n pf2 = plot(time_as,cumnrf, 'b-','Linewidth',2);\n paf = plot(fT1, 0,'h','MarkerFaceColor',[1 1 0],'MarkerSize',12,'MarkerEdgeColor',[0 0 0] );\n\n % Calculate KSTEST2 as a measure of the goodness of fit\n [H,P,KSSTAT] = kstest2(cumnr_modelf,cumnrf)\n\n % Calculate RMS\n i=(1:1:length(time_as))';\n fRMS = (sum((i-cumnr_modelf).^2)/length(i))^0.5;\n\n % Round values for output\n pval1 = round(100*pval1)/100;\n pval2 = round(100*pval2)/100;\n cval1 = round(1000*cval1)/1000;\n cval2 = round(1000*cval2)/1000;\n kval1 = round(10*kval1)/10;\n kval2 = round(10*kval2)/10;\n pmed1 = round(100*pmed1)/100; mStdL(1,1) = round(100*mStdL(1,1))/100;\n pmed2 = round(100*pmed2)/100; mStdL(1,2) = round(100*mStdL(1,2))/100;\n cmed1 = round(1000*cmed1)/1000; mStdL(1,3) = round(1000*mStdL(1,3))/1000;\n cmed2 = round(1000*cmed2)/1000; mStdL(1,4) = round(1000*mStdL(1,4))/1000;\n kmed1 = round(10*kmed1)/10; mStdL(1,5) = round(100*mStdL(1,5))/100;\n kmed2 = round(10*kmed2)/10; mStdL(1,6)= round(100*mStdL(1,6))/100;\n fRMS = round(100*fRMS)/100;\n\n % Get Y limits for positioning texts\n yy = get(gca,'ylim');\n\n if nMod == 1\n string1=['p = ' num2str(pval1) '; c = ' num2str(cval1) '; k = ' num2str(kval1) ];\n string3=['pm = ' num2str(pmed1) '+-' num2str(mStdL(1,1)) '; cm = ' num2str(cmed1) '+-' num2str(mStdL(1,3)) '; km = ' num2str(kmed1) '+-' num2str(mStdL(1,5))];\n text(max(time_asf)*0.05,yy(2)*0.9,string1,'FontSize',10);\n text(max(time_asf)*0.05,yy(2)*0.8,string3,'FontSize',10);\n elseif nMod == 2\n string1=['p = ' num2str(pval1) '; c = ' num2str(cval1) '; k1 = ' num2str(kval1) '; k2 = ' num2str(kval2) ];\n string3=['pm = ' num2str(pmed1) '+-' num2str(mStdL(1,1)) '; cm = ' num2str(cmed1) '+-' num2str(mStdL(1,3)) '; km1 = ' num2str(kmed1) '+-' num2str(mStdL(1,5)) '; km2 = ' num2str(kmed2) '+-' num2str(mStdL(1,6))];\n text(max(time_asf)*0.05,yy(2)*0.9,string1,'FontSize',10);\n text(max(time_asf)*0.05,yy(2)*0.8,string3,'FontSize',10);\n elseif nMod == 3\n string1=['p1 = ' num2str(pval1) '; c = ' num2str(cval1) '; k1 = ' num2str(kval1) ];\n string2=['p2 = ' num2str(pval2) '; k2 = ' num2str(kval2) ];\n string3=['pm1 = ' num2str(pmed1) '+-' num2str(mStdL(1,1)) '; cm = ' num2str(cmed1) '+-' num2str(mStdL(1,3)) '; km1 = ' num2str(kmed1) '+-' num2str(mStdL(1,5))];\n string4=['pm2 = ' num2str(pmed2) '+-' num2str(mStdL(1,2)) '; km2 = ' num2str(kmed2) '+-' num2str(mStdL(1,6))];\n text(max(time_asf)*0.05,yy(2)*0.9,string1,'FontSize',10);\n text(max(time_asf)*0.05,yy(2)*0.85,string2,'FontSize',10);\n text(max(time_asf)*0.05,yy(2)*0.8,string3,'FontSize',10);\n text(max(time_asf)*0.05,yy(2)*0.75,string4,'FontSize',10);\n else\n string1=['p1 = ' num2str(pval1) '; c1 = ' num2str(cval1) '; k1 = ' num2str(kval1) ];\n string2=['p2 = ' num2str(pval2) '; c2 = ' num2str(cval2) '; k2 = ' num2str(kval2) ];\n string3=['pm1 = ' num2str(pmed1) '+-' num2str(mStdL(1,1)) '; cm1 = ' num2str(cmed1) '+-' num2str(mStdL(1,3)) '; km1 = ' num2str(kmed1) '+-' num2str(mStdL(1,5))];\n string4=['pm2 = ' num2str(pmed2) '+-' num2str(mStdL(1,2)) '; cm2 = ' num2str(cmed2) '+-' num2str(mStdL(1,4)) '; km2 = ' num2str(kmed2) '+-' num2str(mStdL(1,6))];\n text(max(time_asf)*0.05,yy(2)*0.9,string1,'FontSize',10);\n text(max(time_asf)*0.05,yy(2)*0.85,string2,'FontSize',10);\n text(max(time_asf)*0.05,yy(2)*0.8,string3,'FontSize',10);\n text(max(time_asf)*0.05,yy(2)*0.75,string4,'FontSize',10);\n end\n string=['H = ' num2str(H) ' P = ' num2str(P) ' KS-Statistic) = ' num2str(KSSTAT)];\n text(max(time_asf)*0.05,yy(2)*0.1,string,'FontSize',10);\n sAIC = ['AIC = ' num2str(fAIC)];\n text(max(time_asf)*0.05,yy(2)*0.05,sAIC,'FontSize',10);\n sRMS = ['RMS = ' num2str(fRMS)];\n text(max(time_asf)*0.05,yy(2)*0.15,sRMS,'FontSize',10);\n % Legend\n sModel = ['Model ' num2str(nMod)];\n legend([pf2 pf1 paf],'Data',sModel,'Sec. AF','location','Best');\n\n\n % Calculate fits of different models\n mRes = [];\n % Modified Omori law (pck)\n nMod = 1; [pval1, pval2, cval1, cval2, kval1, kval2, fAIC, fL] = bruteforceloglike_a2(time_as,fT1,nMod);\n mRes = [mRes; nMod, pval1, pval2, cval1, cval2, kval1, kval2, fAIC, fL];\n % MOL with secondary aftershock (pckk)\n nMod = 2; [pval1, pval2, cval1, cval2, kval1, kval2, fAIC, fL] = bruteforceloglike_a2(time_as,fT1,nMod);\n mRes = [mRes; nMod, pval1, pval2, cval1, cval2, kval1, kval2, fAIC, fL];\n % MOL with secondary aftershock (ppckk)\n nMod = 3; [pval1, pval2, cval1, cval2, kval1, kval2, fAIC, fL] = bruteforceloglike_a2(time_as,fT1,nMod);\n mRes = [mRes; nMod, pval1, pval2, cval1, cval2, kval1, kval2, fAIC, fL];\n % MOL with secondary aftershock (ppcckk)\n nMod = 4; [pval1, pval2, cval1, cval2, kval1, kval2, fAIC, fL] = bruteforceloglike_a2(time_as,fT1,nMod);\n mRes = [mRes; nMod, pval1, pval2, cval1, cval2, kval1, kval2, fAIC, fL];\n\n % Select best fitting model by AIC\n vSel = (mRes(:,8)==min(mRes(:,8)));\n mRes = mRes(vSel,:);\n if length(mRes(:,1)) > 1\n vSel = (mRes(:,1)==min(mRes(:,1)));\n mRes = mRes(vSel,:);\n end\n % Model to use for bootstrapping as of lowest AIC to observed data\n nMod = mRes(1,1);\n\n sModel1 = ['Info: Best model is ' num2str(nMod)];\n text(max(time_asf)*0.05,yy(2)*0.2,sModel1,'FontSize',10);\n % Figure settings\n set(gca,'FontSize',12,'Fontweight','bold','Linewidth',2)\n xlabel('Time [Days after mainshock]','FontSize',12,'Fontweight','bold')\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/afterrate/plot_llkstest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4738971708730051}}
{"text": "%-------------------------------------------------------------------------------------------------------------------%\n%\n% IB2d is an Immersed Boundary Code (IB) for solving fully coupled non-linear \n% \tfluid-structure interaction models. This version of the code is based off of\n%\tPeskin's Immersed Boundary Method Paper in Acta Numerica, 2002.\n%\n% Author: Nicholas A. Battista\n% Email: nick.battista@unc.edu\n% Date Created: May 27th, 2015\n% Institution: UNC-CH\n%\n% This code is capable of creating Lagrangian Structures using:\n% \t1. Springs\n% \t2. Beams (*torsional springs)\n% \t3. Target Points\n%\t4. Muscle-Model (combined Force-Length-Velocity model, \"HIll+(Length-Tension)\")\n%\n% One is able to update those Lagrangian Structure parameters, e.g., spring constants, resting lengths, etc\n% \n% There are a number of built in Examples, mostly used for teaching purposes. \n% \n% If you would like us %to add a specific muscle model, please let Nick (nick.battista@unc.edu) know.\n%\n%--------------------------------------------------------------------------------------------------------------------%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: computes Porous Slip Velocity based on Darcy's Law,\n%\n% U_porous = -alpha / | d vec{X}_Lag /ds |\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [Por_Mat,nX,nY] = please_Compute_Porous_Slip_Velocity(ds,xLag,yLag,porous_info,F_Lag)\n\n% xLag: vector of x-Pts associated w/ x-Lagrangian pts\n% yLag: vector of y-Pts associated w/ y-Lagrangian pts\n% porous_info: col 1: lag-ids for porous media\n% col 2: x-Lag pts for lag-ids \n% col 3: y-Lag pts for lag-ids\n% col 4: porosity coefficient \n\n% # of porous media pts.\nNp = length( porous_info(:,1) );\n\n% Initialize storage\n%Por_X = zeros(length(xLag),1);\n%Por_Y = Por_X;\n\n% Compute Lagrangian Derivatives\n[xL_s,yL_s] = give_Me_Lagrangian_Derivatives(ds,Np,porous_info);\n\n% Compute Normal Vector (unit normals)\n[nX,nY,sqrtNorm] = give_Me_Lagrangian_Normal_Vectors(xL_s,yL_s);\n\n\n% Compute Porous Slip Velocity\nUp_X = - ( porous_info(:,4) ) .* F_Lag( porous_info(:,1) ,1).*nX ./ sqrtNorm;\nUp_Y = - ( porous_info(:,4) ) .* F_Lag( porous_info(:,1) ,2).*nY ./ sqrtNorm;\nPor_Mat = [Up_X Up_Y];\n\n% Store porous slip velocities in appropriate vector for adding to current Lagrangian Velocity Computation\n%Por_X( porous_info(:,1) ) = Up_X;\n%Por_Y( porous_info(:,1) ) = Up_Y;\n%Por_Mat = [Por_X Por_Y];\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: computes Lagrangian Derivatives\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [xL_s,yL_s] = give_Me_Lagrangian_Derivatives(ds,Np,porous_info)\n\nxL = porous_info(:,2); % x-Values for Porous points\nyL = porous_info(:,3); % y-Values for Porous points\nc = porous_info(:,5); % choice of where it falls on stencil\n\nxL_s = zeros(Np,1);\nyL_s = zeros(Np,1);\n\n\nfor i=1:Np\n if c(i) == -2\n xL_s(i) = ( -25/12*xL(i) + 4*xL(i+1) - 3*xL(i+2) + 4/3*xL(i+3) - 1/4*xL(i+4) ) / ds;\n yL_s(i) = ( -25/12*yL(i) + 4*yL(i+1) - 3*yL(i+2) + 4/3*yL(i+3) - 1/4*yL(i+4) ) / ds;\n \n elseif c(i) == -1\n xL_s(i) = ( -0.25*xL(i-1) - 5/6*xL(i) + 1.5*xL(i+1) - 0.5*xL(i+2) + 1/12*xL(i+3) ) / ds;\n yL_s(i) = ( -0.25*yL(i-1) - 5/6*yL(i) + 1.5*yL(i+1) - 0.5*yL(i+2) + 1/12*yL(i+3) ) / ds;\n\n \n elseif c(i) == 0\n xL_s(i) = ( 1/12*xL(i-2) - 2/3*xL(i-1) + 2/3*xL(i+1) - 1/12*xL(i+2) ) / ds;\n yL_s(i) = ( 1/12*yL(i-2) - 2/3*yL(i-1) + 2/3*yL(i+1) - 1/12*yL(i+2) ) / ds;\n\n \n elseif c(i) == 1\n xL_s(i) = ( -1/12*xL(i-3) + 0.5*xL(i-2) - 1.5*xL(i-1) + 5/6*xL(i) + 0.25*xL(i+1) ) / ds;\n yL_s(i) = ( -1/12*yL(i-3) + 0.5*yL(i-2) - 1.5*yL(i-1) + 5/6*yL(i) + 0.25*yL(i+1) ) / ds;\n \n elseif c(i) == 2\n xL_s(i) = ( 0.25*xL(i-4) - 4/3*xL(i-3) + 3*xL(i-2) - 4*xL(i-1) + 25/12*xL(i) ) / ds;\n yL_s(i) = ( 0.25*yL(i-4) - 4/3*yL(i-3) + 3*yL(i-2) - 4*yL(i-1) + 25/12*yL(i) ) / ds;\n \n else\n fprintf('\\n\\n');\n error('Error: Bad file format inside your .porous file!\\n'); \n end\nend\n\n% IF CLOSED STRUCTURE!\n% for i=1:Np\n% if i==1\n% xL_s(1) = ( xL(2) - xL(end) ) / (2*ds); \n% yL_s(1) = ( yL(2) - yL(end) ) / (2*ds);\n% elseif i0)-k3*(qft5);\n\nFrb = u(1)*(u(1)>0);\nFfb = u(1)*(u(1)<0);\n\nFzr = max((-k1*r0(3)-d1*r0d(3))*(r0(3)<0),0) ;\nFtr = t1*Fzr*atan(-vtr/vlr);\nFlr = Fzr*min(max(f1*((b1+a1*cos(q1))*q8d/vlr-1),-1),1);\n\nFzf = max((-k1*r7(3)-d1*r7d(3))*(r7(3)<0),0) ;\nFtf = t6*Fzf*atan(-vtf/vlf);\nFlf = Fzf*min(max(f6*((b6+a6*cos(q5))*q9d/vlf-1),-1),1);\n\nT1 = k3*(pi/2-dot(v1,v2))*cross(v1,v2);\n\n%% experiment\nsr = r0d(1:2);\nFr = -Fzr*(sr./((sr.'*sr)^4+1)^(1/8)+sr./((sr.'*sr)^2+1));\nFlr = c0*Fr(1)+s0*Fr(2);\nFtr = -s0*Fr(1)+c0*Fr(2);\n\nss = r7d(1:2);\nFf = -Fzf*(ss./((ss.'*ss)^4+1)^(1/8)+ss./((ss.'*ss)^2+1));\nFlf = c4*Ff(1)+s4*Ff(2);\nFtf = -s4*Ff(1)+c4*Ff(2);\n%% end of experiment\n\n% work done by forces/torques\nQfs = [0 0 0 0 0 0 0 0 0 0 -Ffs 0 0].';\nQrs = [0 0 0 0 0 -Frs 0 0 0 Frs 0 0 0].'; \nQfb = [0 0 0 0 0 0 0 0 -Ffb 0 0 0 Ffb].';\nQrb = [0 0 0 0 0 0 0 0 0 -Frb 0 Frb 0].'; \nQT1 = [0 0 0 T1(3) c0*T1(1)+s0*T1(2) -s0*c1*T1(1)+c0*c1*T1(2)+s1*T1(3) -T1(3) -c4*T1(1)-s4*T1(2) s4*c5*T1(1)-c4*c5*T1(2)-s5*T1(3) 0 0 0 0].';\nQT3 = [0 0 0 T3(3) c0*T3(1)+s0*T3(2) -s0*c1*T3(1)+c0*c1*T3(2)+s1*T3(3) -T3(3) -c4*T3(1)-s4*T3(2) s4*c5*T3(1)-c4*c5*T3(2)-s5*T3(3) 0 0 0 0].';\nQrz = [0 0 1 0 -s1*(s2*l3+s7*l2-b1) c1*c2*l3 0 0 0 c1*c7*l2 0 0 0 ].'*Fzr;\nQfz = [0 0 1 0 0 0 0 s5*(s6*l4+c6*qf+b6) c5*(s6*qf-c6*l4) 0 -c5*c6 0 0 ].'*Fzf;\nQlf = [c4 s4 0 0 0 0 -s5*(s6*l4+c6*qf+b6) 0 -s6*l4-c6*qf 0 -s6 0 -c5*a6-b6 ].'*Flf; \nQlr = [c0 s0 0 -s1*(-s2*l3-s7*l2+b1) 0 s2*l3 0 0 0 s7*l2 0 -c1*a1-b1 0 ].'*Flr; \nQtf = [-s4 c4 0 0 0 0 c6*l4-s6*qf c5*(s6*l4+c6*qf+b6)+a6 s5*(c6*l4-s6*qf) 0 s5*c6 0 0].'*Ftf;\nQtr = [-s0 c0 0 -c2*l3-c7*l2 c1*(b1-s2*l3-s7*l2)+a1 -s1*c2*l3 0 0 0 -s1*c7*l2 0 0 0 ].'*Ftr;\nVq = -g*[0 0 m1+m2+m3+m4+m5+m6 0 -m1*s1*(s2*l3+s7*l2)-m2*s1*(s2*l3-s7*(-l2+x2))-m3*s1*(-s2*(-l3+x3)+c2*z3) (m1+m2)*c1*c2*l3+m3*c1*(-c2*(-l3+x3)-s2*z3) 0 (-m4*s5*(-s6*x4+c6*z4)-m5*s5*(-s6*(l4+x5)+c6*(-qf+z5))-m6*s5*(-s6*l4-c6*qf)) m4*c5*(-c6*x4-s6*z4)+m5*c5*(-c6*(l4+x5)-s6*(-qf+z5))+m6*c5*(-c6*l4+s6*qf) m1*c1*c7*l2-m2*c1*c7*(-l2+x2) c5*c6*sf 0 0];\n% Q = Vq.'+Qfs+Qrs+Qrz+Qfz+QT1+QT3+Qlf+Qlr+Qtf; \nQ = Vq.'+Qfs+Qrs+Qrz+Qfz+QT1+QT3+Qtf+Qlf+Qlr+Qtr+Qfb+Qrb;\n% Q = Vq.'+Qfs+Qrs+Qrz+Qfz+QT1+QT3+Qflon+Qrlon+Qflat+Qrlat; \n\nqdd = M\\(Q-C*qd);\n\n\nIMU = [0;0;0;0;0;0];\n\nqxdd=qdd(1);\nqydd=qdd(2);\nqzdd=qdd(3);\nq0dd=qdd(4);\nq1dd=qdd(5);\nq2dd=qdd(6);\n\nsu = sin(u7); cu = cos(u7); sv = sin(v7); cv = cos(v7); sw = sin(w7);cw = cos(w7);\n\n% basic rotations\nR0 = [c0 -s0 0;s0 c0 0;0 0 1]; R0q = [-s0 -c0 0;c0 -s0 0;0 0 0]; R0qq = [-c0 s0 0;-s0 -c0 0;0 0 0];\nR1 = [1 0 0;0 c1 -s1;0 s1 c1]; R1q = [0 0 0;0 -s1 -c1;0 c1 -s1]; R1qq = [0 0 0;0 -c1 s1;0 -s1 -c1];\nR2 = [c2 0 s2;0 1 0;-s2 0 c2]; R2q = [-s2 0 c2;0 0 0;-c2 0 -s2]; R2qq = [-c2 0 -s2;0 0 0;s2 0 -c2];\n\nRu = [cu -su 0;su cu 0;0 0 1];\nRv = [1 0 0;0 cv -sv;0 sv cv];\nRw = [cw 0 sw;0 1 0;-sw 0 cw];\n\n% position vector\nrm7 = [qx;qy;qz]+R0*(R1*(R2*[x7;y7;z7]));\n\n% % velocity vector\n% rm7d=jacobian(rm7,q)*qd\n% rm7d1= [qxd;qyd;qzd]+q0d*R0q*(R1*(R2*[x7;y7;z7]))+R0*(q1d*R1q*(R2*[x7;y7;z7])+R1*(q2d*R2q*[x7;y7;z7]))\n% rm7d2= [qxd;qyd;qzd]+R0q*(R1*(R2*q0d*[x7;y7;z7]))+R0*(R1q*(R2*q1d*[x7;y7;z7])+R1*(R2q*q2d*[x7;y7;z7]))\n% temp=simple(rm7d1-rm7d2)\n% acceleration vector\n% rm7dd=(jacobian(rm7d,[q;qd])*[qd;qdd])\n% rm7dd1=(jacobian(rm7d1,[q;qd])*[qd;qdd])% this vector is in global coordinates, but the sensor measures in local coordinates.\n% rm7dd2=[qxdd;qydd;qzdd] ...\n% +R0qq*(R1*(R2*q0d^2*[x7;y7;z7])) +R0q*(R1q*(R2*q0d*q1d*[x7;y7;z7])) +R0q*(R1*(R2q*q0d*q2d*[x7;y7;z7])) +R0q*(R1*(R2*q0dd*[x7;y7;z7])) ...\n% +R0q*(R1q*(R2*q0d*q1d*[x7;y7;z7])) +R0*(R1qq*(R2*q1d^2*[x7;y7;z7])) +R0*(R1q*(R2q*q1d*q2d*[x7;y7;z7])) +R0*(R1q*(R2*q1dd*[x7;y7;z7])) ...\n% +R0q*(R1*(R2q*q0d*q2d*[x7;y7;z7])) +R0*(R1q*(R2q*q1d*q2d*[x7;y7;z7])) +R0*(R1*(R2qq*q2d^2*[x7;y7;z7])) +R0*(R1*(R2q*q2dd*[x7;y7;z7]))\n% temp=simple(rm7dd-rm7dd2)\n\n% absolute position measured in local body coordinates\n% - rm7loc = R2'*R1'*R0'*([qx;qy;qz]+R0*R1*R2*[x7;y7;z7])\n% - rm7loc = R2'*R1'*R0'*[qx;qy;qz]+ R2'*R1'*R0'*R0*R1*R2*[x7;y7;z7]\n% - rm7loc = R2'*R1'*R0'*[qx;qy;qz]+ [x7;y7;z7]\n% rm7loc = R2.'*R1.'*R0.'*[qx;qy;qz]+ [x7;y7;z7] \n% how can this be possible? this implies (or not?) that the velocity of the sensor is\n% independent of its local position [x7;y7;z7].\n\n\n% absolute velocity measured in local body coordinates\n% rm7dloc8 = R2.'*(R1.'*(((R0.'*[qxd;qyd;qzd])) + (R0tR0q *(R1*(R2*q0d*[x7;y7;z7]))))+(R1tR1q*(R2*q1d*[x7;y7;z7])))+(R2tR2q*q2d*[x7;y7;z7])\n\n\n\n% syms s0 s1 s2 c0 c1 c2\n% rm7ddloc6 = R2.'*R1.'*R0.'*[qxdd;qydd;qzdd]+ ...\n% [z7*(q2dd + (q1d^2*sin(2*q2))/2 + q0dd*s1 - (q0d^2*sin(2*q2)*c1^2)/2 + 2*q0d*q1d*cos(q1)*cos(q2)^2) - x7*(q0d^2*(c2^2 + s1^2*s2^2) + q1d^2*s2^2 + q2d^2 + 2*q0d*q2d*s1 + q0d*q1d*sin(2*q2)*c1) - y7*(c1*s1*s2*q0d^2 - 2*q1d*c2*s1*q0d + q1dd*s2 + q0dd*c1*c2);\n% x7*(-c1*s1*s2*q0d^2 - 2*q2d*c1*s2*q0d + q1dd*s2 + 2*q1d*q2d*c2 + q0dd*c1*c2) - y7*(q0d^2*c1^2 + q1d^2) + z7*((sin(2*q1)*c2*q0d^2)/2 + 2*q2d*c1*c2*q0d - q1dd*c2 + 2*q1d*q2d*s2 + q0dd*c1*s2);\n% y7*((sin(2*q1)*c2*q0d^2)/2 + 2*q1d*s1*s2*q0d + q1dd*c2 - q0dd*c1*s2) - z7*(q1d^2*c2^2 - q0d^2*(c1^2*c2^2 - 1) + q2d^2 + 2*q0d*q2d*s1 - q0d*q1d*sin(2*q2)*c1) - x7*(q2dd - (q1d^2*sin(2*q2))/2 + q0dd*s1 + (q0d^2*sin(2*q2)*c1^2)/2 + 2*q0d*q1d*c1*s2^2)]\n\n\nrm7ddloc6 = R2.'*(R1.'*(R0.'*[qxdd;qydd;qzdd+9.81]))+ ...\n[ z7*(q2dd+q0dd*s1+c2*s2*(q1d^2-q0d^2*c1^2)+2*c1*c2^2*q0d*q1d) ...\n- y7*(s2*(c1*s1*q0d^2+q1dd)+c2*(c1*q0dd-2*q1d*s1*q0d)) ...\n- x7*(q1d^2*s2^2+q0d^2*s1^2*s2^2+q0d^2*c2^2+2*q0d*q2d*s1+2*c1*c2*q0d*q1d*s2+q2d^2); ...\n z7*((c1*(s1*q0d^2+2*q2d*q0d)-q1dd)*c2+(c1*q0dd+2*q1d*q2d)*s2) ...\n+ x7*(-c1*s1*s2*q0d^2-2*c1*q2d*s2*q0d+q1dd*s2+c1*c2*q0dd+2*c2*q1d*q2d) ...\n- y7*(c1^2*q0d^2+q1d^2); ...\n y7*(c2*(c1*s1*q0d^2+q1dd)+s2*(2*s1*q0d*q1d-c1*q0dd)) ...\n- x7*(q2dd+q0dd*s1+c2*s2*(q0d^2*c1^2-q1d^2)+2*c1*q0d*q1d*s2^2) ...\n- z7*(q0d^2*(1-c2^2*c1^2)+c2^2*q1d^2+2*q0d*(q2d*s1-c1*c2*q1d*s2)+q2d^2)]...\n;\n\nrm7ddloc6 = Rw.'*(Rv.'*(Ru.'*rm7ddloc6));\n\nwrel=R2.'*R1.'*R0.'*[0;0;q0d]+R2.'*R1.'*[q1d;0;0]+R2.'*[0;q2d;0];\nwrel = Rw.'*(Rv.'*(Ru.'*wrel));\n\nIMU=[wrel;rm7ddloc6];\n\n% from generalized coordinates to nonlinear state space \nfx=[qdd;qd];\nhx=[IMU];\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35045-motorcycle-model/motorcycle_model_3_2012/mdl_motorcycle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.47358670716813883}}
{"text": "function [y_in_x,x_in_y]=cosmo_overlap(xs,ys)\n% compute overlap between vectors or cellstrings in two cells\n%\n% [y_in_x,x_in_y]=cosmo_overlap(xs,ys)\n%\n% Inputs:\n% xs Nx1 cell with all elements either numeric arrays or\n% cells with strings\n% ys Mx1 cell with all elements either numeric arrays or\n% cells with strings\n%\n% Output:\n% y_in_x MxN cell with the (i,j)-th element indicating the ratio of\n% elements in ys{j} that are present in xs{i}\n% x_in_i MxN cell with the (i,j)-th element indicating the ratio of\n% elements in ys{i} that are present in ys{i}\n%\n% Examples:\n% % Compute overlap between two cells with cellstrings\n% xs={{'a'},{'a','b'},{'a','b','c'},{}};\n% ys={{'b'},{'c','b','a'}};\n% [x_in_y,y_in_x]=cosmo_overlap(xs,ys);\n% cosmo_disp(x_in_y);\n% %|| [ 0 0.333\n% %|| 1 0.667\n% %|| 1 1\n% %|| 0 0 ]\n% %||\n% cosmo_disp(y_in_x);\n% %|| [ 0 1\n% %|| 0.5 1\n% %|| 0.333 1\n% %|| NaN NaN ]\n%\n% % Compute overlap between two cells with numeric arrays\n% xs={1,[1 2],1:3,[]};\n% ys={2,[3,2,1]};\n% [x_in_y,y_in_x]=cosmo_overlap(xs,ys);\n% cosmo_disp(x_in_y);\n% %|| [ 0 0.333\n% %|| 1 0.667\n% %|| 1 1\n% %|| 0 0 ]\n% %||\n% cosmo_disp(y_in_x);\n% %|| [ 0 1\n% %|| 0.5 1\n% %|| 0.333 1\n% %|| NaN NaN ]\n%\n%\n% # For CoSMoMVPA's copyright information and license terms, #\n% # see the COPYING file distributed with CoSMoMVPA. #\n\n [xs_vec,nx,nxs,xi]=get_counts(xs);\n [ys_vec,ny,nys,yi]=get_counts(ys);\n\n xy_cell=[xs_vec(:);ys_vec(:)];\n xyc=cat(1,xy_cell{:});\n\n % index xs from 1 to nx, and ys from (nx+1) to (nx+ny)\n xyi=[xi;(nx+yi)];\n\n % space for histogram\n h=zeros(nx,ny);\n\n % position of index of last value in xs\n xs_pos_last=sum(nxs);\n\n % because string comparisons are slow, use their indices instead\n [unq,unused,idxs]=unique(xyc);\n nunq=numel(unq);\n [idxs_sorted,i_sorted]=sort(idxs);\n\n msk=[true; any(diff(idxs_sorted,1),2)];\n unq_start_end_pos=[find(msk); 1+numel(msk)];\n\n for j=1:nunq\n % more readible, but slower:\n % start_pos=unq_start_end_pos(j);\n % end_pos=unq_start_end_pos(j+1)-1;\n % if i_sorted(start_pos)>xs_pos_last [...]\n if i_sorted(unq_start_end_pos(j))<=xs_pos_last && ...\n i_sorted(unq_start_end_pos(j+1)-1)>xs_pos_last\n\n start_pos=unq_start_end_pos(j);\n end_pos=unq_start_end_pos(j+1)-1;\n\n i=i_sorted(start_pos:(end_pos));\n\n first_y=find_first_greater_than(i,xs_pos_last);\n px=xyi(i(1:(first_y-1)));\n py=xyi(i(first_y:end))-nx;\n\n h(px,py)=h(px,py)+1;\n end\n end\n\n x_in_y=bsxfun(@rdivide,h,nxs);\n y_in_x=bsxfun(@rdivide,h,nys');\n\nfunction i=find_first_greater_than(sorted_vs,thr)\n % using binary search, find the first position i in sorted_vs\n % so that sorted(vs)>thr\n % it is assumed that sorted_vs is sorted\n if sorted_vs(end)<=thr\n i=numel(sorted_vs)+1;\n return\n end\n\n first=1;\n last=numel(sorted_vs);\n\n while firstthr);\n %assert(i==1 || sorted_vs(i-1)<=thr);\n\n\nfunction [xs_vec,n,c,i]=get_counts(xs)\n n=numel(xs);\n c=zeros(n,1);\n xs_vec=cell(n,1);\n for k=1:n\n xsk=xs{k};\n if ~isnumeric(xsk) && ~iscellstr(xsk)\n error('only cells with numeric or cellstr input is supported');\n end\n c(k)=numel(xsk);\n xs_vec{k}=xsk(:);\n end\n\n nc=sum(c);\n i=zeros(nc,1);\n pos=0;\n for k=1:n\n ck=c(k);\n idxs=pos+(1:ck);\n i(idxs)=k;\n pos=pos+ck;\n end\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_overlap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.47357844445511993}}
{"text": "function [ar,e,dc]=v_lpccovar(s,p,t,w)\n%V_LPCCOVAR performs covariance LPC analysis [AR,E,DC]=(S,P,T)\n%\n% Inputs: S(NS) is the input signal\n% P is the order (default: 12)\n% T(NF,:) specifies the frames size details: each row specifies one frame\n% T can be a cell array if rows have unequal numbers of values\n% T(:,1) gives the start of the analysis interval: must be >P\n% T(:,2) gives the end of the anaylsis interval [default: t(:+1,1)-1]\n% subsequent pairs can be used to specify multiple disjoint segments\n% If T is omitted, T(1,1)=P+1, T(1,2)=NS;\n% The elements of t need not be integers.\n% W(NS) The error at each sample is weighted by W^2 (default: 1)\n%\n% Outputs: AR(NF,P+1) are the AR coefficients with AR(:,1) = 1\n% E(NF,4) each row is [Er Es Pr Ps] and gives the energy (\"E\") and power (\"P\")\n% in the input signal window (\"s\") and in the LPC residual \"r\".\n% The 'gain' of the LPC filter is g=sqrt(Pr); x=filter(g,ar,randn(:,1)) will\n% generate noise with approximately the same power spectrum as the input s.\n% DC is the DC component of the signal S. If this output is included,\n% the LPC equations are modified to include a DC offset.\n\n% Notes:\n%\n% (1a) If no DC output is specified AR(j,:)*S(n-(0:P)) ~ 0 or, equivalently,\n% S(n) ~ -AR(j,2:P)*S(n-(1:P)) where T(j,1) <= n <= T(j,2).\n% (1b) If a DC output is specified AR(j,:)*(S(n-(0:P))-DC) ~ 0 or, equivalently,\n% S(n) ~ DC - AR(j,2:P)*(S(n-(1:P))-DC) = DC*sum(AR,j,:)) - AR(j,2:P)*S(n-(1:P))\n% where T(j,1) <= n <= T(j,2).\n%\n% (2) For speech processing P should be at least 2*F*L/C where F is the sampling\n% frequency, L the vocal tract length and C the speed of sound. For a typical\n% male (l=17 cm) this gives f/1000.\n%\n% (3) Each analysis frame should contain at least 2P samples. If note (1) is followed\n% this implies at least 2 ms of speech signal per frame.\n%\n% (4) It can be advantageous to restrict the analysis regions to time intervals\n% when the glottis is closed (closed-phase analysis). This can be achieved by\n% setting the T input parameter appropriately. If the closed-phase is shorter than\n% 2 ms then two or more successive closed-phases should be used by defining 4 or more\n% elements in the corresponding row of T.\n%\n% (5) A previous version of this routine allowed T() to have a single row which would\n% be replicated for the entire file length. This has been removed because it gave rise\n% to an ambiguity.\n\n% Bugs: should really detect a singular matrix and reduce the order accordingly\n\n%\t Copyright (C) Mike Brookes 1995\n% Version: $Id: v_lpccovar.m 10865 2018-09-21 17:22:45Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ns = s(:); % make it a column vector\nif nargin < 2 p=12; end;\nif nargin < 3 t=[p+1 length(s)]; end;\nwq = nargin>3;\n[nf,ng]=size(t);\nif iscell(t)\n t{nf+1}=length(s)+1;\nelse\n if rem(ng,2)\n t(:,end+1)=[t(2:nf,1)-1; length(s)];\n end\nend\nar=zeros(nf,p+1);\nar(:,1)=1;\ne=zeros(nf,4);\ndc=zeros(nf,1);\nd0=nargout >2;\nrs=(1:p);\nfor jf=1:nf\n if iscell(t)\n tj=t{jf};\n if rem(length(tj),2)\n tj(end+1)=t{jf+1}(1)-1;\n end\n else\n tj=t(jf,:);\n end\n\n ta = ceil(tj(1));\n tb = floor(tj(2));\n cs = (ta:tb).';\n for js=3:2:length(tj)\n ta = ceil(tj(js));\n tb = floor(tj(js+1));\n cs = [cs; (ta:tb).'];\n end\n %disp(cs([logical(1); (cs(2:end-1)~=cs(1:end-2)+1)|(cs(2:end-1)~=cs(3:end)-1); logical(1)])');\n nc = length(cs);\n pp=min(p,nc-d0);\n dm=zeros(nc,pp);\t% predefine shape\n dm(:) = s(cs(:,ones(1,pp))-rs(ones(nc,1),1:pp));\n if nargout>2\n if wq\n dm = [ones(nc,1) dm].*w(cs(:,ones(1,1+pp)));\n sc=(s(cs).*w(cs));\n aa = (dm\\sc).';\n else\n dm = [ones(nc,1) dm];\n sc=s(cs);\n aa = (dm\\sc).';\n end\n ar(jf,2:pp+1) = -aa(2:pp+1);\n e(jf,1)=sc.'*(sc - dm*aa.');\n e(jf,2)=sc.'*sc;\n e(jf,3:4)=e(jf,1:2)/nc;\n dc(jf)=aa(1)/sum(ar(jf,:));\n else\n if wq\n dm = dm.*w(cs(:,ones(1,pp)));\n sc=(s(cs).*w(cs));\n aa = (dm\\sc).';\n else\n sc=s(cs);\n aa = (dm\\sc).';\n end;\n ar(jf,2:pp+1) = -aa;\n if nargout~=1\n e(jf,1)=real(sc'*(sc - dm*aa.'));\n e(jf,2)=real(sc'*sc);\n e(jf,3:4)=e(jf,1:2)/nc;\n end\n end\nend\nif ~nargout\n v_lpcar2ff(repmat(sqrt(e(:,3).^(-1)),1,p+1).*ar,255);\n ylabel('Power (dB)');\nend\n\n", "meta": {"author": "ImperialCollegeLondon", "repo": "sap-voicebox", "sha": "28f2654b7584f724277ec81de533debe28ff51ac", "save_path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox", "path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox/sap-voicebox-28f2654b7584f724277ec81de533debe28ff51ac/voicebox/v_lpccovar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.47356632425439116}}
{"text": "function x = merl_quadprog(varargin)\n % MERL_QUADPROG Optimize problems of the form:\n % \n % min_x 1/2 x' Q x - x' h\n % \n % s.t. x>=0\n %\n % According to the method described in \"PARALLEL QUADRATIC PROGRAMMING FOR\n % IMAGE PROCESSING\" [Brand & Chen 11]\n %\n % x = merl_quadprog(Q,h,'ParamterName',ParameterValue)\n %\n % Inputs:\n % Q n by n symmetric positive semi-definite quadratic coefficients matrix\n % h n by 1 linear coefficents vector (note sign)\n % Outputs:\n % x n by 1 solution vector\n %\n %\n\n Q = varargin{1};\n h = varargin{2};\n\n n = size(Q,1);\n assert(size(Q,2) == n);\n assert(numel(h) == n);\n h = h(:);\n\n max_iter = inf;\n tol = 1e-7;\n\n % initial guess\n x0 = ones(n,1);\n\n v = 3;\n while v <= numel(varargin)\n switch varargin{v}\n case 'MaxIter'\n assert((v+1)<=numel(varargin));\n v = v+1;\n max_iter = varargin{v};\n case 'X0'\n assert((v+1)<=numel(varargin));\n v = v+1;\n x0 = varargin{v};\n otherwise\n error(['Unknown parameter: ' varargin{v}]);\n end\n v = v+1;\n end\n\n %% \"some r ā R^n ā„ 0\"\n %r = sparse(n,1);\n % ri = max(Qii , ā j Qāi j )\n r = max(diag(Q),max(-Q,[],2));\n\n % \"similarly\" ... \"si>0\"\n s = ones(n,1);\n\n Qp = max(Q,0) + diag(r);\n Qm = max(-Q,0) + diag(r);\n assert(issparse(Qp));\n hp = max(h,0) + s;\n hm = max(-h,0) + s;\n\n x = x0;\n it = 0;\n while true\n x_prev = x;\n x = x.*(hp+Qm*x)./(hm+Qp*x);\n it = it + 1;\n diff = max(abs(x-x_prev));\n %fprintf('%d: %g\\n',it,diff);\n if it >= max_iter\n return;\n end\n if diff<=tol\n return;\n end\n end\n\n\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/matrix/merl_quadprog.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4735663178916123}}
{"text": "function T = sldlda(X, nums, varargin)\n%SLDLDA Performs Direct Linear Discriminant Analysis\n%\n% $ Syntax $\n% - T = sldlda(X, nums)\n% - T = sldlda(X, nums, ...)\n%\n% $ Arguments $\n% - X: the training sample matrix\n% - nums: the numbers of samples in all classes\n% - T: the solved transform matrix\n%\n% $ Description $\n% - T = sldlda(X, nums) performs direct LDA on the samples X using \n% default settings.\n%\n% - T = sldlda(X, nums, ...) performs direct LDA on the samples X\n% with the specified properties.\n% \\*\n% \\t Table 1. The properties of Fisher Discriminant Analysis \\\\\n% \\h name & description \\\\\n% 'pdimset' & The cell containing the arguments for determining\n% the range space of Sb. They will be input to\n% slrangespace for dimension determination.\n% 'whiten' & The cell containing the arguments for computing \n% the whitening transform in 2nd stage. They will\n% input to slwhiten_from_cov.\n% default = {}. \\\\\n% 'Sb' & The pre-computed between-class scattering matrix\n% or the cell containing the arguments for \n% computing the scatter matrix in the form\n% {type, ...}, which is input to slscatter. \\\\\n% 'Sw' & The pre-computed within-class scattering matrix\n% or the cell containing the arguments for \n% computing the scatter matrix in the form\n% {type, ...}, which is input to slscatter. \\\\\n% 'weights' & The sample weights. default = []. \\\\\n% \\* \n%\n% $ Remarks $\n% -# The function solves the transform in mainly following stages: \n% First solves the range space of between-class scattering, \n% projecting all samples onto it. Then, solve the whitening transform\n% of the projected within-class scattering.\n% \n% -# If Sb or its computing rule is given, the range space is directly \n% solved from Sb, otherwise the null space is solved from class \n% centers. If both Sb and Sw are given, then the samples are not \n% used in the function. In this cases, you can simply input an empty X. \n%\n% -# If both Sb and Sw are given, the pre-pca step will not be conducted.\n% no matter whether prepca is true or false.\n%\n% $ History $\n% - Created by Dahua Lin on May 1st, 2006\n%\n\n%% parse and verify input arguments \n\nif nargin < 2\n raise_lackinput('slfld', 2);\nend\n\n% check size\n\nif ~isempty(X) \n if ndims(X) ~= 2\n error('sltoolbox:invaliddims', ...\n 'The sample matrix X should be a 2D matrix');\n end\n [d, n] = size(X);\n \n k = length(nums);\n if ~isequal(size(nums), [1, k]);\n error('sltoolbox:invaliddims', ...\n 'The nums vector should be a row vector');\n end\n if sum(nums) ~= n\n error('sltoolbox:sizmismatch', ...\n 'The total number in nums is not consistent with that in X');\n end\nend\n\n% check options\nopts.pdimset = {};\nopts.whiten = {};\nopts.Sb = {'Sb'};\nopts.Sw = {'Sw'};\nopts.weights = [];\nopts = slparseprops(opts, varargin{:});\n\nhas_Sb = ~isempty(opts.Sb) && isnumeric(opts.Sb);\nhas_Sw = ~isempty(opts.Sw) && isnumeric(opts.Sw);\nif has_Sb && has_Sw\n d = size(opts.Sw, 1);\n \n if ~isequal(size(opts.Sb), [d, d]) || ~isequal(size(opts.Sw), [d, d])\n error('sltoolbox:sizmismatch', ...\n 'Size consistency in Sb and Sw');\n end\n \nelse\n if isempty(X)\n error('sltoolbox:invalidargs', ...\n 'The samples cannot be empty when Sb or Sw is not pre-computed');\n end\n if (has_Sb && ~isequal(size(opts.Sb), [d, d])) || (has_Sw && ~isequal(size(opts.Sw), [d, d]))\n error('sltoolbox:sizmismatch', ...\n 'Size consistency in Sb and Sw');\n end\n \nend\nw = opts.weights;\n\n%% Step 1: Compute range space of Sb\n\nif has_Sb\n T1 = slrangespace({'cov', opts.Sb}, opts.pdimset{:});\nelseif ~isempty(opts.Sb) && ~isequal(opts.Sb, {'Sb'})\n Sb = slscatter({'cov', X}, opts.Sb{:}, 'sweights', w, 'nums', nums);\n T1 = slrangespace(Sb, opts.pdimset{:});\n clear Sb;\nelse\n Xc = get_weighted_centers(X, w, nums);\n T1 = slrangespace(Xc, opts.pdimset{:});\n clear Xc wc;\nend\n\n\n%% Step 2: Compute the whiten transform for Sw on range space\n\nif has_Sw\n PSw = T1' * opts.Sw * T1;\nelse\n X = T1' * X;\n PSw = slscatter(X, opts.Sw{:}, 'sweights', w, 'nums', nums);\nend\nT2 = slwhiten_from_cov(PSw, opts.whiten{:});\nT2 = flipdim(T2, 2);\n\n%% Integrate the transforms\n\nT = T1 * T2;\n\n\n%% The function for computing weighted centers\nfunction [Xc, wc] = get_weighted_centers(X, w, nums)\n\nXc = slmeans(X, w, nums);\nif isempty(w)\n wc = nums;\nelse\n k = length(nums);\n [sp, ep] = slnums2bounds(nums);\n wc = zeros(1, k);\n for i = 1 : k\n wc(i) = sum(w(sp(i):ep(i)));\n end\nend\nwc = sqrt(max(wc, 0));\nXc = slmulvec(Xc, wc, 2);\n\n\n", "meta": {"author": "lmthang", "repo": "nmt.hybrid", "sha": "50d5c025f18ed280ff0fd2e2adce327f4170a2c3", "save_path": "github-repos/MATLAB/lmthang-nmt.hybrid", "path": "github-repos/MATLAB/lmthang-nmt.hybrid/nmt.hybrid-50d5c025f18ed280ff0fd2e2adce327f4170a2c3/code/wordsim/code/sltoolbox_r101/sltoolbox_r101/sltoolbox/subspace/sldlda.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4735663178916123}}
{"text": "classdef Triangle_Linear < Interpolation\n \n methods (Access = public)\n \n function obj = Triangle_Linear(cParams)\n obj.init(cParams);\n obj.computeParams();\n obj.computeCases();\n end\n \n function computeShapeDeriv(obj,xGauss)\n obj.computeShapes(xGauss);\n obj.computeShapeDerivatives(xGauss);\n end\n \n end\n \n methods (Access = private)\n \n function computeParams(obj)\n obj.ndime = 2;\n obj.nnode = 3;\n obj.pos_nodes = [0 0; 1 0; 0 1];\n obj.isoDv = 0.5;\n obj.main_loop = [3 3];\n obj.extra_cases = [];\n end\n \n function computeShapes(obj,posgp)\n ngaus = size(posgp,2);\n nelem = size(posgp,3);\n s = posgp(1,:,:);\n t = posgp(2,:,:);\n I = ones(size(t));\n obj.shape = zeros(obj.nnode,ngaus,nelem);\n obj.shape(1,:,:) = I-s-t;\n obj.shape(2,:,:) = s;\n obj.shape(3,:,:) = t;\n end\n \n function computeShapeDerivatives(obj,posgp)\n ngaus = size(posgp,2);\n nelem = size(posgp,3);\n obj.deriv = zeros(obj.ndime,obj.nnode,ngaus,nelem);\n obj.deriv(1,1,:,:) = -1;\n obj.deriv(1,2,:,:) = 1;\n obj.deriv(1,3,:,:) = 0;\n obj.deriv(2,1,:,:) = -1;\n obj.deriv(2,2,:,:) = 0;\n obj.deriv(2,3,:,:) = 1;\n end\n \n function computeCases(obj)\n obj.iteration = [1 2 3;\n 2 3 1];\n obj.cases(:,:,1) = [1 4 5;\n 4 2 3;\n 5 4 3];\n obj.cases(:,:,2) = [1 4 3;\n 4 2 5;\n 4 5 3];\n obj.cases(:,:,3) = [1 4 5;\n 1 2 4;\n 5 4 3];\n obj.selectcases = [1 0;\n 2 0;\n 3 3;\n 0 2;\n 0 1];\n end\n \n end\n \nend\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/FEM/Interpolation/Triangle_Linear.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6224593382055109, "lm_q1q2_score": 0.47347410187109484}}
{"text": "% NMFLAB for Signal Processing written by A. Cichocki and R. Zdunek \n% in cooperation with other members of Laboratory for Advanced Brain Signal\n% Processing, BSI, RIKEN, Saitama, JAPAN\n\nfunction [A,X,Distance_output]=nmf_cascade(Y,r,Index_norm,A_true,S,mc_on, NoAlts,restart_mc_on,AL,Y_true,type_alg,max_restart,no_iter, alphaA1, alphaA2, alphaX, alphaSa, alphaS, alpha)\n%\n%\n% Non-negative Matrix Factorization (NMF) with the cascade implementation\n% of some NMF algorithms\n%\n% [A,X]=nmf_cascade(Y, r, Index_norm, A_true, S, mc_on, NoAlts, restart_mc_on, AL, Y_true, type_alg, max_restart, no_iter, \n% alphaA1, alphaA2, alphaX, alphaSa, alphaS, alpha)\n% returns mixing matrix A of dimension [m by r],\n% and source matrix X of dimension [r by T], for the linear mixing model: AX = Y, \n% where Y is an observation matrix [m by T]. \n% Note: > m: number of sensors,\n% > r: number of sources,\n% > T: number of samples,\n% \n% INPUTS:\n% > Index_norm: vector of 13 binary entries indicating which number\n% divergence measures are turned on in the View Options,\n%\n% > A_true: true mixing matrix (only for synthetic data),\n% > S: true source matrix (only for synthetic data), \n% > mc_on: 1 - Monte Carlo analysis enabled, 0 - otherwise, \n% > NoAlts: number of alternating steps (only for Monte Carlo\n% analysis and the option \"Fixed Alternatings\" is selected)\n% > restart_mc_on: 1 - restarts in Monte Carlo analysis are enabled,\n% 0 - otherwise, \n% > AL: mixing matrix estimaed from the preceeding layer, \n% > Y_true: the first layer mixed signals (mixtures),\n% > type_alg: indicates the selected algorithm, \n% > max_restart: number of restarts, \n% > no_iter: number of inner iterations, \n% > alphaA1: regularization parameter for computation of\n% the first mixing matrix,\n% > alphaA2: regularization parameter for computation of\n% the second mixing matrix,\n% > alphaX: regularization parameter for computation of\n% the sources,\n% > alphaSa: parameter of non-linear projection in computation\n% of the mixing matrix,\n% > alphaS: parameter of non-linear projection in computation\n% of the sources,\n% > alpha: parameter \"alpha\" in the Amari alpha-divergence,\n% \n% OUTPUTS:\n% > A: estimated mixing matrix,\n% > X: estimated source matrix,\n% > Distance_output: structures of different divergences measured between \"Y\" and estimated \"AX\" versus iterations,\n%\n%\n% #########################################################################\nA = [];\nX = [];\nif (nargin < 19) | isempty(alpha) | max(size(alpha) > 1)\n disp('Incorrect parameter alpha in alpha-divergence');\n return\nend\nif (nargin < 18) | isempty(alphaS) | max(size(alphaS) > 1)\n disp('Incorrect regularization parameter alphaS');\n return\nend\nif (nargin < 17) | isempty(alphaSa) | max(size(alphaSa) > 1)\n disp('Incorrect regularization parameter alphaSa');\n return\nend\nif (nargin < 16) | isempty(alphaX) | max(size(alphaX) > 1)\n disp('Incorrect regularization parameter alphaX');\n return\nend\nif (nargin < 15) | isempty(alphaA2) | max(size(alphaA2) > 1)\n disp('Incorrect regularization parameter alphaA2');\n return\nend\nif (nargin < 14) | isempty(alphaA1) | max(size(alphaA1) > 1)\n disp('Incorrect regularization parameter alphaA1');\n return\nend\nif (nargin < 13) | isempty(no_iter) | (no_iter < 1) | max(size(no_iter) > 1)\n disp('Incorrect number of iterations in the EMML algorithm');\n return\nend\nif (nargin < 12) | isempty(max_restart) | (max_restart < 0) | max(size(max_restart) > 1)\n disp('Number of restarts must be given correctly');\n return\nend\nif (nargin < 11) | isempty(type_alg) | (type_alg < 0) | max(size(type_alg) > 1)\n disp('Unknown algorithm');\n return\nend\nif (nargin < 10) | isempty(Y_true) \n disp('The first layer mixed signals are unknown');\n Y_true = zeros(size(Y_true));\nend\nif (nargin < 9) | isempty(AL) \n disp('Mixing matrix from the preceeding layer unknown');\n AL = eye(size(Y,1));\nend\nif (nargin < 8) | isempty(restart_mc_on) | max(size(restart_mc_on) > 1)\n disp('Index od restarts in MC analysis unknown');\n restart_mc_on = 0;\nend\nif (nargin < 7) | isempty(NoAlts) | max(size(NoAlts) > 1)\n disp('Adjustable number of alternatings');\n NoAlts = [];\nend\nif (nargin < 6) | isempty(mc_on) | max(size(mc_on) > 1)\n disp('No Monte Carlo Analysis');\n mc_on = 0;\nend\nif (nargin < 5) | isempty(S) \n disp('X_true not given');\nend\nif (nargin < 4) | isempty(A_true) \n disp('A_true not given');\n index_fixed_A = 1;\nelse\n index_fixed_A = 0; \nend\nif (nargin < 3) | isempty(Index_norm)\n '\"Index_norm\" must be specified'\n return\nend\nif (nargin < 2) | isempty(r)\n 'Rank of factorization must be given'\n return\nend\nif isempty(Y) | isnan(Y)\n error('No data');\n return\nend\n% test for negative values in Y\nif min(min(Y)) < 0\n disp('Some matrix entries are changed from negative to small positive');\n Y(Y< 0) = eps;\nend\nif min(sum(Y,2)) == 0\n disp('Not all entries in a row can be zero');\n return\nend\n\nY = Y + eps;\n%Y = Y*Y';\n\nif (alpha == 0) & (type_alg == 3)\n type_alg = 4;\nend\n \n[m,T]=size(Y);\nniter_selected = 1000; % maximum number of iterations for the selected sample (can be adjusted)\nniter_sample = 30; % maximum number of iterations for each random sample\nepsil_normA = 1E-12; % tolerance for alternating\n\n% Monte Carlo and alternatings adjustment\nif mc_on & ~restart_mc_on\n max_restart = 0;\nend\nif ~isempty(NoAlts)\n niter_selected = NoAlts;\nend\n\n% Declaration for A and X\nA=zeros(m,r);\nAp = zeros(m); \nX=zeros(r,T);\nAinit = A;\nXinit = X;\nZ = zeros(m,T);\nKL_outer_temp = 0;\nZ_outer = 0;\nnr = 0; restart_on = 0; norm_A = 10; nr_best = -1;\nm_sx = 1:m; r_sx = 1:r; T_sx = 1:T; s_dist = 0;\n\n\nwhile (nr <= max_restart)\n \n % Initialize random A and X\n if ~nr & (~mc_on | restart_mc_on) \n A1_init(m_sx',m_sx) = abs(repmat(.1*sin(2*pi*.1*m_sx'),1,m) + repmat(.1*cos(2*pi*.1*m_sx),m,1) + repmat(cos(2*pi*.471*m_sx'),1,m) + repmat(sin(2*pi*.471*m_sx),m,1));\n A1_init = A1_init/max(max(A1_init));\n \n A2_init(m_sx',r_sx) = abs(repmat(.1*sin(2*pi*.1*m_sx'),1,r) + repmat(.1*cos(2*pi*.1*r_sx),m,1) + repmat(cos(2*pi*.471*m_sx'),1,r) + repmat(sin(2*pi*.471*r_sx),m,1));\n A2_init = A2_init/max(max(A2_init));\n \n Xinit(r_sx',T_sx) = abs(repmat(.1*sin(2*pi*.1*r_sx'),1,T) + repmat(.1*cos(2*pi*.1*T_sx),r,1) + repmat(cos(2*pi*.471*r_sx'),1,T) + repmat(sin(2*pi*.471*T_sx),r,1));\n Xinit = Xinit/max(max(Xinit));\n else\n A1_init=rand(m,m);\n A2_init=rand(m,r);\n Xinit=rand(r,T);\n end\n \n % Normalization of initial guess\n A1_init = A1_init*diag(1./sum(A1_init,1));\n A2_init = A2_init*diag(1./sum(A2_init,1));\n \n if (nr == max_restart)&(max_restart > 0)\n A1 = A1_best;\n A2 = A2_best;\n X = X_best;\n else\n A1 = A1_init;\n A2 = A2_init;\n X = Xinit;\n end % initial guess assignment\n \n Yx = zeros(m,T);\n n = 0; k = 0;\n \nwhile ((k <= niter_sample)&(nr < max_restart)) | ((k <= niter_selected)&(nr == max_restart)&(norm_A > epsil_normA)& isempty(NoAlts)) | ((k <= niter_selected)&(nr == max_restart)& (NoAlts > 0)) \n \nk = k + 1;\n \n% generalized divergence-reducing NMF iterations (main algorithm)\n if no_iter == 1\n \n if type_alg == 1 % KL\n \n Ap = A1;\n \n Nom = (Y./(A1*A2*X + eps))*(A2*X)';\n Nom(Nom <= 0) = eps;\n A1 = (A1.*(Nom./( repmat((A2*X*ones(T,1))',m,1) + eps))).^(1 + alphaSa);\n A1 = A1*diag(1./sum(A1,1));\n \n Nom = A1'*(Y./(A1*A2*X + eps))*X';\n Nom(Nom <= 0) = eps;\n A2 = (A2.*(Nom./(A1'*ones(m,1)*ones(1,T)*X' + eps))).^(1 + alphaSa);\n A2 = A2*diag(1./sum(A2,1));\n \n Nom = (A1*A2)'*(Y./(A1*A2*X + eps));\n Nom(Nom <= 0) = eps;\n X = (X.*(Nom./(repmat((A1*A2)'*ones(m,1),1,T) + eps))).^(1 + alphaS);\n\n\n elseif type_alg == 2 % Frobenius\n \n Ap = A1; \n Nom = Y*(A2*X)' - alphaA1;\n Nom(Nom <= 0) = eps;\n A1 = A1.*(Nom./(A1*A2*X*(A2*X)' + eps));\n A1 = A1*diag(1./sum(A1,1));\n \n Nom = A1'*Y*X' - alphaA2;\n Nom(Nom <= 0) = eps;\n A2 = A2.*(Nom./(A1'*A1*A2*X*X' + eps));\n A2 = A2*diag(1./sum(A2,1));\n \n Nom = (A1*A2)'*Y - alphaX;\n Nom(Nom <= 0) = eps;\n X = X.*(Nom./((A1*A2)'*A1*A2*X + eps));\n \n elseif type_alg == 3 % Amari alpha-divergence\n \n Ap = A1; \n Nom = ((Y./(A1*A2*X + eps)).^alpha )*(A2*X)';\n Nom(Nom <= 0) = eps;\n A1 = (A1.*(Nom./( repmat((A2*X*ones(T,1))',m,1) + eps)).^(1/alpha) ).^(1 + alphaSa);\n A1 = A1*diag(1./sum(A1,1));\n \n Nom = A1'*((Y./(A1*A2*X + eps)).^alpha )*X';\n Nom(Nom <= 0) = eps;\n A2 = (A2.*(Nom./(A1'*ones(m,1)*ones(1,T)*X' + eps)).^(1/alpha) ).^(1 + alphaSa);\n A2 = A2*diag(1./sum(A2,1));\n \n Nom = (A1*A2)'*(Y./(A1*A2*X + eps)).^alpha;\n Nom(Nom <= 0) = eps;\n X = (X.*(Nom./(repmat((A1*A2)'*ones(m,1),1,T) + eps)).^(1/alpha) ).^(1 + alphaS);\n \n elseif type_alg == 4 % SMART\n \n Ap = A1; \n Nom = ( log(Y./(A1*A2*X + eps) +eps) )*(A2*X)';\n A1 = (A1.*exp( Nom* diag(1./(sum( A2*X,2) +eps) ) ) ).^(1 + alphaSa);\n A1 = A1*diag(1./(sum(A1,1) + eps));\n \n Nom = A1'*( log(Y./(A1*A2*X + eps) + eps) )*X';\n A2 = (A2.*exp( diag(1./(sum( A1,1) + eps) )*Nom*diag(1./(sum( X,2) + eps) ) ) ).^(1 + alphaSa);\n A2 = A2*diag(1./(sum(A2,1) + eps));\n \n Nom = (A1*A2)'*log(Y./(A1*A2*X + eps) + eps);\n X = (X.*exp(diag(1./(sum( A1*A2,1) + eps) )*Nom ) ).^(1 + alphaS);\n \n \n end % type_alg\n \n \n else\n \n if type_alg == 1 % KL\n Ap = A1;\n for t = 1:no_iter \n Nom = (Y./(A1*A2*X + eps))*(A2*X)' - alphaA1;\n Nom(Nom <= 0) = eps;\n A1 = (A1.*(Nom./( repmat((A2*X*ones(T,1))',m,1) + eps))).^(1 + alphaSa);\n A1 = A1*diag(1./sum(A1,1));\n \n end\n for t = 1:no_iter \n Nom = A1'*(Y./(A1*A2*X + eps))*X' - alphaA2;\n Nom(Nom <= 0) = eps;\n A2 = (A2.*(Nom./(A1'*ones(m,1)*ones(1,T)*X' + eps))).^(1 + alphaSa);\n A2 = A2*diag(1./sum(A2,1));\n end\n for t = 1:no_iter \n Nom = (A1*A2)'*(Y./(A1*A2*X + eps)) - alphaX;\n Nom(Nom <= 0) = eps;\n X = (X.*(Nom./(repmat((A1*A2)'*ones(m,1),1,T) + eps))).^(1 + alphaS);\n end\n \n elseif type_alg == 2 % Frobenius\n Ap = A1;\n for t = 1:no_iter \n Nom = Y*(A2*X)' - alphaA1;\n Nom(Nom <= 0) = eps;\n A1 = (A1.*(Nom./(A1*A2*X*(A2*X)' + eps))).^(1 + alphaSa);\n A1 = A1*diag(1./sum(A1,1));\n end\n for t = 1:no_iter \n Nom = A1'*Y*X' - alphaA2;\n Nom(Nom <= 0) = eps;\n A2 = (A2.*(Nom./(A1'*A1*A2*X*X' + eps))).^(1 + alphaSa);\n A2 = A2*diag(1./sum(A2,1));\n end\n for t = 1:no_iter \n Nom = (A1*A2)'*Y - alphaX;\n Nom(Nom <= 0) = eps;\n X = (X.*(Nom./((A1*A2)'*A1*A2*X + eps))).^(1 + alphaS);\n end\n \n elseif type_alg == 3 % Amari alpha-divergence\n Ap = A1;\n for t = 1:no_iter \n Nom = ((Y./(A1*A2*X + eps)).^alpha )*(A2*X)';\n Nom(Nom <= 0) = eps;\n A1 = (A1.*(Nom./( repmat((A2*X*ones(T,1))',m,1) + eps)).^(1/alpha) ).^(1 + alphaSa);\n A1 = A1*diag(1./sum(A1,1));\n end\n for t = 1:no_iter \n Nom = A1'*((Y./(A1*A2*X + eps)).^alpha )*X';\n Nom(Nom <= 0) = eps;\n A2 = (A2.*(Nom./(A1'*ones(m,1)*ones(1,T)*X' + eps)).^(1/alpha) ).^(1 + alphaSa);\n A2 = A2*diag(1./sum(A2,1));\n end\n for t = 1:no_iter \n Nom = (A1*A2)'*(Y./(A1*A2*X + eps)).^alpha;\n Nom(Nom <= 0) = eps;\n X = (X.*(Nom./(repmat((A1*A2)'*ones(m,1),1,T) + eps)).^(1/alpha) ).^(1 + alphaS);\n end\n \n elseif type_alg == 4 % SMART\n Ap = A1;\n for t = 1:no_iter \n Nom = ( log(Y./(A1*A2*X + eps) +eps) )*(A2*X)';\n Nom(Nom <= 0) = eps;\n A1 = (A1.*exp( Nom* diag(1./(sum( A2*X,2) +eps) ) ) ).^(1 + alphaSa);\n A1 = A1*diag(1./(sum(A1,1) + eps));\n end\n for t = 1:no_iter \n Nom = A1'*( log(Y./(A1*A2*X + eps) + eps) )*X';\n Nom(Nom <= 0) = eps;\n A2 = (A2.*exp( diag(1./(sum( A1,1) + eps) )*Nom*diag(1./(sum( X,2) + eps) ) ) ).^(1 + alphaSa);\n A2 = A2*diag(1./(sum(A2,1) + eps));\n end\n for t = 1:no_iter \n Nom = (A1*A2)'*log(Y./(A1*A2*X + eps) + eps);\n Nom(Nom <= 0) = eps;\n X = (X.*exp(diag(1./(sum( A1*A2,1) + eps) )*Nom ) ).^(1 + alphaS);\n end \n \n end % type_alg\n \n end % if no_iter\n \n\n \n if (nr == max_restart)&(mod(k,50)==0)& (~mc_on | restart_mc_on)\n norm_A = norm(abs(A1 - Ap),'fro');\n fprintf(1, 'Restart %d, %d-th alternating step\\n',nr_best+1,k);\n end\n \n if sum(Index_norm)\n if (nr == max_restart) & (((k < 50) & (mod(k,5)==0)) | ((k>49) & ((mod(k,50)==0)))) \n \n s_dist = s_dist + 1;\n k_select(s_dist) = k;\n Z = A1*A2*X + eps;\n Z = diag(1./(sqrt(var(Z')) + eps))*Z;\n \n dist_Fro(s_dist) = norm(Y - Z,'fro'); \n dist_KL(s_dist) = sum(sum(Y.*log(Y./Z + eps) - Y + Z)); \n dist_KL2(s_dist) = sum(sum(Z.*log(Z./Y + eps) + Y - Z)); \n dist_Pearson(s_dist) = sum(sum( ((Y - Z).^2)./Z ));\n dist_Hellinger(s_dist) = sum(sum( (sqrt(Z) - sqrt(Y)).^2 )); \n dist_JS_rel(s_dist) = sum(sum(2*Y.*log(2*Y./(Y + Z) + eps) + Z - Y)); \n dist_JS_rel2(s_dist) = sum(sum(2*Z.*log(2*Z./(Y + Z) + eps) - Z + Y)); \n Zy = Y + Z; \n dist_JS(s_dist) = sum(sum(Y.*log(2*Y./Zy + eps) + Z.*log(2*Z./Zy + eps) )); \n dist_AG_rel(s_dist) = sum(sum(Zy.*log(.5*Zy./Y + eps) + Y - Z)); \n dist_AG(s_dist) = sum(sum(.5*Zy.*log(.5*Zy./sqrt(Y.*Z) + eps))); \n dist_J(s_dist) = sum(sum( .5*(Y - Z).*log(Y./Z + eps) )); \n dist_Chi(s_dist) = sum(sum( ((Y + Z).*(Y - Z).^2)./(Y.*Z) )); \n dist_Tria(s_dist) = sum(sum( ((Y - Z).^2)./(Y + Z) )); \n end % if multiple\n end % if sum\n \n \nend % while (k)\n \n% Outer KL divergence\nZ = AL*A1*A2*X; \nZ_outer = norm(Z,'fro') + eps;\nKL_outer = sum(sum(Y_true.*log((Y_true + eps)./(Z + eps)) - Y_true + Z))/Z_outer;\n \n if (nr == 0) | (KL_outer < KL_outer_temp)\n A1_best = A1; A2_best = A2; X_best = X; KL_outer_temp = KL_outer; nr_best = nr;\n end % multi-conditions\n \n nr = nr + 1;\n \n if nr <=max_restart\n fprintf(1, 'Restart %d, Kullback-Leibler divergence = %e\\n',\tnr, KL_outer);\n end\n \nend % while (restarts)\n\n% One-Variance scaling\nX(X <= 0) = eps;\nA = A1*A2;\n\nDistance_output = cell(length(s_dist),1);\nDistance_output(1) = {[]};\nDistance_output(2) = {[]};\nDistance_output(3) = {[]};\nDistance_output(4) = {[]};\nDistance_output(5) = {[]};\nDistance_output(6) = {[]};\nDistance_output(7) = {[]};\nDistance_output(8) = {[]};\nDistance_output(9) = {[]};\nDistance_output(10) = {[]};\nDistance_output(11) = {[]};\nDistance_output(12) = {[]};\nDistance_output(13) = {[]};\nDistance_output(14) = {[]};\n\nif sum(Index_norm)\n Distance_output(1) = {k_select}; \n Distance_output(2) = {dist_Fro};\n Distance_output(3) = {dist_KL};\n Distance_output(4) = {dist_KL2};\n Distance_output(5) = {dist_Pearson};\n Distance_output(6) = {dist_Hellinger};\n Distance_output(7) = {dist_JS_rel};\n Distance_output(8) = {dist_JS_rel2};\n Distance_output(9) = {dist_JS};\n Distance_output(10) = {dist_AG_rel};\n Distance_output(11) = {dist_AG};\n Distance_output(12) = {dist_J};\n Distance_output(13) = {dist_Chi};\n Distance_output(14) = {dist_Tria};\nend\n\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/NMFLABSP_ver1.2/nmf_cascade.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4734740965437591}}
{"text": "function Mh = oprBuilderHmx(opr,k,Xunk,Mx,X,Xnrm,Yunk,My,Y,Ynrm,tol)\n%+========================================================================+\n%| |\n%| OPENOPR - LIBRARY FOR SPECIFIC OPERATORS IN BEM |\n%| openOpr is part of the GYPSILAB toolbox for Matlab |\n%| |\n%| COPYRIGHT : Matthieu Aussal (c) 2017-2019. |\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 : oprBuilderHmx.m |\n%| # | VERSION : 0.61 |\n%| _#_ | AUTHOR(S) : Matthieu Aussal |\n%| ( # ) | CREATION : 14.03.2017 |\n%| / 0 \\ | LAST MODIF : 05.09.2018 |\n%| ( === ) | SYNOPSIS : Finite element builder with low-rank |\n%| `---' | approximation for handle function |\n%+========================================================================+\n\n% Initialize H-Matrix\nMh = hmx(Xunk,Yunk,tol);\n\n% Admissibility\n[isfar,Xdim,Ydim] = hmxFar(Mh);\n\n% Compression for far distances\nif isfar\n % ACA compression for quadrature matrix\n if strcmp(opr,'nxK')\n [A,B,flag] = oprACAv(opr,k,X,Xnrm,Y,Ynrm,tol);\n else\n [A,B,flag] = oprACA(opr,k,X,Xnrm,Y,Ynrm,tol);\n end\n\n % Finite element integration\n if flag\n % Integration \n if strcmp(opr,'H') || strcmp(opr,'T')\n for n = 1:length(Mx)\n Mx{n} = Mx{n} * A;\n My{n} = B * My{n};\n end\n A = cell2mat(Mx);\n B = cell2mat(My');\n elseif strcmp(opr,'nxK') \n A = [ Mx{1}*A(:,:,2) , - Mx{1}*A(:,:,3) , ...\n Mx{2}*A(:,:,3) , - Mx{2}*A(:,:,1) , ...\n Mx{3}*A(:,:,1) , - Mx{3}*A(:,:,2) ] ;\n B = [ B(:,:,2)*My{3} ; B(:,:,3)*My{2} ; ...\n B(:,:,3)*My{1} ; B(:,:,1)*My{3} ; ...\n B(:,:,1)*My{2} ; B(:,:,2)*My{1} ] ;\n else\n A = Mx * A;\n B = B * My;\n end\n \n % Recompression\n [A,B] = hmxQRSVD(A,B,tol);\n end\n \nelse\n flag = 0;\nend\n\n \n%%% Compression\nif flag\n % Type\n Mh.typ = 1;\n \n % Low-rank\n Mh.dat = {A,B};\n\n\n%%%% Full or sparse for smallest box (stopping criterion)\nelseif (min(size(Mh)) < 100)\n % Type\n Mh.typ = 2;\n \n % Quadrature matrix\n if strcmp(opr,'nxK')\n Gxy = zeros(size(X,1),size(Y,1),3);\n for j = 1:size(Gxy,2)\n Gxy(:,j,:) = oprGreenKernel(opr,k,X,Xnrm,Y(j,:),Ynrm(j,:));\n end\n else\n Gxy = zeros(size(X,1),size(Y,1));\n for j = 1:size(Gxy,2)\n Gxy(:,j) = oprGreenKernel(opr,k,X,Xnrm,Y(j,:),Ynrm(j,:));\n end\n end\n \n % Finite element integration \n if strcmp(opr,'H') || strcmp(opr,'T')\n Mh.dat = zeros(size(Mh));\n for n = 1:length(Mx)\n Mh.dat = Mh.dat + Mx{n} * Gxy * My{n};\n end\n elseif strcmp(opr,'nxK')\n Mh.dat = Mx{1} * Gxy(:,:,2) * My{3} - Mx{1} * Gxy(:,:,3) * My{2} + ...\n Mx{2} * Gxy(:,:,3) * My{1} - Mx{2} * Gxy(:,:,1) * My{3} + ...\n Mx{3} * Gxy(:,:,1) * My{2} - Mx{3} * Gxy(:,:,2) * My{1} ;\n else\n Mh.dat = Mx * Gxy * My;\n end\n \n \n%%% H-Matrix (recursion)\nelse\n % Type\n Mh.typ = 0;\n \n % Subdivision for X\n [I1,I2] = hmxSubdivide(Xunk,Xdim);\n Mh.row = {I1 , I1 , I2 , I2};\n \n % Subdivision for Y\n [I1,I2] = hmxSubdivide(Yunk,Ydim);\n Mh.col = {I1 , I2 , I1 , I2};\n\n % H-Matrix (recursion)\n for i = 1:4\n % Dof indices\n Ir = Mh.row{i};\n Ic = Mh.col{i};\n \n % Fem matrix subdivision and quadratures points indices\n [Mxchd,Ix] = oprSubdivideCell(Mx,Ir,'left');\n [Mychd,Iy] = oprSubdivideCell(My,Ic,'right');\n\n % Recursion\n Mh.chd{i} = oprBuilderHmx(opr,k,Xunk(Ir,:),Mxchd,X(Ix,:),Xnrm(Ix,:),...\n Yunk(Ic,:),Mychd,Y(Iy,:),Ynrm(Iy,:),tol);\n end\n \n % Fusion\n Mh = hmxFusion(Mh);\nend\nend\n\n\n% % Add H-Vector\n% Mv(Ix) = Mv(Ix) + tmp\n%\n%\n% % Corrective Matrix-vector product for Stokes Stresslet\n% if strcmp(opr,('Tc'))\n% % H-Matrix (recursion)\n% if (Mh.typ == 0)\n% \n% % Compressed leaf\n% elseif (Mh.typ == 1)\n% TODO\n% % Mv = Mx\\(A*sum(B,2));\n% \n% % Full leaf\n% elseif (Mh.typ == 2)\n% Mv = sum(Gxy*My,2);\n% end\n% end\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/gypsilabModified/openOpr/oprBuilderHmx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.473443294118658}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% PARAMETERS Returns a data structure containing the parameters of the\n% IRB_4600.\n%\n% Author: Arturo Gil. Universidad Miguel Hernļæ½ndez de Elche. \n% email: arturo.gil@umh.es date: 09/01/2012\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Copyright (C) 2012, by Arturo Gil Aparicio\n%\n% This file is part of ARTE (A Robotics Toolbox for Education).\n% \n% ARTE is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% ARTE is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with ARTE. If not, see .\nfunction robot = parameters()\n\nrobot.name= 'abb_IRB_4600';\n\n%Path where everything is stored for this robot\nrobot.path = 'robots/abb/IRB_4600';\n\nrobot.DH.theta= '[q(1) q(2)-pi/2 q(3) q(4) q(5) q(6)+pi]';\nrobot.DH.d='[0.495 0 0 0.960 0 0.135]';\nrobot.DH.a='[0.175 0.9 0.175 0 0 0]';\nrobot.DH.alpha= '[-pi/2 0 -pi/2 pi/2 -pi/2 0]';\nrobot.J=[];\n\n\nrobot.inversekinematic_fn = 'inversekinematic_IRB_4600(robot, T)';\n\n%number of degrees of freedom\nrobot.DOF = 6;\n\n%rotational: 0, translational: 1\nrobot.kind=['R' 'R' 'R' 'R' 'R' 'R'];\n\n%minimum and maximum rotation angle in rad\nrobot.maxangle =[deg2rad(-180) deg2rad(180); %Axis 1, minimum, maximum\n deg2rad(-90) deg2rad(150); %Axis 2, minimum, maximum\n deg2rad(-180) deg2rad(75); %Axis 3\n deg2rad(-400) deg2rad(400); %Axis 4: Unlimited (400ļæ½ default)\n deg2rad(-125) deg2rad(120); %Axis 5\n deg2rad(-400) deg2rad(400)]; %Axis 6: Unlimited (800ļæ½ default)\n\n%maximum absolute speed of each joint rad/s or m/s\nrobot.velmax = [deg2rad(200); %Axis 1, rad/s\n deg2rad(200); %Axis 2, rad/s\n deg2rad(260); %Axis 3, rad/s\n deg2rad(360); %Axis 4, rad/s\n deg2rad(360); %Axis 5, rad/s\n deg2rad(450)];%Axis 6, rad/s\n\nrobot.accelmax=robot.velmax/0.1; % 0.1 is here an acceleration time\n \n % end effectors maximum velocity\nrobot.linear_velmax = 2.5; %m/s\n\n%base reference system\nrobot.T0 = eye(4);\n\n%INITIALIZATION OF VARIABLES REQUIRED FOR THE SIMULATION\n%position, velocity and acceleration\nrobot=init_sim_variables(robot);\n\n% GRAPHICS\nrobot.graphical.has_graphics=1;\nrobot.graphical.color = [255 20 40]./255;\n%for transparency\nrobot.graphical.draw_transparent=0;\n%draw DH systems\nrobot.graphical.draw_axes=1;\n%DH system length and Font size, standard is 1/10. Select 2/20, 3/30 for\n%bigger robots\nrobot.graphical.axes_scale=1;\n%adjust for a default view of the robot\nrobot.axis=[-0.75 0.75 -0.75 0.75 0 1.2];\n%read graphics files\nrobot = read_graphics(robot);\n\n%DYNAMICS\nrobot.has_dynamics=0;", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/robots/ABB/IRB4600/parameters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.4731351335071294}}
{"text": "function getVoxelHull(obj, voxelSize, varargin)\n% GETVOXELHULL Compute the voxel hull of a point cloud.\n% ------------------------------------------------------------------------------\n% DESCRIPTION/NOTES\n% * The voxel hull is a low resolution representation of the volume occupied by\n% a point cloud. For the computation of the voxel hull the object space is\n% subdivided into a voxel structure. The voxel hull of the point cloud\n% consists of all voxels which contain at least one point of the point cloud.\n%\n% * Only active points are considered for the computation of the voxel hull.\n%\n% * The voxel hull can be used to select points, which are overlapping with\n% another point cloud. An example for this task is given in the documentation\n% of the 'select' method. For this call 'help pointCloud.select' and see the\n% examples for the 'InVoxelHull' selection strategy.\n% ------------------------------------------------------------------------------\n% INPUT\n% 1 [voxelSize]\n% Voxel size (equal to edge length) of a single voxel.\n% ------------------------------------------------------------------------------\n% OUTPUT\n% 1 [obj]\n% The voxel hull is attached to the following properties of the ouput object:\n% * obj.voxelHull = n-by-3 matrix containing the x, y, z coordinates \n% of the centers of the voxels\n% * obj.voxelHullVoxelSize = edge length of voxels (given by parameter\n% voxelSize)\n% ------------------------------------------------------------------------------\n% EXAMPLES\n% 1 Import a point cloud and compute its voxel hull.\n% pc = pointCloud('Lion.xyz');\n% pc.getVoxelHull(5); % voxel size is 5mm\n% % The voxel hull can now be found in pc.voxelHull and pc.voxelHullVoxelSize \n% ------------------------------------------------------------------------------\n% philipp.glira@gmail.com\n% ------------------------------------------------------------------------------\n\n% Input parsing ----------------------------------------------------------------\n\np = inputParser;\np.addRequired('voxelSize', @(x) isscalar(x) && x>0);\n% Undocumented\np.addParameter('Centroids', false, @islogical);\np.parse(voxelSize, varargin{:});\np = p.Results;\n% Clear required inputs to avoid confusion\nclear voxelSize\n\n% Start ------------------------------------------------------------------------\n\nprocHierarchy = {'POINTCLOUD' 'GETVOXELHULL'};\nmsg('S', procHierarchy);\nmsg('I', procHierarchy, sprintf('Point cloud label = ''%s''', obj.label));\n \n% Compute voxel hull -----------------------------------------------------------\n\n% Lower left point of activated points\nlim.min = min(obj.X(obj.act,:), [], 1);\n% Round origin (voxel hulls have coincident voxel centers if mod(100, p.voxelSize) == 0)\nlim.min = (floor(lim.min/100))*100;\n\n% Indices of voxel cells in x, y and z direction (indices start with 0!)\nidxXYZ = [floor( (obj.X(obj.act,1) - lim.min(1)) / p.voxelSize ) ...\n floor( (obj.X(obj.act,2) - lim.min(2)) / p.voxelSize ) ...\n floor( (obj.X(obj.act,3) - lim.min(3)) / p.voxelSize )];\n\n% Remove multiple points to get unique voxels\n[voxel, ~, ic] = unique(idxXYZ, 'rows'); % ic for centroids\n\n% Transformation of indices to coordinate system and save to object\nobj.voxelHull = [lim.min(1) + p.voxelSize/2 + voxel(:,1) * p.voxelSize ...\n lim.min(2) + p.voxelSize/2 + voxel(:,2) * p.voxelSize ...\n lim.min(3) + p.voxelSize/2 + voxel(:,3) * p.voxelSize];\n\n% Round voxel hull (because e.g. -100+0.025+1982*0.05 ~= -0.875)\nif p.voxelSize < 1\n noDigits = abs(floor(log10(p.voxelSize)-1)) + 2; % e.g. for 0.05 -> noDigits = 3+2 = 5 (+2 is arbitrary choice to be on the safe side)\n obj.voxelHull = round(obj.voxelHull, noDigits);\nend\n \n% Save voxel size to object\nobj.voxelHullVoxelSize = p.voxelSize;\n\n% Calculate centroids within each voxel ----------------------------------------\n\nif p.Centroids\n \n % Add centroid matrix\n obj.voxelHull = [obj.voxelHull zeros(size(voxel,1),3)];\n \n % Centroid for each voxel\n % Var1\n % tic;\n % for i = 1:size(voxel,1), obj.voxelHull(i,4:6) = mean(obj.X(ic == i,:),1); end\n % toc;\n % c1 = obj.voxelHull(:,4:6);\n \n % Var2\n % tic;\n % cellX = cell(size(voxel,1),1);\n % for i = 1:size(voxel,1), cellX{i,1} = obj.X(ic == i,:); end\n % cellMean = cellfun(@(x) mean(x,1), cellX, 'UniformOutput', false);\n % obj.voxelHull(:,4:6) = vertcat(cellMean{:});\n % toc;\n % c2 = obj.voxelHull(:,4:6);\n \n % Var3\n % tic;\n % cellMean = arrayfun(@(x) mean(obj.X(ic == x,:),1), [1:size(voxel,1)]', 'UniformOutput', false);\n % obj.voxelHull(:,4:6) = vertcat(cellMean{:});\n % toc;\n % c3 = obj.voxelHull(:,4:6);\n \n % Var4\n % tic;\n [~, idx] = sort(ic);\n Xs = obj.X(idx,:);\n rowDist = diff(find([1; diff(ic(idx)); 1]));\n cellX = mat2cell(Xs, rowDist);\n cellMean = cellfun(@(x) mean(x,1), cellX, 'UniformOutput', false);\n obj.voxelHull(:,4:6) = vertcat(cellMean{:});\n % toc;\n % c4 = obj.voxelHull(:,4:6);\n \nend\n \n% End --------------------------------------------------------------------------\n\nmsg('E', {'POINTCLOUD' 'GETVOXELHULL'});\n\nend", "meta": {"author": "pglira", "repo": "Point_cloud_tools_for_Matlab", "sha": "4768f45e7d3527c52e911eb0450c31ca19b58f72", "save_path": "github-repos/MATLAB/pglira-Point_cloud_tools_for_Matlab", "path": "github-repos/MATLAB/pglira-Point_cloud_tools_for_Matlab/Point_cloud_tools_for_Matlab-4768f45e7d3527c52e911eb0450c31ca19b58f72/classes/@pointCloud/getVoxelHull.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4730586493816609}}
{"text": "% Runs a step of non-local Bayes\n%\n% USAGE: [deno, aggw] = nlbayes_step(nisy, bsic, sigma, prms)\n%\n% -> nisy : noisy image\n% -> bsic : basic estimate (can be empty for the first step)\n% -> sigma : noise std. dev.\n% -> prms : struc with prms (wx, px, np, r)\n%\n% <- deno : denoised image\n% <- aggw : aggregation weights\nfunction [deno, aggw] = nlbayes_step(nisy, bsic, sigma, prms)\n\n% image size and channels\nw = size(nisy,2);\nh = size(nisy,1);\nchnls = size(nisy,3);\n\n% in the absence of the basic estimate, define basic as the noisy image\nif isempty(bsic),\n\tbsic = nisy;\n\tstep2 = false;\nelse\n\tstep2 = true\nend\n\n% aggregation\naggw = zeros(size(nisy)); % aggregation weights\naggp = zeros(size(nisy)); % mask of already processed patches (for speed-up trick)\naggu = zeros(size(nisy)); % aggregated image\ndeno = zeros(size(nisy)); % denoised image (deno = aggu ./ aggw);\n\n% step sizes\nstepx = floor(prms.px/2);\nstepy = floor(prms.px/2);\nii = 0; % iteration counter\n\n% patch dimensionality\npdim = prms.px * prms.px * chnls;\n\n% use dct basis\n% U = kron(eye(chnls), dct_basis(prms.px, prms.px));\n% use pca basis\nU = [];\n\n% use an aggregation window\nif prms.pw,\n\twx = chebwin(prms.px);\nelse\n\twx = ones(prms.px,1);\nend\nwwx = repmat(reshape(wx*wx',[prms.px*prms.px 1]),[chnls prms.np]);\n\n% main loop\nfor pay = [1:stepy:h - prms.px+1,h - prms.px+1],\nfor pax = [1:stepx:w - prms.px+1,w - prms.px+1], ii = ii + 1;\n\n\t% acceleration: skip iteration if patch has been been already denoised\n\tif aggp(pay,pax,1),\n\t\tcontinue;\n\tend\n\n\t% -------------------------------------------------- compute patch group\n\n\t% patches in search region\n\tsrch_region = bsic(max(1,pay - prms.wx):min(h,pay + prms.wx + prms.px - 1),...\n\t max(1,pax - prms.wx):min(w,pax + prms.wx + prms.px - 1),:);\n\n\tsrch_patches = im2col_ch(srch_region, [prms.px prms.px]);\n\trefe_patch = bsic(pay:pay+prms.px-1,pax:pax+prms.px-1,:);\n\n\t[distances, idx] = sort(L2_distance(refe_patch(:), srch_patches));\n\n\t% coordinates of the np nearest neighbors to the ref patch\n\tidx = idx(1:prms.np)';\n\n\tsrch_h = size(srch_region,1) - prms.px + 1;\n\tpatches.coords = [max(1,pax - prms.wx) + floor((idx-1)/srch_h),...\n\t max(1,pay - prms.wx) + mod( idx-1 ,srch_h)];\n\n\n\t% ---------------------------------------------- extract similar patches\n\tif step2,\n\t\tpatches.bsic = srch_patches(:,idx);\n\n\t\t% extract noisy patches\n\t\tsrch_region = nisy(max(1,pay - prms.wx):min(h,pay + prms.wx + prms.px - 1),...\n\t\t max(1,pax - prms.wx):min(w,pax + prms.wx + prms.px - 1),:);\n\t\tpatches.nisy = im2col_ch(srch_region, [prms.px prms.px]);\n\t\tpatches.nisy = patches.nisy(:,idx);\n\telse\n\t\tpatches.nisy = srch_patches(:,idx);\n\tend\n\n\n\t% ----------------------------------------------- compute bayes estimate\n\tif step2,\n\t\taa = reshape(patches.bsic,[pdim prms.np]);\n\t\t[dd,gg] = compute_bayes_estimate(patches.nisy,aa,sigma,prms.r,'pos',U);\n\telse\n\t\t[dd,gg] = compute_bayes_estimate(patches.nisy,[],sigma,prms.r,'pos',U);\n\tend\n\n\t% ------------------------------------------- aggregate patches on image\n\tgg = ones(size(dd,1),1)*gg;\n\taggu = aggregate_patches(aggu, wwx.*gg.*dd, [prms.px prms.px], patches.coords);\n\taggw = aggregate_patches(aggw, wwx.*gg , [prms.px prms.px], patches.coords);\n\n\taggp(patches.coords(:,2) + (patches.coords(:,1)-1)*h) = 1+...\n\t aggp(patches.coords(:,2) + (patches.coords(:,1)-1)*h);\n\n\t% draw\n\tif (mod(ii,50) == 1)\n\t\tnonzero = find(aggw ~= 0);\n\t\tdeno(nonzero) = min(255, max(0, aggu(nonzero) ./ aggw(nonzero)));\n\n\t\t% draw a red box indicating limits of search region\n\t\tdeno(max(1,pay-prms.wx):min(h,pay+prms.wx),max(1,pax-prms.wx),:) = 0;\n\t\tdeno(max(1,pay-prms.wx):min(h,pay+prms.wx),min(w,pax+prms.wx),:) = 0;\n\t\tdeno(max(1,pay-prms.wx),max(1,pax-prms.wx):min(w,pax+prms.wx),:) = 0;\n\t\tdeno(min(h,pay+prms.wx),max(1,pax-prms.wx):min(w,pax+prms.wx),:) = 0;\n\t\tdeno(max(1,pay-prms.wx):min(h,pay+prms.wx),max(1,pax-prms.wx),1) = 255;\n\t\tdeno(max(1,pay-prms.wx):min(h,pay+prms.wx),min(w,pax+prms.wx),1) = 255;\n\t\tdeno(max(1,pay-prms.wx),max(1,pax-prms.wx):min(w,pax+prms.wx),1) = 255;\n\t\tdeno(min(h,pay+prms.wx),max(1,pax-prms.wx):min(w,pax+prms.wx),1) = 255;\n\n\t\timagesc(max(min([deno;255-aggw],255),0)/255,[0 1]);\n\t\taxis equal, axis off,\n\t\tcolormap gray\n\t\tdrawnow\n\t\tpause(.01)\n\n\t\t% reset red pixels to 0\n\t\tdeno(max(1,pay-prms.wx):min(h,pay+prms.wx),max(1,pax-prms.wx),1) = 0;\n\t\tdeno(max(1,pay-prms.wx):min(h,pay+prms.wx),min(w,pax+prms.wx),1) = 0;\n\t\tdeno(max(1,pay-prms.wx),max(1,pax-prms.wx):min(w,pax+prms.wx),1) = 0;\n\t\tdeno(min(h,pay+prms.wx),max(1,pax-prms.wx):min(w,pax+prms.wx),1) = 0;\n\tend\n\nend\nend\n\n% compute denoised image\nnonzero = find(aggw ~= 0);\ndeno(nonzero) = min(255, max(0, aggu(nonzero) ./ aggw(nonzero)));\n\nend\n\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/å»åŖē®ę³/nlbayes.m-master/nlbayes_step.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.769080247656264, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4730519202506568}}
{"text": "function [p,f] = spm_powell(p,xi,tolsc,func,varargin)\n% Powell optimisation method\n% FORMAT [p,f] = spm_powell(p,xi,tolsc,func,varargin)\n% p - Starting parameter values\n% xi - columns containing directions in which to begin searching\n% tolsc - stopping criteria, optimisation stops when\n% sqrt(sum(((p-p_prev)./tolsc).^2))<1\n% func - name of evaluated function\n% varargin - remaining arguments to func (after p)\n%\n% p - final parameter estimates\n% f - function value at minimum\n%__________________________________________________________________________\n%\n% Method is based on Powell's optimisation method described in\n% Numerical Recipes (Press, Flannery, Teukolsky & Vetterling).\n%__________________________________________________________________________\n% Copyright (C) 2001-2011 Wellcome Trust Centre for Neuroimaging\n\n% John Ashburner\n% $Id: spm_powell.m 4423 2011-08-04 16:28:51Z guillaume $\n\n\np = p(:);\nf = feval(func,p,varargin{:});\nfor iter=1:512\n %if numel(p)>1, fprintf('iteration %d...\\n', iter); end; %-#\n ibig = numel(p); \n pp = p;\n fp = f;\n del = 0;\n for i=1:length(p)\n ft = f;\n [p,junk,f] = min1d(p,xi(:,i),func,f,tolsc,varargin{:});\n if abs(ft-f) > del,\n del = abs(ft-f);\n ibig = i;\n end\n end\n if numel(p)==1 || sqrt(sum(((p(:)-pp(:))./tolsc(:)).^2))<1, return; end\n ft = feval(func,2.0*p-pp,varargin{:});\n if ft < f\n [p,xi(:,ibig),f] = min1d(p,p-pp,func,f,tolsc,varargin{:});\n end\nend\nwarning('Too many optimisation iterations');\n\n\n%==========================================================================\n% function [p,pi,f] = min1d(p,pi,func,f,tolsc,varargin)\n%==========================================================================\nfunction [p,pi,f] = min1d(p,pi,func,f,tolsc,varargin)\n% Line search for minimum.\n\nglobal lnm % used in funeval\nlnm = struct('p',p,'pi',pi,'func',func,'args',[]);\nlnm.args = varargin;\n\nmin1d_plot('Init', 'Line Minimisation','Function','Parameter Value');\nmin1d_plot('Set', 0, f);\n\ntol = 1/sqrt(sum((pi(:)./tolsc(:)).^2));\nt = bracket(f);\n[f,pmin] = search(t,tol);\npi = pi*pmin;\np = p + pi;\n\n%if length(p)<12,\n% for i=1:length(p), fprintf('%-8.4g ', p(i)); end; %-#\n% fprintf('| %.5g\\n', f); %-#\n%else\n% fprintf('%.5g\\n', f); %-#\n%end\nmin1d_plot('Clear');\n\n\n%==========================================================================\n% function f = funeval(p)\n%==========================================================================\nfunction f = funeval(p)\n% Reconstruct parameters and evaluate.\n\nglobal lnm % defined in min1d\npt = lnm.p+p.*lnm.pi;\nf = feval(lnm.func,pt,lnm.args{:});\nmin1d_plot('Set',p,f);\n\n\n%==========================================================================\n% function t = bracket(f)\n%==========================================================================\nfunction t = bracket(f)\n% Bracket the minimum (t(2)) between t(1) and t(3)\n\ngold = (1+sqrt(5))/2; % Golden ratio\n\nt(1) = struct('p',0,'f',f);\nt(2).p = 1;\nt(2).f = funeval(t(2).p);\n\n% if t(2) not better than t(1) then swap\nif t(2).f > t(1).f\n t(3) = t(1);\n t(1) = t(2);\n t(2) = t(3);\nend\n\nt(3).p = t(2).p + gold*(t(2).p-t(1).p);\nt(3).f = funeval(t(3).p);\n\nwhile t(2).f > t(3).f\n\n % fit a polynomial to t\n tmp = cat(1,t.p)-t(2).p;\n pol = pinv([ones(3,1) tmp tmp.^2])*cat(1,t.f);\n\n % minimum is when gradient of polynomial is zero\n % sign of pol(3) (the 2nd deriv) should be +ve\n if pol(3)>0\n % minimum is when gradient of polynomial is zero\n d = -pol(2)/(2*pol(3)+eps);\n\n % A very conservative constraint on the displacement\n if d > (1+gold)*(t(3).p-t(2).p),\n d = (1+gold)*(t(3).p-t(2).p);\n end\n u.p = t(2).p+d;\n else\n % sign of pol(3) (the 2nd deriv) is not +ve\n % so extend out by golden ratio instead\n u.p = t(3).p+gold*(t(3).p-t(2).p);\n end\n\n % FUNCTION EVALUATION\n u.f = funeval(u.p);\n\n if (t(2).p < u.p) == (u.p < t(3).p)\n\n % u is between t(2) and t(3)\n if u.f < t(3).f\n % minimum between t(2) and t(3) - done\n t(1) = t(2);\n t(2) = u;\n return\n elseif u.f > t(2).f\n % minimum between t(1) and u - done\n t(3) = u;\n return;\n end\n end\n\n % Move all 3 points along\n t(1) = t(2);\n t(2) = t(3);\n t(3) = u;\nend\n\n\n%==========================================================================\n% function [f,p] = search(t, tol)\n%==========================================================================\nfunction [f,p] = search(t, tol)\n% Brent's method for line searching - given that minimum is bracketed\n\ngold1 = 1-(sqrt(5)-1)/2;\n\n% Current and previous displacements\nd = Inf;\npd = Inf;\n\n% sort t into best first order\n[junk,ind] = sort(cat(1,t.f));\nt = t(ind);\nbrk = [min(cat(1,t.p)) max(cat(1,t.p))];\n\nfor iter=1:128\n % check stopping criterion\n if abs(t(1).p - 0.5*(brk(1)+brk(2)))+0.5*(brk(2)-brk(1)) <= 2*tol\n p = t(1).p;\n f = t(1).f;\n return;\n end\n\n % keep last two displacents\n ppd = pd;\n pd = d;\n\n % fit a polynomial to t\n tmp = cat(1,t.p)-t(1).p;\n pol = pinv([ones(3,1) tmp tmp.^2])*cat(1,t.f);\n\n % minimum is when gradient of polynomial is zero\n d = -pol(2)/(2*pol(3)+eps);\n u.p = t(1).p+d;\n\n % check so that displacement is less than the last but two,\n % that the displaced point is between the brackets\n % and that the solution is a minimum rather than a maximum\n eps2 = 2*eps*abs(t(1).p)+eps;\n if abs(d) > abs(ppd)/2 || u.p < brk(1)+eps2 || u.p > brk(2)-eps2 || pol(3)<=0\n % if criteria are not met, then golden search into the larger part\n if t(1).p >= 0.5*(brk(1)+brk(2)),\n d = gold1*(brk(1)-t(1).p);\n else\n d = gold1*(brk(2)-t(1).p);\n end\n u.p = t(1).p+d;\n end\n\n % FUNCTION EVALUATION\n u.f = funeval(u.p);\n\n % Insert the new point into the appropriate position and update\n % the brackets if necessary\n if u.f <= t(1).f\n if u.p >= t(1).p, brk(1)=t(1).p; else brk(2)=t(1).p; end\n t(3) = t(2);\n t(2) = t(1);\n t(1) = u;\n else\n if u.p < t(1).p, brk(1)=u.p; else brk(2)=u.p; end\n if u.f <= t(2).f\n t(3) = t(2);\n t(2) = u;\n elseif u.f <= t(3).f\n t(3) = u;\n end\n end\nend\n\n\n%==========================================================================\n% function min1d_plot(action,arg1,arg2,arg3)\n%==========================================================================\nfunction min1d_plot(action,arg1,arg2,arg3)\n% Visual output for line minimisation\npersistent min1dplot\n\nif ~nargin, action = 'Init'; end\n\n% Find the Interactive window and exit if not\n%--------------------------------------------------------------------------\nfg = spm_figure('FindWin','Interactive');\nif isempty(fg), return; end\n\n%-Initialize\n%--------------------------------------------------------------------------\nif strcmpi(action,'init')\n if nargin<4, arg3 = 'Function'; end\n if nargin<3, arg2 = 'Value'; end\n if nargin<2, arg1 = 'Line minimisation'; end\n \n min1dplot = struct('pointer',get(fg,'Pointer'),...\n 'name', get(fg,'Name'),...\n 'ax', [],...\n 'buffer', get(fg,'DoubleBuffer'));\n min1d_plot('Clear');\n set(fg,'Pointer','Watch');\n set(fg,'DoubleBuffer','on');\n min1dplot.ax = axes('Position', [0.15 0.1 0.8 0.75],...\n 'Box', 'on',...\n 'Parent', fg);\n lab = get(min1dplot.ax,'Xlabel');\n set(lab,'string',arg3,'FontSize',10);\n lab = get(min1dplot.ax,'Ylabel');\n set(lab,'string',arg2,'FontSize',10);\n lab = get(min1dplot.ax,'Title');\n set(lab,'string',arg1);\n line('Xdata',[], 'Ydata',[],...\n 'LineWidth',2,'Tag','LinMinPlot',...\n 'LineStyle','-','Marker','o',...\n 'Parent',min1dplot.ax);\n drawnow;\n \n%-Reset\n%--------------------------------------------------------------------------\nelseif strcmpi(action,'set')\n br = findobj(fg,'Tag','LinMinPlot');\n if ~isempty(br)\n [xd,indx] = sort([get(br,'Xdata') arg1]);\n yd = [get(br,'Ydata') arg2];\n yd = yd(indx);\n set(br,'Ydata',yd,'Xdata',xd);\n drawnow;\n end\n \n%-Clear\n%--------------------------------------------------------------------------\nelseif strcmpi(action,'clear')\n fg = spm_figure('FindWin','Interactive');\n if isstruct(min1dplot)\n if ishandle(min1dplot.ax), delete(min1dplot.ax); end\n set(fg,'Pointer',min1dplot.pointer);\n set(fg,'Name',min1dplot.name);\n set(fg,'DoubleBuffer',min1dplot.buffer);\n end\n spm_figure('Clear',fg);\n drawnow;\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/spm12/spm_powell.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.47303467778593833}}
{"text": "function [models] = featureSelectionTime_HN(X,Y,maxOrder,nBoot,Info,censoring,seed)\n% -------------------------------------------------------------------------\n% function [models] = featureSelection(X,Y,maxOrder,nBoot,Info,imbalance,batchNum)\n% -------------------------------------------------------------------------\n% DESCRIPTION: \n% This function computes feature set selection according to the 0.632+ \n% bootstrap methodology for an input matrix of features and and input \n% outcome vector, and for multiple model orders as defined by the user. \n% See ref. [1] for more details. This function uses logistic regression \n% utilities from DREES , and a fast \n% implementation of AUC calculation by Enric JunquƩ de Fortuny that is\n% available at: \n% \n% NOTE: This function now maximizes 0.5*AUC + 0.5*(1-abs(SENSITIVITY-SPECIFICITY))\n% -------------------------------------------------------------------------\n% REFERENCE:\n% [1] Vallieres, M. et al. (2015). A radiomics model from joint FDG-PET and \n% MRI texture features for the prediction of lung metastases in soft-tissue \n% sarcomas of the extremities. Physics in Medicine and Biology, 60(14), \n% 5471-5496. doi:10.1088/0031-9155/60/14/5471\n% -------------------------------------------------------------------------\n% INPUTS:\n% - X: Matrix of size [nInst X nFeat], specifying the numerical data of the \n% features of the input features, where 'nInst' refers to the number \n% of instances in X, and 'nFeat' to the number of features in X. \n% Each column is a different feature.\n% - Y: Column vector of size [nInst X 1] specifying the outcome status \n% (1 or 0) for all instances.\n% - maxOrder: Integer specifying the maximal model order to construct.\n% - nBoot: Number of bootstrap samples to use.\n% - Info: Cell of size [nFeat X 1] of strings specifying the name of each \n% feature in 'X'.\n% - imbalance: String specifying the type of imbalance-adjustement strategy\n% employed. Either 'IABR' for imbalance-adjusted bootstrap\n% resampling (see ref.[1]), or 'IALR' for imbalance-adjusted\n% logistic regression.\n% - batchNum: (optional input). If present, integer that specifies the\n% batch number for parallelization purposes.\n% -------------------------------------------------------------------------\n% OUTPUTS:\n% - models: Structure specifying the resulting multivariable models for the\n% input feature set in 'data', for each model order. Example for\n% order 4:\n% --> models.Order4.Data: Matrix of size [nInst X order], specifying\n% the selected features, in order of\n% selection.\n% --> models.Order4.Name: Cell specifying the names of the selected\n% features, in order of selection.\n% -------------------------------------------------------------------------\n% AUTHOR(S): \n% - Martin Vallieres \n% - DREES development team (logistic regression)\n% - Enric JunquƩ de Fortuny (fastAUC.cpp)\n% -------------------------------------------------------------------------\n% HISTORY:\n% - Creation - May 2015\n% - Revision I - July 2015: including imbalance-adjusted logistic regression \n% - Revision II - July 2015: maximizing 0.5*AUC + 0.5*(1-abs(SENSITIVITY-SPECIFICITY))\n%--------------------------------------------------------------------------\n% STATEMENT:\n% This file is part of , \n% a package providing MATLAB programming tools for radiomics analysis.\n% --> Copyright (C) 2015 Martin Vallieres\n% --> Copyright 2010, Joseph O. Deasy, on behalf of the DREES development team.\n%\n% This package is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This package is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this package. If not, see .\n%\n% _______________________________________________________________\n%\n% --> Copyright (c) 2013, Enric JunquƩ de Fortuny\n% All rights reserved.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are\n% met:\n%\n% * Redistributions of source code must retain the above copyright \n% notice, this list of conditions and the following disclaimer.\n% * Redistributions in binary form must reproduce the above copyright \n% notice, this list of conditions and the following disclaimer in \n% the documentation and/or other materials provided with the distribution\n% \n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE \n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE \n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS \n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN \n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE \n% POSSIBILITY OF SUCH DAMAGE.\n% -------------------------------------------------------------------------\n\n\n% RANDOM NUMBER GENERATOR SEED\nrng(seed);\n\n\n% INITIALIZATION\ntop = 1-1/exp(1);\nlow = 1/exp(1);\nnFeat = size(X,2);\nmodels = struct; % Final model structure\n\n\n% GETTING BOOTSTRAP SAMPLES FOR ALL EXPERIMENTS\nnInst = numel(Y);\ntrainSets = ceil(nInst .* rand(nInst,nBoot));\ntestSets = findBootTestSet(trainSets);\n\n\n% FORWARD FEATURE SELECTION (for all different starters)\nmodelMat = zeros(nFeat,maxOrder);\nmetricMat = zeros(nFeat,maxOrder);\nfor i = 1:nFeat \n indLeft = 1:nFeat;\n % Order 1\n indLeft(i) = [];\n modelMat(i,1) = i;\n Xtrain = X(:,i); \n [Xtrain] = normalizeZeroOne(Xtrain);\n \n % Cox regression code\n CIdata = applyCoxfit(Xtrain,Y,Xtrain,Y,censoring,censoring);\n \n CItemp = 0;\n for n = 1:nBoot\n Xtrain = X(trainSets(:,n),i);Xtest = X(testSets{n},i); Ytrain = Y(trainSets(:,n),1); Ytest = Y(testSets{n},1);\n [Xtrain,Xtest] = normalizeZeroOne(Xtrain,Xtest);\n \n % Cox regression code\n CIboot = applyCoxfit(Xtrain,Ytrain,Xtest,Ytest,censoring(trainSets(:,n)),censoring(testSets{n}));\n \n % FOR CI (concordance index)\n alpha = top/(1-low*(CIdata-CIboot)/(CIdata-0.5+eps));\n if alpha > 1\n alpha = 1;\n elseif alpha < top\n alpha = top;\n end\n if CIboot < 0.5\n CIboot = 0.5;\n end\n CItemp = CItemp + (1-alpha)*CIdata + alpha*CIboot;\n \n end\n CItemp = CItemp/nBoot;\n metricMat(i,1) = CItemp;\n \n % Going for orders 2 to maxOrder\n for j = 2:maxOrder\n maxMetric = 0;\n for k = 1:(nFeat-j+1)\n indexModel = [modelMat(i,1:(j-1)),indLeft(k)];\n Xtrain = X(:,indexModel);\n [Xtrain] = normalizeZeroOne(Xtrain);\n \n % Cox regression code\n CIdata = applyCoxfit(Xtrain,Y,Xtrain,Y,censoring,censoring);\n \n CItemp = 0;\n for n = 1:nBoot\n Xtrain = X(trainSets(:,n),indexModel); Xtest = X(testSets{n},indexModel); Ytrain = Y(trainSets(:,n),1); Ytest = Y(testSets{n},1);\n [Xtrain,Xtest] = normalizeZeroOne(Xtrain,Xtest);\n \n % Cox regression code\n CIboot = applyCoxfit(Xtrain,Ytrain,Xtest,Ytest,censoring(trainSets(:,n)),censoring(testSets{n}));\n \n % FOR CI (concordance index)\n alpha = top/(1-low*(CIdata-CIboot)/(CIdata-0.5+eps));\n if alpha > 1\n alpha = 1;\n elseif alpha < top\n alpha = top;\n end\n if CIboot < 0.5\n CIboot = 0.5;\n end\n CItemp = CItemp + (1-alpha)*CIdata + alpha*CIboot;\n \n end\n CItemp = CItemp/nBoot;\n metricTemp = CItemp;\n if metricTemp >= maxMetric\n maxMetric = metricTemp;\n index = indLeft(k);\n end\n end\n modelMat(i,j) = index;\n metricMat(i,j) = maxMetric;\n indLeft(find(indLeft==index)) = [];\n end\nend\n\n\n% OBTAINING MAXIMUM RESULTS FOR EVERY MODEL ORDER (maximum from all different starters)\n[~,indMax] = max(metricMat);\nfor i = 1:maxOrder\n nameOrder = ['Order',num2str(i)];\n models.(nameOrder).Data = X(:,modelMat(indMax(i),1:i));\n models.(nameOrder).Name = cell(i,1);\n for j = 1:i\n models.(nameOrder).Name{j} = Info{modelMat(indMax(i),j)};\n end\nend\n\nend", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/HN_study/Functions/MULTIVARIABLE_MODELING/featureSelectionTime_HN.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4730346777859383}}
{"text": "function info = muteinf(A, Y, method)\n\tn = size(A,1);\t\n\tZ = [A Y];\t\n\tif(n/10 > 20)\n\t\tnbins = 20;\n\telse\n\t\tnbins = max(floor(n/10),10);\n\tend;\n\tpA = hist(A, nbins);\n\tpA = pA ./ n;\n\t\n\ti = find(pA == 0); % that's a hack!\n\tpA(i) = 0.00001;\n\tif(strcmp(method,'regression'))\n\t\tpY = hist(Y, nbins);\n\t\tpY = pY ./ n;\n\t\tj = find(pY == 0);\n\t\tpY(j) = 0.00001;\t\n\t\t\t\t\t\n\t\trx = abs(max(A) - min(A)) / nbins;\n\t\try = abs(max(Y) - min(Y)) / nbins;\t\n\t\tyl = min(Y);\n\t\tp = zeros(nbins, nbins);\t\n\t\tfor i = 1:nbins\n\t\t\txl = min(A);\n\t\t\tfor j = 1:nbins\n\t\t\t\t%disp(['intervals [' num2str(xl) ',' num2str(xl+rx) '|' num2str(yl) ',' num2str(yl+ry) ']'])\n\t\t\t\tinterval = (xl <= Z(:,1)) & (yl <= Z(:,2));\n\t\t\t\tif(j < nbins)\n\t\t\t\t\tinterval = interval & (Z(:,1) < xl + rx);\n\t\t\t\tend;\n\t\t\t\tif(i < nbins)\n\t\t\t\t\tinterval = interval & (Z(:,2) < yl + ry);\n\t\t\t\tend;\t\t\t\n\t\t\t\t%find(interval)\t\t\t\n\t\t\t\tp(i,j) = length(find(interval));\n\n\t\t\t\tif p(i,j) == 0 % hack!\n\t\t\t\t\tp(i,j) = 0.00001;\n\t\t\t\tend\n\n\t\t\t\txl = xl + rx;\n\t\t\tend;\n\t\t\tyl = yl + ry;\n\t\tend;\t\n\t\tHA = -sum(pA .* log(pA));\n\t\tHY = -sum(pY .* log(pY));\t\t\t\t\t\t\t\t\t\t\t\n\t\tpA = repmat(pA,nbins,1);\n\t\tpY = repmat(pY',1,nbins);\t\n\telse\n\t\tod = size(Y,2);\n\t\tcl = od;\n\t\tif(od == 1)\n\t\t\tpY = [length(find(Y==+1)) length(find(Y==-1))] / n;\t\t\t\n\t\t\tcl = 2;\n\t\telse\n\t\t\tpY = zeros(1,od);\n\t\t\tfor i=1:od\n\t\t\t\tpY(i) = length(find(Y==+1));\n\t\t\tend;\n\t\t\tpY = pY / n;\t\t\t\n\t\tend;\n\t\tp = zeros(cl,nbins);\n\t\trx = abs(max(A) - min(A)) / nbins;\n\t\tfor i = 1:cl\n\t\t\txl = min(A);\n\t\t\tfor j = 1:nbins\t\t\t\t\n\t\t\t\tif(i == 2) & (od == 1)\n\t\t\t\t\tinterval = (xl <= Z(:,1)) & (Z(:,2) == -1);\t\n\t\t\t\telse\n\t\t\t\t\tinterval = (xl <= Z(:,1)) & (Z(:,i+1) == +1);\n\t\t\t\tend;\n\t\t\t\tif(j < nbins)\n\t\t\t\t\tinterval = interval & (Z(:,1) < xl + rx);\n\t\t\t\tend;\t\t\t\t\n\t\t\t\t%find(interval)\t\t\t\n\t\t\t\tp(i,j) = length(find(interval));\n\n\t\t\t\tif p(i,j) == 0 % hack!\n\t\t\t\t\tp(i,j) = 0.00001;\n\t\t\t\tend\n\n\t\t\t\txl = xl + rx;\t\n\t\t\tend;\n\t\tend;\n\t\tHA = -sum(pA .* log(pA));\n\t\tHY = -sum(pY .* log(pY));\n\t\tpA = repmat(pA,cl,1);\n\t\tpY = repmat(pY',1,nbins);\n\tend;\n\tp = p ./ n;\n\t\n\t\n\tinfo = sum(sum(p .* log(p ./ (pA .* pY))));\t\n\tinfo = 2 * info ./ (HA + HY);", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/spider/functions/muteinf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290698, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4729760148263255}}
{"text": "function xf = cfft2(x)\n\n% calculate output size\nin_sz = size(x);\n\n% if both dimensions are odd\nif all(mod(in_sz(1:2), 2) == 1)\n xf = fftshift(fftshift(fft2(x), 1), 2);\nelse\n out_sz = in_sz;\n out_sz(1:2) = out_sz(1:2) + mod(out_sz(1:2)+1,2);\n \n % allocate\n xf = complex(zeros(out_sz, 'single'));\n \n xf(1:in_sz(1),1:in_sz(2),:,:) = fftshift(fftshift(fft2(x), 1), 2);\n \n if out_sz(1) ~= in_sz(1)\n xf(end,:,:,:) = conj(fliplr(xf(1,:,:,:)));\n end\n if out_sz(2) ~= in_sz(2)\n xf(:,end,:,:) = conj(flipud(xf(:,1,:,:)));\n end\nend", "meta": {"author": "martin-danelljan", "repo": "Continuous-ConvOp", "sha": "a79708be1f6f8bd8ec5489281cb37b164bebea83", "save_path": "github-repos/MATLAB/martin-danelljan-Continuous-ConvOp", "path": "github-repos/MATLAB/martin-danelljan-Continuous-ConvOp/Continuous-ConvOp-a79708be1f6f8bd8ec5489281cb37b164bebea83/implementation/cfft2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4728991771261914}}
{"text": "function det = dgbdi ( abd, lda, n, ml, mu, ipvt )\n\n%*****************************************************************************80\n%\n%% DGBDI computes the determinant of a band matrix factored by DGBCO or DGBFA.\n%\n% Discussion:\n%\n% If the inverse is needed, use DGBSL N times.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 June 2005\n%\n% Author:\n%\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Dongarra, Moler, Bunch and Stewart,\n% LINPACK User's Guide,\n% SIAM, (Society for Industrial and Applied Mathematics),\n% 3600 University City Science Center,\n% Philadelphia, PA, 19104-2688.\n% ISBN 0-89871-172-X\n%\n% Parameters:\n%\n% Input, real ABD(LDA,N), the output from DGBCO or DGBFA.\n%\n% Input, integer LDA, the leading dimension of the array ABD.\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, integer ML, MU, the number of diagonals below and above the\n% main diagonal. 0 <= ML < N, 0 <= MU < N.\n%\n% Input, integer IPVT(N), the pivot vector from DGBCO or DGBFA.\n%\n% Output, real DET(2), the determinant of the original matrix.\n% determinant = DET(1) * 10.0**DET(2)\n% with 1.0 <= abs ( DET(1) ) < 10.0 or DET(1) = 0.0.\n%\n ten = 10.0;\n\n m = ml + mu + 1;\n det(1) = 1.0;\n det(2) = 0.0;\n\n for i = 1 : n\n\n if ( ipvt(i) ~= i )\n det(1) = -det(1);\n end\n\n det(1) = abd(m,i) * det(1);\n\n if ( det(1) == 0.0 )\n return\n end\n\n while ( abs ( det(1) ) < 1.0 )\n det(1) = ten * det(1);\n det(2) = det(2) - 1.0;\n end\n\n while ( ten <= abs ( det(1) ) )\n det(1) = det(1) / ten;\n det(2) = det(2) + 1.0;\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linpack_d/dgbdi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.4726800741595297}}
{"text": "function varargout = createSoccerBall()\n%CREATESOCCERBALL Create a 3D mesh representing a soccer ball.\n%\n% It is basically a wrapper of the 'bucky' function in matlab.\n% [V, E, F] = createSoccerBall\n% return vertices, edges and faces that constitute a soccerball\n% V is a 60-by-3 array containing vertex coordinates\n% E is a 90-by-2 array containing indices of neighbor vertices\n% F is a 32-by-1 cell array containing vertex indices of each face\n% Example\n% [v, f] = createSoccerBall;\n% drawMesh(v, f);\n%\n% See also\n% meshes, drawMesh, bucky\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2006-08-09\n% Copyright 2006 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas).\n\n% HISTORY\n% 2007-01-04 remove unused variables, enhance output processing\n% 2010-12-07 clean up edges, uses formatMeshOutput\n\n\n% get vertices and adjacency matrix of the buckyball\n[b, n] = bucky;\n\n% compute edges\n[i, j] = find(b);\ne = [i j];\ne = unique(sort(e, 2), 'rows');\n\n% compute polygons that correspond to each 3D face\nf = minConvexHull(n)';\n\n% format output\nvarargout = formatMeshOutput(nargout, n, e, f);\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_geom3d/meshes3d/createSoccerBall.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6791786991753929, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.4726800741595296}}
{"text": "function [ a1, a2 ] = r8vec2_sort_a ( n, a1, a2 )\n\n%*****************************************************************************80\n%\n%% R8VEC2_SORT_A ascending sorts an R8VEC2.\n%\n% Discussion:\n%\n% An R8VEC2 is two R8VEC's.\n%\n% An R8VEC is a vector of R8 values.\n%\n% Each item to be sorted is a pair (I,J), with the I\n% and J values stored in separate vectors A1 and A2.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 November 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of items of data.\n%\n% Input, real A1(N), A2(N), the data to be sorted.\n%\n% Output, real A1(N), A2(N), the sorted data.\n%\n if ( n <= 1 )\n return\n end\n%\n% Initialize.\n%\n i = 0;\n indx = 0;\n isgn = 0;\n j = 0;\n%\n% Call the external heap sorter.\n%\n while ( 1 )\n\n [ indx, i, j ] = sort_heap_external ( n, indx, isgn );\n%\n% Interchange the I and J objects.\n%\n if ( 0 < indx )\n\n [ a1(i), a1(j) ] = r8_swap ( a1(i), a1(j) );\n [ a2(i), a2(j) ] = r8_swap ( a2(i), a2(j) );\n%\n% Compare the I and J objects.\n%\n elseif ( indx < 0 )\n\n isgn = r8vec2_compare ( n, a1, a2, i, j );\n\n elseif ( indx == 0 )\n\n break\n\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8vec2_sort_a.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.47266582544593694}}
{"text": "function [assignment, cost] = assignmentsuboptimal1(distMatrix)\n\n%ASSIGNMENTSUBOPTIMAL1 Compute suboptimal assignment\n%\t\tASSIGNMENTSUBOPTIMAL1(DISTMATRIX) computes a suboptimal assignment for the\n%\t\tgiven rectangular distance (or weight) matrix, for example the assignment \n%\t\tof tracks (in rows) to observations (in columns). The result is a column \n%\t\tvector containing the assigned column number in each row (or 0 if no \n%\t\tassignment could be done).\n%\n%\t\t[ASSIGNMENT, COST] = ASSIGNMENTSUBOPTIMAL1(DISTMATRIX) returns the \n%\t\tassignment vector and the overall cost. \n%\n%\t\tThe algorithm is designed for distance matrices with many forbidden and \n%\t\tsingly validated assignments, (rows or columns containing only one finite \n%\t\telement). The algorithm first searches the matrix for singly validated \n%\t\tcolumns and rejects all assignments with multiply validated row. \n%\t\tAfterwards, singly validated rows are searched and assignments to\n%\t\tmultiply validated columns are rejected. Then, for each row that\n%\t\tvalidates only with singly validated columns (and the other way around), \n%\t\tthe minimum elements is chosen and the assignment is made. If there are \n%\t\tstill assignments open, the minimum element in the distMatrix is\n%\t\tsearched and the corresponding assignment is made.\n%\n%\t\tIn scenarios without any forbidden assignments, the algorithm reduceds\n%\t\tto the last step is will give the same result as ASSIGNMENTOPTIMAL2. If\n%\t\tthere are only some assignments forbidden, the algorithm will perform\n%\t\tpoorly because singly validated assignments are preferred.\n%\n%\t\tThe last step can still be optimized, see the comments in\n%\t\tASSIGNMENTOPTIMAL2.\n%\n%\t\tWritten by Markus Buehren, www.Lss.uni-stuttgart.de\n%\t\tLast modified 14.12.2004\n\n% initialize\n[nOfRows, nOfColumns] = size(distMatrix);\nnOfValidObservations = zeros(nOfRows,1);\nnOfValidTracks = zeros(1,nOfColumns);\nassignment = zeros(nOfRows,1);\ncost = 0;\n\n% compute number of validations for each track\nfor row=1:nOfRows\n\tnOfValidObservations(row) = length(find(isfinite(distMatrix(row,:))));\nend\n\nif any(nOfValidObservations < nOfColumns)\n\t\n\tif all(nOfValidObservations == 0)\n\t\treturn\n\tend\n\t\n\trepeatSteps = 1;\n\twhile repeatSteps\n\t\t\n\t\trepeatSteps = 0;\n\t\t\n\t\t% step 1: reject assignments of multiply validated tracks to singly validated observations\t\t\n\t\tfor col=1:nOfColumns\n\t\t\tindex = isfinite(distMatrix(:,col));\n\t\t\tnOfValidTracks(col) = length(find(index));\n\t\t\tif any(nOfValidObservations(index) == 1)\n\t\t\t\tindex = index & (nOfValidObservations > 1);\n\t\t\t\tif any(index)\n\t\t\t\t\tdistMatrix(index, col) = inf;\n\t\t\t\t\tnOfValidObservations(index) = nOfValidObservations(index) - 1;\n\t\t\t\t\tnOfValidTracks(col) = nOfValidTracks(col) - length(find(index));\n\t\t\t\t\trepeatSteps = 1;\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\t\n\t\t% step 2: reject assignments of multiply validated observations to singly validated tracks\n\t\tif nOfColumns > 1\n\t\t\tfor row=1:nOfRows\n\t\t\t\tindex = isfinite(distMatrix(row,:));\n\t\t\t\tif any(nOfValidTracks(index) == 1)\n\t\t\t\t\tindex = index & (nOfValidTracks > 1);\n\t\t\t\t\tif any(index)\n\t\t\t\t\t\tdistMatrix(row, index) = inf;\n\t\t\t\t\t\tnOfValidTracks(index) = nOfValidTracks(index) - 1;\n\t\t\t\t\t\tnOfValidObservations(row) = nOfValidObservations(row) - length(find(index));\n\t\t\t\t\t\trepeatSteps = 1;\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\t\n\tend % while repeatSteps\n\t%disp(sprintf('xx = %d', xx));\n\n\t% for each multiply validated track that validates only with singly validated \n\t% observations, choose the observation with minimum distance\n\tfor row=1:nOfRows\n\t\tif nOfValidObservations(row) > 1\n\t\t\tindex = isfinite(distMatrix(row,:));\n\t\t\tif all(nOfValidTracks(index) == 1)\n\t\t\t\t[minDist, col] = min(distMatrix(row,:));\n\t\t\t\tassignment(row) = col;\n\t\t\t\tcost = cost + minDist;\n\t\t\t\tdistMatrix(row,:) = inf;\n\t\t\t\tdistMatrix(:,col) = inf;\n\t\t\tend\n\t\tend\n\tend\n\t\n\t% for each multiply validated observation that validates only with singly validated \n\t% track, choose the track with minimum distance\n\tfor col=1:nOfColumns\n\t\tif nOfValidTracks(col) > 1\n\t\t\tindex = isfinite(distMatrix(:,col));\n\t\t\tif all(nOfValidObservations(index) == 1)\n\t\t\t\t[minDist, row] = min(distMatrix(:,col));\n\t\t\t\tassignment(row) = col;\n\t\t\t\tcost = cost + minDist;\n\t\t\t\tdistMatrix(row,:) = inf;\n\t\t\t\tdistMatrix(:,col) = inf;\n\t\t\tend\n\t\tend\n\tend\n\t\nend\n\n% now, recursively search for the minimum element and do the assignment\nwhile 1\n\t\n\t% find minimum distance observation-to-track pair\n\t[minDist, index1] = min(distMatrix, [], 1);\n\t[minDist, index2] = min(minDist);\n\trow = index1(index2);\n\tcol = index2;\n\t\n\tif isfinite(minDist)\n\t\t\n\t\t% make the assignment\n\t\tassignment(row) = col;\n\t\tcost = cost + minDist;\n\t\tdistMatrix(row, :) = inf;\n\t\tdistMatrix(:, col) = inf;\n\t\t\n\telse\n\t\tbreak\n\tend\n\t\nend\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/misc/assignmentsuboptimal1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407017, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.472612089164693}}
{"text": "function c = tapas_hgf_binary_config\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Contains the configuration for the Hierarchical Gaussian Filter (HGF)\n% for binary inputs in the absence of perceptual uncertainty.\n%\n% The HGF is the model introduced in \n%\n% Mathys C, Daunizeau J, Friston, KJ, and Stephan KE. (2011). A Bayesian foundation\n% for individual learning under uncertainty. Frontiers in Human Neuroscience, 5:39.\n%\n% The binary HGF model has since been augmented with a positive factor kappa1 which\n% scales the second level with respect to the first, i.e., the relation between the\n% first and second level is\n%\n% p(x1=1|x2) = s(kappa1*x2), where s(.) is the logistic sigmoid.\n%\n% By default, kappa1 is fixed to 1, leading exactly to the model introduced in\n% Mathys et al. (2011).\n%\n% This file refers to BINARY inputs (Eqs 1-3 in Mathys et al., (2011));\n% for continuous inputs, refer to tapas_hgf_config.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% The HGF configuration consists of the priors of parameters and initial values. All priors are\n% Gaussian in the space where the quantity they refer to is estimated. They are specified by their\n% sufficient statistics: mean and variance (NOT standard deviation).\n% \n% Quantities are estimated in their native space if they are unbounded (e.g., the omegas). They are\n% estimated in log-space if they have a natural lower bound at zero (e.g., the sigmas).\n% \n% Parameters can be fixed (i.e., set to a fixed value) by setting the variance of their prior to\n% zero. Aside from being useful for model comparison, the need for this arises whenever the scale\n% and origin at the j-th level are arbitrary. This is the case if the observation model does not\n% contain the representations mu_j and sigma_j. A choice of scale and origin is then implied by\n% fixing the initial value mu_j_0 of mu_j and either kappa_j-1 or omega_j-1.\n%\n% Fitted trajectories can be plotted by using the command\n%\n% >> tapas_hgf_binary_plotTraj(est)\n% \n% where est is the stucture returned by tapas_fitModel. This structure contains the estimated\n% perceptual parameters in est.p_prc and the estimated trajectories of the agent's\n% representations (cf. Mathys et al., 2011). Their meanings are:\n% \n% est.p_prc.mu_0 row vector of initial values of mu (in ascending order of levels)\n% est.p_prc.sa_0 row vector of initial values of sigma (in ascending order of levels)\n% est.p_prc.rho row vector of rhos (representing drift; in ascending order of levels)\n% est.p_prc.ka row vector of kappas (in ascending order of levels)\n% est.p_prc.om row vector of omegas (in ascending order of levels)\n%\n% Note that the first entry in all of the row vectors will be NaN because, at the first level,\n% these parameters are either determined by the second level (mu_0 and sa_0) or undefined (rho,\n% kappa, and omega).\n%\n% est.traj.mu mu (rows: trials, columns: levels)\n% est.traj.sa sigma (rows: trials, columns: levels)\n% est.traj.muhat prediction of mu (rows: trials, columns: levels)\n% est.traj.sahat precisions of predictions (rows: trials, columns: levels)\n% est.traj.v inferred variance of random walk (rows: trials, columns: levels)\n% est.traj.w weighting factors (rows: trials, columns: levels)\n% est.traj.da volatility prediction errors (rows: trials, columns: levels)\n% est.traj.ud updates with respect to prediction (rows: trials, columns: levels)\n% est.traj.psi precision weights on prediction errors (rows: trials, columns: levels)\n% est.traj.epsi precision-weighted prediction errors (rows: trials, columns: levels)\n% est.traj.wt full weights on prediction errors (at the first level,\n% this is the learning rate) (rows: trials, columns: levels)\n%\n% Note that in the absence of sensory uncertainty (which is the assumption here), the first\n% column of mu, corresponding to the first level, will be equal to the inputs. Likewise, the\n% first column of sa will be 0 always.\n%\n% Tips:\n% - When analyzing a new dataset, take your inputs u and use\n%\n% >> est = tapas_fitModel([], u, 'tapas_hgf_binary_config', 'tapas_bayes_optimal_binary_config');\n%\n% to determine the Bayes optimal perceptual parameters (given your current priors as defined in\n% this file here, so choose them wide and loose to let the inputs influence the result). You can\n% then use the optimal parameters as your new prior means for the perceptual parameters.\n%\n% - If you get an error saying that the prior means are in a region where model assumptions are\n% violated, lower the prior means of the omegas, starting with the highest level and proceeding\n% downwards.\n%\n% - Alternatives are lowering the prior means of the kappas, if they are not fixed, or adjusting\n% the values of the kappas or omegas, if any of them are fixed.\n%\n% - If the log-model evidence cannot be calculated because the Hessian poses problems, look at\n% est.optim.H and fix the parameters that lead to NaNs.\n%\n% - Your guide to all these adjustments is the log-model evidence (LME). Whenever the LME increases\n% by at least 3 across datasets, the adjustment was a good idea and can be justified by just this:\n% the LME increased, so you had a better model.\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2012-2017 Christoph Mathys, TNU, UZH & ETHZ\n%\n% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or .\n\n\n% Config structure\nc = struct;\n\n% Model name\nc.model = 'hgf_binary';\n\n% Number of levels (minimum: 3)\nc.n_levels = 3;\n\n% Input intervals\n% If input intervals are irregular, the last column of the input\n% matrix u has to contain the interval between inputs k-1 and k\n% in the k-th row, and this flag has to be set to true\nc.irregular_intervals = false;\n\n% Sufficient statistics of Gaussian parameter priors\n\n% Initial mus and sigmas\n% Format: row vectors of length n_levels\n% For all but the first two levels, this is usually best\n% kept fixed to 1 (determines origin on x_i-scale). The \n% first level is NaN because it is determined by the second,\n% and the second implies neutrality between outcomes when it\n% is centered at 0.\nc.mu_0mu = [NaN, 0, 1];\nc.mu_0sa = [NaN, 0, 0];\n\nc.logsa_0mu = [NaN, log(0.1), log(1)];\nc.logsa_0sa = [NaN, 0, 0];\n\n% Rhos\n% Format: row vector of length n_levels.\n% Undefined (therefore NaN) at the first level.\n% Fix this to zero to turn off drift.\nc.rhomu = [NaN, 0, 0];\nc.rhosa = [NaN, 0, 0];\n\n% Kappas\n% Format: row vector of length n_levels-1.\n% Fixing log(kappa1) to log(1) leads to the original HGF model.\n% Higher log(kappas) should be fixed (preferably to log(1)) if the\n% observation model does not use mu_i+1 (kappa then determines the\n% scaling of x_i+1).\nc.logkamu = [log(1), log(1)];\nc.logkasa = [ 0, 0];\n\n% Omegas\n% Format: row vector of length n_levels.\n% Undefined (therefore NaN) at the first level.\nc.ommu = [NaN, -3, -6];\nc.omsa = [NaN, 4^2, 4^2];\n\n% Gather prior settings in vectors\nc.priormus = [\n c.mu_0mu,...\n c.logsa_0mu,...\n c.rhomu,...\n c.logkamu,...\n c.ommu,...\n ];\n\nc.priorsas = [\n c.mu_0sa,...\n c.logsa_0sa,...\n c.rhosa,...\n c.logkasa,...\n c.omsa,...\n ];\n\n% Check whether we have the right number of priors\nexpectedLength = 3*c.n_levels+2*(c.n_levels-1)+1;\nif length([c.priormus, c.priorsas]) ~= 2*expectedLength;\n error('tapas:hgf:PriorDefNotMatchingLevels', 'Prior definition does not match number of levels.')\nend\n\n% Model function handle\nc.prc_fun = @tapas_hgf_binary;\n\n% Handle to function that transforms perceptual parameters to their native space\n% from the space they are estimated in\nc.transp_prc_fun = @tapas_hgf_binary_transp;\n\nreturn;\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/HGF/tapas_hgf_binary_config.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4724288077084628}}
{"text": "% LOTKA-VOLTERRA system\n% System identification: DelayDMDc\n\nclear all, close all, clc\nfigpath = '../FIGURES/';\ndatapath = '../DATA/';\naddpath('../utils');\n\nModelName = 'SparseModels';\n%% Generate Data\nInputSignalType = 'sphs';%prbs; chirp; noise; sine2; sphs; mixed\nNdelay = 1;%35;%35;\nONLY_TRAINING_LENGTH = 1;\ngetTrainingData\n\nDataTrain.x = x;\nDataTrain.t = t;\nDataTrain.tspan = tspan;\nDataTrain.u = u;\nDataTrain.xmean = xmean;\nxstd = std(DataTrain.x(:,1));\n\n%% Parameters\nclose all\nrng(0,'twister')\n\neta_vec = [0.01 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5];\nN_ETA = length(eta_vec);\n\nlambda_vec = [0,1e-5,1e-4,1e-3,1e-2,1e-1,1e-0,1e+1];\nN_LAMBDA = length(lambda_vec);\n\nmodel_collection = {'sDMDc','sEDMDc2', 'sEDMDc3','SINDYc'};\nN_MODEL = length(model_collection);\n\nN_REP = 30;\n\noptions_method.sparsify = 'ILSTH'; % 'LASSO'\noptions_method.usesine = 0;\n\nnVars = 2;\n%% Initialization\nTrainingError = inf*ones(N_ETA,N_LAMBDA,N_MODEL,N_REP);\nValidationError = inf*ones(N_ETA,N_LAMBDA,N_MODEL,N_REP);\n\nPredictionResults_Training = zeros(1000,nVars,N_ETA,N_LAMBDA,N_MODEL,N_REP);\nPredictionResults_Validation = zeros(1000,nVars,N_ETA,N_LAMBDA,N_MODEL,N_REP);\n\n%% Model Identification\n\nfor iR = 1:N_REP\n counter = 0;\n \n tstart = tic;\n for iEta = 1:N_ETA\n \n % Add noise to data\n eps = eta_vec(iEta)*xstd;\n x = DataTrain.x + eps*randn(size(DataTrain.x));\n u = DataTrain.u;\n M = length(x);\n \n for iLambda = 1:N_LAMBDA\n lambda = lambda_vec(iLambda);\n \n %% Model Identification\n Hx = getHankelMatrix_MV(x - repmat(DataTrain.xmean,[M 1]),1); % No time delay (=1)\n Hu = getHankelMatrix_MV(u',1);\n \n % sparse DMDc\n options_method.order = 1;\n yout = poolData(Hx',nVars,options_method.order,0);\n Y = yout(1:end-1,2:end)'; % remove constant\n Yp = yout(2:end,2:end)';\n U = Hu(1:end-1);\n sys_DMDc = SparseRegression(Y,Yp,U,dt, options_method, lambda);\n \n % sparse EDMDc\n options_method.order = 2;\n yout = poolData(Hx',nVars,options_method.order,0);\n Y = yout(1:end-1,2:end)'; % remove constant\n Yp = yout(2:end,2:end)';\n U = Hu(1:end-1);\n sys_EDMDc2 = SparseRegression(Y,Yp,U,dt, options_method, lambda);\n \n % sparse EDMDc\n options_method.order = 3;\n yout = poolData(Hx',nVars,options_method.order,0);\n Y = yout(1:end-1,2:end)'; % remove constant\n Yp = yout(2:end,2:end)';\n U = Hu(1:end-1);\n sys_EDMDc3 = SparseRegression(Y,Yp,U,dt, options_method, lambda);\n \n % SINDYc (not xmean-substracted)\n options_method.order = 3;\n Xi = NonlinearSparseRegression(x,u',dt,options_method,lambda);\n \n %% Prediction on training data\n Nt = M-1;\n % sparse DMDc\n options_method.order = 1;\n x0train = poolData(Hx(:,1)',nVars,options_method.order,0)';\n x0train = x0train(2:end);\n [xDMDc,~] = lsim(sys_DMDc,Hu,tspan(1:Nt),x0train);\n xDMDc = xDMDc(:,end-1:end);\n xDMDc = xDMDc + repmat(xmean,[Nt 1]);\n xPredTrain{1}.x = xDMDc;\n \n % sparse EDMDc\n options_method.order = 2;\n x0train = poolData(Hx(:,1)',nVars,options_method.order,0)';\n x0train = x0train(2:end);\n [xEMD2,~] = lsim(sys_EDMDc2,Hu,tspan(1:Nt),x0train);\n xEMD2 = xEMD2(:,1:2);\n xEMD2 = xEMD2 + repmat(xmean,[Nt 1]);\n xPredTrain{2}.x = xEMD2;\n \n % sparse EDMDc\n options_method.order = 3;\n x0train = poolData(Hx(:,1)',nVars,options_method.order,0)';\n x0train = x0train(2:end);\n [xEMD3,~] = lsim(sys_EDMDc3,Hu,tspan(1:Nt),x0train);\n xEMD3 = xEMD3(:,1:2);\n xEMD3 = xEMD3 + repmat(xmean,[Nt 1]);\n xPredTrain{3}.x = xEMD3;\n \n % SINDYc\n p.ahat = Xi(:,1:2);\n p.polyorder = options_method.order; p.usesine = options_method.usesine; p.dt = dt;\n [Ns,N] = size(Hx);\n xSINDYc = zeros(Ns,N); xSINDYc(:,1) = x(1,:)';\n for ct=1:N-1\n xSINDYc(:,ct+1) = rk4u(@sparseGalerkinControl_Discrete,xSINDYc(:,ct),DataTrain.u(ct),dt,1,[],p);\n end\n xSINDYc = xSINDYc';\n xPredTrain{4}.x = xSINDYc;\n \n % Store results\n for iM = 1:N_MODEL\n PredictionResults_Training(:,:,N_ETA,N_LAMBDA,iM,N_REP) = xPredTrain{iM}.x;\n end\n \n % clear ph\n % figure,box on,\n % ccolors = get(gca,'colororder');\n % ph(1) = plot(tspan(1:Nt),x(1:Nt,1),'-','Color','k','LineWidth',1); hold on\n % plot(tspan(1:Nt),x(1:Nt,2),'-','Color','k','LineWidth',1);\n % for iM = 1:N_MODEL\n % for iVar = 1:nVars\n % ph(iM+1) = plot(tspan(1:Nt),xPredTrain{iM}.x(:,iVar),'--','Color',ccolors(iM,:),'LineWidth',1); hold on\n % end\n % end\n % legend(ph,model_collection)\n \n for iM = 1:N_MODEL\n TrainingError(iEta,iLambda,iM,iR) = norm(x(1:Nt,:)-xPredTrain{iM}.x,'fro');\n end\n \n %disp(['Training Error: ', num2str(squeeze(TrainingError(iEta,iLambda,:,iR))')])\n % disp([' DMDc: ', num2str(DMDc_err)])\n % disp([' sparseDMDc: ', num2str(sparseDMDc_err)])\n %% Prediction on validation data\n Nt = M-1;\n % sparse DMDc\n options_method.order = 1;\n x0train = poolData(Hx(:,1)',nVars,options_method.order,0)';\n x0train = x0train(2:end);\n [xDMDc,~] = lsim(sys_DMDc,Hu,tspan(1:Nt),x0train);\n xDMDc = xDMDc(:,end-1:end);\n xDMDc = xDMDc + repmat(xmean,[Nt 1]);\n xPredTrain{1}.x = xDMDc;\n \n % sparse EDMDc\n options_method.order = 2;\n x0train = poolData(Hx(:,1)',nVars,options_method.order,0)';\n x0train = x0train(2:end);\n [xEMD2,~] = lsim(sys_EDMDc2,Hu,tspan(1:Nt),x0train);\n xEMD2 = xEMD2(:,1:2);\n xEMD2 = xEMD2 + repmat(xmean,[Nt 1]);\n xPredTrain{2}.x = xEMD2;\n \n % sparse EDMDc\n options_method.order = 3;\n x0train = poolData(Hx(:,1)',nVars,options_method.order,0)';\n x0train = x0train(2:end);\n [xEMD3,~] = lsim(sys_EDMDc3,Hu,tspan(1:Nt),x0train);\n xEMD3 = xEMD3(:,1:2);\n xEMD3 = xEMD3 + repmat(xmean,[Nt 1]);\n xPredTrain{3}.x = xEMD3;\n \n % SINDYc\n p.ahat = Xi(:,1:2);\n p.polyorder = options_method.order; p.usesine = options_method.usesine; p.dt = dt;\n [Ns,N] = size(Hx);\n xSINDYc = zeros(Ns,N); xSINDYc(:,1) = x(1,:)';\n for ct=1:N-1\n xSINDYc(:,ct+1) = rk4u(@sparseGalerkinControl_Discrete,xSINDYc(:,ct),DataTrain.u(ct),dt,1,[],p);\n end\n xSINDYc = xSINDYc';\n xPredTrain{4}.x = xSINDYc;\n \n % Store results\n for iM = 1:N_MODEL\n PredictionResults_Validation(:,:,N_ETA,N_LAMBDA,iM,N_REP) = xPredTrain{iM}.x;\n end\n \n for iM = 1:N_MODEL\n ValidationError(iEta,iLambda,iM,iR) = norm(x(1:Nt,:)-xPredTrain{iM}.x,'fro');\n end\n \n \n \n counter = counter + 1;\n end\n end\n \n tstop = toc(tstart);\n disp(['STATUS (',num2str(iR),' of ', num2str(N_REP),'): ', num2str(100*counter/(N_ETA*N_LAMBDA)),'%', '[Time=',num2str(tstop),'s]'])\nend\n\n%% STATS\nidxnan = isnan(TrainingError(:));\nmaxerr = max(TrainingError(:));\nTrainingError(idxnan) = maxerr; % change later\nErrStats.mean = zeros(N_ETA,N_LAMBDA,N_MODEL);\nErrStats.median = zeros(N_ETA,N_LAMBDA,N_MODEL);\nErrStats.std = zeros(N_ETA,N_LAMBDA,N_MODEL);\nErrStats.min = zeros(N_ETA,N_LAMBDA,N_MODEL);\nfor iEta = 1:N_ETA\n for iLambda = 1:N_LAMBDA\n for iModel = 1:N_MODEL\n ErrStats.mean(iEta,iLambda,iModel) = mean(TrainingError(iEta,iLambda,iModel,:));\n ErrStats.median(iEta,iLambda,iModel) = median(TrainingError(iEta,iLambda,iModel,:));\n ErrStats.std(iEta,iLambda,iModel) = std(TrainingError(iEta,iLambda,iModel,:));\n ErrStats.min(iEta,iLambda,iModel) = min(TrainingError(iEta,iLambda,iModel,:));\n end\n end\nend\n\n%%\nerr_axis = [min(TrainingError(:)), 1e3];%max(TrainingError(:))\nfigure,\nfor iModel = 1:N_MODEL\n subplot(4,4,(iModel-1)*4+1)\n surf(lambda_vec,eta_vec,ErrStats.median(:,:,iModel)), shading interp\n xlabel('\\lambda'), ylabel('\\eta'), zlabel('median')\n % zlim([0 1e6])\n caxis(err_axis);\n set(gca,'xscale','log')\n view(2)\n \n subplot(4,4,(iModel-1)*4+2)\n surf(lambda_vec,eta_vec,ErrStats.mean(:,:,iModel)) , shading interp\n xlabel('\\lambda'), ylabel('\\eta'), zlabel('mean')\n % zlim([0 1e6])\n caxis(err_axis);\n set(gca,'xscale','log')\n view(2)\n \n subplot(4,4,(iModel-1)*4+3)\n surf(lambda_vec,eta_vec,ErrStats.std(:,:,iModel)) , shading interp\n xlabel('\\lambda'), ylabel('\\eta'), zlabel('std')\n % zlim([0 1e6])\n caxis(err_axis);\n set(gca,'xscale','log')\n view(2)\n \n subplot(4,4,(iModel-1)*4+4)\n surf(lambda_vec,eta_vec,ErrStats.min(:,:,iModel)) , shading interp\n xlabel('\\lambda'), ylabel('\\eta'), zlabel('min')\n % zlim([0 1e6])\n caxis(err_axis);\n set(gca,'xscale','log')\n view(2)\nend\n% for iEta = 1:N_ETA\n% for iLambda = 1:N_LAMBDA\n% plot3()\n% end\n% end\n\n%% TIme series stats\niEta = 1; iLambda = 1; iM = 4;\ndata = squeeze(PredictionResults_Training(:,:,iEta,iLambda,iM,N_REP));\n\nxBmin = min(data(:,1:nVars,:),[],3);\nxBmax = max(data(:,1:nVars,:),[],3);\nclear ph\nfigure('visible','off'),box on, hold on,\nccolors = get(gca,'colororder');\nplot([tB(1),tB(1)],[-25 65],':','Color',[0.4,0.4,0.4],'LineWidth',1.5)\nplot([t(end),t(end)],[-25 65],':','Color',[0.4,0.4,0.4],'LineWidth',1.5)\nylim([-25 65])\nt1 = text(5,55,'Training', 'FontSize',12);\nt2 = text(5+tA(1),55,'Validation', 'FontSize',12);\n\n\nX=[tB(2:end)',fliplr(tB(2:end)')]; %#create continuous x value array for plotting\nY=[xBmin(:,1)',flipud(xBmax(:,1))']; %#create y values for out and then back\nfillh1 = fill(X,Y,ccolors(1,:)-[0 0.2 0.2]); %#plot filled area\nfillh1.EdgeColor = ccolors(1,:)-[0 0.2 0.2]; fillh1.FaceAlpha = 0.5;\n\nX=[tB(2:end)',fliplr(tB(2:end)')]; %#create continuous x value array for plotting\nY=[xBmin(:,2)',flipud(xBmax(:,2))']; %#create y values for out and then back\nfillh = fill(X,Y,ccolors(2,:)-[0.1 0.2 0.09]); %#plot filled area\nfillh.EdgeColor = ccolors(2,:)-[0.1 0.2 0.09]; fillh.FaceAlpha = 0.5;\n\nX=[tB(2:end)',fliplr(tB(2:end)')]; %#create continuous x value array for plotting\nY=[xBmin(:,3)',flipud(xBmax(:,3))']; %#create y values for out and then back\nfillh = fill(X,Y,ccolors(3,:)-[0.1 0.2 0.09]); %#plot filled area\nfillh.EdgeColor = ccolors(3,:)-[0.1 0.2 0.09]; fillh.FaceAlpha = 0.5;\n\n% plot(tB(2:end),xBmin(:,1),'-k','LineWidth',2)\n% plot(tB(2:end),xBmin(:,1),'--g','LineWidth',2)\n\nif eps~=0\n ph(4) = plot(tspan,x(:,1),'-','Color',0.7*ones(1,3),'LineWidth',1); %ccolors(1,:)+[0.15 0.3 0.25]\n plot(tspan,x(:,2),'-','Color',0.7*ones(1,3),'LineWidth',1); %ccolors(2,:)+[0.15 0.3 0.25]\n plot(tspan,x(:,3),'-','Color',0.7*ones(1,3),'LineWidth',1);\n ph(1) = plot([DataTrain.t;tA],[DataTrain.x(:,1);xA(:,1)],'-','Color',ccolors(1,:),'LineWidth',1);\n ph(2) = plot([DataTrain.t;tA],[DataTrain.x(:,2);xA(:,2)],'-','Color',ccolors(2,:),'LineWidth',1);\n ph(3) = plot([DataTrain.t;tA],[DataTrain.x(:,3);xA(:,3)],'-','Color',ccolors(3,:),'LineWidth',1);\nelse\n ph(1) = plot([DataTrain.t;tA],[DataTrain.x(:,1);xA(:,1)],'-','Color',ccolors(1,:),'LineWidth',1);\n ph(2) = plot([DataTrain.t;tA],[DataTrain.x(:,2);xA(:,2)],'-','Color',ccolors(2,:),'LineWidth',1);\n ph(3) = plot([DataTrain.t;tA],[DataTrain.x(:,3);xA(:,3)],'-','Color',ccolors(3,:),'LineWidth',1);\n ph(4) = plot(t,x(:,1),'--','Color',[0 1 0],'LineWidth',1); % Training data\n plot(t,x(:,2),'--','Color',[0 1 0],'LineWidth',1);\n plot(t,x(:,3),'--','Color',[0 1 0],'LineWidth',1);\nend\n\n% ph(4) = plot(tB,xB(:,1),'-.','Color',ccolors(1,:)-[0 0.2 0.2],'LineWidth',2);\n% ph(5) = plot(tB,xB(:,2),'-.','Color',ccolors(2,:)-[0.1 0.2 0.09],'LineWidth',2);\ngrid off\nxlim([0 tv(end)])\nxlabel('Time')\nylabel('xi')\nset(gca,'LineWidth',1, 'FontSize',14)\nset(gcf,'Position',[100 100 300 200])\nset(gcf,'PaperPositionMode','auto');\n\nif eps~=0\n lh = legend([ph([1,4]),fillh1],'Truth','Training',ModelName,'Location','NorthWest');\n % lh.Position = [lh.Position(1)+0.13,lh.Position(2)-0.2,lh.Position(3:4)];\n lh.Position = [lh.Position(1)+0.02,lh.Position(2)-0.06,lh.Position(3:4)];\nelse\n lh = legend(ph([1,4]),'Truth','Training',ModelName,'Location','NorthWest');\n % lh.Position = [lh.Position(1)+0.13,lh.Position(2)-0.2,lh.Position(3:4)];\n lh.Position = [lh.Position(1)+0.02,lh.Position(2)-0.06,lh.Position(3:4)];\nend\n\nprint('-depsc2', '-painters','-loose','-cmyk', [figpath,'EX_',SystemModel,'_SI_',ModelName,'_',InputSignalType,'_Validation_N',sprintf('%04g',Ntrain_vec(iN)),'_Eta',sprintf('%03g',100*eta_vec(iNoise)),'_STATS.eps']);\n\ndelete(lh), delete(t1), delete(t2)\n% print('-depsc2', '-painters','-loose','-cmyk', [figpath,'EX_',SystemModel,'_SI_',ModelName,'_',InputSignalType,'_Validation_N',sprintf('%04g',Ntrain_vec(iN)),'_Eta',sprintf('%03g',100*eta_vec(iNoise)),'_STATS_noleg.eps']);\n\nreturn\n%% Show validation\nclear ph\nfigure,box on,\nccolors = get(gca,'colororder');\nph(1) = plot(tspan,x(:,1),'-','Color','k','LineWidth',1); hold on\nph(2) = plot(tspan,x(:,2),'-','Color','k','LineWidth',1);\nph(3) = plot(tspan(Ndelay:Nt+Ndelay-1),xDMDc(:,1),'--','Color','r','LineWidth',2);\nph(4) = plot(tspan(Ndelay:Nt+Ndelay-1),xDMDc(:,2),'--','Color','r','LineWidth',2);\nph(5) = plot(tspan(Ndelay:Nt+Ndelay-1),xDMDc_sparse(:,1),':','Color','b','LineWidth',2);\nph(6) = plot(tspan(Ndelay:Nt+Ndelay-1),xDMDc_sparse(:,2),':','Color','b','LineWidth',2);\nxlim([0 100]), ylim([0,120]);\nxlabel('Time')\nylabel('Population size')\n% legend('Prey (True)','Predator (True)', 'Prey (DMDc)','Predator (DMDc)')\nlegend(ph([1,3,5]),'True','DMDc',ModelName)\nset(gca,'LineWidth',1, 'FontSize',14)\nset(gcf,'Position',[100 100 300 200])\nset(gcf,'PaperPositionMode','auto')\nprint('-depsc2', '-loose', '-cmyk', [figpath,'EX_LOTKA_SI_',ModelName,'_',InputSignalType,'.eps']);\n\n\nDMDc_err = norm(x(1:end-1,:)-xDMDc,'fro');\nsparseDMDc_err = norm(x(1:end-1,:)-xDMDc_sparse,'fro');\ndisp(['Training Error: '])\ndisp([' DMDc: ', num2str(DMDc_err)])\ndisp([' sparseDMDc: ', num2str(sparseDMDc_err)])\n\n\n%% Prediction\n% Reference\ntspanV = [100:dt:200];\nxA = xv;\ntA = tv;\n\n% Model DMDc\nx0 = [x(end,1:2)];\nHunew = [u(end),uv(1:end)];\n[xB,tB] = lsim(sysmodel_DMDc,Hunew,tspanV,[x0-[xmean]]');\nxB = xB + repmat(xmean,[length(tB) 1]);\n\n% Model sparseDMDc / sparseEDMDc\nif Nstates == 2\n [xB_sparse,tB] = lsim(sysmodel_sparseDMDc,Hunew,tspanV,[x0-[xmean]]');\n xB_sparse = xB_sparse(:,end-1:end);\n xB_sparse = xB_sparse + repmat(xmean,[length(tB) 1]);\nelseif Nstates > 2\n x0dmdc = [x0(1)-xmean(1); x0(2)-xmean(2); (x0(1)-xmean(1)).^2; (x0(1)-xmean(1)).*(x0(2)-xmean(2)); (x0(2)-xmean(2)).^2];\n [xB_sparse,tB] = lsim(sysmodel_sparseDMDc,Hunew,tspanV,x0dmdc);\n xB_sparse = xB_sparse(:,1:2);\n xB_sparse = xB_sparse + repmat(xmean,[length(tB) 1]);\nend\n\n\nDMDc_err = norm(xA-xB(1:end-1,:),2);\nsparseDMDc_err = norm(xA-xB_sparse(1:end-1,:),2);\ndisp(['Validation Error: '])\ndisp([' DMDc: ', num2str(DMDc_err)])\ndisp([' sparseDMDc: ', num2str(sparseDMDc_err)])\n%% Show training and prediction\nVIZ_SI_Validation\n\n%% Save Data\nModel.name = 'sparseDMDc';\nModel.sys = sysmodel_DMDc;\nModel.Ndelay = Ndelay;\nModel.dt = dt;\nsave(fullfile(datapath,['EX_LOTKA_SI_',ModelName,'_',InputSignalType,'.mat']),'Model')", "meta": {"author": "eurika-kaiser", "repo": "SINDY-MPC", "sha": "e1dfd9908b2b56af303ee9fb30a133aced4fd757", "save_path": "github-repos/MATLAB/eurika-kaiser-SINDY-MPC", "path": "github-repos/MATLAB/eurika-kaiser-SINDY-MPC/SINDY-MPC-e1dfd9908b2b56af303ee9fb30a133aced4fd757/EX_LOTKA_VOLTERRA/EX_LOTKA_SI_SparseModels_Comparison.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.47237297778205045}}
{"text": "% Attenuation Compensation Using Time Reversal Example\n%\n% This example demonstrates how the acoustic attenuation present in\n% photoacoustic forward problem can be compensated for using time reversal\n% image reconstruction. It builds on the 2D Time Reversal Reconstruction\n% For A Circular Sensor Example. \n%\n% For a more detailed discussion of this example and the underlying\n% techniques, see B. E. Treeby, E. Z. Zhang, and B. T. Cox, \"Photoacoustic\n% tomography in absorbing acoustic media using time reversal,\" Inverse\n% Problems, vol. 26, no. 11, p. 115003, 2010. \n%\n% author: Bradley Treeby\n% date: 6th September 2010\n% last update: 25th August 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% FORWARD SIMULATION\n% =========================================================================\n\n% define the size of the simulation grid and the PML\nsimulation_size = 512; % [grid points]\nPML_size = 20; % [grid points]\nx = 52e-3; % [m]\ny = x; % [m]\n\n% reduce the number of grid points in Nx and Ny by the size of the PML so\n% that using 'PMLInside' set to false will still give the correct\n% simulation size \nNx = simulation_size - 2*PML_size; % [grid points] \nNy = Nx; % [grid points]\ndx = x/Nx; % [m]\ndy = dx; % [m]\n\n% create the computational grid\nkgrid = makeGrid(Nx, dx, Ny, dy);\n\n% define the properties of the propagation medium\nmedium_non_absorbing.sound_speed = 1510;\t% [m/s]\n\n% create a duplicate of the propagation medium structure and append the\n% absorption properties\nmedium = medium_non_absorbing;\nmedium.alpha_power = 1.5; \nmedium.alpha_coeff = 3; % [dB/(MHz^y cm)]\n\n% store maximum supported frequency\nf_max = kgrid.k_max*medium.sound_speed/(2*pi);\n\n% load the shepp logan phantom (note if the simulation or PML sizes are\n% changed, the loaded data will need to be resized)\nload EXAMPLE_shepp_logan\n\n% smooth the phantom and assign it to the initial pressure\nshepp_logan = smooth(kgrid, shepp_logan, true);\nsource.p0 = shepp_logan;\n\n% define a circular Cartesian sensor mask\nsensor_radius = 25e-3; % [m]\nsensor_points = 200;\ncart_sensor_mask = makeCartCircle(sensor_radius, sensor_points);\nsensor.mask = cart_sensor_mask;\n\n% create the time array used for the simulation, with t_max defined using\n% Huygens' principle to avoid artifact trapping in the reconstruction\nt_max = 2*sensor_radius/medium.sound_speed;\n[kgrid.t_array, dt] = makeTime(kgrid, medium.sound_speed, [], t_max);\n\n% set the input options, switching off the smoothing (the input has already\n% been smoothed), setting the PML to be outside the defined grid, casting\n% to 'single' to speed up the example, and switching off visualisation\ninput_args = {'Smooth', false, 'PMLInside', false, 'PMLSize', PML_size, 'DataCast', 'single', 'PlotSim', false};\n\n% run the forward simulation\nsensor_data = kspaceFirstOrder2D(kgrid, medium, source, sensor, input_args{:});\n\n% add noise to the recorded sensor data\nsignal_to_noise_ratio = 40; % [dB]\nsensor_data = addNoise(sensor_data, signal_to_noise_ratio, 'peak');\n\n% =========================================================================\n% IMAGE RECONSTRUCTION WITHOUT ABSORPTION COMPENSATION\n% =========================================================================\n\n% create a second computation grid for the reconstruction to avoid the\n% inverse crime\nPML_size = 25; % [grid points]\nNx = simulation_size - 2*PML_size; % [grid points]\nNy = Nx; % [grid points]\ndx = x/Nx; % [m]\ndy = dx; % [m]\nkgrid_recon = makeGrid(Nx, dx, Ny, dy);\n\n% attach the original time array\nkgrid_recon.t_array = kgrid.t_array;\n\n% remove the initial pressure field from the source structure\nsource = rmfield(source, 'p0');\n\n% create a continuous binary sensor mask with the same radius as the\n% Cartesian sensor mask used in the forward simulation\npixel_radius = round(sensor_radius/kgrid_recon.dx);\nbinary_sensor_mask = makeCircle(kgrid_recon.Nx, kgrid_recon.Ny, floor(kgrid_recon.Nx/2) + 1, floor(kgrid_recon.Ny/2) + 1, pixel_radius);\n\n% assign the sensor mask to the sensor structure\nsensor.mask = binary_sensor_mask;\n\n% interpolate the simulated sensor data onto the continuous binary sensor\n% mask to remove any gaps and assign to the time reversal field\nsensor.time_reversal_boundary_data = interpCartData(kgrid_recon, sensor_data, cart_sensor_mask, binary_sensor_mask, 'linear');\n\n% re-assign the input options (the PML_size has changed)\ninput_args = {'Smooth', false, 'PMLInside', false, 'PMLSize', PML_size, 'DataCast', 'single', 'PlotSim', false};\n\n% run the time-reversal reconstruction using the non absorbing medium\np0_recon = kspaceFirstOrder2D(kgrid_recon, medium_non_absorbing, source, sensor, input_args{:});\n\n% =========================================================================\n% CHOOSING THE CUTOFF FREQUENCY\n% =========================================================================\n\n% get the average frequency spectrum of the simulated sensor data\nnum_signals = length(sensor_data(:,1));\n[as_f, as] = spect(sensor_data(1, :), 1/dt);\nfor index = 2:num_signals\n [as_f, sp] = spect(sensor_data(index, :), 1/dt);\n as = as + sp;\nend\nas = as/num_signals;\n\n% compute the relative power spectrum\nps = log10(as.^2);\noffset = max(ps(:));\nps = ps - offset;\n\n% get the frequency spectrum of a single measurement\nas_sing = spect(sensor_data(1,:), 1/dt);\nps_sing = log10(as_sing.^2) - offset;\n\n% scale the frequency variable\n[f_sc, scale, prefix] = scaleSI(as_f(end));\n\n% define the cutoff frequency for the filter\nf_cutoff = 3e6;\n\n% =========================================================================\n% IMAGE RECONSTRUCTION WITH ABSORPTION COMPENSATION\n% =========================================================================\n\n% create the filter to regularise the absorption parameters\nmedium.alpha_filter = getAlphaFilter(kgrid_recon, medium, f_cutoff);\n\n% reverse the sign of the absorption proportionality coefficient\nmedium.alpha_sign = [-1, 1]; % [absorption, dispersion];\n\n% run the time-reversal reconstruction\np0_recon_compensated = kspaceFirstOrder2D(kgrid_recon, medium, source, sensor, input_args{:});\n\n% =========================================================================\n% VISUALISATION\n% =========================================================================\n\n% plot the amplitude spectrum\nfigure;\nplot(as_f*scale, ps_sing, 'r-');\nylabel('Power Spectrum [dB]');\nxlabel(['Frequency [' prefix 'Hz]']);\nhold on;\nplot(as_f*scale, ps, 'k-');\nylim = [-8 0];\nplot([f_cutoff*scale f_cutoff*scale], [ylim(1) ylim(2)], 'k--'); \nplot([f_max*scale f_max*scale], [ylim(1) ylim(2)], 'k--'); \nset(gca, 'XLim', [0 15], 'Ylim', ylim);\n\n% plot the filter, reducing the number of plotting points by a factor of 10\nfigure;\nmesh(medium.alpha_filter(1:10:end, 1:10:end), 'EdgeColor', 'black');\naxis tight; \nview([-29, 46]);\n\n% set the pressure outside the sensor mask to be zero\nbinary_sensor_map = makeDisc(kgrid_recon.Nx, kgrid_recon.Ny, kgrid_recon.Nx/2, kgrid_recon.Ny/2, pixel_radius - 50);\np0_recon(binary_sensor_map ~= 1) = 0;\np0_recon_compensated(binary_sensor_map ~= 1) = 0;\n\n% shrink the data sets\nphantom_padding = 50;\nshepp_logan = shepp_logan(1+ phantom_padding:end-phantom_padding, 1+ phantom_padding:end-phantom_padding);\np0_recon = p0_recon(1+ phantom_padding:end-phantom_padding, 1+ phantom_padding:end-phantom_padding);\np0_recon_compensated = p0_recon_compensated(1+ phantom_padding:end-phantom_padding, 1+ phantom_padding:end-phantom_padding);\n\n% plot the initial pressure distribution\nfigure;\nsubplot(2, 2, 1), imagesc(kgrid_recon.y_vec(1+ phantom_padding:end-phantom_padding)*1e3, kgrid_recon.x_vec(1+ phantom_padding:end-phantom_padding)*1e3, shepp_logan, [0 1]);\nylabel('x-position [mm]');\nxlabel('y-position [mm]');\naxis image;\ncolormap(flipud(gray));\n\n% plot the reconstruction without attenuation compensation\nsubplot(2, 2, 2), imagesc(kgrid_recon.y_vec(1+ phantom_padding:end-phantom_padding)*1e3, kgrid_recon.x_vec(1+ phantom_padding:end-phantom_padding)*1e3, p0_recon, [0 1]);\nylabel('x-position [mm]');\nxlabel('y-position [mm]');\naxis image;\ncolormap(flipud(gray));\n\n% plot the reconstruction with attenuation compensation\nsubplot(2, 2, 3), imagesc(kgrid_recon.y_vec(1+ phantom_padding:end-phantom_padding)*1e3, kgrid_recon.x_vec(1+ phantom_padding:end-phantom_padding)*1e3, p0_recon_compensated, [0 1]);\nylabel('x-position [mm]');\nxlabel('y-position [mm]');\naxis image;\ncolormap(flipud(gray));\n\n% plot a reconstruction profile\nfigure;\nplot(kgrid.y_vec(1+ phantom_padding:end-phantom_padding)*1e3, shepp_logan(end/2,:), 'k');\nhold on;\nplot(kgrid_recon.y_vec(1+ phantom_padding:end-phantom_padding)*1e3, p0_recon(end/2,:), 'r-');\nplot(kgrid_recon.y_vec(1+ phantom_padding:end-phantom_padding)*1e3, p0_recon_compensated(end/2, :), 'b-');\nset(gca, 'XLim', [-20, 20], 'YLim', [-0.1 1.1]);\nylabel('Pressure Magnitude [au]');\nxlabel('y-position [mm]');\nlegend('Original', 'No Compensation', 'With Attenuation Compensation', 'Location', 'Best');", "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_pr_2D_TR_absorption_compensation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.4723332226005753}}
{"text": "function prob = problem_type(om, recheck)\n%PROBLEM_TYPE Return a string identifying the type of mathematical program\n% PROB_TYPE = OM.PROBLEM_TYPE()\n% PROB_TYPE = OM.PROBLEM_TYPE(RECHECK)\n%\n% Returns a string identifying the type of mathematical program\n% represented by the current model, based on the variables, costs,\n% and constraints that have been added to the model. Used to\n% automatically select an appropriate solver.\n%\n% Linear and nonlinear equations are models with no costs, no inequality\n% constraints, and an equal number of continuous variables and equality\n% constraints. If the number of variables in a nonlinear equation model\n% is one more than the number of constraints, it is a parameterized\n% nonlinear equation.\n%\n% Outputs:\n% PROB_TYPE : problem type, one of the following strings:\n% 'LEQ' - linear equations\n% 'NLEQ' - nonlinear equations\n% 'PNE' - parameterized nonlinear equations\n% 'LP' - linear program\n% 'QP' - quadratic program\n% 'NLP' - nonlinear program\n% 'MILP' - mixed-integer linear program\n% 'MIQP' - mixed-integer quadratic program\n% 'MINLP' - mixed-integer nonlinear program\n%\n% The output value is cached for future calls, but calling with a true\n% value for the optional RECHECK argument will force it to recheck in\n% case the problem type has changed due to modifying the variables,\n% constraints or costs in the model.\n%\n% See also OPT_MODEL\n\n% MP-Opt-Model\n% Copyright (c) 2020, Power Systems Engineering Research Center (PSERC)\n% by Ray Zimmerman, PSERC Cornell\n%\n% This file is part of MP-Opt-Model.\n% Covered by the 3-clause BSD License (see LICENSE file for details).\n% See https://github.com/MATPOWER/mp-opt-model for more info.\n\nif isempty(om.prob_type) || nargin > 1 && recheck\n nleN = om.getN('nle'); %% nonlinear equalities\n nliN = om.getN('nli'); %% nonlinear inequalities\n nlcN = om.getN('nlc'); %% general nonlinear costs\n qdcN = om.getN('qdc'); %% quadratic costs\n linN = om.getN('lin'); %% linear constraints\n varN = om.getN('var'); %% variables\n if varN == 0\n prob = '';\n elseif nlcN || qdcN %% problem has costs\n if nliN || nleN || nlcN %% nonlinear\n prob = 'NLP'; %% nonlinear program\n else %% linear constraints, no general nonlinear costs\n %% get quadratic cost coefficients\n H = om.params_quad_cost();\n if isempty(H) || ~any(any(H))\n prob = 'LP'; %% linear program\n else\n prob = 'QP'; %% quadratic program\n end\n end\n else %% problem has no costs\n if nliN\n error('@opt_model/problem_type: invalid problem - nonlinear inequality constraints with no costs');\n end\n if nleN + linN == varN || nleN + linN == varN - 1 %% square (or almost) system\n if linN > 0\n %% get lower & upper bounds\n [A, l, u] = om.params_lin_constraint();\n if any(l ~= u)\n error('@opt_model/problem_type: invalid problem - linear inequality constraints with no costs');\n end\n end\n if nleN + linN == varN %% square system\n if nleN\n prob = 'NLEQ'; %% square nonlinear set of equations\n else\n prob = 'LEQ'; %% square linear set of equations\n end\n elseif nleN + linN + 1 == varN %% square + 1 extra (parameterization) variable\n if nleN\n prob = 'PNE'; %% parameterized nonlinear set of equations\n else\n prob = 'PLEQ'; %% parameterized linear set of equations\n error('@opt_model/problem_type: invalid problem - PNE not implemented for for linear constraints only');\n end\n else\n error('@opt_model/problem_type: invalid problem - PNE must have num of vars = num of constraints + 1');\n end\n else\n error('@opt_model/problem_type: invalid problem - non-square system with no costs');\n end\n end\n if om.is_mixed_integer() && ~strcmp(prob, 'NLEQ')\n prob = ['MI' prob];\n end\n om.prob_type = prob; %% cache it\nelse\n prob = om.prob_type; %% return cached type\nend\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/mp-opt-model/lib/@opt_model/problem_type.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.47214546556221637}}
{"text": "function [M0,q0,X,x,f,M1,L] = spm_fp(M,x,u)\n% Fokker-Planck operators and equilibrium density for dynamic systems\n% FORMAT [M0,q0,X,x,f,M1,L] = spm_fp(M,x,u)\n%--------------------------------------------------------------------------\n% M - model specification structure\n% Required fields:\n% M.f - dx/dt = f(x,u,P) or f(x,u,a,P) {function string or m-file}\n% M.g - y(t) = g(x,u,P) {function string or m-file}\n% M.m - m inputs\n% M.n - n states\n% M.l - l outputs\n% M.x - (n x 1) = x(0) = expansion point\n% M.W - (n x n) - precision matrix of state noise\n% x - cell array of vectors specifying evaluation grid\n% u - expansion point for inputs or causes;\n%\n% M0 - 1st order FP operator dq/dt = M0*q + u*M1*q, q = p(X);\n% q0 - stable or equilibrium mode: M0*q0 = 0\n% X - evaluation points of state space\n% x - cell array of vectors specifying evaluation grid\n% f - flow\n% M1 - 2nd order FP operator\n% L - output matrix = L*q;\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: spm_fp.m 5219 2013-01-29 17:07:07Z spm $\n \n% default: first level of hierarchical model\n%--------------------------------------------------------------------------\nM = M(1);\n \n% default expansion point for inputs\n%--------------------------------------------------------------------------\nif nargin < 3\n u0 = zeros(M.m,1);\nelse\n u0 = u;\nend\n\n% event space: get or create X - coordinates of evaluation grid\n%--------------------------------------------------------------------------\nn = length(M.x);\nif nargin < 2\n\n % use M.X\n %----------------------------------------------------------------------\n X = M.X;\n for i = 1:size(X,2)\n x{i} = unique(X(:,i));\n end\nelse\n \n % use x\n %----------------------------------------------------------------------\n [X,x] = spm_ndgrid(x);\nend\n\n% f(x,0)\n%--------------------------------------------------------------------------\nN = length(X);\nf = sparse(n,N);\ntry\n for i = 1:N\n f(:,i) = feval(M.f,X(i,:)',u0,M.pE);\n end\ncatch\n for i = 1:N\n f(:,i) = feval(M.f,X(i,:)',u0,0,M.pE);\n end\nend\n\n\n% Fokker-Planck operator; i.e., Jacobian J - M0\n%==========================================================================\nfor i = 1:n\n d(i) = length(x{i});\n dx(i) = x{i}(2) - x{i}(1);\n I{i} = speye(d(i),d(i));\nend\nJ = sparse(N,N);\n \n \n% cycle over dimensions of state space\n%--------------------------------------------------------------------------\nfor i = 1:length(x)\n \n % differential operators (for positive and negative flows)\n %----------------------------------------------------------------------\n j = find(f(i,:) < 0);\n u = sparse(j,1,f(i,j),N,1);\n j = find(f(i,:) > 0);\n v = sparse(j,1,f(i,j),N,1);\n \n dp = spdiags(ones(d(i),1)*[1 -1],[ 0;1],d(i),d(i))/dx(i);\n dp(:,1) = 0;\n dq = spdiags(ones(d(i),1)*[1 -1],[-1;0],d(i),d(i))/dx(i);\n dq(:,end) = 0;\n \n % Kronecker tensor products\n %----------------------------------------------------------------------\n Dp = 1;\n Dq = 1;\n for j = 1:(i - 1)\n Dp = spm_kron(I{j},Dp);\n Dq = spm_kron(I{j},Dq);\n end\n Dp = spm_kron(dp,Dp);\n Dq = spm_kron(dq,Dq);\n for j = (i + 1):n\n Dp = spm_kron(I{j},Dp);\n Dq = spm_kron(I{j},Dq);\n end\n DP{i} = Dp;\n \n % augment Jacobian\n %----------------------------------------------------------------------\n J = J + Dp*spdiags(u,0,N,N) + Dq*spdiags(v,0,N,N);\n \nend\n \n% dispersion\n%--------------------------------------------------------------------------\nC = inv(M.W);\nif length(C) ~= n\n C = C(1)*speye(n,n);\nend\nfor i = 1:n\n for j = 1:n\n if C(i,j)\n J = J - C(i,j)*DP{i}*DP{j}'/2;\n end\n end\nend\n \n% return if only M0 is required\n%--------------------------------------------------------------------------\nM0 = J;\nif nargout == 1, return, end\n\n \n% stable mode - stochastic iteration\n%==========================================================================\nq = sparse(N,1) + 1/N;\nfor i = 1:1024\n dq = M0*q;\n if norm(dq,1) < exp(-4), break, end\n while min(q + dq) < 0\n dq = dq - dq/2;\n end\n q = q + dq;\nend\nfor i = 1:n\n nx{i} = length(x{i});\nend\nq0 = reshape(q,nx{:});\n\nif nargout < 6, return, end\n\n% input induced changes to Jacobian dJ/du - M1\n%==========================================================================\nM1 = spm_diff('spm_fp',M,x,u0,3);\nif nargout < 6, return, end\n \n \n% Output matrix L - M1\n%==========================================================================\n \n% l(x,0)\n%--------------------------------------------------------------------------\nL = sparse(M.l,N);\nfor i = 1:N\n try\n L(:,i) = feval(M.g,X(i,:)',u0,M.pE);\n catch\n L(:,i) = feval(M.g,X(i,:)',u0,[],M.pE);\n end\nend\n\nreturn\n\n% NOTES: analytic solution for q0\n%--------------------------------------------------------------------------\nq = length(M0);\nJ = [M0; ones(1,q)];\nq0 = sum(inv(J'*J),2);\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_fp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.47207869911134825}}
{"text": "function [LLF, likelihoods, errors] = sarimax_likelihood(parameters,p,q,constant,seasonal,y,x,sigma)\n% PURPOSE:\n% Likelihood function for armaxfilter\n%\n% USAGE:\n% [LLF, LIKELIHOODS, ERRORS] = armaxfilter_likelihood(PARAMETERS,P,Q,CONSTANT,Y,X,M)\n% [LLF, LIKELIHOODS, ERRORS] = armaxfilter_likelihood(PARAMETERS,P,Q,CONSTANT,Y,X,M)\n%\n% INPUTS:\n% PARAMETERS - A vector of GARCH process aprams of the form [constant, arch, garch]\n% P - Vector containing lag indices of the AR component\n% Q - Vector containing lag indices of the MA component\n% CONSTANT - Value indicating whether the model contains a constant (1) or not (0)\n% Y -\n% X -\n% M - Index to first element to use in the recursive residual calculation\n% SIGMA - T by 1 vector\n%\n% OUTPUTS:\n% LLF - Minus 1 times the log likelihood\n% LIKELIHOODS - Time series of likelihoods\n% ERRORS - Time series of model errors\n%\n% COMMENTS:\n%\n% See also armaerrors\n\n% Author: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 3 Date: 4/1/2004\n\nm = size(x,2);\n[armaParameters, p, q] = sarma2arma(parameters(m+1:length(parameters)), p, q, seasonal);\nparameters = [parameters(1:m);armaParameters];\n\ne = armaxerrors(parameters,p,q,constant,y,x,m,ones(size(y)));\nT = length(e);\n\n% Do not divide e by sigma since this is done in armaxerrors\nlikelihoods = 0.5*(2*log(sigma) + (e./sigma).^2 + log(2*pi));\n\nif isempty(p)\n p = 0;\nend\nif isempty(q)\n q = 0;\nend\nif max(q)>max(p) % prepend y and x, if needed\n t = (max(q)-max(p))+1:T;\nelse\n t = 1:T;\nend\n\nlikelihoods = likelihoods(t);\nerrors=e(t);\nLLF = sum(likelihoods);\n\nif isnan(LLF)\n LLF=1e7;\nend\n", "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/sandbox/sarimax_likelihood.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.47169617753214266}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% MATLAB Code for %\n% %\n% Multi-Objective Particle Swarm Optimization (MOPSO) %\n% Version 1.0 - Feb. 2011 %\n% %\n% According to: %\n% Carlos A. Coello Coello et al., %\n% \"Handling Multiple Objectives with Particle Swarm Optimization,\" %\n% IEEE Transactions on Evolutionary Computation, Vol. 8, No. 3, %\n% pp. 256-279, June 2004. %\n% %\n% Developed Using MATLAB R2009b (Version 7.9) %\n% %\n% Programmed By: S. Mostapha Kalami Heris %\n% %\n% e-Mail: sm.kalami@gmail.com %\n% kalami@ee.kntu.ac.ir %\n% %\n% Homepage: http://www.kalami.ir %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction pop=DetermineDomination(pop)\n\n npop=numel(pop);\n \n for i=1:npop\n pop(i).Dominated=false;\n for j=1:i-1\n if ~pop(j).Dominated\n if Dominates(pop(i),pop(j))\n pop(j).Dominated=true;\n elseif Dominates(pop(j),pop(i))\n pop(i).Dominated=true;\n break;\n end\n end\n end\n end\n\nend", "meta": {"author": "sfvsfv", "repo": "Mathematical-modeling", "sha": "cef1a3688246851f067777b3599b1b3831d3d948", "save_path": "github-repos/MATLAB/sfvsfv-Mathematical-modeling", "path": "github-repos/MATLAB/sfvsfv-Mathematical-modeling/Mathematical-modeling-cef1a3688246851f067777b3599b1b3831d3d948/ē¾čµAé¢åøøč§ä»£ē /å¤ē®ę ē²å群ä¼åē®ę³ä»£ē /DetermineDomination.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.47169617222481125}}
{"text": "function [wedge_data wedge_density] = wedge();\n\n% wedge coordinates\nY = [-7.0 -4.35 0 3.0 0 -4.35 -7.0 -7.0];\nZ = [-5.8 -5.8 -2.46 0 0 0 0 -5.8];\nfigure; line(Y,Z, 'LineStyle', '-', 'Marker', 'o');\ndisp('This wedge can be modeled as a rectangle and a triangle, as shown below')\nY = [-7.0 -4.35 -4.35 -7.0 -7.0];\nZ = [-5.8 -5.8 0 0 -5.8];\nfigure; line(Y,Z, 'Color', 'b', 'LineStyle', '-', 'Marker', 'o');\nY = [-4.35 3.0 -4.35 -4.35];\nZ = [-5.8 0 0 -5.8];\nhold on; line(Y,Z, 'Color', 'r', 'LineStyle', '-', 'Marker', 'o'); axis equal;\nxlabel('Y/cm'); ylabel('Z/cm'); title('Elekta Universal Wedge');\n\n% From the NIST website, get the attenuation coefficients.\n% Components of the wedge:\nPb = 0.96 %Fraction by weigth for Lead\nSb = 0.04 %Fraction by weight for Antimony\n\n% Ref:\n%http://physics.nist.gov/PhysRefData/XrayMassCoef/ElemTab/z82.html\n%Energy mu over rho mu e n over rho \n% (MeV) (cm2/g) (cm2/g)\n%____________________________________\n%\nPb_data = [1.00000E-03 5.210E+03 5.197E+03 \n 1.50000E-03 2.356E+03 2.344E+03 \n 2.00000E-03 1.285E+03 1.274E+03 \n 2.48400E-03 8.006E+02 7.895E+02 \n 2.48400E-03 1.397E+03 1.366E+03 \n 2.53429E-03 1.726E+03 1.682E+03 \n 2.58560E-03 1.944E+03 1.895E+03 \n 2.58560E-03 2.458E+03 2.390E+03 \n 3.00000E-03 1.965E+03 1.913E+03 \n 3.06640E-03 1.857E+03 1.808E+03 \n 3.06640E-03 2.146E+03 2.090E+03 \n 3.30130E-03 1.796E+03 1.748E+03 \n 3.55420E-03 1.496E+03 1.459E+03 \n 3.55420E-03 1.585E+03 1.546E+03 \n 3.69948E-03 1.442E+03 1.405E+03 \n 3.85070E-03 1.311E+03 1.279E+03 \n 3.85070E-03 1.368E+03 1.335E+03 \n 4.00000E-03 1.251E+03 1.221E+03 \n 5.00000E-03 7.304E+02 7.124E+02 \n 6.00000E-03 4.672E+02 4.546E+02 \n 8.00000E-03 2.287E+02 2.207E+02 \n 1.00000E-02 1.306E+02 1.247E+02 \n 1.30352E-02 6.701E+01 6.270E+01 \n 1.30352E-02 1.621E+02 1.291E+02 \n 1.50000E-02 1.116E+02 9.100E+01 \n 1.52000E-02 1.078E+02 8.807E+01 \n 1.52000E-02 1.485E+02 1.131E+02 \n 1.55269E-02 1.416E+02 1.083E+02 \n 1.58608E-02 1.344E+02 1.032E+02 \n 1.58608E-02 1.548E+02 1.180E+02 \n 2.00000E-02 8.636E+01 6.899E+01 \n 3.00000E-02 3.032E+01 2.536E+01 \n 4.00000E-02 1.436E+01 1.211E+01 \n 5.00000E-02 8.041E+00 6.740E+00 \n 6.00000E-02 5.021E+00 4.149E+00 \n 8.00000E-02 2.419E+00 1.916E+00 \n 8.80045E-02 1.910E+00 1.482E+00 \n 8.80045E-02 7.683E+00 2.160E+00 \n 1.00000E-01 5.549E+00 1.976E+00 \n 1.50000E-01 2.014E+00 1.056E+00 \n 2.00000E-01 9.985E-01 5.870E-01 \n 3.00000E-01 4.031E-01 2.455E-01 \n 4.00000E-01 2.323E-01 1.370E-01 \n 5.00000E-01 1.614E-01 9.128E-02 \n 6.00000E-01 1.248E-01 6.819E-02 \n 8.00000E-01 8.870E-02 4.644E-02 \n 1.00000E+00 7.102E-02 3.654E-02 \n 1.25000E+00 5.876E-02 2.988E-02 \n 1.50000E+00 5.222E-02 2.640E-02 \n 2.00000E+00 4.606E-02 2.360E-02 \n 3.00000E+00 4.234E-02 2.322E-02 \n 4.00000E+00 4.197E-02 2.449E-02 \n 5.00000E+00 4.272E-02 2.600E-02 \n 6.00000E+00 4.391E-02 2.744E-02 \n 8.00000E+00 4.675E-02 2.989E-02 \n 1.00000E+01 4.972E-02 3.181E-02 \n 1.50000E+01 5.658E-02 3.478E-02 \n 2.00000E+01 6.206E-02 3.595E-02];\n\n\n%Antimony\n%Z = 51\n%\n%ASCII format\n%\n%____________________________________\n%\n% Energy mu over rho mu e n over rho \n% (MeV) (cm2/g) (cm2/g)\n%____________________________________\n\nSb_data = [1.00000E-03 8.582E+03 8.568E+03 \n 1.50000E-03 3.491E+03 3.481E+03 \n 2.00000E-03 1.767E+03 1.759E+03 \n 3.00000E-03 6.536E+02 6.469E+02 \n 4.00000E-03 3.169E+02 3.113E+02 \n 4.13220E-03 2.918E+02 2.863E+02 \n 4.13220E-03 8.691E+02 8.252E+02 \n 4.25449E-03 8.308E+02 7.865E+02 \n 4.38040E-03 7.776E+02 7.392E+02 \n 4.38040E-03 1.050E+03 9.906E+02 \n 4.53657E-03 9.743E+02 9.178E+02 \n 4.69830E-03 8.939E+02 8.457E+02 \n 4.69830E-03 1.029E+03 9.725E+02 \n 5.00000E-03 8.846E+02 8.377E+02 \n 6.00000E-03 5.569E+02 5.305E+02 \n 8.00000E-03 2.631E+02 2.518E+02 \n 1.00000E-02 1.459E+02 1.396E+02 \n 1.50000E-02 4.923E+01 4.657E+01 \n 2.00000E-02 2.268E+01 2.105E+01 \n 3.00000E-02 7.631E+00 6.755E+00 \n 3.04912E-02 7.307E+00 6.452E+00 \n 3.04912E-02 4.073E+01 1.391E+01 \n 4.00000E-02 2.027E+01 9.789E+00 \n 5.00000E-02 1.120E+01 6.400E+00 \n 6.00000E-02 6.879E+00 4.311E+00 \n 8.00000E-02 3.176E+00 2.173E+00 \n 1.00000E-01 1.758E+00 1.237E+00 \n 1.50000E-01 6.361E-01 4.312E-01 \n 2.00000E-01 3.381E-01 2.084E-01 \n 3.00000E-01 1.677E-01 8.504E-02 \n 4.00000E-01 1.172E-01 5.288E-02 \n 5.00000E-01 9.453E-02 4.061E-02 \n 6.00000E-01 8.153E-02 3.465E-02 \n 8.00000E-01 6.670E-02 2.896E-02 \n 1.00000E+00 5.797E-02 2.608E-02 \n 1.25000E+00 5.086E-02 2.378E-02 \n 1.50000E+00 4.628E-02 2.230E-02 \n 2.00000E+00 4.105E-02 2.081E-02 \n 3.00000E+00 3.686E-02 2.043E-02 \n 4.00000E+00 3.567E-02 2.118E-02 \n 5.00000E+00 3.559E-02 2.219E-02 \n 6.00000E+00 3.598E-02 2.321E-02 \n 8.00000E+00 3.745E-02 2.509E-02 \n 1.00000E+01 3.921E-02 2.664E-02 \n 1.50000E+01 4.351E-02 2.920E-02 \n 2.00000E+01 4.704E-02 3.038E-02]; \n\n% put data on the same, unique intervals.\n[A, s] = unique(Pb_data(:,1));\n[B,I] = unique(Sb_data(:,1));\nPb_data = [B interp1(Pb_data(s,1), Pb_data(s,2), B) interp1(Pb_data(s,1), Pb_data(s,3), B)];\nSb_data = [B interp1(Sb_data(I,1), Sb_data(I,2), B) interp1(Sb_data(I,1), Sb_data(I,3), B)];\n\nwedge_data = Pb*Pb_data + Sb*Sb_data;\nfigure; loglog(Pb_data(:,1), Pb_data(:,2), Sb_data(:,1), Sb_data(:,2), wedge_data(:,1), wedge_data(:,2));\nwedge_density = 11.16;\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/IMRTP/recompDose/MC/wedge.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332532, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4716771620954581}}
{"text": "%% Spherical Functions\n%\n% The |S2Fun| toolbox is a collection of Matlab classes for numerical computations with functions on the two-dimensional sphere.\n% It overloads the default commands for vectors and matrices to compute the analogous operations for functions of the given type.\n% The underlying mathematical approach is accomplished via spherical harmonics which form an orthonormal basis of the square-integrable functions on the two-dimensional sphere.\n%\n%%\n%\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/doc/SphericalFunctions/SphericalFunctions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4715188171270417}}
{"text": "%DEMO_PASSGP Demonstration of PASS-GP routine for GP classification\n%\n% Description\n% Here we demonstrate pass-gp routine for Gaussian Processes\n% classification. Data used is 2-dimensional toy data with Gaussian\n% bumbs defining classes. We demonstrate with both fixed and not fixed\n% sizes of active set for pass-gp.\n%\n% See also PASSGP\n\n% Copyright (c) 2013 Ville Tolvanen\n\n% This software is distributed under the GNU General Public \n% License (version 3 or later); please refer to the file \n% License.txt, included with the software, for details.\n\n% Generate toy data\nprevstream=setrandstream(0);\n[x1,x2]=meshgrid(-5:0.1:5,-5:0.1:5);\nx=[x1(:) x2(:)]; x=x(randperm(size(x,1),3000),:);\ny=2.*mnorm_pdf(x, [0 0], [0.5 0;0 0.5]) + mnorm_pdf(x, [3 3], [0.5 0;0 0.5]) + mnorm_pdf(x, [-3 -3], [0.5 0;0 0.5]);\ny=y+mnorm_pdf(x, [3 -3], [0.5 0;0 0.5])+mnorm_pdf(x, [-3 3], [0.5 0;0 0.5]);\ny=y+0.03.*randn(size(y,1),1);\ny(y>0.15)=1; y(y<=0.15)=-1;\n\n[xt1, xt2]=meshgrid(-5:0.23:5,-5:0.23:5);\nxt=[xt1(:) xt2(:)];\nyt=ones(size(xt,1),1);\n\n[n, nin] = size(x);\n\n% Define covariance and likelihood functions and create model\ngpcf = gpcf_sexp();\nlik=lik_probit();\ngp=gp_set('lik', lik, 'cf', gpcf, 'jitterSigma2', 1e-6);\n\nopt=optimset('TolX',1e-3,'TolFun',1e-3,'display','on');\nw0=gp_pak(gp);\n\n% fPASS-GP with fixed size of 800 points in active set and data divided to\n% 10 subsets with 4 sweeps over data\nstart=tic;[gp, indA]=passgp(gp, x, y, 'opt', opt, 'npass', 4, 'ninit', 800, 'nsub', 10, 'display', 'on', 'fixed', 'on', 'pexc', 0.1, 'optimn', 2);time=toc(start);\ntt=time;\n[Eft, Varft, lpyt, Eyt, Varyt]=gp_pred(gp, x(indA,:), y(indA,:), xt, 'yt', yt);\nfigure, [cc,hh]=contour(reshape(xt(:,1),size(xt1,1), size(xt1,1)), reshape(xt(:,2),size(xt1,1), size(xt1,1)), reshape(exp(lpyt),size(xt1,1), size(xt1,1)), [0.1 0.9]);\nclabel(cc,hh); title('Pr(y==1) (fpass-gp)')\nparam=gp_pak(gp);\n\n% PASS-GP with inclusion threshold 0.65, deletion threshold 0.99, intial\n% size of 400 points in active set and 3 sweeps over data.\ngp=gp_unpak(gp,w0);\nstart=tic;[gp, indA2]=passgp(gp, x, y, 'opt', opt, 'pinc', 0.65, 'pdel', 0.99, 'npass', 3, 'ninit', 400, 'nsub', 10, 'display', 'on', 'optimn', 2);time=toc(start);\ntt2=time;\n[Eft2, Varft2, lpyt2, Eyt2, Varyt2]=gp_pred(gp, x(indA2,:), y(indA2,:), xt, 'yt', yt);\nfigure, [cc,hh]=contour(reshape(xt(:,1),size(xt1,1), size(xt1,1)), reshape(xt(:,2),size(xt1,1), size(xt1,1)), reshape(exp(lpyt2),size(xt1,1), size(xt1,1)), [0.1 0.9]);\nclabel(cc,hh); title('Pr(y==1) (pass-gp)')\nparam2=gp_pak(gp);\n\n% Full Gaussian Process for comparison\ngp=gp_unpak(gp,w0);\nopt.Display='iter';\nstart=tic;gp=gp_optim(gp,x,y,'opt',opt);tt3=toc;\n[Eft3, Varft3, lpyt3, Eyt3, Varyt3]=gp_pred(gp, x, y, xt, 'yt', yt);\nfigure, [cc,hh]=contour(reshape(xt(:,1),size(xt1,1), size(xt1,1)), reshape(xt(:,2),size(xt1,1), size(xt1,1)), reshape(exp(lpyt3),size(xt1,1), size(xt1,1)), [0.1 0.9]);\nclabel(cc,hh); title('Pr(y==1) (full gp)')\n\n% Display some statistics\n\nmlpd_fpassgp=mean(mean(lpyt,2))\ntime_fpassgp=mean(tt)\nmlpd_passgp=mean(mean(lpyt2,2))\ntime_passgp=mean(tt2)\nmlpd_full=mean(lpyt3)\ntime_full=tt3\n\n% Plot data and active sets for both methods\nfigure(4), subplot(1,2,1), plot(x(y==1,1),x(y==1,2),'or',x(y==-1,1),x(y==-1,2),'ob'); \nhold all; plot(x(indA,1), x(indA,2), '.k'); title('Data and active set (fpass-gp)')\nlegend('y=1', 'y=-1', 'Active set for fpass-gp');\nsubplot(1,2,2), plot(x(y==1,1),x(y==1,2),'or',x(y==-1,1),x(y==-1,2),'ob'); \nhold all; plot(x(indA2,1), x(indA2,2), '.k'); title('Data and active set (pass-gp)')\nlegend('y=1', 'y=-1', 'Active set for pass-gp');\nsetrandstream(prevstream);\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/demo_passgp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4715138648025148}}
{"text": "function [pvec, pstruct] = tapas_ehgf_jget_transp(r, ptrans)\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2013-2020 Christoph Mathys, TNU, UZH & ETHZ\n%\n% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or .\n\n\npvec = NaN(1,length(ptrans));\npstruct = struct;\n\nl = r.c_prc.n_levels;\n\npvec(1:l) = ptrans(1:l); % mux_0\npstruct.mux_0 = pvec(1:l);\npvec(l+1:2*l) = exp(ptrans(l+1:2*l)); % sax_0\npstruct.sax_0 = pvec(l+1:2*l);\npvec(2*l+1:3*l) = ptrans(2*l+1:3*l); % mua_0\npstruct.mua_0 = pvec(2*l+1:3*l);\npvec(3*l+1:4*l) = exp(ptrans(3*l+1:4*l)); % saa_0\npstruct.saa_0 = pvec(3*l+1:4*l);\npvec(4*l+1) = exp(ptrans(4*l+1)); % kau\npstruct.kau = pvec(4*l+1);\npvec(4*l+2:5*l) = exp(ptrans(4*l+2:5*l)); % kax\npstruct.kax = pvec(4*l+2:5*l);\npvec(5*l+1:6*l-1) = exp(ptrans(5*l+1:6*l-1)); % kaa\npstruct.kaa = pvec(5*l+1:6*l-1);\npvec(6*l) = ptrans(6*l); % omu\npstruct.omu = pvec(6*l);\npvec(6*l+1:7*l) = ptrans(6*l+1:7*l); % omx\npstruct.omx = pvec(6*l+1:7*l);\npvec(7*l+1:8*l) = ptrans(7*l+1:8*l); % oma\npstruct.oma = pvec(7*l+1:8*l);\n\nend\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/HGF/tapas_ehgf_jget_transp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4713763290972085}}
{"text": "function [stats,st] = SStat_CoxExt(sID_ext,X_ext,d_ext,t_ext,e)\n% [stats,st] = SStat_CoxExt(sID_ext,X_ext,d_ext,t_ext,e)\n%\n% Parameter estimation for the extended Cox model. This function uses as\n% input the output of SStat_X_ext but with X_ext having new time-dependent \n% columns added by the user (eg. the product of a column of X_ext with\n% t_ext. Survival time ties are handled using Efron's method. \n%\n% Input\n% sID_ext: Extended subjects' IDs (nx1).\n% X_ext: Extended design matrix (nxp).\n% d_ext: Extended censorship status vector (nx1).\n% t_ext: Extended survival time vector (nx1).\n% e: Convergence epsilon (gradient's norm). Default 10^-3;\n%\n% Output\n% stats.Bhat: Estimated vector of the population regression parameters.\n% stats.CovBhat: Estimated covariance matrix of the population regression \n% parameters.\n% stats.llh: Values of the maximum log-likelihood across the optimization \n% process.\n% st: Termination state (1 for convergence and 0 otherwise).\n%\n% $Revision: 1.1 $ $Date: 2015/01/06 17:04:02 $\n% Original Author: Jorge Luis Bernal Rusiel \n% CVS Revision Info:\n% $Author: mreuter $\n% $Date: 2015/01/06 17:04:02 $\n% $Revision: 1.1 $\n% References: Kleinbaum, D.G., Klein, M., 2005. Survival analysis. A self-\n% learning approach, second edition. New York: Springer..\n% \nif nargin < 4\n error('Too few inputs');\nelseif nargin < 5\n e = 0.001;\nend;\ntic;\n[n,p] = size(X_ext);\nif (length(sID_ext)~=n) || (length(d_ext)~=n) || (length(t_ext)~=n)\n error(['The design matrix X_ext, censorship status vector d_ext, time'...\n ' vector t_ext and subject ID vector sID_ext must all have the same'...\n ' number of rows.']);\nend;\n%indices of unique failure times in ft_ix (last index when ties happen)\nst_ix = find(d_ext==1);\n[~,ft_ix] = unique(t_ext(st_ix),'last');\nft_ix = st_ix(ft_ix);\n%Starting values\nBhat = zeros(p,1);\n\n%% Iterations\nnit = 50;\ngnorm = e+1;\nit = 1;\ndisplay('Starting Newton-Raphson iterations');\nwhile (gnorm>e) && (it<=nit) \n gr = SStat_Gradient(X_ext,t_ext,Bhat,ft_ix);\n He = SStat_Hessian(X_ext,t_ext,Bhat,ft_ix);\n if (cond(He) < 1e+10)\n invHe = He\\eye(p);\n else\n [Vtemp,Dtemp] = eig(He);\n invHe = Vtemp*diag(1./max(diag(Dtemp),1e-5))*Vtemp';\n end\n Bhat = Bhat - invHe*gr;\n %log-likelihood\n llh = SStat_Likelihood(X_ext,t_ext,Bhat,ft_ix);\n display(['Likelihood at iteration ' num2str(it) ' : ' num2str(llh)]);\n gnorm = norm(gr);\n display(['Gradient norm: ' num2str(gnorm)]); \n it = it+1;\nend; \n%% Termination\nz_sc = Bhat./sqrt(diag(-invHe));\npval = 2*(1-normcdf(abs(z_sc),0,1));\nstats = struct('Bhat',Bhat,'zscore',z_sc,'pval',pval,'CovBhat',-invHe,'llh',llh);\nif (gnorm<=e)\n st = 1;\nelse\n st = 0;\n display(['Algorithm does not converge after ' num2str(nit)...\n ' iterations!!!']);\nend;\net = toc;\ndisplay(['Total elapsed time is ' num2str(et) ' seconds']);\nend\n\n\n\n\n\n\n%% Likelihood, Gradient and Hessian\n\nfunction llk = SStat_Likelihood(X_ext,t_ext,Bhat,ft_ix)\n% \n% Log-likelihood value.\n%\n% Input\n% X_ext: Extended design matrix.\n% t_ext: Extended survival time vector.\n% Bhat: Estimated vector of the population regression parameters.\n% ft_ix: Failure time indices in X_ext (last index if any tie).\n%\n% Output\n% llk: Log-likelihood value.\n%\nllk = 0;\nnft = length(ft_ix);\nfor j=1:nft\n term = 0;\n ties = ft_ix(t_ext(ft_ix(j))==t_ext(ft_ix));\n nties = length(ties)-1;\n lpr = X_ext(ties,:)*Bhat;\n aux1 = sum(exp(lpr));\n aux2 = sum(exp(X_ext(t_ext(ft_ix(j))==t_ext,:)*Bhat));\n for l=0:nties\n term = term + log(aux2-l*aux1/(nties+1));\n end;\n llk = llk + sum(lpr) - term;\nend;\nend\n\n\nfunction gr = SStat_Gradient(X_ext,t_ext,Bhat,ft_ix)\n% \n% Gradient vector for the log-likelihood.\n%\n% Input\n% X_ext: Extended design matrix.\n% t_ext: Extended survival time vector.\n% Bhat: Estimated vector of the population regression parameters.\n% ft_ix: Failure time indices in X_ext (last index if any tie).\n%\n% Output\n% gr: Gradient vector.\n%\np = size(X_ext,2);\ngr = zeros(p,1);\nnft = length(ft_ix);\nfor j=1:nft\n ties = ft_ix(t_ext(ft_ix(j))==t_ext(ft_ix));\n nties = length(ties)-1;\n riskset = t_ext(ft_ix(j))==t_ext;\n term1 = sum(X_ext(ties,:),1);\n term2 = exp(X_ext(riskset,:)*Bhat);\n term3 = exp(X_ext(ties,:)*Bhat);\n term4 = term2'*X_ext(riskset,:);\n term5 = term3'*X_ext(ties,:);\n term = 0; \n for l=0:nties\n term = term + (term4-l*term5/(nties+1))/(sum(term2)-l*sum(term3)/(nties+1));\n end;\n gr = gr + (term1 - term)';\nend;\nend\n\n\nfunction He = SStat_Hessian(X_ext,t_ext,Bhat,ft_ix)\n% \n% Hessian matrix for the log-likelihood.\n%\n% Input\n% X_ext: Extended design matrix.\n% t_ext: Extended survival time vector.\n% Bhat: Estimated vector of the population regression parameters.\n% ft_ix: Failure time indices in X_ext (last index if any tie).\n%\n% Output\n% He: Hessian matrix.\n%\np = size(X_ext,2);\nHe = zeros(p,p);\nnft = length(ft_ix);\nfor j=1:nft\n ties = ft_ix(t_ext(ft_ix(j))==t_ext(ft_ix));\n nties = length(ties)-1;\n rsk_ix = find(t_ext(ft_ix(j))==t_ext); \n m = length(rsk_ix);\n term1 = 0;\n for i=1:m\n term1 = term1 + exp(X_ext(rsk_ix(i),:)*Bhat)*X_ext(rsk_ix(i),:)'*X_ext(rsk_ix(i),:);\n end;\n term2 = 0; \n for i=1:nties\n term2 = term2 + exp(X_ext(ties(i),:)*Bhat)*X_ext(ties(i),:)'*X_ext(ties(i),:);\n end;\n term3 = sum(exp(X_ext(rsk_ix,:)*Bhat));\n term4 = sum(exp(X_ext(ties,:)*Bhat));\n term5 = exp(X_ext(rsk_ix,:)*Bhat)'*X_ext(rsk_ix,:);\n term6 = exp(X_ext(ties,:)*Bhat)'*X_ext(ties,:);\n term = 0; \n for l=0:nties\n Z = term5 - l*term6/(nties+1);\n phi = term3 - l*term4/(nties+1);\n term = term + (term1-l*term2/(nties+1))/phi - Z'*Z/(phi*phi); \n end;\n He = He - term;\nend;\nend\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/external/freesurfer/Survival/univariate/SStat_CoxExt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.471337913621337}}
{"text": "function value = r4_bide ( x )\n\n%*****************************************************************************80\n%\n%% R4_BIDE: exponentially scaled derivative, Airy function Bi of an R4 argument.\n%\n% Discussion:\n%\n% if X < 0,\n% R4_BIDE ( X ) = R4_BID ( X )\n% else\n% R4_BIDE ( X ) = R4_BID ( X ) * exp ( - 2/3 * X^(3/2) )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 October 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Wayne Fullerton.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Wayne Fullerton,\n% Portable Special Function Routines,\n% in Portability of Numerical Software,\n% edited by Wayne Cowell,\n% Lecture Notes in Computer Science, Volume 57,\n% Springer 1977,\n% ISBN: 978-3-540-08446-4,\n% LC: QA297.W65.\n%\n% Parameters:\n%\n% Input, real X, the argument.\n%\n% Output, real VALUE, the exponentially scaled derivative of\n% the Airy function Bi of X.\n%\n persistent atr\n persistent bif2cs\n persistent bifcs\n persistent big2cs\n persistent bigcs\n persistent bip1cs\n persistent bip2cs\n persistent btr\n persistent nbif\n persistent nbif2\n persistent nbig\n persistent nbig2\n persistent nbip1\n persistent nbip2\n persistent x2sml\n persistent x3sml\n persistent x32sml\n persistent xbig\n\n atr = 8.7506905708484345;\n btr = -2.0938363213560543;\n\n if ( isempty ( nbif ) )\n\n bif2cs = [ ...\n 0.323493987603522033521E+00, ...\n 0.086297871535563559139E+00, ...\n 0.002994025552655397426E+00, ...\n 0.000051430528364661637E+00, ...\n 0.000000525840250036811E+00, ...\n 0.000000003561751373958E+00, ...\n 0.000000000017146864007E+00, ...\n 0.000000000000061663520E+00, ...\n 0.000000000000000171911E+00, ...\n 0.000000000000000000382E+00 ]';\n bifcs = [ ...\n 0.1153536790828570243E+00, ...\n 0.0205007894049192875E+00, ...\n 0.0002135290278902876E+00, ...\n 0.0000010783960614677E+00, ...\n 0.0000000032094708833E+00, ...\n 0.0000000000062930407E+00, ...\n 0.0000000000000087403E+00, ...\n 0.0000000000000000090E+00 ]';\n big2cs = [ ...\n 1.6062999463621294578E+00, ...\n 0.7449088819876088652E+00, ...\n 0.0470138738610277380E+00, ...\n 0.0012284422062548239E+00, ...\n 0.0000173222412256624E+00, ...\n 0.0000001521901652368E+00, ...\n 0.0000000009113560249E+00, ...\n 0.0000000000039547918E+00, ...\n 0.0000000000000130017E+00, ...\n 0.0000000000000000335E+00 ]';\n bigcs = [ ...\n -0.097196440416443537390E+00, ...\n 0.149503576843167066571E+00, ...\n 0.003113525387121326042E+00, ...\n 0.000024708570579821297E+00, ...\n 0.000000102949627731379E+00, ...\n 0.000000000263970373987E+00, ...\n 0.000000000000458279271E+00, ...\n 0.000000000000000574283E+00, ...\n 0.000000000000000000544E+00 ]';\n bip1cs = [ ...\n -0.1729187351079553719E+00, ...\n -0.0149358492984694364E+00, ...\n -0.0005471104951678566E+00, ...\n 0.0001537966292958408E+00, ...\n 0.0000154353476192179E+00, ...\n -0.0000065434113851906E+00, ...\n 0.0000003728082407879E+00, ...\n 0.0000002072078388189E+00, ...\n -0.0000000658173336470E+00, ...\n 0.0000000074926746354E+00, ...\n 0.0000000011101336884E+00, ...\n -0.0000000007265140553E+00, ...\n 0.0000000001782723560E+00, ...\n -0.0000000000217346352E+00, ...\n -0.0000000000020302035E+00, ...\n 0.0000000000019311827E+00, ...\n -0.0000000000006044953E+00, ...\n 0.0000000000001209450E+00, ...\n -0.0000000000000125109E+00, ...\n -0.0000000000000019917E+00, ...\n 0.0000000000000015154E+00, ...\n -0.0000000000000004977E+00, ...\n 0.0000000000000001155E+00, ...\n -0.0000000000000000186E+00 ]';\n bip2cs = [ ...\n -0.13269705443526630495E+00, ...\n -0.00568443626045977481E+00, ...\n -0.00015643601119611610E+00, ...\n -0.00001136737203679562E+00, ...\n -0.00000143464350991284E+00, ...\n -0.00000018098531185164E+00, ...\n 0.00000000926177343611E+00, ...\n 0.00000001710005490721E+00, ...\n 0.00000000476698163504E+00, ...\n -0.00000000035195022023E+00, ...\n -0.00000000058890614316E+00, ...\n -0.00000000006678499608E+00, ...\n 0.00000000006395565102E+00, ...\n 0.00000000001554529427E+00, ...\n -0.00000000000792397000E+00, ...\n -0.00000000000258326243E+00, ...\n 0.00000000000121655048E+00, ...\n 0.00000000000038707207E+00, ...\n -0.00000000000022487045E+00, ...\n -0.00000000000004953477E+00, ...\n 0.00000000000004563782E+00, ...\n 0.00000000000000332998E+00, ...\n -0.00000000000000921750E+00, ...\n 0.00000000000000094157E+00, ...\n 0.00000000000000167154E+00, ...\n -0.00000000000000055134E+00, ...\n -0.00000000000000022369E+00, ...\n 0.00000000000000017487E+00, ...\n 0.00000000000000000207E+00 ]';\n\n eta = 0.1 * r4_mach ( 3 );\n nbif = r4_inits ( bifcs, 8, eta );\n nbig = r4_inits ( bigcs, 9, eta );\n nbif2 = r4_inits ( bif2cs, 10, eta );\n nbig2 = r4_inits ( big2cs, 10, eta );\n nbip1 = r4_inits ( bip1cs, 24, eta );\n nbip2 = r4_inits ( bip2cs, 29, eta );\n x2sml = sqrt ( eta );\n x3sml = eta^0.3333;\n x32sml = 1.3104 * x3sml * x3sml;\n xbig = r4_mach ( 2 )^0.6666;\n\n end\n\n if ( x <= - 1.0 )\n [ xn, phi ] = r4_admp ( x );\n value = xn * sin ( phi );\n elseif ( 0.0 <= x && x <= x32sml )\n x2 = 0.0;\n x3 = 0.0;\n value = x2 * ( r4_csevl ( x3, bifcs, nbif ) + 0.25 ) ...\n + r4_csevl ( x3, bigcs, nbig ) + 0.5;\n elseif ( abs ( x ) <= x2sml )\n x2 = 0.0;\n x3 = 0.0;\n value = x2 * ( r4_csevl ( x3, bifcs, nbif ) + 0.25 ) ...\n + r4_csevl ( x3, bigcs, nbig ) + 0.5;\n value = value * exp ( - 2.0 * x * sqrt ( x ) / 3.0 );\n elseif ( x <= x3sml )\n x2 = x * x;\n x3 = 0.0;\n value = x2 * ( r4_csevl ( x3, bifcs, nbif ) + 0.25 ) ...\n + r4_csevl ( x3, bigcs, nbig ) + 0.5;\n value = value * exp ( - 2.0 * x * sqrt ( x ) / 3.0 );\n elseif ( x <= 1.0 )\n x2 = x * x;\n x3 = x * x * x;\n value = x2 * ( r4_csevl ( x3, bifcs, nbif ) + 0.25 ) ...\n + r4_csevl ( x3, bigcs, nbig ) + 0.5;\n value = value * exp ( - 2.0 * x * sqrt ( x ) / 3.0 );\n elseif ( x <= 2.0 )\n z = ( 2.0 * x * x * x - 9.0 ) / 7.0;\n value = exp ( - 2.0 * x * sqrt ( x ) / 3.0 ) ...\n * ( x * x * ( 0.25 + r4_csevl ( z, bif2cs, nbif2 ) ) ...\n + 0.5 + r4_csevl ( z, big2cs, nbig2 ) );\n elseif ( x <= 4.0 )\n sqrtx = sqrt ( x );\n z = atr / ( x * sqrtx ) + btr;\n value = ( 0.625 ...\n + r4_csevl ( z, bip1cs, nbip1 ) ) * sqrt ( sqrtx );\n elseif ( x < xbig )\n sqrtx = sqrt ( x );\n z = 16.0 / ( x * sqrtx ) - 1.0;\n value = ( 0.625 + r4_csevl ( z, bip2cs, nbip2 ) ) ...\n * sqrt ( sqrtx );\n else\n sqrtx = sqrt ( x );\n z = - 1.0;\n value = ( 0.625 + r4_csevl ( z, bip2cs, nbip2 ) ) * sqrt ( sqrtx );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fn/r4_bide.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.47111296333894664}}
{"text": "function output = bicubic_interpolation_at(input,uu,vv,nx,ny,border_out,BOUNDARY_CONDITION)\noutput = 0.0;\nsx = 0;\nsy = 0;\nif(uu < 0)\n sx = -1;\nelse\n sx = 1;\nend\nif(vv < 0)\n sy = -1;\nelse\n sy = 1;\nend\nout = 0;\n\nswitch(BOUNDARY_CONDITION)\n case 0\n [out,x] = neumann_bc(uu, nx);\n [out,y] = neumann_bc(vv, ny);\n [out,mx] = neumann_bc(uu - sx, nx);\n [out,my] = neumann_bc(vv - sx, ny);\n [out,dx] = neumann_bc( uu + sx, nx);\n [out,dy] = neumann_bc( vv + sy, ny);\n [out,ddx] = neumann_bc( uu + 2*sx, nx);\n [out,ddy] = neumann_bc( vv + 2*sy, ny);\n case 1\n [out,x] =periodic_bc(uu, nx);\n [out,y] = periodic_bc(vv, ny);\n [out,mx] = periodic_bc(uu - sx, nx);\n [out,my] = periodic_bc(vv - sx, ny);\n [out,dx] = periodic_bc( uu + sx, nx);\n [out,dy] = periodic_bc( vv + sy, ny);\n [out,ddx] = periodic_bc( uu + 2*sx, nx);\n [out,ddy] = periodic_bc( vv + 2*sy, ny);\n case 2\n [out,x] = symmetric_bc(uu, nx);\n [out,y] = symmetric_bc(vv, ny);\n [out,mx] = symmetric_bc(uu - sx, nx);\n [out,my] = symmetric_bc(vv - sx, ny);\n [out,dx] = symmetric_bc( uu + sx, nx);\n [out,dy] = symmetric_bc( vv + sy, ny);\n [out,ddx] = symmetric_bc( uu + 2*sx, nx);\n [out,ddy] = symmetric_bc( vv + 2*sy, ny);\n otherwise\n [out,x] = neumann_bc(uu, nx);\n [out,y] = neumann_bc(vv, ny);\n [out,mx] = neumann_bc(uu - sx, nx);\n [out,my] = neumann_bc(vv - sx, ny);\n [out,dx] = neumann_bc( uu + sx, nx);\n [out,dy] = neumann_bc( vv + sy, ny);\n [out,ddx] = neumann_bc( uu + 2*sx, nx);\n [out,ddy] = neumann_bc( vv + 2*sy, ny);\n if((out == 1) && (border_out == 0))\n \n output = 0.0;\n else\n p11 = input(mx + nx * my);\n p12 = input(x + nx * my);\n p13 = input(dx + nx * my);\n p14 = input(ddx + nx * my);\n\n p21 = input(mx + nx * y);\n p22 = input(x + nx * y);\n p23 = input(dx + nx * y);\n p24 = input(ddx + nx * y);\n\n p31 = input(mx + nx * dy);\n p32 = input(x + nx * dy);\n p33 = input(dx + nx * dy);\n p34 = input(ddx + nx * dy);\n\n p41 = input(mx + nx * ddy);\n p42 = input(x + nx * ddy);\n p43 = input(dx + nx * ddy);\n p44 = input(ddx + nx * ddy);\n pol = [p11, p21, p31, p41;\n p12, p22, p32, p42;\n p13, p23, p33, p43;\n p14, p24, p34, p44];\n output = bicubic_interpolation_cell(pol, uu-x, vv-y);\n end\n \nend", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/å»åŖē®ę³/SPTWO_matlab-master/bicubic_interpolation_at.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.47106253636643847}}
{"text": "function x = strmv ( uplo, trans, diag, n, a, lda, x, incx )\n\n%*****************************************************************************80\n%\n%% STRMV computes x: = A*x or x = A'*x for a triangular matrix A.\n%\n% Discussion:\n%\n% STRMV performs one of the matrix-vector operations\n%\n% x := A*x, or x := A'*x,\n%\n% where x is an n element vector and A is an n by n unit, or non-unit,\n% upper or lower triangular matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 04 April 2014\n%\n% Author:\n%\n% This MATLAB version by John Burkardt.\n%\n% Parameters:\n%\n% Input, character UPLO, specifies whether the matrix is an upper or\n% lower triangular matrix as follows:\n% 'u' or 'U': A is an upper triangular matrix.\n% 'l' or 'L': A is a lower triangular matrix.\n%\n% Input, character TRANS, specifies the operation to be performed as\n% follows:\n% 'n' or 'N': x := A*x.\n% 't' or 'T': x := A'*x.\n% 'c' or 'C': x := A'*x.\n%\n% Input, character DIAG, specifies whether or not A is unit\n% triangular as follows:\n% 'u' or 'U': A is assumed to be unit triangular.\n% 'n' or 'N': A is not assumed to be unit triangular.\n%\n% Input, integer N, the order of the matrix A.\n% 0 <= N.\n%\n% Input, real A(LDA,N).\n% Before entry with UPLO = 'u' or 'U', the leading n by n\n% upper triangular part of the array A must contain the upper\n% triangular matrix and the strictly lower triangular part of\n% A is not referenced.\n% Before entry with UPLO = 'l' or 'L', the leading n by n\n% lower triangular part of the array A must contain the lower\n% triangular matrix and the strictly upper triangular part of\n% A is not referenced.\n% Note that when DIAG = 'u' or 'U', the diagonal elements of\n% A are not referenced either, but are assumed to be unity.\n%\n% Input, integer LDA, the first dimension of A as declared\n% in the calling program. max ( 1, N ) <= LDA.\n%\n% Input/output, real X(1+(N-1)*abs( INCX)).\n% Before entry, the incremented array X must contain the n\n% element vector x. On exit, X is overwritten with the\n% tranformed vector x.\n%\n% Input, integer INCX, the increment for the elements of\n% X. INCX must not be zero.\n%\n\n%\n% Test the input parameters.\n%\n info = 0;\n if ( ~ lsame ( uplo , 'U' ) && ~ lsame ( uplo , 'L' ) )\n info = 1;\n elseif ( ~ lsame ( trans, 'N' ) && ~ lsame ( trans, 'T' ) && ...\n ~ lsame ( trans, 'C' ) )\n info = 2;\n elseif ( ~ lsame ( diag , 'U' ) && ~ lsame ( diag , 'N' ) )\n info = 3;\n elseif ( n < 0 )\n info = 4;\n elseif ( lda < max ( 1, n ) )\n info = 6;\n elseif ( incx == 0 )\n info = 8;\n end\n\n if ( info ~= 0 )\n xerbla ( 'DTRMV', info );\n return\n end\n%\n% Quick return if possible.\n%\n if ( n == 0 )\n return\n end\n\n nounit = lsame ( diag, 'N' );\n%\n% Set up the start point in X if the increment is not unity. This\n% will be ( N - 1 ) * INCX too small for descending loops.\n%\n if ( incx <= 0 )\n kx = 1 - ( n - 1 ) * incx;\n elseif ( incx ~= 1 )\n kx = 1;\n end\n%\n% Start the operations. In this version the elements of A are\n% accessed sequentially with one pass through A.\n%\n if ( lsame ( trans, 'N' ) )\n%\n% Form x := A*x.\n%\n if ( lsame ( uplo, 'U' ) )\n if ( incx == 1 )\n for j = 1 : n\n if ( x(j) ~= 0.0 )\n temp = x(j);\n for i = 1 : j - 1\n x(i) = x(i) + temp * a(i,j);\n end\n if ( nounit )\n x(j) = x(j) * a(j,j);\n end\n end\n end\n else\n jx = kx;\n for j = 1 : n\n if ( x(jx) ~= 0.0 )\n temp = x(jx);\n ix = kx;\n for i = 1 : j - 1\n x(ix) = x(ix) + temp * a(i,j);\n ix = ix + incx;\n end\n if ( nounit )\n x(jx) = x(jx) * a(j,j);\n end\n end\n jx = jx + incx;\n end\n end\n else\n if ( incx == 1 )\n for j = n : -1 : 1\n if ( x(j) ~= 0.0 )\n temp = x(j);\n for i = n : -1 : j + 1\n x(i) = x(i) + temp * a(i,j);\n end\n if ( nounit )\n x(j) = x(j) * a(j,j);\n end\n end\n end\n else\n kx = kx + ( n - 1 ) * incx;\n jx = kx;\n for j = n : -1 : 1\n if ( x(jx) ~= 0.0 )\n temp = x(jx);\n ix = kx;\n for i = n : -1 : j + 1\n x(ix) = x(ix) + temp * a(i,j);\n ix = ix - incx;\n end\n if ( nounit )\n x(jx) = x(jx) * a(j,j);\n end\n end\n jx = jx - incx;\n end\n end\n end\n else\n%\n% Form x := A'*x.\n%\n if ( lsame ( uplo, 'U' ) )\n if ( incx == 1 )\n for j = n : -1 : 1\n temp = x(j);\n if ( nounit )\n temp = temp * a(j,j);\n end\n for i = j - 1 : -1 : 1\n temp = temp + a(i,j) * x(i);\n end\n x(j) = temp;\n end\n else\n jx = kx + ( n - 1 ) * incx;\n for j = n : -1 : 1\n temp = x(jx);\n ix = jx;\n if ( nounit )\n temp = temp * a(j,j);\n end\n for i = j - 1 : -1 : 1\n ix = ix - incx;\n temp = temp + a(i,j) * x(ix);\n end\n x(jx) = temp;\n jx = jx - incx;\n end\n end\n else\n if ( incx == 1 )\n for j = 1 : n\n temp = x(j);\n if ( nounit )\n temp = temp * a(j,j);\n end\n for i = j + 1 : n\n temp = temp + a(i,j) * x(i);\n end\n x(j) = temp;\n end\n else\n jx = kx;\n for j = 1 : n\n temp = x(jx);\n ix = jx;\n if ( nounit )\n temp = temp * a(j,j);\n end\n for i = j + 1 : n\n ix = ix + incx;\n temp = temp + a(i,j) * x(ix);\n end\n x(jx) = temp;\n jx = jx + incx;\n end\n end\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/blas2/strmv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4710476791456065}}
{"text": "function [K] = ku1u1(x, y, xp, yp, hyp, i)\n\nlogsigma = hyp(1);\nlogthetax = hyp(2);\nlogthetay = hyp(3);\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\nswitch i\n\n\ncase 0\n\nK=exp(1).^(logsigma+(-2).*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).^logthetay+(-1).*(y+(-1).*yp).^2);\n\n\ncase 1 % logsigma\n\nK=exp(1).^(logsigma+(-2).*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).^logthetay+(-1).*(y+(-1).*yp).^2);\n\n\ncase 2 % logthetax\n\nK=(1/2).*exp(1).^(logsigma+(-1).*logthetax+(-2).*logthetay+(-1/2).*exp(1) ...\n .^((-1).*logthetax).*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).* ...\n (y+(-1).*yp).^2).*(x+(-1).*xp).^2.*(exp(1).^logthetay+(-1).*(y+(-1).*yp) ...\n .^2);\n\n\ncase 3 % logthetay\n\nK=(-1/2).*exp(1).^(logsigma+(-3).*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.*logthetay)+(-5).*exp(1).^logthetay.*(y+(-1).* ...\n yp).^2+(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/+k11/ku1u1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105441, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4710358007135724}}
{"text": "function [sCodebook, settings] = gmlvq(sCodebook, sData, varargin)\n\n%GMLVQ trains a codebook using the Generalized Matrix LVQ (GMLVQ) \n%algorithm.\n%\n% sM = gmlvq(sM, sD, [argID, value, ...])\n%\n% sM = gmlvq(sM, sD)\n% sM = gmlvq(sM, sD, 'learningRatePrototypes', [0.01 0.001], 'relevanceStart', 10);\n%\n% Required Input Arguments:\n% sM (struct) map struct containing the labels as the \n% first column of .labels\n% sD (struct) data struct containing the labels as \n% the first column of .labels\n%\n% Optional Input Arguments:\n% PrototypesPerClass (vector) number of prototypes per class used;\n% a number or a vector with a number \n% for each class (default=1)\n% initialMatrix (matrix) initial Matrix omega\n% regularization (scalar) regularization for relevances\n% dim (scalar) maximum rank or projection dimension\n% comparable (scalar) a flag which resets the random \n% generator to produce comparable results\n% if set to 1\n% optimization (string) choice for the optimization technique: \n% sgd or fminlbfgs (default=fminlbfgs)\n% Parameter for the stochastic gradient descent sgd:\n% nb_epochs (scalar) the number of epochs (default=100)\n% learningRatePrototypes (vector) learning rate for the prototypes; could \n% be the start and end value or a vector\n% of length nb_epochs\n% learningRateMatrix (vector) learning rate for the relevance matrix;\n% could be the start and end value or a\n% vector of length nb_epochs\n% MatrixStart (scalar) epoch to start the matrix learning\n% (default=1)\n% Parameter for the build-in function fminlbfgs:\n% threshstop (scalar) the training error for early stopping\n% (default=0)\n% nb_reiterations (scalar) the number of optimization reiterations\n% performed (default=100)\n% useEarlyStopping (scalar) use early stopping based on threshstop\n% (default=1)\n% Display (string) the optimization output 'iter' or 'off'\n% (default='off')\n% GradObj (string) turn the usage of gradient information \n% on or off (default='on')\n% HessUpdate (string) the update can be 'lbfgs', 'bfgs' or \n% 'steepdesc' (default='lbfgs')\n% TolFun (scalar) the tolerance (default=1e-6)\n% MaxIter (scalar) the maximal number of iterations \n% (default=2500)\n% MaxFunEvals the maximal number of function\n% evaluations (default=1000000)\n% TolX (scalar) tolerance on the minimum \n% (default=1e-10)\n% DiffMinChange (scalar) minimal change (default=1e-10)\n%\n% Output Arguments:\n% sM (struct) map struct containing the optimized \n% prototypes and the decomposed \n% relevances omega\n% settings (struct) information on the settings of the\n% algorithm\n%\n% NOTE: does not take the vector mask into account but trains a relevance\n% matrix.\n% \n% For more help, try 'type gmlvq', or check out the online documentation.\n% See also GRLVQ, GMLVQ_CORE, LVQ3, LVQ1.\n\n%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% gmlvq\n%\n% PURPOSE\n%\n% Trains a codebook and a global metric with the Generalized Matrix LVQ\n% (GMLVQ) algorithm. \n%\n% SYNTAX\n%\n% sM = gmlvq(sM, sD)\n% sM = gmlvq(sM, sD, 'learningRatePrototypes', [0.01 0.001], 'MatrixStart', 10);\n% sM = gmlvq(sM, sD, argID, value, ...);\n%\n% DESCRIPTION\n%\n% GMLVQ constitutes an enhancement of the LVQ algorithm by minimizing an\n% explicit error function and optimizing the metric of the space where the\n% computation is performed. Distances are calculated by \n% d(x,y) = (x - y) * lambda * (x - y)', where lambda = omega' * omega.\n% The matrix omega is optimized by the algorithm.\n%\n% Two optimization techniques are implemented: \n% - stochastic gradient descent (sgd)\n% - limited memory Quasi Newton Broyden-Fletcher-Goldfarb-Shanno\n% (L-BFGS)\n%\n% Classification is performed similarly to standard LVQ, with the only\n% difference that the above specified formula is applied for the \n% computation of distances.\n%\n% This function provides an interface in the style of the som-toolbox and\n% is basically a wrapper for the method gmlvq_core. It deals with structs\n% rather then directly with data matrices.\n%\n% REFERENCES\n%\n% Petra Schneider, Michael Biehl, Barbara Hammer: Adaptive Relevance\n% Matrices in Learning Vector Quantization. Neural Computation 21(12):\n% 3532-3561 (2009).\n%\n% K. Bunte, P. Schneider, B. Hammer, F.-M. Schleif, T. Villmann and M. \n% Biehl: Limited Rank Matrix Learning - Discriminative Dimension\n% Reduction and Visualization, Neural Networks, vol. 26, nb. 4,\n% pp. 159-173, 2012.\n%\n% P. Schneider, K. Bunte, B. Hammer and M. Biehl: Regularization in \n% Matrix Relevance Learning, IEEE Transactions on Neural Networks, vol. \n% 21, nb. 5, pp. 831-840, 2010.\n%\n% REQUIRED INPUT ARGUMENTS\n% sM (struct) map struct containing the initialized\n% prototype vectors as rows of the\n% .codebooks matrix and the labels as the\n% first column of .labels\n% sD (struct) data struct containing the data vectors\n% as rows of .data and the labels as the\n% first column of .labels\n%\n% OPTIONAL INPUT ARGUMENTS\n% PrototypesPerClass (vector) number of prototypes per class used;\n% a number or a vector with a number \n% for each class (default=1)\n% initialMatrix (matrix) initial Matrix omega\n% (default: identity matrix)\n% regularization (scalar) regularization for relevances\n% (detault=0)\n% dim (scalar) maximum rank or projection dimension,\n% i.e. of the matrix omega\n% (default=nb of features for training)\n% comparable (scalar) a flag which resets the random \n% generator to produce comparable results\n% if set to 1 (default=0)\n% optimization (string) choice for the optimization technique: \n% sgd (stochastic gradient descent) or \n% fminlbfgs (Limited memory Quasi Newton \n% Broyden-Fletcher-Goldfarb-Shanno) \n% (default=fminlbfgs)\n% Parameter for the stochastic gradient descent sgd:\n% nb_epochs (scalar) the number of epochs (default=100)\n% learningRatePrototypes (vector) learning rate for the prototypes; could \n% be the value for the first and the last\n% epoch or a vector of length nb_epochs\n% learningRateMatrix (vector) learning rate for the relevance matrix;\n% could be the value for the first and\n% the last epoch or a vector of length\n% nb_epochs\n% MatrixStart (scalar) epoch to start the matrix learning\n% (default=1)\n% Parameter for the build-in function fminlbfgs:\n% threshstop (scalar) the training error for early stopping\n% (default=0)\n% nb_reiterations (scalar) the number of optimization reiterations\n% performed (default=100)\n% useEarlyStopping (scalar) use early stopping based on threshstop\n% (default=1)\n% Display (string) the optimization output 'iter' or 'off'\n% (default='off')\n% GradObj (string) turn the usage of gradient information \n% on or off (default='on')\n% HessUpdate (string) the update can be 'lbfgs', 'bfgs' or \n% 'steepdesc' (default=lbfgs)\n% TolFun (scalar) the tolerance (default=1e-6)\n% MaxIter (scalar) the maximal number of iterations \n% (default=2500)\n% MaxFunEvals the maximal number of function\n% evaluations (default=1000000)\n% TolX (scalar) tolerance on the minimum \n% (default=1e-10)\n% DiffMinChange (scalar) minimal change (default=1e-10)\n%\n% OUTPUT ARGUMENTS\n% sM (struct) map struct containing the optimized \n% prototypes and the decomposed \n% relevances omega\n% settings (struct) information on the settings of the\n% algorithm\n%\n% EXAMPLES\n% \n% lab = unique(sD.labels(:,1)); % different classes\n% nProt = length(lab)*5; % 5 prototypes for each \n% sM = som_randinit(sD,'msize',[nProt 1]); % initial prototypes\n% sM.labels = [lab;lab;lab;lab;lab]; % and their classes\n% sM = gmlvq(sM,sD); % use GMLVQ to adjust the\n% % prototypes and the metric\n%\n% SEE ALSO\n%\n% grlvq Use the GRLVQ algorithm for training.\n% gmlvq_core Access the GMLVQ functionality without using structs.\n% lvq3 Use LVQ3 algorithm for training.\n% lvq1 Use LVQ1 algorithm for training.\n\n% Contributed to SOM Toolbox vs2, December 3rd, 2012 by Alexander Schulz\n% Copyright (c) Alexander Schulz\n% http://www.cis.hut.fi/projects/somtoolbox/\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\ncods = sCodebook.codebook;\ncodLabels = sCodebook.labels;\ndata = sData.data;\nlabels = sData.labels;\n\n% convert labels from cell to a vector\nlabelsV = som_label2num(labels);\ncodLabelsV = som_label2num(codLabels);\n\n% calculate the number of prototypes per class\nn_prot_per_class = zeros(1, max(codLabelsV));\nfor i=1:max(codLabelsV)\n n_prot_per_class(i) = sum(codLabelsV == i);\nend\n\n\n% call the main function\n[model, settings] = gmlvq_core(data, labelsV, 'initialPrototypes', ... \n [cods, codLabelsV], 'PrototypesPerClass', n_prot_per_class, varargin{:});\n\n\n\n% write the results in the output struct\nsCodebook.codebook = model.w;\nsCodebook.omega = model.omega;\n%sCodebook.lambda = sCodebook.omega'*sCodebook.omega;\n\nif strcmp(settings.optimization, 'sgd')\n trainlen = settings.nb_epochs;\n alpha_ini = settings.learningRatePrototypes(1);\n alpha_type = 'power';\nelse\n trainlen = NaN;\n alpha_ini = NaN;\n alpha_type = '';\nend\n\n\n\nsTrain = som_set('som_train','algorithm','GMLVQ',...\n\t\t 'data_name',sData.name,...\n\t\t 'neigh','',...\n\t\t 'mask',ones(size(model.w,2),1),...\n\t\t 'radius_ini',NaN,...\n\t\t 'radius_fin',NaN,...\n\t\t 'alpha_ini',alpha_ini,... \n\t\t 'alpha_type',alpha_type,...\n\t\t 'trainlen',trainlen,...\n\t\t 'time',datestr(now,0));\nsCodebook.trainhist(end+1) = sTrain;\n\n\n", "meta": {"author": "ilarinieminen", "repo": "SOM-Toolbox", "sha": "f2597abc1ae33c2060e0443d49e854011ff21831", "save_path": "github-repos/MATLAB/ilarinieminen-SOM-Toolbox", "path": "github-repos/MATLAB/ilarinieminen-SOM-Toolbox/SOM-Toolbox-f2597abc1ae33c2060e0443d49e854011ff21831/contrib/gmlvq/gmlvq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.4708902555012384}}
{"text": "function [data] = iHOSVD(core, U)\n\nsite = size(core);\ndata = core;\n\nfor i=1:ndims(core)\n [m n] = size(U{i});\n site(i) = m;\n data = folding(U{i}*unfolding(data,i), i, site);\nend", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/td/RSTD/utils/iHOSVD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8152324713956856, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4707929737799833}}
{"text": "function [ r, z, rho, c, s, info ] = dchdd ( r, ldr, p, x, z, ldz, nz, y, rho )\n\n%*****************************************************************************80\n%\n%% DCHDD downdates an augmented Cholesky decomposition.\n%\n% Discussion:\n%\n% DCHDD can also downdate the triangular factor of an augmented QR\n% decomposition.\n%\n% Specifically, given an upper triangular matrix R of order P, a\n% row vector X, a column vector Z, and a scalar Y, DCHDD\n% determines an orthogonal matrix U and a scalar ZETA such that\n%\n% (R Z ) (RR ZZ)\n% U * ( ) = ( ),\n% (0 ZETA) ( X Y)\n%\n% where RR is upper triangular.\n%\n% If R and Z have been obtained from the factorization of a least squares\n% problem, then RR and ZZ are the factors corresponding to the problem\n% with the observation (X,Y) removed. In this case, if RHO\n% is the norm of the residual vector, then the norm of\n% the residual vector of the downdated problem is\n% sqrt ( RHO * RHO - ZETA * ZETA ). DCHDD will simultaneously downdate\n% several triplets (Z, Y, RHO) along with R.\n%\n% For a less terse description of what DCHDD does and how\n% it may be applied, see the LINPACK guide.\n%\n% The matrix U is determined as the product U(1)*...*U(P)\n% where U(I) is a rotation in the (P+1,I)-plane of the form\n%\n% ( C(I) -S(I) )\n% ( ).\n% ( S(I) C(I) )\n%\n% The rotations are chosen so that C(I) is real.\n%\n% The user is warned that a given downdating problem may be impossible\n% to accomplish or may produce inaccurate results. For example, this\n% can happen if X is near a vector whose removal will reduce the\n% rank of R. Beware.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 May 2005\n%\n% Author:\n%\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Dongarra, Moler, Bunch and Stewart,\n% LINPACK User's Guide,\n% SIAM, (Society for Industrial and Applied Mathematics),\n% 3600 University City Science Center,\n% Philadelphia, PA, 19104-2688.\n% ISBN 0-89871-172-X\n%\n% Parameters:\n%\n% Input, real R(LDR,P), the upper triangular matrix that\n% is to be downdated. The part of R below the diagonal is not referenced.\n%\n% Input, integer LDR, the leading dimension of the array R.\n% LDR must be at least P.\n%\n% Input, integer P, the order of the matrix R.\n%\n% Input, real X(P), the row vector that is to be removed from R.\n%\n% Input, real Z(LDZ,NZ), an array of NZ P-vectors\n% which are to be downdated along with R.\n%\n% Input, integer LDZ, the leading dimension of the array Z.\n% LDZ must be at least P.\n%\n% Input, integer NZ, the number of vectors to be downdated.\n% NZ may be zero, in which case Z, Y, and RHO are not referenced.\n%\n% Input, real Y(NZ), the scalars for the downdating of\n% the vectors Z.\n%\n% Input, real RHO(NZ), the norms of the residual vectors.\n%\n% Output, real R(LDR,P), the downdated upper triangular matrix.\n%\n% Output, real Z(LDZ,NZ), the downdated vectors.\n%\n% Output, real RHO(NZ), the norms of the residual vectors,\n% which have been changed along with R and Z.\n%\n% Output, real C(P), S(P), the cosines and sines of the\n% transforming rotations.\n%\n% Output, integer INFO, return flag.\n% 0, the entire downdating was successful.\n% -1, if R could not be downdated. In this case, all quantities\n% are left unaltered.\n% 1, if some RHO could not be downdated. The offending RHO's are\n% set to -1.\n%\n\n%\n% Solve R' * A = X, placing the result in the array S.\n%\n info = 0;\n s(1) = x(1) / r(1,1);\n\n for j = 2 : p\n s(j) = x(j) - ddot ( j-1, r(1:j-1,j), 1, s(1:j-1), 1 );\n s(j) = s(j) / r(j,j);\n end\n\n norm = dnrm2 ( p, s(1:p), 1 );\n\n if ( 1.0 <= norm )\n info = -1;\n return\n end\n\n alpha = sqrt ( 1.0 - norm * norm );\n%\n% Determine the transformations.\n%\n for ii = 1 : p\n i = p - ii + 1;\n scale = alpha + abs ( s(i) );\n a = alpha / scale;\n b = s(i) / scale;\n norm = sqrt ( a * a + b * b );\n c(i) = a / norm;\n s(i) = b / norm;\n alpha = scale * norm;\n end\n%\n% Apply the transformations to R.\n%\n for j = 1 : p\n xx = 0.0;\n for ii = 1 : j\n i = j - ii + 1;\n t = c(i) * xx + s(i) * r(i,j);\n r(i,j) = c(i) * r(i,j) - s(i) * xx;\n xx = t;\n end\n end\n%\n% If required, downdate Z and RHO.\n%\n for j = 1 : nz\n\n zeta = y(j);\n for i = 1 : p\n z(i,j) = ( z(i,j) - s(i) * zeta ) / c(i);\n zeta = c(i) * zeta - s(i) * z(i,j);\n end\n\n azeta = abs ( zeta );\n\n if ( rho(j) < azeta )\n info = 1;\n rho(j) = -1.0;\n else\n rho(j) = rho(j) * sqrt ( 1.0 - ( azeta / rho(j) )^2 );\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linpack_d/dchdd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.4707302545778351}}
{"text": "%This Matlab script can be used to reproduce Figure 5.13 in the monograph:\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%Empty workspace and close figures\nclose all;\nclear;\n\n\n%Load SE simulation data, generated using the code from Section 4\nload section5_Mvarying_K10_20;\n\n%Number of UEs per BS\nk_index = 2; %Selecting K = 10 from the loaded SE results\nK = Krange(k_index);\n\n%Fractions of data samples used for UL and DL\nULfraction = 1/3;\nDLfraction = 2/3;\n\n%Compute joint UL/DL sum SE using the fractions of UL/DL data\nsumSE_MMMSE = ULfraction*sumSE_MMMSE_UL(:,k_index) + DLfraction*sumSE_MMMSE_DL(:,k_index);\nsumSE_SMMSE = ULfraction*sumSE_SMMSE_UL(:,k_index) + DLfraction*sumSE_SMMSE_DL(:,k_index);\nsumSE_RZF = ULfraction*sumSE_RZF_UL(:,k_index) + DLfraction*sumSE_RZF_DL(:,k_index);\nsumSE_ZF = ULfraction*sumSE_ZF_UL(:,k_index) + DLfraction*sumSE_ZF_DL(:,k_index);\nsumSE_MR = ULfraction*sumSE_MR_UL(:,k_index) + DLfraction*sumSE_MR_DL(:,k_index);\n\n%Number of BSs\nL = 16;\n\n%Communication bandwidth\nB = 20e6;\n\n%PA efficiency UEs and BSs\nmu_UE = 0.4;\nmu_BS = 0.5;\n\n%Define the pilot reuse factor\nf = 1;\n\n%Select length of coherence block\ntau_c = 200;\n\n%Compute length of pilot sequences\ntau_p = f*K;\n\n%Transmit power per UE in W\np = 0.1;\n\n%Compute total effective transmit power\nETP_total = K*p*(tau_p/mu_UE + (tau_c-tau_p)*(ULfraction/mu_UE + DLfraction/mu_BS))/tau_c;\n\n\n%% Go through the two value sets of the CP model\nfor valueset = 1:2\n \n %Compute the total CP with different schemes\n [P_MR,P_RZF,P_MMMSE,P_ZF,P_SMMSE] = functionCPcomputation(Mrange,K,L,B,tau_c,tau_p,valueset,sumSE_MR,sumSE_RZF,sumSE_MMMSE,sumSE_ZF,sumSE_SMMSE);\n \n \n %Compute EE with M-MMSE\n EE_MMMSE = (B*sumSE_MMMSE)./(ETP_total + P_MMMSE);\n \n %Compute EE with S-MMSE\n EE_SMMSE = (B*sumSE_SMMSE)./(ETP_total + P_SMMSE);\n \n %Compute EE with RZF\n EE_RZF = (B*sumSE_RZF)./(ETP_total + P_RZF);\n \n %Compute EE with ZF\n EE_ZF = (B*sumSE_ZF)./(ETP_total + P_ZF);\n \n %Compute EE with MR\n EE_MR = (B*sumSE_MR)./(ETP_total + P_MR);\n \n \n %Plot simulation results\n figure;\n \n plot(B*sumSE_MMMSE/10^6,EE_MMMSE/10^6, 'rd-','LineWidth',1);hold on;\n plot(B*sumSE_SMMSE/10^6,EE_SMMSE/10^6,'b:','LineWidth',1);\n plot(B*sumSE_RZF/10^6,EE_RZF/10^6,'k-.','LineWidth',1);\n plot(B*sumSE_ZF/10^6,EE_ZF/10^6,'r--','LineWidth',1);\n plot(B*sumSE_MR/10^6,EE_MR/10^6,'bs-','LineWidth',1);\n \n xlabel('Throughput [Mbit/s/cell]');\n ylabel('EE [Mbit/Joule/cell]');\n legend('M-MMSE','S-MMSE','RZF','ZF','MR','Location','NorthWest');\n \nend\n", "meta": {"author": "emilbjornson", "repo": "massivemimobook", "sha": "4e429497dea72d52172972f3f686b34d1d047013", "save_path": "github-repos/MATLAB/emilbjornson-massivemimobook", "path": "github-repos/MATLAB/emilbjornson-massivemimobook/massivemimobook-4e429497dea72d52172972f3f686b34d1d047013/Code/section5_figure13.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431679972357831, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.47073024222888366}}
{"text": "% SP_PRECOMPUTE: compute the basis functions in the whole mesh. The output\n% can consume a lot of memory. Use with care.\n%\n% space = sp_precompute (space, msh);\n% space = sp_precompute (space, msh, 'option', value);\n%\n% INPUT:\n% \n% space: object representing the discrete function space (see sp_vector)\n% msh: mesh object containing the quadrature information (see msh_cartesian)\n% 'option', value: additional optional parameters, currently available options are:\n% \n% Name | Default value | Meaning\n% ------------+-----------------+----------------------------------\n% value | true | compute shape_functions\n% gradient | false | compute shape_function_gradients\n% divergence | false | compute shape_function_divs\n% curl | false | compute shape_function_curls\n%\n% OUTPUT:\n%\n% space: object containing the information of the input object, plus the \n% fields of the old structure, that are listed below. If no option\n% is given all the fields are computed. If an option is given,\n% only the selected fields will be computed.\n%\n% FIELD_NAME (SIZE) DESCRIPTION\n% ncomp (scalar) number of components of the functions of the space\n% ndof (scalar) total number of degrees of freedom\n% ndof_dir (ncomp x ndim matrix) for each component, number of degrees of freedom along each direction\n% nsh_max (scalar) maximum number of shape functions per element\n% nsh (1 x msh.nel vector) actual number of shape functions per each element\n% connectivity (nsh_max x msh.nel vector) indices of basis functions that do not vanish in each element\n% shape_functions (ncomp x msh.nqn x nsh_max x msh.nel) basis functions evaluated at each quadrature node in each element\n% shape_function_gradients\n% (ncomp x rdim x msh.nqn x nsh_max x msh.nel) basis function gradients evaluated at each quadrature node in each element\n% shape_function_divs (msh.nqn x nsh_max x msh.nel) basis function divergence evaluated at each quadrature node in each element\n% shape_function_curls\n% 2D: (msh.nqn x nsh_max x msh.nel) basis function curl evaluated at each quadrature node in each element\n% 3D: (3 x msh.nqn x nsh_max x msh.nel) \n%\n% Copyright (C) 2009, 2010 Carlo de Falco\n% Copyright (C) 2015, 2019 Rafael Vazquez\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\nfunction sp_out = sp_precompute (sp, msh, varargin)\n\nvalue = true;\ngradient = false;\ndivergence = false;\ncurl = false;\nhessian = false;\n\nif (~isempty (varargin))\n if (~rem (length (varargin), 2) == 0)\n error ('sp_precompute: options must be passed in the [option, value] format');\n end\n for ii=1:2:length(varargin)-1\n if (strcmpi (varargin {ii}, 'value'))\n value = varargin {ii+1};\n elseif (strcmpi (varargin {ii}, 'gradient'))\n gradient = varargin {ii+1};\n elseif (strcmpi (varargin {ii}, 'curl'))\n curl = varargin {ii+1};\n elseif (strcmpi (varargin {ii}, 'divergence'))\n divergence = varargin {ii+1};\n elseif (strcmpi (varargin {ii}, 'hessian'))\n hessian = varargin {ii+1};\n else\n warning ('Ignoring unknown option %s', varargin {ii});\n end\n end\nend\n\nif (~isstruct (msh))\n msh = msh_precompute (msh);\nend\n \ngrad_param = gradient || divergence || curl || hessian;\nvalue_param = value || grad_param;\ndiv_param = false; curl_param = false;\nswitch (lower (sp.transform))\n case {'curl-preserving'}\n curl_param = curl;\n case {'div-preserving'}\n div_param = divergence;\nend\n\nsp_out = sp_precompute_param (sp, msh, 'value', value_param, 'gradient', grad_param, 'divergence', div_param, 'curl', curl_param, 'hessian', hessian);\n\nswitch (lower (sp.transform))\n case {'grad-preserving'}\n sp_out = sp_vector_grad_preserving_transform (sp_out, msh, value, gradient, curl, divergence, hessian);\n case {'curl-preserving'}\n sp_out = sp_vector_curl_preserving_transform (sp_out, msh, value, curl);\n if (gradient || divergence || hessian)\n warning ('Gradient, divergence and hessian not implemented for curl-preserving transformation')\n end\n case {'div-preserving'}\n sp_out = sp_vector_div_preserving_transform (sp_out, msh, value, gradient, curl, divergence);\n if (hessian)\n warning ('Hessian not implemented for div-preserving transformation')\n end\nend\n\nend\n", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/space/@sp_vector/sp_precompute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.63341024983754, "lm_q1q2_score": 0.47073023400649877}}
{"text": "% PTrc2sp()\n\n% from emuflight\n\nfunction [RCcommand_dps] = PTrc2sp(RCcommand, rateSystem)\n%function [RCcommand_dps] = PTrc2sp(RCcommand)\n% converts rc command to deg/s\n\nBetaflightRates = 1;\nBFActualRates = 2;\n\nEmuflightRates = 2;\n\n rcCommandf = RCcommand / 500.0;\n rcCommandfAbs = abs(rcCommandf);\n\n % if rc_expo \n expof = rc_expo / 100;\n rcCommandf = rcCommandf * Math.pow(rcCommandfAbs, RC_EXPO_POWER) * expof + rcCommandf * (1-expof);\n % end\n\n rcRate = rc_rates / 100.0;\n % if (rcRate > 2.0) \n rcRate += RC_RATE_INCREMENTAL * (rcRate - 2.0);\n % end\n\n angleRate = 200.0 * rcRate * rcCommandf;\n % if rates \n rcSuperfactor = 1.0 / ((1.0 - (rcCommandfAbs * rates / 100.0)));\n angleRate = angleRate * rcSuperfactor;\n % end\n\n return calculateSetpointRate(axis, value);\n\n\n%%%%% From betaflight configurator RC3\n\n\n const minRc = 1000;\nconst midRc = 1500;\nconst maxRc = 2000;\n\nconst RateCurve = function (useLegacyCurve) {\n this.useLegacyCurve = useLegacyCurve;\n this.maxAngularVel = null;\n\n this.constrain = function (value, min, max) {\n return Math.max(min, Math.min(value, max));\n };\n\n this.rcCommand = function (rcData, rcRate, deadband) {\n const tmp = Math.min(Math.max(Math.abs(rcData - midRc) - deadband, 0), 500);\n\n let result = tmp * rcRate;\n\n if (rcData < midRc) {\n result = -result;\n }\n\n return result;\n };\n\n \n \n \n this.getBetaflightRates = function (rcCommandf, rcCommandfAbs, rate, rcRate, rcExpo, superExpoActive, limit) {\n let angularVel;\n\n if (rcRate > 2) {\n rcRate = rcRate + (rcRate - 2) * 14.54;\n }\n\n let expoPower;\n let rcRateConstant;\n\n if (semver.gte(FC.CONFIG.apiVersion, \"1.20.0\")) {\n expoPower = 3;\n rcRateConstant = 200;\n } else {\n expoPower = 2;\n rcRateConstant = 205.85;\n }\n\n if (rcExpo > 0) {\n rcCommandf = rcCommandf * Math.pow(rcCommandfAbs, expoPower) * rcExpo + rcCommandf * (1-rcExpo);\n }\n\n if (superExpoActive) {\n const rcFactor = 1 / this.constrain(1 - rcCommandfAbs * rate, 0.01, 1);\n angularVel = rcRateConstant * rcRate * rcCommandf; // 200 should be variable checked on version (older versions it's 205,9)\n angularVel = angularVel * rcFactor;\n } else {\n angularVel = (((rate * 100) + 27) * rcCommandf / 16) / 4.1; // Only applies to old versions ?\n }\n\n angularVel = this.constrain(angularVel, -1 * limit, limit); // Rate limit from profile\n\n return angularVel;\n };\n\n this.getRaceflightRates = function (rcCommandf, rate, rcRate, rcExpo) {\n let angularVel = ((1 + 0.01 * rcExpo * (rcCommandf * rcCommandf - 1.0)) * rcCommandf);\n angularVel = (angularVel * (rcRate + (Math.abs(angularVel) * rcRate * rate * 0.01)));\n return angularVel;\n };\n\n this.getKISSRates = function (rcCommandf, rcCommandfAbs, rate, rcRate, rcExpo) {\n const kissRpy = 1 - rcCommandfAbs * rate;\n const kissTempCurve = rcCommandf * rcCommandf;\n rcCommandf = ((rcCommandf * kissTempCurve) * rcExpo + rcCommandf * (1 - rcExpo)) * (rcRate / 10);\n return ((2000.0 * (1.0 / kissRpy)) * rcCommandf);\n };\n\n this.getActualRates = function (rcCommandf, rcCommandfAbs, rate, rcRate, rcExpo) {\n let angularVel;\n const expof = rcCommandfAbs * ((Math.pow(rcCommandf, 5) * rcExpo) + (rcCommandf * (1 - rcExpo)));\n\n angularVel = Math.max(0, rate-rcRate);\n angularVel = (rcCommandf * rcRate) + (angularVel * expof);\n\n return angularVel;\n };\n\n this.getQuickRates = function (rcCommandf, rcCommandfAbs, rate, rcRate, rcExpo) {\n rcRate = rcRate * 200;\n rate = Math.max(rate, rcRate);\n\n let angularVel;\n const superExpoConfig = (((rate / rcRate) - 1) / (rate / rcRate));\n const curve = Math.pow(rcCommandfAbs, 3) * rcExpo + rcCommandfAbs * (1 - rcExpo);\n\n angularVel = 1.0 / (1.0 - (curve * superExpoConfig));\n angularVel = rcCommandf * rcRate * angularVel;\n\n return angularVel;\n };\n\n};\n\nRateCurve.prototype.rcCommandRawToDegreesPerSecond = function (rcData, rate, rcRate, rcExpo, superExpoActive, deadband, limit) {\n let angleRate;\n\n if (rate !== undefined && rcRate !== undefined && rcExpo !== undefined) {\n let rcCommandf = this.rcCommand(rcData, 1, deadband);\n if (semver.gte(FC.CONFIG.apiVersion, API_VERSION_1_43)) {\n rcCommandf = rcCommandf / (500 - deadband);\n } else {\n rcCommandf = rcCommandf / 500;\n }\n\n const rcCommandfAbs = Math.abs(rcCommandf);\n\n switch(TABS.pid_tuning.currentRatesType) {\n case TABS.pid_tuning.RATES_TYPE.RACEFLIGHT:\n angleRate=this.getRaceflightRates(rcCommandf, rate, rcRate, rcExpo);\n\n break;\n\n case TABS.pid_tuning.RATES_TYPE.KISS:\n angleRate=this.getKISSRates(rcCommandf, rcCommandfAbs, rate, rcRate, rcExpo);\n\n break;\n\n case TABS.pid_tuning.RATES_TYPE.ACTUAL:\n angleRate=this.getActualRates(rcCommandf, rcCommandfAbs, rate, rcRate, rcExpo);\n\n break;\n\n case TABS.pid_tuning.RATES_TYPE.QUICKRATES:\n angleRate=this.getQuickRates(rcCommandf, rcCommandfAbs, rate, rcRate, rcExpo);\n\n break;\n\n // add future rates types here\n default: // BetaFlight\n angleRate=this.getBetaflightRates(rcCommandf, rcCommandfAbs, rate, rcRate, rcExpo, superExpoActive, limit);\n\n break;\n }\n }\n\n return angleRate;\n};\n\nRateCurve.prototype.getMaxAngularVel = function (rate, rcRate, rcExpo, superExpoActive, deadband, limit) {\n let maxAngularVel;\n if (!this.useLegacyCurve) {\n maxAngularVel = this.rcCommandRawToDegreesPerSecond(maxRc, rate, rcRate, rcExpo, superExpoActive, deadband, limit);\n }\n\n return maxAngularVel;\n};\n\nRateCurve.prototype.setMaxAngularVel = function (value) {\n this.maxAngularVel = Math.ceil(value/200) * 200;\n return this.maxAngularVel;\n\n};\n\nRateCurve.prototype.draw = function (rate, rcRate, rcExpo, superExpoActive, deadband, limit, maxAngularVel, context) {\n if (rate !== undefined && rcRate !== undefined && rcExpo !== undefined) {\n const height = context.canvas.height;\n const width = context.canvas.width;\n\n if (this.useLegacyCurve) {\n this.drawLegacyRateCurve(rate, rcRate, rcExpo, context, width, height);\n } else {\n this.drawRateCurve(rate, rcRate, rcExpo, superExpoActive, deadband, limit, maxAngularVel, context, width, height);\n }\n }\n};", "meta": {"author": "bw1129", "repo": "PIDtoolbox", "sha": "0a6c2944ae728968f44467a629cc53b63db75dd7", "save_path": "github-repos/MATLAB/bw1129-PIDtoolbox", "path": "github-repos/MATLAB/bw1129-PIDtoolbox/PIDtoolbox-0a6c2944ae728968f44467a629cc53b63db75dd7/PTrc2sp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989815306765, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.4706810265233031}}
{"text": "function [rc,var,ASAcontrol] = burg_s(f,b,max_order,last)\n%BURG_S Burg type AR estimator for multiple segments\n% [RC,VAR] = BURG_S(SIG_MTX,MAX_ORDER) estimates a single vector of AR-\n% reflectioncoefficients RC up to order MAX_ORDER, using data from \n% multiple segments simultaneously. The data segments must be of equal \n% length and arranged columnwise in SIG_MTX. VAR is the estimated \n% variance based on all elements of SIG_MTX.\n% \n% RC = BURG_S(F,B,ADD_ORDER) estimates ADD_ORDER additional \n% reflectioncoefficients from matrices of forward and backward \n% residuals F and B, that have been internally used in a previous Burg \n% estimation procedure.\n% \n% Since forward and backward residual vectors are internally assigned \n% to the ASAglob variables 'ASAglob_final_f' and 'ASAglob_final_b', an \n% appropriate F and B can be retrieved after the program has finished \n% execution. This is most easily done by typing:\n% F = ASAglobretr('ASAglob_final_f');\n% B = ASAglobretr('ASAglob_final_b');\n% \n% BURG_S is an ARMASA main function.\n% \n% See also: BURG, ASAGLOB, ASAGLOBRETR.\n\n% References: S. de Waele and P. M. T. Broersen, The Burg Algorithm for\n% Segments, IEEE Transactions on Signal Processing,\n% vol. 48, no. 10, pp. 2876-2880, October 2000.\n% W. Wunderink, The Introduction of a Computationally\n% Efficient Burg Estimator Algorithm,\n% Tech. Report SSC-March00-1, Delft University of\n% Technology, Department of Applied Physics, Systems\n% Signals and Control Group, the Netherlands, March 2000.\n\n%Header\n%==============================================================================\n\n%Declaration of variables\n%------------------------\n\n%Declare and assign values to local variables\n%according to the input argument pattern\nswitch nargin\ncase 1 \n if isa(f,'struct'), ASAcontrol=f;\n else, error(ASAerr(39))\n end\n f=[]; b=[]; max_order=[];\ncase 2 \n if isa(b,'struct'), error(ASAerr(2,mfilename))\n end\n max_order=b; b=[]; ASAcontrol=[];\ncase 3 \n if isa(max_order,'struct'), ASAcontrol=max_order; max_order=b; b=[];\n else, ASAcontrol=[];\n end\ncase 4\n if isa(last,'struct'), ASAcontrol=last;\n else, error(ASAerr(39))\n end\notherwise\n error(ASAerr(1,mfilename))\nend\n\nstate = 0;\nif isequal(nargin,1) & ~isempty(ASAcontrol)\n %ASAcontrol is the only input argument\n ASAcontrol.error_chk = 0;\n ASAcontrol.run = 0;\nelseif (isequal(nargin,3) & isempty(ASAcontrol)) | ...\n isequal(nargin,4) %f and b have been provided\n %as input arguments (empty b not excluded)\n state = 1;\nend\n\n%Declare ASAglob variables \nASAglob = {'ASAglob_final_f';'ASAglob_final_b'};\n\n%Assign values to ASAglob variables by screening the\n%caller workspace\nfor ASAcounter = 1:length(ASAglob)\n ASAvar = ASAglob{ASAcounter};\n eval(['global ' ASAvar]);\n if evalin('caller',['exist(''' ASAvar ''',''var'')'])\n eval([ASAvar '=evalin(''caller'',ASAvar);']);\n else\n eval([ASAvar '=[];']);\n end\nend\n\n%ARMASA-function version information\n%-----------------------------------\n\n%This ARMASA-function is characterized by\n%its current version,\nASAcontrol.is_version = [2000 12 30 20 0 0];\n%and its compatability with versions down to,\nASAcontrol.comp_version = [2000 12 30 20 0 0];\n\n%This function calls other functions of the ARMASA\n%toolbox. The versions of these other functions must\n%be greater than or equal to:\nASAcontrol.req_version.convolrev = [2000 12 6 12 17 20];\n\n%Checks\n%------\n\nif ~any(strcmp(fieldnames(ASAcontrol),'error_chk')) | ASAcontrol.error_chk\n %Perform standard error checks\n %Input argument format checks\n ASAcontrol.error_chk = 1;\n if ~isnum(f)\n error(ASAerr(11,'f'))\n elseif isavector(f) & size(f,2)>1\n f = f(:);\n warning(ASAwarn(25,{'row';'f';'column'},ASAcontrol))\n elseif ~(length(size(f))==2)\n error(ASAerr(35,'f'))\n end\n if ~isavector(f)\n warning(ASAwarn(36,ASAcontrol))\n end\n if ~isempty(b)\n if ~isnum(b)\n error(ASAerr(11,'b'))\n elseif isavector(b) & size(b,2)>1\n b = b(:);\n warning(ASAwarn(25,{'row';'b';'column'},ASAcontrol))\n elseif ~(length(size(b))==2)\n error(ASAerr(35,'b'))\n end\n end\n if ~isnum(max_order) | ~isintscalar(max_order) | ...\n max_order<0\n error(ASAerr(17,'max_order'))\n end\n \n %Input argument value checks\n if ~isreal(f) | (~isempty(b) & ~isreal(b))\n error(ASAerr(13))\n end\n if isempty(b)\n if max_order>size(f,1)-1\n error(ASAerr(21))\n end\n elseif ~isequal(size(f),size(b))\n error(ASAerr(28,{'f','b'}))\n elseif max_order>size(f,1)-2\n error(ASAerr(29,'max_order'))\n end\nend\n\nif ~any(strcmp(fieldnames(ASAcontrol),'version_chk')) | ASAcontrol.version_chk\n %Perform version check\n ASAcontrol.version_chk = 1;\n \n %Make sure the requested version of this function\n %complies with its actual version\n ASAversionchk(ASAcontrol);\n \n %Make sure the requested versions of the called\n %functions comply with their actual versions\n convolrev(ASAcontrol);\nend\n\nif ~any(strcmp(fieldnames(ASAcontrol),'run')) | ASAcontrol.run\n %Run the computational kernel\n ASAcontrol.run = 1;\n ASAcontrol.version_chk = 0;\n ASAcontrol.error_chk = 0;\n \n%Main \n%==========================================================================\n\n[N,n] = size(f);\nP = max_order;\n\nif P>0\n %The protocol is tuned using Matlab R12,\n %but also works fine on R11.\n if ~isempty(b)\n P = P+1;\n protocol = [0 3 0;0 0 0;0 0 0;0 P 0];\n else \n if N<128\n protocol = [0 3 0;0 0 0;0 0 0;0 P 0];\n elseif N<12000 %C_7 (& C_13)\n if P<(0.1+6.7e-006*N)*N %C_14 & S\n protocol = [0 1 0;0 0 0;0 0 0;0 P 0];\n else\n protocol = [0 3 0;0 0 0;0 0 0;0 P 0];\n end\n else\n if P<0.18*N %S\n protocol = [0 1 0;0 0 0;0 0 0;0 P 0];\n else\n protocol = [0 1 3 0;0 0 0 0;0 1 0 0;0 round(0.03*N) P 0]; %C_5\n end\n end\n end\nelse\n protocol = zeros(4,2);\nend\n\np = 0;\np_max = 0;\ni2 = 2;\nwhile protocol(4,i2)~=0;\n p = protocol(4,i2)-protocol(4,i2-1);\n if p>p_max\n p_max = p;\n end\n i2 = i2+1;\nend\ni9 = 1;\ni10 = 2;\nif n>N\n i9 = 2;\n i10 = 1;\nend\n\nv = zeros(N+p_max,n,2);\na = zeros(N+p_max,n,2);\nif isempty(b)\n v(1:N,:,2) = f;\n a(1+p_max:N+p_max,:,2) = f;\n if protocol(1,2)==3 | protocol(1,2)==0\n var = sum(sum(f(1:N,:).^2,i9),i10)/(n*N);\n den = 2*var*n*N;\n end\nelse\n v(1:N,:,2) = f;\n a(1+p_max:N+p_max,:,2) = b;\n den = sum(sum(f(1:N,:).^2+b(1:N,:).^2,i9),i10);\n var = [];\nend\n\nr1 = p_max+1;\nv1 = [1 1];\nv2 = [N N];\nv3 = [N N];\na1 = [r1 r1];\na2 = [r1 r1];\na3 = [r1+N-1 r1+N-1];\nrc = zeros(1,P+1);\ni1 = 0;\ni2 = 2;\ni4 = 0;\nc = 0;\n\nwhile protocol(4,i2)~=0\n i1 = i1+1;\n p = protocol(4,i2);\n \n if protocol(1,i2)==3 %SP\n r2 = a2(1)+1;\n r3 = v2(1)-1;\n r4 = a2(2)+1;\n r5 = v2(2)-1;\n i5 = i1;\n for i1 = i1:p\n i5 = i5+1;\n if c, c0 = 2; c1 = 1;\n else c0 = 1; c1 = 2;\n end \n v1(c0) = v1(c1)+1;\n a3(c0) = a3(c1)-1;\n v(v1(c0):v2(c0),:,c0) = v(v1(c0):v2(c1),:,c1)+...\n rc(i1)*a(r4:a3(c1),:,c1);\n a(a2(c0):a3(c0),:,c0) = a(a2(c1):a3(c0),:,c1)+...\n rc(i1)*v(v1(c1):r5,:,c1);\n den = (1-rc(i1)^2)*den-...\n sum((v(v1(c1),:,c1)+rc(i1)*a(a2(c1),:,c1)).^2)-...\n sum((a(a3(c1),:,c1)+rc(i1)*v(v2(c1),:,c1)).^2);\n rc(i5) = -2*sum(sum(v(v1(c0):v2(c0),:,c0).*...\n a(a2(c0):a3(c0),:,c0),i9),i10)/den;\n c = ~c;\n end\n v(v1(c1),:,c0) = v(v1(c1),:,c1)+rc(i1)*a(a2(c1),:,c1);\n a(a3(c1),:,c0) = a(a3(c1),:,c1)+rc(i1)*v(v2(c1),:,c1);\n \n elseif protocol(1,i2)==1 %ACC\n i13 = 2*p;\n i14 = p+1;\n i15 = 0;\n i16 = 0;\n i17 = 0;\n jj = zeros(2,i13);\n jjm_h = zeros(2,i14);\n jj_h = zeros(2,i14);\n jj(2,1) = 1;\n jjm_h(2,1) = 1;\n jj_h(2,2) = 1;\n for i4 = 1:n\n acov_x(:,i4) = convolrev(f(:,i4),p,ASAcontrol);\n end\n i1 = i1+1;\n var = sum(acov_x(1,:));\n den = (2*var-sum(v(v1(2),:,2).^2)-sum(a(a3(2),:,2).^2));\n rc(i1) = -2*sum(acov_x(2,:))/den;\n var = var/(n*N);\n v1(2) = v1(2)+1;\n a3(2) = a3(2)-1;\n t = 0;\n r5 = v1(2)+p-2;\n r6 = a3(2)-p+2;\n if protocol(3,i2)==1\n r11 = r5+1;\n r12 = r6-1;\n i33 = 0;\n else \n r11 = v2(2)-p+2;\n r12 = a2(2)+p-2;\n i33 = 1;\n end\n r7 = v2(2)+1;\n r8 = a2(2)-1;\n r9 = v1(2);\n r10 = a3(2);\n r13 = r5-r9;\n r14 = r10-r6;\n r15 = r11-r9;\n r16 = r10-r12;\n \n for i1 = i1:p\n i13 = i1+1;\n i14 = i1-1;\n i15 = 2*i1-1;\n i16 = 2*i1-2;\n i17 = 2*i1-3;\n rc_h1 = rc(i1)^2;\n rc_h2 = 2*rc(i1);\n if c, c0 = 2; c1 = 1;\n else c0 = 1; c1 = 2;\n end \n jj(c0,1:2) = jj(c1,1:2);\n jj(c0,3:i15) = jj(c1,3:i15)+rc_h1*jj(c1,i17:-1:1);\n jj(c0,i1:i16) = jj(c0,i1:i16)+rc_h2*jjm_h(c1,1:i14);\n jj(c0,2:i14) = jj(c0,2:i14)+rc_h2*jjm_h(c1,i14:-1:2);\n jjm_h(c0,1:i1) = rc(i1)*jj_h(c1,1:i1);\n jjm_h(c0,1:i14) = jjm_h(c0,1:i14)+(1+rc(i1)^2)*jjm_h(c1,1:i14);\n jj_h(c0,1:i13) = jj(c0,i13:-1:1);\n jj_h(c0,1:i14) = jj_h(c0,1:i14)+jj(c0,i13:i15);\n va_t(1,:) = jj(c0,1:i1)*acov_x(i13:-1:2,:);\n va_t(2,:) = jj(c0,i13:i15)*acov_x(1:i14,:);\n v1(c0) = v1(c1)+1; v3(c0) = v3(c1)+1;\n a1(c0) = a1(c1)-1; a3(c0) = a3(c1)-1;\n t = t+i33;\n v(r9:r5,:,c0) = v(r9:r5,:,c1)+...\n rc(i1)*a(a1(c1):a1(c1)+r13,:,c1);\n v(r11+t:v3(c1),:,c0) = v(r11+t:v3(c1),:,c1)+...\n rc(i1)*a(a1(c1)+r15+t:r10,:,c1);\n v(v3(c0),:,c0) = rc(i1)*f(N,:);\n a(r6:r10,:,c0) = a(r6:r10,:,c1)+...\n rc(i1)*v(v3(c1)-r14:v3(c1),:,c1);\n a(a1(c1):r12-t,:,c0) = a(a1(c1):r12-t,:,c1)+...\n rc(i1)*v(r9:v3(c1)-r16-t,:,c1);\n a(a1(c0),:,c0) = rc(i1)*f(1,:); \n omega_va(c0) = sum(sum(v(r9:v1(c1),:,c0).*a(a1(c0):r8,:,c0)+...\n v(r7:v3(c0),:,c0).*a(a3(c1):r10,:,c0),1));\n den = den*(1-rc_h1)-sum(v(v1(c1),:,c0).^2)-sum(a(a3(c1),:,c0).^2);\n rc(i13) = -2*(sum(sum(va_t,2),1)-omega_va(c0))/den;\n c=~c;\n end\n i1 = p;\n end\n i2 = i2+1;\nend\n\nif state %f and b have been provided as input \n %arguments (empty b not excluded)\n if isempty(b)\n rc = rc(2:end);\n else\n rc = rc(3:end);\n end\nelse\n rc(1) = 1;\nend\n\ni2 = i2-1;\nASAglob_final_f = [];\nASAglob_final_b = [];\nif protocol(3,i2)==1 | protocol(1,i2)==3\n ASAglob_final_f = v(v1(c1):v2(c0),:,c0);\n ASAglob_final_b = a(a2(c0):a3(c1),:,c0);\nelseif isequal(P,0)\n ASAglob_final_f = f;\nend\n\n%Footer\n%=====================================================\n\nelse %Skip the computational kernel\n %Return ASAcontrol as the first output argument\n if nargout>1\n warning(ASAwarn(9,mfilename,ASAcontrol))\n end\n rc = ASAcontrol;\n ASAcontrol = [];\nend\n\n%Program history\n%======================================================================\n%\n% Version Programmer(s) E-mail address\n% ------- ------------- --------------\n% former version S. de Waele waele@tn.tudelft.nl\n% [2000 12 30 20 0 0] W. Wunderink wwunderink01@freeler.nl\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/1330-armasa/ARMASA/fast/estimation/estimator_tools/burg_s.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.4706036896941429}}
{"text": "function SR = superresolve_dbrsr(slidingWindows, magFactor)\n\nnumberOfFrames = size(slidingWindows.frames,3);\n\n\n% Set PSF kernels for the different binning factors.\npsf{1} = fspecial('gaussian', 5, 0.8); % PSF for binning factor 2\npsf{2} = fspecial('gaussian', 7, 1.2); % PSF for binning factor 3\npsf{3} = fspecial('gaussian', 9, 1.6); % PSF for binning factor 4\n\n% Specific preprocessing steps for the non-uniform interpolation based multi-frame methods.\nweighting_struct = struct('mec_weight_flag',4,'dis_weight_flag',1,'qps_weight_flag',0,'mec_confMapN',[],...\n 'mec_thr_scaler',2,'mec_weight_exp',2,'mec_weighting',[],'dis_rho',0.7,'dis_scaler',magFactor*10,'dis_weighting',[],...\n 'qps_map',[],'qps_rho',0.7,'qps_weighting',[],'alpha',1,'beta',1,'gamma',1,'whi_mode',2);\nwarped_meshXN = zeros(size(slidingWindows.referenceFrame,1),size(slidingWindows.referenceFrame,2),numberOfFrames-1);\nwarped_meshYN = zeros(size(slidingWindows.referenceFrame,1),size(slidingWindows.referenceFrame,2),numberOfFrames-1);\n\nlr_seq_sorted = slidingWindows.frames;\nlr_seq_tmp = lr_seq_sorted(:,:,(numberOfFrames+1)/2);\nlr_seq_sorted(:,:,(numberOfFrames+1)/2) = lr_seq_sorted(:,:,1);\nlr_seq_sorted(:,:,1) = lr_seq_tmp;\n\nlr_seq_sorted = permute(lr_seq_sorted,[1 2 4 3]);\n\npermutation_vec = 1:numberOfFrames-1;\npermutation_vec((numberOfFrames+1)/2:end) = permutation_vec((numberOfFrames+1)/2:end) + 1;\npermutation_vec(1:(numberOfFrames-1)/2) = circshift(permutation_vec(1:(numberOfFrames-1)/2),[0 -1]);\n\nfw_optFlowN_xc = zeros(size(lr_seq_sorted,1),size(lr_seq_sorted,2),2,numberOfFrames-1);\n\nfor itera = 1:numberOfFrames-1\n [warped_meshXN(:,:,itera),warped_meshYN(:,:,itera)] = lmsSR_warpImgGridLocalTrans(size(slidingWindows.referenceFrame,1),size(slidingWindows.referenceFrame,2),slidingWindows.flowToReference{permutation_vec(itera)}.mvs_xc);\n \n % Storing the MEC-SSD-Confidence into the Weighting Struct\n weighting_struct.mec_confMapN(:,:,itera) = slidingWindows.mec_confMap{permutation_vec(itera)};\n \n % Forward MVF for WDBR\n fw_optFlowN_xc(:,:,:,itera) = slidingWindows.flowToReference{permutation_vec(itera)}.mvs_xc;\nend\n\n% Actual SR call\n[~,wnuisr_nodeconv,~,~] = lmsSR_generateSRusingNUIv4weighted(lr_seq_sorted,warped_meshXN,warped_meshYN,[magFactor, magFactor],psf{magFactor-1},2,weighting_struct);\n[SR,~] = lmsSR_generateSRusingWDBR(wnuisr_nodeconv,fw_optFlowN_xc,magFactor,numberOfFrames,psf{magFactor-1},2,weighting_struct);\n\n", "meta": {"author": "thomas-koehler", "repo": "SupER", "sha": "d8c6f2e4b26db002ff55bc2beba18639f1d0bb49", "save_path": "github-repos/MATLAB/thomas-koehler-SupER", "path": "github-repos/MATLAB/thomas-koehler-SupER/SupER-d8c6f2e4b26db002ff55bc2beba18639f1d0bb49/matlab/algorithms/SRAlgorithms/superresolve_dbrsr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933535169629, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.47035511332650876}}
{"text": "function dvh = matRad_calcDVH(cst,doseCube,dvhType,doseGrid)\n% matRad dvh calculation\n% \n% call\n% dvh = matRad_calcDVH(cst,doseCube)\n% dvh = matRad_calcDVH(cst,doseCube,dvhType)\n% dvh = matRad_calcDVH(cst,doseCube,doseGrid)\n% dvh = matRad_calcDVH(cst,doseCube,dvhType,doseGrid)\n%\n% input\n% cst: matRad cst struct\n% doseCube: arbitrary doseCube (e.g. physicalDose)\n% dvhType: (optional) string, 'cum' for cumulative, 'diff' for differential\n% dvh\n% doseGrid: (optional) use predefined evaluation points. Useful when\n% comparing multiple realizations\n%\n% output\n% dose volume histogram\n%\n% References\n% van't Riet et. al., IJROBP, 1997 Feb 1;37(3):731-6.\n% Kataria et. al., J Med Phys. 2012 Oct-Dec; 37(4): 207ļæ½213.\n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Copyright 2016 the matRad development team. \n% \n% This file is part of the matRad project. It is subject to the license \n% terms in the LICENSE file found in the top-level directory of this \n% distribution and at https://github.com/e0404/matRad/LICENSES.txt. No part \n% of the matRad project, including this file, may be copied, modified, \n% propagated, or distributed except according to the terms contained in the \n% LICENSE file.\n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif ~exist('dvhType','var') || isempty(dvhType)\n dvhType = 'cum';\nend\n\nif ~exist('doseGrid', 'var') || isempty(doseGrid)\n maxDose = max(doseCube(:));\n minDose = min(doseCube(:));\n\n % get dvhPoints for every structure and every scenario the same\n n = 1000;\n if strcmp(dvhType, 'cum')\n doseGrid = linspace(0,maxDose*1.05,n);\n elseif strcmp(dvhType, 'diff')\n doseGrid = linspace(0.95*minDose,maxDose*1.05,n);\n end\nend\n\nnumOfVois = size(cst,1);\ndvh = struct;\nfor i = 1:numOfVois\n dvh(i).doseGrid = doseGrid;\n dvh(i).volumePoints = getDVHPoints(cst, i, doseCube, doseGrid, dvhType);\n dvh(i).name = cst{i,2};\nend\n\nend %eof \n\nfunction dvh = getDVHPoints(cst, sIx, doseCube, dvhPoints, dvhType)\nn = numel(dvhPoints);\ndvh = NaN * ones(1,n);\nindices = cst{sIx,4}{1};\nnumOfVoxels = numel(indices);\n\ndoseInVoi = doseCube(indices);\n\nswitch dvhType\n case 'cum' % cummulative DVH\n for j = 1:n\n dvh(j) = sum(doseInVoi >= dvhPoints(j));\n end\n\n case 'diff' % differential DVH\n binning = (dvhPoints(2) - dvhPoints(1))/2;\n for j = 1:n % differential DVH \n dvh(j) = sum(dvhPoints(j) + binning > doseInVoi & doseInVoi > dvhPoints(j) - binning);\n end\n\nend\ndvh = dvh ./ numOfVoxels * 100;\nend %eof getDVHPoints\n\n", "meta": {"author": "e0404", "repo": "matRad", "sha": "0a03aee5ef4a100dbc4bef8927db41b59f44946e", "save_path": "github-repos/MATLAB/e0404-matRad", "path": "github-repos/MATLAB/e0404-matRad/matRad-0a03aee5ef4a100dbc4bef8927db41b59f44946e/matRad_calcDVH.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.470355103227803}}
{"text": "function [parameters, ll, ht, intercept, VCV, scores, diagnostics] = scalar_vt_vech(data,dataAsym,p,o,q,composite,startingvals,options)\n% Estimation of symmetric and asymmetric scalar multivariate vech ARCH models using variance\n% targeting to reduce the number of parameters needing to be estimated simultaneously\n%\n% USAGE:\n% [PARAMETERS,LL,HT,INTERCEPT,VCV,SCORES,DIAGNOSTICS] = scalar_vt_vech(DATA,DATAASYM,P,O,Q,COMPOSITE,STARTINGVALS,OPTIONS)\n%\n% INPUTS:\n% DATA - A T by K matrix of zero mean residuals -OR-\n% K by K by T array of covariance estimators (e.g. realized covariance)\n% DATAASYM - [OPTIONAL] K by K by T array of asymmetric covariance estimators\n% P - Positive, scalar integer representing the number of lags of the innovation process\n% O - Non-negative scalar integer representing the number of asymmetric lags to include\n% Q - Non-negative scalar integer representing the number of lags of conditional covariance\n% COMPOSUTE - [OPTIONAL] String, one of:\n% 'None' - Standard K-dimensional QMLE (Default)\n% 'Diagonal' - Use only pairwise likelihoode for i,i+1, i=1,2,...,K-1\n% 'Full' - Use all pairwise likelihoods\n% STARTINGVALS - [OPTIONAL] (p+o+q) x 1 vector of starting values\n% OPTIONS - [OPTIONAL] Options to use in the optimization (fminunc)\n%\n% OUTPUTS:\n% PARAMETERS - A p+o+q column vector of parameters. The intercept is reported in DIAGNOSTICS\n% LL - The log likelihood at the optimum\n% HT - A [K K T] dimension matrix of conditional covariances\n% INTERCEPT - K by K matrix containing the intercept computed from the unconditional variance\n% and parameters\n% VCV - A numParams^2 square matrix of robust parameter covariances (A^(-1)*B*A^(-1)*t^(-1))\n% SCORES - A T by numParams matrix of individual scores\n%\n% COMMENTS:\n% The conditional variance, H(t), of a scalar variance-targeting vech is modeled\n% as follows:\n%\n% H(t) = (1-alpha(1)+...+alpha(p)-beta(1)-...-beta(q))*C + ...\n% alpha(1)*r_{t-1}'*r_{t-1} + ... + alpha(p)*r_{t-p}'*r_{t-p}+...\n% gamma(1)*n_{t-1}'*n_{t-1} + ... + gamma(o)*n_{t-p}'*n_{t-p}+...\n% beta(1)*H(t-1) +...+ beta(q)*H(t-q)\n%\n% where n_{t} = r_{t} .* (r_{t}<0)\n%\n% EXAMPLES:\n% Estimation of a Scalar VECH(1,0,1)\n% [simulatedData, Ht, pseudoRC] = scalar_vt_vech_simulate(1000, [.02 .04 .95], .01*eye(2), 1, 1, 1, 72);\n% parameters = scalar_vt_vech(simulatedData,[],1,0,1)\n% Estimation of an asymmetric Scalar VECH(1,1,1)\n% parameters = scalar_vt_vech(simulatedData,[],1,1,1)\n% Estimation of an asymmetric Scalar VECH(1,1,1) using realized-type data\n% asymPseudoRC = zeros(size(pseudoRC));\n% for i = 1:1000\n% asymPseudoRC(:,:,i) = pseudoRC(:,:,i).*(double(simulatedData(i,:)<0)'*double(simulatedData(i,:)<0));\n% end\n% parameters = scalar_vt_vech(pseudoRC,asymPseudoRC,1,1,1);\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 3 Date: 10/28/2009\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Argument Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nswitch nargin\n case 3\n o=0;\n q=0;\n composite = 'None';\n startingvals=[];\n options = [];\n case 4\n q=0;\n composite = 'None';\n startingvals=[];\n options = [];\n case 5\n composite = 'None';\n startingvals=[];\n options = [];\n case 6\n startingvals=[];\n options = [];\n case 7\n options = [];\n case 8\n % Nothing\n otherwise\n error('Between 3 and 8 arguments required.')\nend\n\n%data should be TxK, T>K\nif ndims(data)==2\n [t,k]=size(data);\n if ~isempty(dataAsym)\n error('If DATA is a T by K matrix, DATAASYM must be empty.');\n end\n temp = zeros(k,k,t);\n dataAsym = zeros(k,k,t);\n for i=1:t\n temp(:,:,i) = data(i,:)'*data(i,:);\n dataAsym(:,:,i) = (data(i,:).*(data(i,:)<0))'*(data(i,:).*(data(i,:)<0));\n end\n data = temp;\nelseif ndims(data)==3\n [k,m,t] = size(data);\n if m~=k\n error('DATA must be K by K by T is a 3D array.');\n end\n if ~isempty(dataAsym)\n if ndims(dataAsym)~=3\n error('DATAASYM must be a 3D array with the same dimensions as DATA');\n end\n [k2,m2,t2]=size(dataAsym);\n if any([k m t]~=[k2 m2 t2])\n error('DATAASYM must be a 3D array with the same dimensions as DATA');\n end\n end\nend\n\nif min(t,k)<2 || tK>1');\nend\n\n%p, o, q much be non-negative scalars\nif length(p)>1 || any(p<1) || floor(p)~=p\n error('P must be a positive scalar');\nend\nif isempty(o)\n o = 0;\nend\nif length(o)>1 || any(o<0) || floor(o)~=o\n error('O must be a non-negative scalar');\nend\nif o>0 && isempty(dataAsym)\n error('DATAASYM must be non-empty if O>0.')\nend\n\nif isempty(q)\n q = 0;\nend\nif length(q)>1 || any(q<0) || floor(q)~=q\n error('Q must be a non-negative scalar');\nend\n\nif isempty(composite)\n composite = 'None';\nend\nswitch lower(composite)\n case {'none'}\n useComposite = 0;\n case {'diagonal'}\n useComposite = 1;\n case {'full'}\n useComposite = 2;\nend\n\n% Startingvals must have p+o+q parameters sum(alpha)+kappa*sum(gamma)+sum(beta)<1\nC = mean(data,3);\nif o>0\n Casym = mean(dataAsym,3);\n kappa = 1 / (max(eig(C^(-0.5)*Casym*C^(-0.5))) + eps);\nelse\n Casym = zeros(k);\n kappa = 2;\nend\nif ~isempty(startingvals)\n if size(startingvals,2)>size(startingvals,1)\n startingvals = startingvals';\n end\n if length(startingvals)<(p+o+q)\n error('STARTINGVALS should be a P+O+Q by 1 vector');\n end\n %Only validate if provided\n A=startingvals(1:p);\n G=startingvals(p+1:p+o);\n B=startingvals(p+o+1:p+o+q);\n if (sum(A)+sum(G)/kappa+sum(B))>=.999998\n error('Weighted sum of STATINGVALUES must be less than 1. See Comments.');\n end\n if any(A<0) || any(B<0) || any(G<0)\n error('STARTINGVALS must all be nonnegative.');\n end\nend\n\n%Make sure options is a valid option structure\nif isempty(options)\n options=optimset('fminunc');\n options.Display='iter';\n options.Diagnostics='on';\n options.LargeScale='off';\nend\ntry\n optimset(options);\ncatch ME\n error('OPTIONS is not a valid options structure');\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Argument Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Compute the backCast\nbackCast = zeros(k);\nbackCastAsym = zeros(k);\ntau = max(ceil(sqrt(t)),k);\nweights = .06 * .94.^(0:tau);\nweights = weights / sum(weights);\nfor i=1:tau\n backCast = backCast + weights(i) * data(:,:,i);\n if o>0\n backCastAsym = backCastAsym + weights(i) * dataAsym(:,:,i);\n end\nend\n\n%Augment the data with backcasts\n[startingvals,lls,output_parameters] = scalar_vt_vech_starting_values(startingvals,data,dataAsym,p,o,q,C,Casym,kappa,useComposite,backCast,backCastAsym); %#ok\n\n% finally to transform the parameters to the unrestricted equivalents\nstartingvals=scalar_vt_vech_transform(startingvals,p,o,q,kappa);\n\n[parameters,ll,exitflag,output]=fminunc('scalar_vt_vech_likelihood',startingvals,options,data,dataAsym,p,o,q,C,Casym,kappa,backCast,backCastAsym,false,useComposite,true);\n%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%Estimation Robustification\n%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif exitflag<=0 && ll1\n [ll,~,ht]=scalar_vt_vech_likelihood(parameters,data,dataAsym,p,o,q,C,Casym,kappa,backCast,backCastAsym,false,useComposite,false);\n ll=-ll;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Compute the VCV\n%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif nargout>4\n k2 = k*(k+1)/2;\n CVech=vech(C);\n if o==0\n momentCount = k2;\n CasymVech = [];\n else\n momentCount = 2*k2;\n CasymVech=vech(Casym);\n end\n \n A = zeros(momentCount + p + o + q);\n A(1:momentCount, 1:momentCount) = - t * eye(momentCount);\n jointParameters=[CVech;CasymVech;parameters];\n \n % A will be k2 + p + q square\n scores = zeros(t,momentCount+p+q);\n scoreCount = 1;\n for i=1:k\n for j=i:k\n scores(:,scoreCount) = squeeze(data(j,i,:));\n if o>0\n scores(:,k2+scoreCount) = squeeze(dataAsym(j,i,:));\n end\n scoreCount = scoreCount + 1;\n end\n end\n [~,gt] = gradient_2sided(@scalar_vt_vech_likelihood,parameters,data,dataAsym,p,o,q,C,Casym,kappa,backCast,backCastAsym,false,useComposite,false);\n scores(:,momentCount+1:momentCount+p+o+q) = gt;\n A(momentCount+1:momentCount+p+o+q,:) = hessian_2sided_nrows(@scalar_vt_vech_likelihood,jointParameters,p+o+q,data,dataAsym,p,o,q,C,Casym,kappa,backCast,backCastAsym,true,useComposite,false);\n \n A = A/t;\n B = covnw(scores);\n Ainv = inv(A);\n VCV = Ainv*B*Ainv'/t; %#ok\n VCV = VCV(momentCount+1:momentCount+p+o+q,momentCount+1:momentCount+p+o+q);\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Compute the VCV\n%%%%%%%%%%%%%%%%%%%%%%%%%%%\ndiagnostics.EXITFLAG=exitflag;\ndiagnostics.ITERATIONS=output.iterations;\ndiagnostics.FUNCCOUNT=output.funcCount;\ndiagnostics.MESSAGE=output.message;\ndiagnostics.kappa=kappa;\nalpha = sum(parameters(1:p));\ngamma = sum(parameters(p+1:p+o));\nbeta = sum(parameters(p+o+1:p+o+q));\ndiagnostics.intercept = C*(1-alpha-beta);\ndiagnostics.composite = composite;\nif o>0\n diagnostics.intercept = diagnostics.intercept - gamma*Casym;\nend\nintercept = diagnostics.intercept;", "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/multivariate/scalar_vt_vech.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4702017994336412}}
{"text": "function [ point_num2, edge_num2, face_num2, face_order_max2 ] = ...\n dual_size_3d ( point_num, edge_num, face_num, face_order_max, ...\n point_coord, face_order, face_point )\n\n%*****************************************************************************80\n%\n%% DUAL_SIZE_3D determines sizes for a dual of a shape in 3D.\n%\n% Discussion:\n%\n% We don't actually need FACE_POINT as input here. But since the\n% three arrays occur together everywhere else, it seems unnecessarily\n% user-confusing to vary the usage here!\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 July 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer POINT_NUM, the number of points.\n%\n% Input, integer EDGE_NUM, the number of edges.\n%\n% Input, integer FACE_NUM, the number of faces.\n%\n% Input, integer FACE_ORDER_MAX, the maximum number of vertices per face.\n%\n% Input, real POINT_COORD(3,POINT_NUM); POINT_COORD(*,J) is\n% the X, Y and Z coordinates of point J.\n%\n% Input, integer FACE_ORDER(FACE_NUM), the number of vertices per face.\n%\n% Input, integer FACE_POINT(FACE_ORDER_MAX,FACE_NUM); FACE_POINT(I,J)\n% is the index of the I-th point in the J-th face. The\n% points are listed in the counter-clockwise direction defined\n% by the outward normal at the face.\n%\n% Output, integer POINT_NUM2, the number of points in the dual.\n%\n% Output, integer EDGE_NUM2, the number of edges in the dual.\n%\n% Output, integer FACE_NUM2, the number of faces in the dual.\n%\n% Output, integer FACE_ORDER_MAX2, the maximum number of vertices per face\n% in the dual.\n%\n\n%\n% These values are easy to compute:\n%\n point_num2 = face_num;\n edge_num2 = edge_num;\n face_num2 = point_num;\n%\n% To determine FACE_ORDER_MAX2 is not so easy.\n% You have to construct the FACE_ORDER array for the dual shape.\n% The order of a dual face is the number of edges that the vertex occurs in.\n% But then all we have to do is count how many times each item shows up\n% in the FACE_POINT array.\n%\n face_order_max2 = 0;\n face_order2(1:face_num2) = 0;\n\n for face = 1 : face_num\n for i = 1 : face_order(face)\n face2 = face_point(i,face);\n face_order2(face2) = face_order2(face2) + 1;\n end\n end\n\n face_order_max2 = max ( face_order2(1:face_num2) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/dual_size_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.47013092149655134}}
{"text": "function g = glmderiv(net, x)\n%GLMDERIV Evaluate derivatives of GLM outputs with respect to weights.\n%\n%\tDescription\n%\tG = GLMDERIV(NET, X) takes a network data structure NET and a matrix\n%\tof input vectors X and returns a three-index matrix mat{g} whose I,\n%\tJ, K element contains the derivative of network output K with respect\n%\tto weight or bias parameter J for input pattern I. The ordering of\n%\tthe weight and bias parameters is defined by GLMUNPAK.\n%\n\n%\tCopyright (c) Ian T Nabney (1996-2001)\n\n% Check arguments for consistency\nerrstring = consist(net, 'glm', x);\nif ~isempty(errstring)\n error(errstring);\nend\n\nndata = size(x, 1);\nif isfield(net, 'mask')\n nwts = size(find(net.mask), 1);\n mask_array = logical(net.mask)*ones(1, net.nout);\nelse\n nwts = net.nwts;\nend\ng = zeros(ndata, nwts, net.nout);\n\ntemp = zeros(net.nwts, net.nout);\nfor n = 1:ndata\n % Weight matrix w1\n temp(1:(net.nin*net.nout), :) = kron(eye(net.nout), (x(n, :))');\n % Bias term b1\n temp(net.nin*net.nout+1:end, :) = eye(net.nout);\n if isfield(net, 'mask')\n\tg(n, :, :) = reshape(temp(find(mask_array)), nwts, net.nout);\n else\n\tg(n, :, :) = temp;\n end\nend\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/netlab3.3/glmderiv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.47004740749162605}}
{"text": "function p=v_psychofunc(m,q,x,r)\n%V_PSYCHOFUNC Calculate psychometric functions: trial success probability versus SNR\n%\n% Usage: p=v_psychofunc('',q,x) % calculate probabilities\n% b=v_psychofunc('r',q,x) % generate boolean variables with success prob p\n% p=v_psychofunc(m,q,x,r) % Calculate likelihoods for observations r\n% x=v_psychofunc([m 'i'],q,p) % Calculate inverse\n%\n% Inputs:\n% m mode string [may be omitted if not required]\n% 'n' do not normalize likelihoods\n% 'f' do not squeeze output arrays to remove singleton dimensions\n% 'i' calculate inverse function\n% 'r' calculate binary random variables with probability p\n% ['s' calculate sweet points for threshold and slope]\n% ['d' calculate partial derivatives with respect to q(1:5)]\n% 'g' plot graph\n% 'G' plot image\n% 'c' include colourbar\n% q model parameters. Either a column vector with a single model,\n% a matrix with one model per column or a cell array with multiple values for\n% some or all of the parameters\n% 1 probability at threshold [0.5]\n% 2 threshhold [0 dB]\n% 3 slope at threshold [0.1 prob/dB ]\n% 4 miss or lapse probability [0]\n% 5 guess probability [0]\n% 6 psychometric function type [1]\n% 1 = logistic\n% 2 = cumulative Gaussian\n% 3 = Weibull\n% [4 = reversed Weibull]\n% [5 = Gumbell]\n% [6 = reversed Gumbell]\n% x vector of SNR values\n% r test results (0 or 1) corresponding to x\n% p vector of probabilities\n%\n% Outputs:\n% p array of probabilities or random variates ('r' option).\n% p is a squeezed 7-dimensional array\n% whose dimensions correspond to x followed by the 6 model parameter entries.\n% if q is a cell array, singleton dimensions are removed unless the 'f' option is given.\n% x Inverse function gives SNR, x, as a function of p\n% b array of boolean variables\n\n% Copyright (C) Mike Brookes 2009-2010\n% Version: $Id: v_psychofunc.m 10865 2018-09-21 17:22:45Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% first sort out input arguments\nminp=0.01; % minimum probability to use for inverse function by default\nqq=[0.5 0 0.1 0 0 1]'; % default values for q\nif nargin<4\n r=[];\n if nargin<3\n x=[];\n if nargin<2\n q=[];\n if ~nargin\n m='';\n end\n end\n end\nend\nif ~ischar(m); % mode argument is optional\n r=x;\n x=q;\n q=m;\n m='';\nend\nsq=size(q);\nckmod=0;\nif iscell(q)\n nq=ones(1,6);\n qax=num2cell([0; qq]); % used for plotting\n for i=1:min(numel(q),6)\n nq(i)=numel(q{i});\n if nq(i)>=1\n nr=size(qq,2);\n qax{i+1}=q{i};\n if i<=5 % do not replicate for multiple models\n qq=repmat(qq,1,nq(i));\n qq(i,:)=reshape(repmat(q{i}(:)',nr,1),1,nr*nq(i));\n else\n qq(i,:)=repmat(q{i}(1),1,nr);\n end\n end\n end\n nq=max(nq,1);\n nmod=nq(6);\n if nmod>1 % list of models to use\n modlist=q{6};\n else\n modlist=qq(6,1); % default model\n end\nelse\n nq=sq(2);\n if nq\n ql=repmat(qq,1,nq);\n ql(1:sq(1),:)=q;\n else\n ql=qq;\n nq=1;\n end\n modlist=unique(ql(6,:));\n nmod=length(modlist);\n ckmod=nmod>1; % need to check model list\n qq=ql;\nend\n% now perform the calculation\nnx=numel(x);\nnpt=50; % number of points\nif any(m=='i') % doing inverse\n if ~nx\n nx=npt;\n xlim=[max(qq(5,:)),1-max(qq(4,:))]*[1-minp minp; minp 1-minp];\n x=linspace(xlim(1),xlim(2),nx)';\n end\n p=zeros([nx nq]); % space for SNRs\n ia=0;\n for i=1:nmod % loop for each model type\n mod=modlist(i);\n if ckmod\n qq=ql(:,ql(6,:)==mod);\n end\n pscale=1-qq(4,:)-qq(5,:);\n pstd=(qq(1,:)-qq(5,:))./pscale; % prob target compensating for miss and lapse probs\n sstd=qq(3,:)./pscale; % slope compensating for miss and lapse probs\n px=x(:)*pscale.^(-1)-repmat(qq(5,:)./pscale,nx,1); % adjust for miss and lapse probs\n switch mod\n case 1\n beta=sstd./(pstd.*(1-pstd));\n% alpha=qq(2,:)+log((1-pstd)./pstd)./beta;\n px=repmat(qq(2,:)+log((1-pstd)./pstd)./beta,nx,1)-log(px.^(-1)-1).*repmat(beta.^(-1),nx,1);\n case 2 % cumulative Gaussian function\n xtstd=norminv(pstd); % x position of target in std measure\n sig=normpdf(xtstd)./sstd;\n px= repmat(qq(2,:)-sig.*xtstd,nx,1) + repmat(sig,nx,1).*norminv(px);\n case 3\n wlog=log(1-pstd);\n kbeta=sstd./((pstd-1).*wlog);\n alpha=qq(2,:)-log(-wlog)./kbeta;\n px=repmat(alpha,nx,1)+log(-log(1-px)).*repmat(kbeta.^(-1),nx,1);\n otherwise\n error('Invalid psychometric model index');\n end\n if ckmod\n p(:,ql(6,:)==i)=px;\n else\n ib=ia+numel(p)/nmod;\n p(ia+1:ib)=px(:);\n ia=ib;\n end\n end\nelse % doing forward mapping\n if ~nx\n ef=2; % expansion factor\n nx=npt;\n x=linspace(min(qq(2,:)-ef*(qq(1,:)-qq(5,:))./qq(3,:)), ...\n max(qq(2,:)+ef*(1-qq(1,:)-qq(4,:))./qq(3,:)),nx)';\n end\n p=zeros([nx nq]); % space for probabilities\n ia=0;\n for i=1:nmod % loop for each model type\n mod=modlist(i);\n if ckmod\n qq=ql(:,ql(6,:)==mod);\n end\n pscale=1-qq(4,:)-qq(5,:); % prob range excluding miss and lapse probs\n pstd=(qq(1,:)-qq(5,:))./pscale; % prob target compensating for miss and lapse probs\n sstd=qq(3,:)./pscale; % slope compensating for miss and lapse probs\n switch mod\n case 1 % logistic function\n beta=sstd./(pstd.*(1-pstd));\n% alpha=qq(2,:)+log((1-pstd)./pstd)./beta;\n px=(1+exp(repmat(beta.*qq(2,:)+log((1-pstd)./pstd),nx,1)-x(:)*beta)).^(-1);\n case 2 % cumulative Gaussian function\n xtstd=norminv(pstd); % x position of target in std measure\n sigi=sstd./normpdf(xtstd);\n px=normcdf(x(:)*sigi-repmat(qq(2,:).*sigi-xtstd,nx,1));\n case 3\n wlog=log(1-pstd);\n kbeta=sstd./((pstd-1).*wlog);\n alpha=qq(2,:)-log(-wlog)./kbeta;\n px=1-exp(-exp(x(:)*kbeta-repmat(alpha.*kbeta,nx,1)));\n otherwise\n error('Invalid psychometric model index');\n end\n px=repmat(qq(5,:),nx,1)+repmat(pscale,nx,1).*px; % adjust for miss and lapse probs\n if ckmod\n p(:,ql(6,:)==i)=px;\n else\n ib=ia+numel(p)/nmod;\n p(ia+1:ib)=px(:);\n ia=ib;\n end\n end\n if numel(r) % we are calculating likelihoods\n mk=r(:)==0;\n p(mk,:)=1-p(mk,:); % invert probability for results that are zero\n if nx>1\n if any(m=='n')\n p=prod(p,1);\n else\n p=sum(log(p),1);\n p=exp(p-max(p(:)));\n p=p/sum(p(:)); % normalize to equal 1\n end\n nx=1;\n end\n end\n\nend\npg=p; % save unsqueezed p for plotting\nif ~any(m=='f') && iscell(q) % remove all singleton dimensions\n szp=size(p);\n szq=szp(szp>1);\n szq=[szq ones(1,max(0,2-numel(szq)))];\n p=reshape(p,szq);\nend\nif any(m=='r') && ~any(m=='i');\n p=rand(size(p))1);\n if czp>0 % check if there is anything to plot\n if iscell(q)\n axlab={'Input SNR','Threshold prob','Threshold SNR','Threshold slope','Lapse prob','Guess prob','Sigmoid type'};\n [szs,izs]=sort(szp,'descend');\n pg=permute(pg,izs);\n qax{1}=x;\n if any(m=='G') || czp>2 % image\n ngr=prod(szs(3:end));\n ncol=ceil(sqrt(ngr));\n nrow=ceil(ngr/ncol);\n npix=szs(1)*szs(2);\n ia=0;\n for i=1:ngr\n subplot(nrow,ncol,i);\n ib=ia+npix;\n imagesc(qax{izs(1)},qax{izs(2)},reshape(pg(ia+1:ib),szs(1:2))');\n axis 'xy'\n if any(m=='c')\n colorbar;\n end\n if nrow*ncol-i=nq\n plot(x,pg,'-');\n xlabel('Input SNR (dB)');\n else\n plot(1:nq,pg','-');\n xlabel('Model Index');\n end\n end\n end\n end\nend\n\n\n", "meta": {"author": "ImperialCollegeLondon", "repo": "sap-voicebox", "sha": "28f2654b7584f724277ec81de533debe28ff51ac", "save_path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox", "path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox/sap-voicebox-28f2654b7584f724277ec81de533debe28ff51ac/voicebox/v_psychofunc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4699482820573398}}
{"text": "% MP_SOLVE_STOKES_DIV_CONFORMING: Solve a Stokes flow problem on a multipatch domain with \n% divergence-conforming spaces, using an interior penalty method between patches.\n%\n% The function solves the Stokes problem\n%\n% -div(mu(x) grad(vel)) + grad(press) = f in Omega\n% div(vel) = 0 in Omega\n% vel = h on Gamma_D\n%\n% USAGE:\n%\n% [geometry, msh, space_v, vel, space_p, press] = ...\n% mp_solve_stokes_div_conforming (problem_data, method_data)\n%\n% INPUT:\n%\n% problem_data: a structure with data of the problem. It contains the fields:\n% - geo_name: name of the file containing the geometry\n% - drchlt_sides: sides with Dirichlet boundary condition\n% - f: force term\n% - h: function for Dirichlet boundary condition\n% - viscosity: viscosity coefficient (mu in the equation)\n%\n% method_data : a structure with discretization data. Its fields are:\n% - degree: degree of the spline functions for pressure\n% - regularity: continuity of the spline functions for pressure\n% - nsub: number of subelements with respect to the geometry mesh \n% for the pressure space (nsub=1 leaves the mesh unchanged)\n% - nquad: number of points for Gaussian quadrature rule\n% - element_name: one of {RT,NDL}, specify how to build the velocity\n% space from the data for the pressure space\n% +RT is the generalized Raviart-Thomas element\n% +NDL is the generalized Nedelec element of the second family\n% OUTPUT:\n%\n% geometry: array of geometry structures (see geo_load)\n% msh: multipatch mesh, consisting of several Cartesian meshes (see msh_multipatch)\n% space_v: multipatch space, formed by several tensor product spaces plus the connectivity (see sp_multipatch). \n% Only the normal component is continuous at the interfaces.\n% vel: the computed degrees of freedom for the velocity\n% space_p: multipatch space for the pressure (see sp_multipatch). The functions are discountinuous at the interfaces.\n% press: the computed degrees of freedom for the pressure\n%\n% See also EX_STOKES_BIFURCATION_2D_RT_MP for an example\n%\n% Copyright (C) 2009, 2010 Carlo de Falco\n% Copyright (C) 2010, 2011, 2015, 2020 Rafael Vazquez\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\nfunction [geometry, msh, space_v, vel, space_p, press] = ...\n mp_solve_stokes_div_conforming (problem_data, method_data)\n\n% Extract the fields from the data structures into local variables\ndata_names = fieldnames (problem_data);\nfor iopt = 1:numel (data_names)\n eval ([data_names{iopt} '= problem_data.(data_names{iopt});']);\nend\ndata_names = fieldnames (method_data);\nfor iopt = 1:numel (data_names)\n eval ([data_names{iopt} '= method_data.(data_names{iopt});']);\nend\n\nif (strcmpi ('element_name', 'TH') || strcmpi ('element_name', 'SG'))\n error ('For TH and SG spaces, use mp_solve_stokes');\nend\n\n% Construct geometry structure, and information for interfaces and boundaries\n[geometry, boundaries, interfaces, ~, boundary_interfaces] = mp_geo_load (geo_name);\nnpatch = numel (geometry);\n\nmsh = cell (1, npatch);\nspv = cell (1, npatch);\nspp = cell (1, npatch);\nfor iptc = 1:npatch\n% Construct msh structure using the finest mesh\n msh_breaks = msh_set_breaks (element_name, ...\n geometry(iptc).nurbs.knots, nsub);\n rule = msh_gauss_nodes (nquad);\n [qn, qw] = msh_set_quad_nodes (msh_breaks, rule);\n msh{iptc} = msh_cartesian (msh_breaks, qn, qw, geometry(iptc));\n\n% Construct space structure\n [spv{iptc}, spp{iptc}] = sp_bspline_fluid (element_name, ...\n geometry(iptc).nurbs.knots, nsub, degree, regularity, msh{iptc});\nend\n\nmsh = msh_multipatch (msh, boundaries);\nspace_v = sp_multipatch (spv, msh, interfaces, boundary_interfaces);\nspace_p = sp_multipatch (spp, msh, interfaces, boundary_interfaces);\nclear spv spp\n\n% Compute and assemble the matrices\nif (msh.rdim == 2)\n fun_one = @(x, y) ones (size(x));\nelseif (msh.rdim == 3)\n fun_one = @(x, y, z) ones (size(x));\nend\n\nA = op_gradu_gradv_mp (space_v, space_v, msh, viscosity);\nB = op_div_v_q_mp (space_v, space_p, msh);\nE = (op_f_v_mp (space_p, msh, fun_one)).';\nF = op_f_v_mp (space_v, msh, f);\n\nvel = zeros (space_v.ndof, 1);\npress = zeros (space_p.ndof, 1);\n\n% Apply DG techniques on the interfaces\nA = A + mp_dg_penalty (space_v, msh, interfaces, viscosity, Cpen);\n\n% Apply Neumann boundary conditions\nrhs_nmnn = zeros(space_v.ndof,1);\nNbnd = cumsum ([0, boundaries.nsides]);\nfor iref = nmnn_sides\n iref_patch_list = Nbnd(iref)+1:Nbnd(iref+1);\n gref = @(varargin) g(varargin{:},iref);\n \n for bnd_side = 1:msh.boundaries(iref).nsides\n iptc = msh.boundaries(iref).patches(bnd_side);\n iside = msh.boundaries(iref).faces(bnd_side);\n\n msh_side = msh_eval_boundary_side (msh.msh_patch{iptc}, iside);\n msh_side_from_interior = msh_boundary_side_from_interior (msh.msh_patch{iptc}, iside);\n\n sp_bnd = space_v.sp_patch{iptc}.constructor (msh_side_from_interior);\n sp_bnd = sp_precompute (sp_bnd, msh_side_from_interior, 'value', true);\n% sp_bnd.dofs = 1:sp_bnd.ndof;\n\n x = cell (msh_side.rdim, 1);\n for idim = 1:msh_side.rdim\n x{idim} = reshape (msh_side.geo_map(idim,:,:), msh_side.nqn, msh_side.nel);\n end\n gval = reshape (gref(x{:}), msh.rdim, msh_side.nqn, msh_side.nel);\n rhs_nmnn(space_v.gnum{iptc}) = rhs_nmnn(space_v.gnum{iptc}) + ...\n op_f_v (sp_bnd, msh_side, gval);\n end\nend\n\n% Apply Dirichlet boundary conditions\n[N_mat, N_rhs] = sp_weak_drchlt_bc_stokes (space_v, msh, drchlt_sides, h, viscosity, Cpen);\nA = A - N_mat; F = F + N_rhs;\n[vel_drchlt, drchlt_dofs] = sp_drchlt_l2_proj_udotn (space_v, msh, drchlt_sides, h);\nvel(drchlt_dofs) = vel_drchlt;\n\nint_dofs = setdiff (1:space_v.ndof, drchlt_dofs);\nnintdofs = numel (int_dofs);\nrhs_dir = -A(int_dofs, drchlt_dofs)*vel(drchlt_dofs);\n\n% Solve the linear system\nif (isempty (nmnn_sides))\n mat = [A(int_dofs, int_dofs), -B(:,int_dofs).', sparse(nintdofs, 1);\n -B(:,int_dofs), sparse(space_p.ndof, space_p.ndof), E.';\n sparse(1, nintdofs), E, 0];\n rhs = [F(int_dofs) + rhs_dir; \n B(:, drchlt_dofs)*vel(drchlt_dofs); \n 0];\n sol = mat \\ rhs;\n vel(int_dofs) = sol(1:nintdofs);\n press = sol(1+nintdofs:end-1);\nelse\n% With natural boundary condition, the constraint on the pressure is not needed.\n mat = [ A(int_dofs, int_dofs), -B(:,int_dofs).';\n -B(:,int_dofs), sparse(size (B,1), size (B,1))];\n rhs = [F(int_dofs) + rhs_dir + rhs_nmnn(int_dofs); \n B(:, drchlt_dofs)*vel(drchlt_dofs)];\n sol = mat \\ rhs;\n vel(int_dofs) = sol(1:nintdofs);\n press = sol(1+nintdofs:end);\nend\n\nend\n", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/multipatch/mp_solve_stokes_div_conforming.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4699482820573398}}
{"text": "function [params] = gui_CalcOmori(params,nNodeStart, nNodeEnd)\n % gui_CalcOmori Calculate Omori parameters, here setting up the data\n %\n % [params] = gui_CalcOmori(params,nNodeStart, nNodeEnd);\n % ----------------------------------------------------------------\n %\n % Input parameters:\n % params.mCatalog Earthquake catalog\n % params.mPolygon Polygon (defined by ex_selectgrid)\n % params.vX X-vector (defined by ex_selectgrid)\n % params.vY Y-vector (defined by ex_selectgrid)\n % params.vUsedNodes Used nodes vX * vY defining the mPolygon (defined by ex_selectgrid)\n % params.nCalculation Number of random simulations\n % params.bMap Calculate a map (true) or a cross-section (false)\n % params.bNumber Use constant number (true) or constant radius (false)\n % params.nNumberEvents Number of earthquakes if bNumber is true\n % params.fMaxRadius Maximum Radius using a constant number of events; works only with bNumber is true\n % params.fRadius Radius of gridnode if bNumber is false\n % params.nMinimumNumber Minimum number of earthquakes per node for determining a b-value\n % params.fMinMag Lower limit of magnitude range for testing\n % params.fMaxMag Upper limit of magnitude range for testing\n % params.bTimePeriod Calculate seismicity difference for 2 periods (0) until start and end of catalog or\n % a specific time period before and after fSplitTime (1)\n % params.fTimePeriodDays Length of time periods\n % params.bTstart Check for starting time of temporal mapping\n % params.fTstart Starting time for temporal mapping\n % params.bBstnum Check for boostrap sampling\n % params.fBstnum Number of bootstrap samples\n % params.fBinning Bin size for magnitude binning\n % params.sComment Comment on calculation\n\n % Output parameters:\n % Same as input parameters including\n % params.mValueGrid Matrix of calculated values\n % params.vcsGridNames Names of parameters calculated\n % Check gui_NodeCalcOmori.m for a list of variables!!\n %\n % J. Woessner; j.woessner@sed.ethz.ch\n % updated: 16.02.2006\n\n report_this_filefun();\n\n % Check calculation for splitting of nodes\n if nargin < 2\n nNodeStart = 1;\n nNodeEnd = length(params.mPolygon(:,1));\n end\n\n % Initialize\n vResults = [];\n params.sComment = [];\n if isempty(params.fBinning)\n params.fBinning = 0.1;\n end\n\n % Determine time period of catalog\n params.fTminCat = min(params.mCatalog.Date);\n params.fTmaxCat = max(params.mCatalog.Date);\n\n % Init result matrix\n mValueGrid_ = [];\n\n % Temporary saving the original catalog\n mCatalog = params.mCatalog;\n\n % Force saving all 100 nodes\n fDivide = length(params.mPolygon(:,1))/100\n fForceSave = length(params.mPolygon(:,1))/fDivide;\n\n % % Loop over time\n fTstart = params.fTstart;\n % while fTstart < params.fTmaxCat\n % mValueGrid_ = [];\n % params.mCatalog = mCatalog;\n\n % Create Indices to catalog\n [params.caNodeIndices] = ex_CreateIndexCatalog(params.mCatalog, params.mPolygon, params.bMap, params.nGriddingMode, ...\n params.nNumberEvents, params.fRadius, params.fSizeRectHorizontal, params.fSizeRectDepth);\n % Loop over all grid nodes\n hWaitbar1 = waitbar(0,'Calculating nodes...');\n set(hWaitbar1,'Numbertitle','off','Name','Node percentage');\n for nNode_ = nNodeStart:nNodeEnd\n % Create node catalog\n mNodeCatalog_ = params.mCatalog(params.caNodeIndices{nNode_}, :);\n % Check for constant number of events calculations\n if (params.nGriddingMode == 0)\n [mNodeCatalog_] = ex_CheckMaxRadius(mNodeCatalog_, params.mPolygon, nNode_, params.caNodeIndices, params.fMaxRadius, params.nNumberEvents, params.bMap);\n end\n % Check for number of events in aftershock sequence\n % Create catalog after split time (aftershock sequence)\n vSelAf = (params.fTstart <= mNodeCatalog_(:,3) & mNodeCatalog_(:,3) < params.fTstart+params.fTimePeriodDays);\n [nX,nY] = size(mNodeCatalog_(vSelAf,:));\n if (nX < params.nMinimumNumber)\n [nNumBgr,nY2] = size(mNodeCatalog_(~vSelAf,:));\n mValueGrid_= [mValueGrid_; NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN nNumBgr nNumBgr/params.fTimeBgr NaN NaN];\n else\n [rCalcNodeResult_] = gui_NodeCalcOmori(params,mNodeCatalog_);\n % Store the results\n mValueGrid_= [mValueGrid_;rCalcNodeResult_.pval1 rCalcNodeResult_.cval1 rCalcNodeResult_.kval1 rCalcNodeResult_.nNumEvents rCalcNodeResult_.fLogEqdens...\n rCalcNodeResult_.H rCalcNodeResult_.pmean1 rCalcNodeResult_.cmean1 rCalcNodeResult_.kmean1...\n rCalcNodeResult_.pmeanStd1 rCalcNodeResult_.cmeanStd1 rCalcNodeResult_.kmeanStd1...\n rCalcNodeResult_.fTafseq rCalcNodeResult_.fTafseqmean rCalcNodeResult_.nNumAf rCalcNodeResult_.nNumBgr...\n rCalcNodeResult_.fBgrate rCalcNodeResult_.fLog10Bgrate rCalcNodeResult_.fLog10Tafseq];\n end % End of if on nNode_\n if rem(nNode_,floor(fForceSave)) == 0\n waitbar(nNode_/length(params.mPolygon(:,1)))\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Temporary saving\n params.vcsGridNames = cellstr(char('p-value','c-value','k-value','Number of events','log(EQ_density)',...\n 'H','p-mean','c-mean','k-mean','\\sigma (p)','\\sigma (c)','\\sigma (k)','t_a [years]','t_a(Bst) [years]',...\n 'Number of aftershock','Num. events background','Background rate [year]','Log10(Bgr rate) [year]',...\n 'log10(t_a) [years]'));\n params.mValueGrid = mValueGrid_;\n % Add parameter to params.sComment\n if params.nGriddingMode == 0; % Constant number\n params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n ' Time period (days) ' num2str(params.fTimePeriodDays) ' d, Constant number: ' num2str(params.nNumberEvents) ', MaxRadius: '...\n num2str(params.fMaxRadius) ' km'];\n vResults = params;\n save(['tmp_result_Time' num2str(fTstart) '_Constnum_' num2str(params.nNumberEvents) '_MaxRad_' num2str(params.fMaxRadius)...\n '_Nmin_' num2str(params.nMinimumNumber) '_Node' num2str(nNode_) '.mat'], 'vResults');\n elseif params.nGriddingMode == 1; % Constant radius\n params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n ' Time period (days) ' num2str(params.fTimePeriodDays) ' d, Radius: ' num2str(params.fRadius) ' km, Nmin: ' num2str(params.nMinimumNumber)];\n vResults = params;\n save(['tmp_result_Time' num2str(fTstart) '_Rad_' num2str(params.fRadius) '_Nmin_' num2str(params.nMinimumNumber) '_Node' num2str(nNode_) '.mat'], 'vResults');\n else % Rectangle mode\n params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n ' Time period (days) ' num2str(params.fTimePeriodDays) ' d, Rect. X: ' num2str(params.fSizeRectHorizontal) ' km, Rect. Y: ' num2str(params.fSizeRectDepth)...\n ' km, Nmin: ' num2str(params.nMinimumNumber)];\n vResults = params;\n save(['tmp_result_Time' num2str(fTstart) '_RectX_' num2str(params.fSizeRectHorizontal) '_RectY_' num2str(params.fSizeRectDepth)...\n '_Nmin_' num2str(params.nMinimumNumber) '_Node' num2str(nNode_) '.mat'], 'vResults');\n end % END of params.nGriddingmode\n vResults =[];\n end % End updating waitbar\n end % for nNode\n close(hWaitbar1);\n % Parameter description\n params.vcsGridNames = cellstr(char('p-value','c-value','k-value','Number of events','log(EQ_density)',...\n 'H','p-mean','c-mean','k-mean','\\sigma (p)','\\sigma (c)','\\sigma (k)','t_a [years]','t_a(Bst) [years]',...\n 'Number of aftershock','Num. events background','Background rate [year]','Log10(Bgr rate) [year]',...\n 'log10(t_a) [years]'));\n params.mValueGrid = mValueGrid_;\n % Add parameter to params.sComment\n if params.nGriddingMode == 0; % Constant number\n params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n ' Time period (days) ' num2str(params.fTimePeriodDays) ' d, Constant number: ' num2str(params.nNumberEvents) ', MaxRadius: '...\n num2str(params.fMaxRadius) ' km'];\n vResults = params;\n save(['result_Time' num2str(fTstart) '_Constnum_' num2str(params.nNumberEvents) '_MaxRad_' num2str(params.fMaxRadius)...\n '_Nmin_' num2str(params.nMinimumNumber) '_Nodes_' num2str(nNodeStart) '_' num2str(nNodeEnd) '.mat'], 'vResults');\n elseif params.nGriddingMode == 1; % Constant radius\n params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n ' Time period (days) ' num2str(params.fTimePeriodDays) ' d, Radius: ' num2str(params.fRadius) ' km, Nmin: ' num2str(params.nMinimumNumber)];\n vResults = params;\n save(['result_Time' num2str(fTstart) '_Rad_' num2str(params.fRadius) '_Nmin_' num2str(params.nMinimumNumber)...\n '_Nodes_' num2str(nNodeStart) '_' num2str(nNodeEnd) '.mat'], 'vResults');\n else % Rectangle mode\n params.sComment = ['Starttime ' num2str(fTstart) ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.,'...\n ' Time period (days) ' num2str(params.fTimePeriodDays) ' d, Rect. X: ' num2str(params.fSizeRectHorizontal) ' km, Rect. Y: ' num2str(params.fSizeRectDepth)...\n ' km, Nmin: ' num2str(params.nMinimumNumber)];\n vResults = params;\n save(['result_Time' num2str(fTstart) '_RectX_' num2str(params.fSizeRectHorizontal) '_RectY_' num2str(params.fSizeRectDepth)...\n '_Nmin_' num2str(params.nMinimumNumber) '_Nodes_' num2str(nNodeStart) '_' num2str(nNodeEnd) '.mat'], 'vResults');\n end\n\n\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/afterrate/gui_CalcOmori.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.469937915274214}}
{"text": "%SerialLink.GRAVJAC Fast gravity load and Jacobian\n% \n% [TAU,JAC0] = R.gravjac(Q) is the generalised joint force/torques due to\n% gravity (1xN) and the manipulator Jacobian in the base frame (6xN) for\n% robot pose Q (1xN), where N is the number of robot joints.\n%\n% [TAU,JAC0] = R.gravjac(Q,GRAV) as above but gravity is given explicitly\n% by GRAV (3x1).\n%\n% Trajectory operation::\n%\n% If Q is MxN where N is the number of robot joints then a trajectory is\n% assumed where each row of Q corresponds to a pose. TAU (MxN) is the\n% generalised joint torque, each row corresponding to an input pose, and\n% JAC0 (6xNxM) where each plane is a Jacobian corresponding to an input pose.\n%\n% Notes::\n% - The gravity vector is defined by the SerialLink property if not explicitly given.\n% - Does not use inverse dynamics function RNE.\n% - Faster than computing gravity and Jacobian separately.\n%\n% Author::\n% Bryan Moutrie\n%\n% See also SerialLink.pay, SerialLink, SerialLink.gravload, SerialLink.jacob0.\n\n% Copyright (C) Bryan Moutrie, 2013-2015\n% Licensed under the GNU Lesser General Public License\n% see full file for full statement\n%\n% LICENSE STATEMENT:\n%\n% This file is part of pHRIWARE.\n% \n% pHRIWARE is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as \n% published by the Free Software Foundation, either version 3 of \n% the License, or (at your option) any later version.\n%\n% pHRIWARE 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 Lesser General Public \n% License along with pHRIWARE. If not, see .\n%\n\nfunction [tauB, J] = gravjac(robot, q, grav)\n \n n = robot.n;\n revolute = [robot.links(:).isrevolute];\n if ~robot.mdh\n baseAxis = robot.base(1:3,3);\n baseOrigin = robot.base(1:3,4);\n end\n \n poses = size(q, 1);\n tauB = zeros(poses, n);\n if nargout == 2, J = zeros(6, robot.n, poses); end\n \n % Forces\n force = zeros(3,n);\n if nargin < 3, grav = robot.gravity; end\n for joint = 1: n\n force(:,joint) = robot.links(joint).m * grav;\n end\n \n % Centre of masses (local frames)\n r = zeros(4,n);\n for joint = 1: n\n r(:,joint) = [robot.links(joint).r'; 1];\n end\n com_arr = zeros(3, n);\n \n for pose = 1: poses\n \n [Te, T] = robot.fkine(q(pose,:));\n \n jointOrigins = squeeze(T(1:3,4,:));\n jointAxes = squeeze(T(1:3,3,:));\n \n if ~robot.mdh\n jointOrigins = [baseOrigin, jointOrigins(:,1:end-1)];\n jointAxes = [baseAxis, jointAxes(:,1:end-1)];\n end\n \n % Backwards recursion\n for joint = n: -1: 1\n \n com = T(:,:,joint) * r(:,joint); % C.o.M. in world frame, homog\n com_arr(:,joint) = com(1:3); % Add it to the distal others\n \n t = 0;\n for link = joint: n % for all links distal to it\n if revolute(joint)\n d = com_arr(:,link) - jointOrigins(:,joint);\n t = t + cross3(d, force(:,link));\n % Though r x F would give the applied torque and not the\n % reaction torque, the gravity vector is nominally in the\n % positive z direction, not negative, hence the force is\n % the reaction force\n else\n t = t + force(:,link); %force on prismatic joint\n end\n end\n \n tauB(pose,joint) = t' * jointAxes(:,joint);\n end\n \n if nargout == 2\n J(:,:,pose) = makeJ(jointOrigins,jointAxes,Te(1:3,4),revolute);\n end\n \n end\n \n \nend\n\nfunction J = makeJ(O,A,e,r)\n J(4:6,:) = A;\n for j = 1:length(r)\n if r(j)\n J(1:3,j) = cross3(A(:,j),e-O(:,j));\n else\n J(:,j) = J([4 5 6 1 2 3],j); %J(1:3,:) = 0;\n end\n end\nend\n\nfunction c = cross3(a,b)\n c(3,1) = a(1)*b(2) - a(2)*b(1);\n c(1,1) = a(2)*b(3) - a(3)*b(2);\n c(2,1) = a(3)*b(1) - a(1)*b(3);\nend\n", "meta": {"author": "Allopart", "repo": "rbpf-gmapping", "sha": "affe0adc25fa446fc7af4902d699d92864bdba1b", "save_path": "github-repos/MATLAB/Allopart-rbpf-gmapping", "path": "github-repos/MATLAB/Allopart-rbpf-gmapping/rbpf-gmapping-affe0adc25fa446fc7af4902d699d92864bdba1b/rvctools/robot/@SerialLink/gravjac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.4698218049043293}}
{"text": "% pdfbcalc_imagekld.m\n% written by: Duncan Po\n% Date: November 16, 2002\n% calculate the Kublick-Liebler distance between two images based on \n% on their hidden markov tree parameters\n% Usage: kld = pdfbcalc_imagekld(savename, sdir, model1, model2)\n% kld = pdfbcalc_imagekld(savename, sdir, image1, model2, imformat1)\n% kld = pdfbcalc_imagekld(savename, sdir, image1, image2, imformat1, \n% imformat2)\n% Inputs: model1 - first Hidden Markov Tree Model\n% model2 - second Hidden Markov Tree Model\n% image1 - first image file name\n% image2 - second image file name\n% imformat1 - format of the first image file\n% imformat2 - format of the second image file\n% savename - filename to save the model of image1\n% - set to '' if no save desired\n% sdir - full pathname to save the model 1 (also set to ''\n% if savename == '')\n% Output: kld - the Kullback Liebler distance between the trees\n% kld2 - KLD estimation using Monte Carlo method\n\n%function [kld, kld2] = pdfbcalc_imagekld(savename, sdir, model1, model2, ...\n% imf1, imf2)\nfunction [kld, kld2] = pdfbcalc_imagekld(savename, sdir, model1, model2, ...\n imf1, imf2)\n\n% initialize the kld\nkld = 0;\nkld2 = 0;\n\nif nargin == 6\n % this case is when the images are provided but not the models\n image1 = model1;\n image2 = model2;\n \n % train the HMT models first\n [model1, dummy] = pdfbtrainimagethmt(image1, imf1, '', 0.01);\n [model2, dummy] = pdfbtrainimagethmt(image2, imf2, '', 0.01);\n\nelseif nargin == 5\n % this case is when we have one model and one image, need to \n % train a second model using the image provided\n image1 = model1;\n \n % train the HMT model\n [model1, dummy] = pdfbtrainimagethmt(image1, imf1, '', 0.01);\n \n %there is also the case for two models and no image when nargin==3\n %in that case, no training is needed\nend;\n\nif strcmp(savename, '') ~= 1\n file = sprintf('%s%s', sdir, savename);\n save(file,'model1');\nend;\n\nN = 60;\nnlevel = model1{1}.nlevels;\n\nfor k = 1:nlevel\n levndir(k) = log2(length(model1{1}.stdv{k}));\nend;\n\n% treat each tree as independent and using chain rule of KLD for\n% independent variables, simply add up the distances\nfor index = 1:length(model1)\n minkld = 10000;\n dbmodels = pdfbcreate_equiv_models(model1{index});\n for mmm = 1:length(dbmodels)\n tkld = pdfbcalc_KLD(nlevel, levndir, model2{index}, dbmodels{mmm});\n if tkld < minkld\n minkld = tkld;\n end;\n end;\n kld = kld + minkld;\nend;\n\n% Also apply the Monte Carlo method to verify the KLD estimation\nfor index = 1:length(model1)\n kld2 = kld2 + pdfbest_KLD(nlevel, levndir ,model2{index}, ...\n model1{index}, N); \nend;\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/29322-hidden-markov-tree-model-of-contourlet-transform/contourletHMT/pdfbcalc_imagekld.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.46973196331278555}}
{"text": "function cpp = subsetconnectivity ( t, p, nds )\n\n%*****************************************************************************80\n%\n%% SUBSETCONNECTIVITY: connectivity of boundary node subset in a triangulation.\n%\n% Licensing:\n%\n% Copyright (C) 2014 Marcus R. Garvie. \n% See 'mycopyright.txt' for details.\n%\n% Modified: \n% \n% 29 April 2014\n%\n% Author:\n%\n% Marcus Garvie\n%\n% Parameters:\n%\n% Input, real P(NP,2), the coordinates of a set of nodes.\n%\n% Input, integer T(NT,3), a list of the nodes which make up each \n% triangle of a triangulation of the nodes in P.\n%\n% Input, integer NDS(NN,1), a list of nodes comprising a subset of the\n% boundary nodes.\n%\n% Output, CPP(NE,2), a list of edges, each edge defined by 2 nodes from \n% the list NDS.\n%\n cpp = [];\n%\n% Work out connectivity for the whole boundary.\n%\n edges = boundedges (p,t);\n%\n% NO_EDGES = Number of edges in whole boundary.\n%\n [no_edges,~] = size(edges);\n%\n% NN = Number of nodes in the subset of boundary nodes.\n%\n NN = length(nds);\n%\n% Find the edges in the subset of the boundary NDS.\n%\n count = 0;\n\n for i = 1:no_edges\n\n node1 = edges(i,1);\n node2 = edges(i,2);\n bin1 = ismember(node1,nds);\n bin2 = ismember(node2,nds);\n\n if (bin1==1) & (bin2==1)\n count = count + 1;\n cpp(count,:) = edges(i,:);\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fe2d_predator_prey_fast/subsetconnectivity.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.469636827329991}}
{"text": "function [Ireg,O_trans,Spacing,M,B,F] = image_registration(Imoving,Istatic,Options)\n% This function image_registration is the most easy way to register two\n% 2D or 3D images both affine and nonrigidly.\n%\n% Features:\n% - It can be used with images from different type of scans or modalities.\n% - It uses both a rigid transform and a nonrigid b-spline grid transform.\n% - It uses grid refinement\n% - It can be used with images of different sizes.\n% - The function will automaticaly detect if the images can be registered\n% with the sum of squared pixel distance (SSD), or when mutual information\n% must be used as image similarity measure.\n%\n% Note: Compile the c-files with compile_c_files to allow 3D, and for more\n% more speed in 2D.\n%\n% [Ireg,Grid,Spacing,M,B,F] = image_registration(Imoving,Istatic,Options);\n%\n% Inputs,\n% Imoving : The image which will be registerd\n% Istatic : The image on which Imoving will be registered\n% Options : Registration options, see help below\n%\n% Outputs,\n% Ireg : The registered moving image\n% Grid: The b-spline controlpoints, can be used to transform another\n% image in the same way: I=bspline_transform(Grid,I,Spacing);\n% Spacing: The uniform b-spline knot spacing\n%\tM : The affine transformation matrix\n% B : The backwards transformation fields of the pixels in\n% x,y and z direction seen from the static image to the moving image.\n%\t\tin 2D, Bx=B(:,:,1); By=B(:,:,2);\n% F : The (approximated) forward transformation fields of the pixels in\n% x, y and z direction seen from the moving image to the static image.\n%\t\tin 2D, Fx=F(:,:,1); Fy=F(:,:,2);\n% (See the function backwards2forwards)\n%\n% Options,\n% Options.Similarity: Similarity measure (error) used can be set to:\n% sd : Squared pixel distance\n% mi : Normalized (Local) mutual information\n% d, gd, gc, cc, pi, ld : see image_difference.m.\n% Options.Registration:\n% Rigid : Translation, Rotation\n% Affine : Translation, Rotation, Shear, Resize\n% NonRigid : B-spline grid based local registration\n% Both : Nonrigid and Affine (Default)\n% Options.Penalty: Thin sheet of metal smoothness penalty, default in 2D 1e-3 ,\n%\t\t\t\tdefault in 3D, 1e-5\n% if set to zero the registration will take a shorter time, but\n% will give a more distorted transformation field.\n% Options.Interpolation: Linear (default) or Cubic, the final result is\n% always cubic interpolated.\n% Options.MaxRef : Maximum number of grid refinements steps (default 2)\n% Options.Grid: Initial B-spline controlpoints grid, if not defined is initalized\n% with an uniform grid. (Used for in example while\n% registering\n% a number of movie frames)\n% Options.Spacing: Spacing of initial B-spline grid in pixels 1x2 [sx sy] or 1x3 [sx sy sz]\n% sx, sy, sz must be powers of 2, to allow grid refinement.\n% Options.MaskMoving: Image which is transformed in the same way as Imoving and\n% is multiplied with the individual pixel errors\n% before calculation of the te total (mean) similarity\n% error. In case of measuring the mutual information similariy\n% the zero mask pixels will be simply discarded.\n% Options.MaskStatic: Also a Mask but is used for Istatic\n% Options.Verbose: Display Debug information 0,1 or 2\n%\n% Corresponding points / landmarks Options,\n% Options.Points1: List N x 2 or N x 3 of landmarks x,y(,z) in Imoving image\n% Options.Points2: List N x 2 or N x 3 of landmarks x,y(,z) in Istatic image, in which\n% every row correspond to the same row with landmarks\n% in Points1.\n% Options.PStrength: List Nx1 with the error strength used between the\n% corresponding points, (lower the strenght of the landmarks\n% if less sure of point correspondence).\n%\n%\n% Example 2D,\n% % Read two greyscale images of Lena\n% Imoving=imread('images/lenag1.png');\n% Istatic=imread('images/lenag2.png');\n%\n% % Register the images\n% [Ireg,O_trans,Spacing,M,B,F] = image_registration(Imoving,Istatic);\n%\n% % Show the registration result\n% figure,\n% subplot(2,2,1), imshow(Imoving); title('moving image');\n% subplot(2,2,2), imshow(Istatic); title('static image');\n% subplot(2,2,3), imshow(Ireg); title('registerd moving image');\n% % Show also the static image transformed to the moving image\n% Ireg2=movepixels(Istatic,F);\n% subplot(2,2,4), imshow(Ireg2); title('registerd static image');\n%\n% % Show the transformation fields\n% figure,\n% subplot(2,2,1), imshow(B(:,:,1),[]); title('Backward Transf. in x direction');\n% subplot(2,2,2), imshow(F(:,:,2),[]); title('Forward Transf. in x direction');\n% subplot(2,2,3), imshow(B(:,:,1),[]); title('Backward Transf. in y direction');\n% subplot(2,2,4), imshow(F(:,:,2),[]); title('Forward Transf. in y direction');\n%\n% % Calculate strain tensors\n% E = strain(F(:,:,1),F(:,:,2));\n% % Show the strain tensors\n% figure,\n% subplot(2,2,1), imshow(E(:,:,1,1),[-1 1]); title('Strain Tensors Exx');\n% subplot(2,2,2), imshow(E(:,:,1,2),[-1 1]); title('Strain Tensors Exy');\n% subplot(2,2,3), imshow(E(:,:,2,1),[-1 1]); title('Strain Tensors Eyx');\n% subplot(2,2,4), imshow(E(:,:,2,2),[-1 1]); title('Strain Tensors Eyy');\n%\n% Example 2D with Landmarks,\n%\n% % Read two images with triangles inside\n% Imoving=imread('images/landmarks1.png');\n% Istatic=imread('images/landmarks2.png');\n%\n% % Load the corresponding (matched) points\n% load('images/landmarks');\n%\n% % Register the images affine\n% Options = struct('Points1',Points1,'Points2',Points2,'PStrength',PStrength);\n% Ireg = image_registration(Imoving,Istatic,Options);\n%\n% % Show the start images\n% figure, imshow(Imoving+Istatic,[]);\n% % Show the registration result\n% figure, imshow(Ireg+Istatic,[]);\n%\n% Example 2D Prostate,\n% % Read two images\n% Imoving=im2double(imread('images/prostate1.png'));\n% Istatic=im2double(imread('images/prostate2.png'));\n%\n% % Use mutual information\n% Options.Similarity='mi';\n% % Set grid smoothness penalty\n% Options.Penalty = 1e-3;\n% Ireg = image_registration(Imoving,Istatic,Options);\n% % Show the registration result\n% figure,\n% subplot(2,2,1), imshow(Imoving); title('moving image');\n% subplot(2,2,2), imshow(Istatic); title('static image');\n% subplot(2,2,3), imshow(Ireg); title('registerd moving image');\n%\n% Example 3D,\n% % add needed function paths\n% functiondir=which('image_registration.m');\n% addpath([functiondir(1:end-length('image_registration.m')) '/low_level_examples'])\n%\n% % Get the volume data\n% [Imoving,Istatic]=get_example_data;\n%\n% % Register the images\n% Ireg = image_registration(Imoving,Istatic);\n%\n% % Show the results\n% showcs3(Imoving);\n% showcs3(Istatic);\n% showcs3(Ireg);\n%\n% Function is written by D.Kroon University of Twente (August 2010)\n\n% add all needed function paths\nadd_function_paths;\n\n% Disable warning\nwarning('off', 'MATLAB:maxNumCompThreads:Deprecated')\n\nif(size(Imoving,3)>3), IS3D=true; else IS3D=false; end\n% Check for presence of needed functions\nif(IS3D), check_mexfiles(); end\n\n\n% Process inputs\ndefaultoptions=struct('Similarity',[],'Registration','Both','Penalty',1e-3,'MaxRef',2,'Grid',[],'Spacing',[],'MaskMoving',[],'MaskStatic',[],'Verbose',2,'Points1',[],'Points2',[],'PStrength',[],'Interpolation','Linear','Scaling',[1 1]);\nif(IS3D), defaultoptions.Penalty=1e-5; defaultoptions.Scaling=[1 1 1]; end\nif(~exist('Options','var')), Options=defaultoptions;\nelse\n tags = fieldnames(defaultoptions);\n for i=1:length(tags),\n if(~isfield(Options,tags{i})), Options.(tags{i})=defaultoptions.(tags{i}); end\n end\n if(length(tags)~=length(fieldnames(Options))),\n warning('image_registration:unknownoption','unknown options found');\n end\nend\n\n% Set parameters\ntype=Options.Similarity;\nO_trans=Options.Grid; Spacing=Options.Spacing;\nMASKmoving=Options.MaskMoving; MASKstatic=Options.MaskStatic;\nPoints1=Options.Points1; Points2=Options.Points2; PStrength=Options.PStrength;\n\n% Start time measurement\nif(Options.Verbose>0), tic; end\n\n% Convert the input images to double with range 0..1\nif(IS3D)\n [Iclass,Imin,Imax,Imoving,Istatic]=images2doublesingle(Imoving,Istatic);\nelse\n [Iclass,Imin,Imax,Imoving,Istatic]=images2double(Imoving,Istatic);\nend\n\n% Resize the moving image to fit the static image\n[Istatic,Imoving,MASKmoving]=images2samesize(Istatic,Imoving,MASKmoving,IS3D);\n\n% Detect if the mutual information or pixel distance can be used as\n% similarity measure. By comparing the histograms.\nif(isempty(type)), type=check_image_modalities(Imoving,Istatic,Options); end\n\n% Register the moving image affine to the static image\nif(~strcmpi(Options.Registration(1),'N'))\n M=affine_registration(O_trans,Spacing,Options,Imoving,Istatic,MASKmoving,MASKstatic,type,Points1,Points2,PStrength,IS3D);\nelse M=[];\nend\n\n% Make the initial b-spline registration grid\n[O_trans,Spacing,MaxItt]=Make_Initial_Grid(O_trans,Spacing,Options,Imoving,M,IS3D);\n\n% Register the moving image nonrigid to the static image\nif(strcmpi(Options.Registration(1),'N')||strcmpi(Options.Registration(1),'B'))\n [O_trans,Spacing]=nonrigid_registration(O_trans,Spacing,Options,Imoving,Istatic,MASKmoving,MASKstatic,type,Points1,Points2,PStrength,MaxItt,IS3D);\nend\n\n% Transform the input image with the found optimal grid.\nif ( nargout<5 )\n Ireg=bspline_transform(O_trans,Imoving,Spacing,3);\nelse\n [Ireg,B]=bspline_transform(O_trans,Imoving,Spacing,3);\nend\n\n% Make the forward transformation fields from the backwards\nif ( nargout>5 ), F=backwards2forwards(B); end\n\n% Convert the double registered image to the class and range of the input images\nIreg=Back2OldRange(Ireg,Iclass,Imin,Imax);\n\n% End time measurement\nif(Options.Verbose>0), toc, end\n\nfunction add_function_paths()\ntry\n functionname='image_registration.m';\n functiondir=which(functionname);\n functiondir=functiondir(1:end-length(functionname));\n addpath([functiondir '/functions'])\n addpath([functiondir '/functions_affine'])\n addpath([functiondir '/functions_nonrigid'])\ncatch me\n disp(me.message);\nend\n\nfunction [Istatic,Imoving,MASKmoving]=images2samesize(Istatic,Imoving,MASKmoving,IS3D)\n% Resize the moving image to fit the static image\nif(sum(size(Istatic)-size(Imoving))~=0)\n % Resize the moving image to fit the static image\n if(IS3D)\n Imoving=imresize3d(Imoving,[],size(Istatic),'cubic');\n if(~isempty(MASKmoving))\n MASKmoving=imresize3d(MASKmoving,[],size(Istatic),'cubic');\n end\n else\n Imoving = imresize(Imoving,[size(Istatic,1) size(Istatic,2)],'bicubic');\n if(~isempty(MASKmoving))\n MASKmoving = imresize(MASKmoving,[size(Istatic,1) size(Istatic,2)],'bicubic');\n end\n end\nend\n\nfunction [Iclass,Imin,Imax,Imoving,Istatic]=images2double(Imoving,Istatic)\n% Store the class of the inputs\nIclass=class(Imoving);\n\n% Convert the inputs to double\nImoving=double(Imoving);\nIstatic=double(Istatic);\nImin=min(min(Istatic(:)),min(Imoving(:))); Imax=max(max(Istatic(:)),max(Istatic(:)));\nImoving=(Imoving-Imin)/(Imax-Imin);\nIstatic=(Istatic-Imin)/(Imax-Imin);\n\nfunction Ireg=Back2OldRange(Ireg,Iclass,Imin,Imax)\n% Back to old image range\nIreg=Ireg*(Imax-Imin)+Imin;\n\n% Set the class of output to input class\nif(strcmpi(Iclass,'uint8')), Ireg=uint8(Ireg); end\nif(strcmpi(Iclass,'uint16')), Ireg=uint16(Ireg); end\nif(strcmpi(Iclass,'uint32')), Ireg=uint32(Ireg); end\nif(strcmpi(Iclass,'int8')), Ireg=int8(Ireg); end\nif(strcmpi(Iclass,'int16')), Ireg=int16(Ireg); end\nif(strcmpi(Iclass,'int32')), Ireg=int32(Ireg); end\nif(strcmpi(Iclass,'single')), Ireg=single(Ireg); end\n\nfunction M=affine_registration(O_trans,Spacing,Options,Imoving,Istatic,MASKmoving,MASKstatic,type,Points1,Points2,PStrength,IS3D)\n% Make smooth for fast affine registration\nif(IS3D)\n ISmoving=imgaussian(Imoving,2.5,[10 10 10]);\n ISstatic=imgaussian(Istatic,2.5,[10 10 10]);\nelse\n ISmoving=imfilter(Imoving,fspecial('gaussian',[10 10],2.5));\n ISstatic=imfilter(Istatic,fspecial('gaussian',[10 10],2.5));\nend\n\n% Affine register the smoothed images to get the registration parameters\nif(strcmpi(Options.Registration(1),'R'))\n if(Options.Verbose>0), disp('Start Rigid registration'); drawnow; end\n if(IS3D)\n x=[0 0 0 0 0 0];\n else\n % Parameter scaling of the Translation and Rotation\n scale=[1 1 1];\n % Set initial affine parameters\n x=[0 0 0];\n end\nelseif(strcmpi(Options.Registration(1),'A'))\n if(Options.Verbose>0), disp('Start Affine registration'); drawnow; end\n % Parameter scaling of the Translation, Rotation, Resize and Shear\n if(IS3D)\n x=[0 0 0 0 0 0 1 1 1 0 0 0 0 0 0];\n else\n scale=[1 1 0.01 0.01 0.01 0.01 0.01];\n % Set initial affine parameters\n x=[0 0 0 1 1 0 0];\n end\nelseif(strcmpi(Options.Registration(1),'B'))\n if(Options.Verbose>0), disp('Start Affine part of Non-Rigid registration'); drawnow; end\n % Parameter scaling of the Translation, Rotation, Resize and Shear\n if(IS3D)\n x=[0 0 0 0 0 0 1 1 1 0 0 0 0 0 0];\n else\n scale=[1 1 0.01 0.01 0.01 0.01 0.01];\n % Set initial affine parameters\n x=[0 0 0 1 1 0 0];\n end\nelse\n warning('image_registrations:unknownoption','unknown registration method');\nend\n\nif(Options.Interpolation(1)=='L'), interpolation_mode=0; else interpolation_mode=2; end\n\n% Register Affine with 3 scale spaces\nfor refine_itt=1:3\n if(refine_itt==1)\n if(IS3D)\n ITmoving=imresize3d(ISmoving,0.25);\n ITstatic=imresize3d(ISstatic,0.25);\n else\n ITmoving=imresize(ISmoving,0.25);\n ITstatic=imresize(ISstatic,0.25);\n end\n Points1t=Points1*0.25; Points2t=Points2*0.25; PStrengtht=PStrength;\n if(IS3D)\n if(~isempty(MASKmoving)), ITMASKmoving = imresize3d(MASKmoving,0.25); else ITMASKmoving=[]; end\n if(~isempty(MASKstatic)), ITMASKstatic = imresize3d(MASKstatic,0.25); else ITMASKstatic=[]; end\n else\n if(~isempty(MASKmoving)), ITMASKmoving = imresize(MASKmoving,0.25); else ITMASKmoving=[]; end\n if(~isempty(MASKstatic)), ITMASKstatic = imresize(MASKstatic,0.25); else ITMASKstatic=[]; end\n end\n elseif(refine_itt==2)\n x(1:2)=x(1:2)*2;\n if(IS3D)\n ITmoving=imresize3d(ISmoving,0.5);\n ITstatic=imresize3d(ISstatic,0.5);\n else\n ITmoving=imresize(ISmoving,0.5);\n ITstatic=imresize(ISstatic,0.5);\n end\n Points1t=Points1*0.5; Points2t=Points2*0.5; PStrengtht=PStrength;\n if(IS3D),\n if(~isempty(MASKmoving)), ITMASKmoving = imresize3d(MASKmoving,0.5); else ITMASKmoving=[]; end\n if(~isempty(MASKstatic)), ITMASKstatic = imresize3d(MASKstatic,0.5); else ITMASKstatic=[]; end\n else\n if(~isempty(MASKmoving)), ITMASKmoving = imresize(MASKmoving,0.5); else ITMASKmoving=[]; end\n if(~isempty(MASKstatic)), ITMASKstatic = imresize(MASKstatic,0.5); else ITMASKstatic=[]; end\n end\n elseif(refine_itt==3)\n if(IS3D),\n x(1:3)=x(1:3)*2;\n else\n x(1:2)=x(1:2)*2;\n end\n ITmoving=Imoving;\n ITstatic=Istatic;\n ITMASKmoving = MASKmoving;\n ITMASKstatic = MASKstatic;\n Points1t=Points1; Points2t=Points2; PStrengtht=PStrength;\n end\n % Minimizer parameters\n % Use struct because expanded optimset is part of the Optimization Toolbox.\n if(IS3D)\n optim=struct('GradObj','on','GoalsExactAchieve',1,'Display','off','StoreN',10,'HessUpdate','lbfgs','MaxIter',100,'MaxFunEvals',1000,'TolFun',1e-7,'DiffMinChange',1e-5);\n else\n optim=struct('GradObj','on','GoalsExactAchieve',1,'Display','off','StoreN',10,'HessUpdate','lbfgs','MaxIter',100,'MaxFunEvals',1000,'TolFun',1e-7,'DiffMinChange',1e-3);\n end\n if(Options.Verbose>0), optim.Display='iter'; end\n if(IS3D)\n % Optimal scaling of values, to make the influence of every parameter in the\n % optimizer almost the same:\n [s_Trans, s_Rotation, s_Scale, s_Shear] = affine_parameter_scaling(size(ITmoving));\n if(strcmpi(Options.Registration(1),'R'))\n scale =[s_Trans s_Rotation];\n else\n if(strcmpi(type,'sd')),\n scale =[s_Trans s_Rotation s_Scale s_Shear];\n else \n scale =[s_Trans s_Rotation s_Scale/10 s_Shear/10];\n end\n end\n end\n \n % Scale the translation, resize and rotation parameters to scaled\n % optimizer values\n x=x./scale;\n % Find the Afffine deformation\n x=fminlbfgs(@(x)affine_registration_error(x,scale,ITmoving,ITstatic,type,O_trans,Spacing,ITMASKmoving,ITMASKstatic,Points1t,Points2t,PStrengtht,interpolation_mode),x,optim);\n % Scale the translation, resize and rotation parameters to the real values\n x=x.*scale;\nend\n\n\nif(strcmpi(Options.Registration(1),'R'))\n % Make the rigid transformation matrix\n if(IS3D)\n M=make_transformation_matrix(x(1:3),x(4:6));\n else\n M=make_transformation_matrix(x(1:2),x(3));\n end\nelse\n % Make the affine transformation matrix\n if(IS3D)\n M=make_transformation_matrix(x(1:3),x(4:6),x(7:9),x(10:15));\n else\n M=make_transformation_matrix(x(1:2),x(3),x(4:5),x(6:7));\n end\nend\n\nfunction type=check_image_modalities(Imoving,Istatic,Options)\n% Detect if the mutual information or pixel distance can be used as\n% similarity measure. By comparing the histograms.\nHmoving = hist(Imoving(:),(1/60)*[0.5:60])./numel(Imoving);\nHstatic = hist(Istatic(:),(1/60)*[0.5:60])./numel(Istatic);\nif(sum(abs(Hmoving(:)-Hstatic(:)))>0.25),\n type='mi';\n if(Options.Verbose>0), disp('Multi Modalities, Mutual information is used'); drawnow; end\nelse\n type='sd';\n if(Options.Verbose>0), disp('Same Modalities, Pixel Distance is used'); drawnow; end\nend\n\nfunction [O_trans,Spacing,MaxItt]=Make_Initial_Grid(O_trans,Spacing,Options,Imoving,M,IS3D)\nif(isempty(O_trans)),\n \n if(isempty(Options.Spacing))\n if(IS3D)\n % Calculate max refinements steps\n MaxItt=min(floor(log2(size(Imoving)/4)));\n \n % set b-spline grid spacing in x,y and z direction\n Spacing=[2^MaxItt 2^MaxItt 2^MaxItt];\n else\n % Calculate max refinements steps\n MaxItt=min(floor(log2([size(Imoving,1) size(Imoving,2)]/4)));\n \n % set b-spline grid spacing in x and y direction\n Spacing=[2^MaxItt 2^MaxItt];\n end\n else\n % set b-spline grid spacing in x and y direction\n Spacing=round(Options.Spacing);\n t=Spacing; MaxItt=0; while((nnz(mod(t,2))==0)&&(nnz(t<8)==0)), MaxItt=MaxItt+1; t=t/2; end\n end\n % Make the Initial b-spline registration grid\n if(IS3D)\n O_trans=make_init_grid(Spacing,size(Imoving),M);\n else\n if(strcmpi(Options.Registration(1),'N'))\n O_trans=make_init_grid(Spacing,[size(Imoving,1) size(Imoving,2)]);\n else\n O_trans=make_init_grid(Spacing,[size(Imoving,1) size(Imoving,2)],M);\n end\n end\nelse\n MaxItt=0;\n TestSpacing=Spacing;\n while(mod(TestSpacing,2)==0), TestSpacing=TestSpacing/2; MaxItt=MaxItt+1; end\n \n if(IS3D)\n % Calculate center of the image\n mean=size(Imoving)/2;\n % Make center of the image coordinates 0,0\n xd=O_trans(:,:,:,1)-mean(1); yd=O_trans(:,:,:,2)-mean(2); zd=O_trans(:,:,:,3)-mean(3);\n % Calculate the rigid transformed coordinates\n O_trans(:,:,:,1) = mean(1) + M(1,1) * xd + M(1,2) *yd + M(1,3) *zd + M(1,4)* 1;\n O_trans(:,:,:,2) = mean(2) + M(2,1) * xd + M(2,2) *yd + M(2,3) *zd + M(2,4)* 1;\n O_trans(:,:,:,3) = mean(3) + M(3,1) * xd + M(3,2) *yd + M(3,3) *zd + M(3,4)* 1;\n else\n if(~strcmpi(Options.Registration(1),'N'))\n % Calculate center of the image\n mean=size(Imoving)/2;\n % Make center of the image coordinates 0,0\n xd=O_trans(:,:,1)-mean(1); yd=O_trans(:,:,2)-mean(2);\n % Calculate the affine transformed coordinates\n O_trans(:,:,1) = mean(1) + M(1,1) * xd + M(1,2) *yd + M(1,3) * 1;\n O_trans(:,:,2) = mean(2) + M(2,1) * xd + M(2,2) *yd + M(2,3) * 1;\n end\n end\nend\n% Limit refinements steps to user input\nif(Options.MaxRef0), disp('Start non-rigid b-spline grid registration'); drawnow; end\n\nif(IS3D),\n if (Options.Verbose>0), disp(['Current Grid size : ' num2str(size(O_trans,1)) 'x' num2str(size(O_trans,2)) 'x' num2str(size(O_trans,3)) ]); drawnow; end\nelse\n if (Options.Verbose>0), disp(['Current Grid size : ' num2str(size(O_trans,1)) 'x' num2str(size(O_trans,2))]); drawnow; end\nend\n\n% set registration options.\noptions.type=type;\noptions.penaltypercentage=Options.Penalty;\noptions.interpolation=Options.Interpolation;\noptions.scaling=Options.Scaling;\noptions.verbose=false;\n\n% Enable forward instead of central gradient incase of error measure is pixel distance\nif(strcmpi(type,'sd')), options.centralgrad=false; end\n\n\n% Make smooth images for fast registration without local minimums\nif(IS3D)\n Hsize=round(0.1667*(size(Istatic,1)/size(O_trans,1)+size(Istatic,2)/size(O_trans,2)+size(Istatic,3)/size(O_trans,3)));\n ISmoving=imgaussian(Imoving,Hsize/5,[Hsize Hsize Hsize]);\n ISstatic=imgaussian(Istatic,Hsize/5,[Hsize Hsize Hsize]);\nelse\n Hsize=round(0.25*(size(Imoving,1)/size(O_trans,1)+size(Istatic,2)/size(O_trans,2)));\n ISmoving=imfilter(Imoving,fspecial('gaussian',[Hsize Hsize],Hsize/5));\n ISstatic=imfilter(Istatic,fspecial('gaussian',[Hsize Hsize],Hsize/5));\nend\nresize_per=2^(MaxItt-1);\n\n% Modified by Yuan Zhou on 3.7.2017\nresize_per = max(resize_per,1);\n% Reshape O_trans from a matrix to a vector.\nsizes=size(O_trans); O_trans=O_trans(:);\n\n\n% Resize the mask to the image size used in the registration\nif(IS3D)\n if(~isempty(MASKmoving)), MASKmovingsmall=imresize3d(MASKmoving,1/resize_per); else MASKmovingsmall=[]; end\n if(~isempty(MASKstatic)), MASKstaticsmall=imresize3d(MASKstatic,1/resize_per); else MASKstaticsmall=[]; end\nelse\n if(~isempty(MASKmoving)), MASKmovingsmall=imresize(MASKmoving,1/resize_per); else MASKmovingsmall=[]; end\n if(~isempty(MASKstatic)), MASKstaticsmall=imresize(MASKstatic,1/resize_per); else MASKstaticsmall=[]; end\nend\n\n% Use struct because expanded optimset is part of the Optimization Toolbox.\nif(IS3D)\n optim=struct('GradObj','on','GoalsExactAchieve',0,'StoreN',10,'HessUpdate','lbfgs','Display','off','MaxIter',100,'DiffMinChange',0.03,'DiffMaxChange',1,'MaxFunEvals',1000,'TolX',0.05,'TolFun',1e-8);\nelse\n optim=struct('GradObj','on','GoalsExactAchieve',0,'StoreN',10,'HessUpdate','lbfgs','Display','off','MaxIter',100,'DiffMinChange',0.001,'DiffMaxChange',1,'MaxFunEvals',1000,'TolX',0.005,'TolFun',1e-8);\nend\nif(Options.Verbose>0), optim.Display='iter'; end\n\n% Start the b-spline nonrigid registration optimizer\nif(IS3D)\n ISmoving_small=imresize3d(ISmoving,1/resize_per,[],'linear');\n ISstatic_small=imresize3d(ISstatic,1/resize_per,[],'linear');\nelse\n ISmoving_small=imresize(ISmoving,1/resize_per);\n ISstatic_small=imresize(ISstatic,1/resize_per);\nend\nSpacing_small=Spacing/resize_per;\nPoints1_small=Points1/resize_per;\nPoints2_small=Points2/resize_per;\nPStrength_small=PStrength;\nO_trans = resize_per*fminlbfgs(@(x)bspline_registration_gradient(x,sizes,Spacing_small,ISmoving_small,ISstatic_small,options,MASKmovingsmall,MASKstaticsmall,Points1_small,Points2_small,PStrength_small),O_trans/resize_per,optim);\n\n% Reshape O_trans from a vector to a matrix\nO_trans=reshape(O_trans,sizes);\n\nfor refine_itt=1:MaxItt\n if (Options.Verbose>0), disp('Registration Refinement'); drawnow; end\n \n % Refine the b-spline grid\n [O_trans,Spacing]=refine_grid(O_trans,Spacing,size(Imoving));\n \n % Make smooth images for fast registration without local minimums\n if(IS3D)\n Hsize=round(0.1667*(size(ISmoving,1)/size(O_trans,1)+size(ISstatic,2)/size(O_trans,2)+size(ISstatic,3)/size(O_trans,3)));\n ISmoving=imgaussian(Imoving,Hsize/5,[Hsize Hsize Hsize]);\n ISstatic=imgaussian(Istatic,Hsize/5,[Hsize Hsize Hsize]);\n else\n Hsize=round(0.25*(size(ISmoving,1)/size(O_trans,1)+size(ISstatic,2)/size(O_trans,2)));\n ISmoving=imfilter(Imoving,fspecial('gaussian',[Hsize Hsize],Hsize/5));\n ISstatic=imfilter(Istatic,fspecial('gaussian',[Hsize Hsize],Hsize/5));\n end\n resize_per=2^(MaxItt-1-refine_itt);\n \n % No smoothing in last registration step\n if(IS3D)\n if(refine_itt==MaxItt), ISmoving=Imoving; ISstatic=Istatic; optim.TolX=0.05; resize_per=1; end\n else\n if(refine_itt==MaxItt), ISmoving=Imoving; ISstatic=Istatic; resize_per=1; optim.TolX = 0.03; end\n end\n \n if(IS3D),\n if (Options.Verbose>0), disp(['Current Grid size : ' num2str(size(O_trans,1)) 'x' num2str(size(O_trans,2)) 'x' num2str(size(O_trans,3)) ]); drawnow; end\n else\n if (Options.Verbose>0), disp(['Current Grid size : ' num2str(size(O_trans,1)) 'x' num2str(size(O_trans,2))]); drawnow; end\n end\n \n % Reshape O_trans from a matrix to a vector.\n sizes=size(O_trans); O_trans=O_trans(:);\n \n % Resize the mask to the image size used in the registration\n if(IS3D)\n if(~isempty(MASKmoving)), MASKmovingsmall=imresize3d(MASKmoving,1/resize_per); else MASKmovingsmall=[]; end\n if(~isempty(MASKstatic)), MASKstaticsmall=imresize3d(MASKstatic,1/resize_per); else MASKstaticsmall=[]; end\n else\n if(~isempty(MASKmoving)), MASKmovingsmall=imresize(MASKmoving,1/resize_per); else MASKmovingsmall=[]; end\n if(~isempty(MASKstatic)), MASKstaticsmall=imresize(MASKstatic,1/resize_per); else MASKstaticsmall=[]; end\n end\n \n % Start the b-spline nonrigid registration optimizer\n if(IS3D)\n ISmoving_small=imresize3d(ISmoving,1/resize_per,[],'linear');\n ISstatic_small=imresize3d(ISstatic,1/resize_per,[],'linear');\n else\n ISmoving_small=imresize(ISmoving,1/resize_per);\n ISstatic_small=imresize(ISstatic,1/resize_per);\n end\n Spacing_small=Spacing/resize_per;\n Points1_small=Points1/resize_per;\n Points2_small=Points2/resize_per;\n PStrength_small=PStrength;\n O_trans = resize_per*fminlbfgs(@(x)bspline_registration_gradient(x,sizes,Spacing_small,ISmoving_small,ISstatic_small,options,MASKmovingsmall,MASKstaticsmall,Points1_small,Points2_small,PStrength_small),O_trans/resize_per,optim);\n \n % Reshape O_trans from a vector to a matrix\n O_trans=reshape(O_trans,sizes);\nend\n\n\nfunction check_mexfiles()\nif(exist('bspline_transform_3d_double','file')~=3)\n error('bspline_transform_3d_double mex function not found, compile the c-file');\nend\nif(exist('bspline_transform_3d_single','file')~=3)\n error('bspline_transform_3d_single mex function not found, compile the c-file');\nend\n\nfunction [Iclass,Imin,Imax,Imoving,Istatic]=images2doublesingle(Imoving,Istatic)\n% Store the class of the inputs\nIclass=class(Imoving);\n\n% Convert uint8, uint32 etc. to single.\nif(~strcmpi(Iclass,'single')&&~strcmpi(Iclass,'double'))\n Imoving=single(Imoving);\n Istatic=single(Istatic);\nend\nImin=min(min(Istatic(:)),min(Imoving(:))); Imax=max(max(Istatic(:)),max(Istatic(:)));\nImoving=(Imoving-Imin)/(Imax-Imin);\nIstatic=(Istatic-Imin)/(Imax-Imin);", "meta": {"author": "zhouyuanzxcv", "repo": "Hyperspectral", "sha": "f32dcca86677f8d37596376f57e9c733058f8cff", "save_path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral", "path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral/Hyperspectral-f32dcca86677f8d37596376f57e9c733058f8cff/REG/mi_bspline/image_registration.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.46960959746625053}}
{"text": "function exact = p01_exact ( )\n\n%*****************************************************************************80\n%\n%% P01_EXACT returns the exact integral for problem 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 November 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real EXACT, the value of the integral.\n%\n exact = exp ( 1.0 ) - 1.0;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_int/p01_exact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.46960959084594533}}
{"text": "function stokes_gnuplot ( header, n, x, y, u, v, s )\n\n%*****************************************************************************80\n%\n%% STOKES_GNUPLOT writes the Stokes vector field to files for GNUPLOT.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 January 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string HEADER, a header to be used to name the files.\n%\n% Input, integer N, the number of evaluation points.\n%\n% Input, real X(N), Y(N), the coordinates of the evaluation points.\n%\n% Input, real U(N), V(N), the velocity components.\n%\n% Input, real S, a scale factor for the velocity vectors.\n%\n\n%\n% Write the data file.\n%\n data_filename = strcat ( header, '_data.txt' );\n\n data_unit = fopen ( data_filename, 'wt' );\n\n for i = 1 : n\n fprintf ( data_unit, ' %10.4f %10.4f %10.4f %10.4f\\n', x(i), y(i), s * u(i), s * v(i) );\n end\n\n fclose ( data_unit );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Data written to \"%s\".\\n', data_filename );\n%\n% Write the command file.\n%\n command_filename = strcat ( header, '_commands.txt' );\n plot_filename = strcat ( header, '.png' );\n\n command_unit = fopen ( command_filename, 'wt' );\n\n fprintf ( command_unit, '# %s\\n', command_filename );\n fprintf ( command_unit, '#\\n' );\n fprintf ( command_unit, 'set term png\\n' );\n fprintf ( command_unit, 'set output \"%s\"\\n', plot_filename );\n fprintf ( command_unit, '#\\n' );\n fprintf ( command_unit, '# Add titles and labels.\\n' );\n fprintf ( command_unit, '#\\n' );\n fprintf ( command_unit, 'set xlabel \"<--- X --->\"\\n' );\n fprintf ( command_unit, 'set ylabel \"<--- Y --->\"\\n' );\n fprintf ( command_unit, 'set title \"Stokes velocity field\"\\n' );\n fprintf ( command_unit, 'unset key\\n' );\n fprintf ( command_unit, '#\\n' );\n fprintf ( command_unit, '# Add grid lines.\\n' );\n fprintf ( command_unit, '#\\n' );\n fprintf ( command_unit, 'set grid\\n' );\n fprintf ( command_unit, 'set size ratio -1\\n' );\n fprintf ( command_unit, '#\\n' );\n fprintf ( command_unit, '# Timestamp the plot.\\n' );\n fprintf ( command_unit, '#\\n' );\n fprintf ( command_unit, 'set timestamp\\n' );\n fprintf ( command_unit, 'plot \"%s\" using 1:2:3:4 with vectors \\\\\\n', data_filename );\n fprintf ( command_unit, ' head filled lt 2 linecolor rgb \"blue\"\\n' );\n fprintf ( command_unit, 'quit\\n' );\n\n fclose ( command_unit );\n\n fprintf ( 1, ' Commands written to \"%s\".\\n', command_filename );\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stokes_2d_exact/stokes_gnuplot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.46959245735396404}}
{"text": "function [u,p,info] = mgstokes(A,B,f,g,u,p,elem,freeDof,option) \n%% MGSTOKES: multigrid methods for Stokes equations\n%\n% Created by Ming Wang and Jie Zhou on Mar,3,2013 for P2 elements. Add\n% other elements by Jie and Long on Mar 24,2013.\n\nt = cputime;\n\n%% Size of systems\nN = max(elem(:));\nNdof = length(f) + length(g);\n\n%% Options\n% Assign default values to unspecified parameters\nif ~exist('option','var'), \n option = []; \nend\noption = mgoptions(option,Ndof); % parameters\ntol = option.tol; maxIt = option.solvermaxit; \nprintlevel = option.printlevel; \nsolver = option.solver;\n\n%% Mesh on each level\nN0 = 10;\nHB = zeros(N,3);\nlevel = 20;\nNL(level+1) = N; % now NL(1:level) = 0;\nelemi = cell(level,1);\nelemi{level} = elem;\nfor j = level: -1 : 2\n [elemi{j-1},newHB] = uniformcoarsenred(elemi{j}); % try coasen red refinement\n if (isempty(newHB)) || (size(elemi{j-1},1)< 2*N0) \n % no nodes are removed or it reaches the coarsest level\n NL = NL(j:end); \n break; \n end\n NL(j) = NL(j+1) - size(newHB,1); % update NL(k)\n HB(NL(j)+1:NL(j+1),1:3) = newHB(:,1:3);\nend\nlevel = length(NL)-1; % actual level\nelemi = elemi(end-level+1:end);\n\n%% Transfer operators between levels\nPro_u = cell(level,1);\nRes_u = cell(level,1);\nPro_p = cell(level,1);\nRes_p = cell(level,1);\n\nswitch(upper(option.elemType(1:end-2))) % transfer operator of velocity \n case 'P2'\n P2FreeDof = freeDof(1:end/2); % again only one component\n for i = level:-1:2 \n [ProU0,P2FreeDof] = nodeP2TansferUniform(elemi{i-1},elemi{i},P2FreeDof);\n Pro_u{i-1} = ProU0;\n Res_u{i} = ProU0';\n end \n case 'CR'\n CRfreeDof = freeDof(1:end/2);\n for i=level:-1:2 \n [ProU0,CRfreeDof] = transferCRred(elemi{i-1},elemi{i},CRfreeDof);\n Pro_u{i-1} = ProU0;\n Res_u{i} = ProU0';\n end \n case 'P1B' \n for i=level:-1:2 \n Pro_u{i-1} = speye(length(ufreeDof),length(freeEdge));\n Res_u{i} = Pro_u{i-1}';\n end\n case 'ISOP2'\n P2FreeDof = freeDof(1:end/2); % again only one component\n for i = level:-1:2 \n [ProU0,P2FreeDof] = nodeisoP2TansferUniform(elemi{i-1},elemi{i},P2FreeDof);\n Pro_u{i-1} = ProU0;\n Res_u{i} = ProU0';\n end \nend\nswitch upper(option.elemType(end-1:end)) \n case 'P0'\n for k = level:-1:2 \n Np(k-1) = size(elemi{k-1},1);\n Pro_p{k-1} = repmat(speye(Np(k-1)),4,1);\n Res_p{k} = Pro_p{k-1}';\n end \n case 'P1'\n [Pro_p,Res_p] = transferoperator(HB,NL); \nend\n\n%% Matrices in each level\n% size of u and p\nNu = zeros(level,1); \nNp = zeros(level,1);\nNu(level) = size(A,1)/2; % one component of velocity\nNp(level) = size(B,1);\n\nAi = cell(level,1);\nBi = cell(level,1);\nbigAi = cell(level,1);\nAi{level} = A; \nBi{level} = B;\nbigAi{level} = [Ai{level} Bi{level}'; Bi{level} sparse(Np(level),Np(level))];\n\nfor j = level:-1:2\n Ai{j-1} = blkdiag(Res_u{j},Res_u{j})*Ai{j}*blkdiag(Pro_u{j-1},Pro_u{j-1}); % Ac = Res*Af*Pro\n Bi{j-1} = Res_p{j}*Bi{j}*blkdiag(Pro_u{j-1},Pro_u{j-1});\n Nu(j-1) = size(Ai{j-1},1)/2; \n Np(j-1) = size(Bi{j-1},1);\n bigAi{j-1} = [Ai{j-1} Bi{j-1}'; Bi{j-1} sparse(Np(j-1),Np(j-1))];\nend\nNdof = 2*Nu+Np;\n\n%% matrix used for smoothing\nif isfield(option,'smootherType')\nsmoother = option.smootherType;\nelse \nsmoother ='LSCDGS';\nend\nauxMat = cell(level,1);\nswitch(smoother)\n case 'LSCDGS'\n for k = 2:level\n Bt = (Bi{k})';\n BBt = Bi{k}*Bt;\n BABt = Bi{k}*Ai{k}*Bt;\n Su = tril(Ai{k});\n Sp = tril(BBt);\n Spt = triu(BBt);\n DSp = diag(BBt);\n auxMat{k} = struct('Bt',Bt,'BBt',BBt,'BABt',BABt,'Su',Su,...\n 'Spt',Spt,'Sp',Sp,'DSp',DSp);\n end\n case 'IUzawa'\n for k = 2:level\n Bt = (Bi{k})';\n DA = 2*diag(Ai{k});\n invDA = spdiags(1./DA,0,2*Nu(k),2*Nu(k));\n BinvDABt = Bi{k}*invDA*Bt;\n auxMat{k} = struct('Bt',Bt,'DA',DA,'BinvDABt',BinvDABt);\n end\nend\nAi_IU = cell(level,1);\nSi_IU = cell(level,1);\nSSi_IU = cell(level,1);\nRes_IU = cell(level,1);\nPro_IU = cell(level,1);\nif strcmp(option.smootherbarSp,'VCYCLE')\n% option.smootherbarSp = 'VCYCLE';\n innerMGoption.solver = 'NO';\n innerMGoption.N0 = 10;\n for j = 2:level\n [tempvar,tempvar,Ai_IU{j},Si_IU{j},SSi_IU{j},Res_IU{j},Pro_IU{j}] = ...\n mg(auxMat{j}.BBt,ones(Np(j),1),elemi{j},innerMGoption); \n end\nend\n\n%% Solver\n% initial set up\nbigF = [f; g-mean(g)];\nbigu = [u; p];\nbigr = bigF - bigAi{level}*bigu;\nnb = norm(bigF);\nerr = zeros(maxIt,1);\nerr(1) = norm(bigr)/nb;\nk = 1;\n\nwhile (max(err(k)) > tol) && (k <= maxIt)\n k = k + 1;\n switch (solver)\n case 'VCYCLE'\n bigerru = vcycle(bigr);\n case 'WCYCLE'\n bigerru = wcycle(bigr);\n end\n bigu = bigu+bigerru;\n bigr = bigr - bigAi{level}*bigerru;\n % compute the relative error\n err(k) = norm(bigr)/nb;\n if printlevel >= 2 \n fprintf('#dof: %8.0u, MG %8s iter: %2.0u, err = %8.4e\\n',...\n Ndof(level), solver,k-1, err(k));\n end\nend\nerr = err(1:k);\nitStep = k-1;\nu = bigu(1:2*Nu(level)); \np = bigu(2*Nu(level)+1:end);\n\n%% Output\nif k > maxIt\n flag = 1;\nelse\n flag = 0;\nend\ntime = cputime-t;\nif printlevel >= 1\n fprintf('#dof: %6.0u, #nnz: %6.0u, level: %2.0u MG %6s iter: %2.0u, err = %8.4e, time = %4.2g s\\n',...\n Ndof(level), nnz(bigAi{level}), level, solver, itStep, err(end), time); \nend\nif (flag == 1) && (printlevel>0)\n fprintf('NOTE: the iterative method does not converge! \\n'); \nend\ninfo = struct('solverTime',time,'itStep',itStep,'error',err,'flag',flag,'stopErr',max(err(end,:)));\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% subfunctions vcycle, wcycle, smoothing\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%% subfunctions v-cycle\n function e = vcycle(r,J)\n if nargin < 2, J = level; end\n if J == 1 % solver in the coaresest grid\n e = zeros(size(r));\n e(1:end-1) = bigAi{J}(1:end-1,1:end-1)\\r(1:end-1);\n e(2*Nu(J)+1:end) = e(2*Nu(J)+1:end)-mean(e(2*Nu(J)+1:end));\n return\n end\n ru = r(1:2*Nu(J)); rp = r(2*Nu(J)+1:end);\n\n % pre-smoothing\n [eu,ep] = smoothing(zeros(2*Nu(J),1),zeros(Np(J),1),ru,rp,J);\n \n % form residual and restrict onto coarse grid\n rru = ru-Ai{J}*eu-(Bi{J})'*ep;\n rrp = rp-Bi{J}*eu;\n ruc = reshape(Res_u{J}*reshape(rru,Nu(J),2),2*Nu(J-1),1);\n rpc = Res_p{J}*rrp;\n \n % coarse grid correction\n rc = [ruc;rpc]; \n ec = vcycle(rc,J-1); \n \n % correction on the fine grid\n tempeu = reshape(Pro_u{J-1}*reshape(ec(1:2*Nu(J-1)),Nu(J-1),2),2*Nu(J),1);\n tempep = Pro_p{J-1}*ec(2*Nu(J-1)+1:end);\n eu = tempeu + eu; \n ep = tempep + ep;\n \n % post-smoothing\n [eu,ep] = smoothing(eu,ep,ru,rp,J);\n e = [eu;ep];\n\n end\n \n %% Wcycle MG\n function e = wcycle(r,J)\n if nargin < 2, J = level; end\n if J == 1 % solver in the coaresest grid\n e = zeros(size(r));\n e(1:end-1) = bigAi{J}(1:end-1,1:end-1)\\r(1:end-1);\n e(2*Nu(J)+1:end) = e(2*Nu(J)+1:end)-mean(e(2*Nu(J)+1:end));\n return\n end\n ru = r(1:2*Nu(J)); \n rp = r(2*Nu(J)+1:end);\n% \n % pre-smoothing in the fine grid \n [eu,ep] = smoothing(zeros(2*Nu(J),1),zeros(Np(J),1),ru,rp,J);\n \n % form residual and restrict onto coarse grid\n rru = ru - Ai{J}*eu-(Bi{J})'*ep;\n rrp = rp - Bi{J}*eu;\n ruc = reshape(Res_u{J}*reshape(rru,Nu(J),2),2*Nu(J-1),1);\n rpc = Res_p{J}*rrp;\n\n % coarse grid correction\n rc = [ruc;rpc];\n ec = wcycle(rc,J-1);\n % once more for w-cycle\n ec = ec+ wcycle(rc - bigAi{J-1}*ec,J-1);\n \n % correction on the fine grid\n tempeu = reshape(Pro_u{J-1}*reshape(ec(1:2*Nu(J-1)),Nu(J-1),2),2*Nu(J),1);\n tempep = Pro_p{J-1}*ec(2*Nu(J-1)+1:end);\n eu = eu + tempeu; \n ep = ep + tempep;\n \n % post-smoothing in the fine grid\n [eu,ep] = smoothing(eu,ep,ru,rp,J);\n e = [eu;ep];\n end\n \n %% Smoothing\n function [u,p] = smoothing(u,p,f,g,J)\n if strcmp(smoother,'LSCDGS')\n [u,p] = StokesLSCDGS(u,p,f,g,Ai{J},Bi{J},auxMat{J},elemi{J},option,...\n Ai_IU{J},Si_IU{J},SSi_IU{J},Res_IU{J},Pro_IU{J});\n elseif strcmp(smoother,'BDDGS')\n % e = StokesBiDGStri(Ai{J}, Bi{J}, e, r, smoothStep, invDM{J},area{J});\n elseif strcmp(smoother,'iUzawa')\n [u,p] = StokesIUzawa(u,p,f,g,Ai{J},Bi{J},auxMat{J},elemi{J},option,...\n Ai_IU{J},Si_IU{J},SSi_IU{J},Res_IU{J},Pro_IU{J});\n end\n end\nend", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/iFEM/solver/mgstokes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325345, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4690914795733288}}
{"text": "function [x,I,exitFlag]=getMinNrFluxes(model, toMinimize, params,scores)\n% getMinNrFluxes\n% Returns the minimal set of fluxes that satisfy the model using\n% mixed integer linear programming.\n%\n%\tmodel a model structure\n% toMinimize either a cell array of reaction IDs, a logical vector\n% with the same number of elements as reactions in the model,\n% of a vector of indexes for the reactions that should be\n% minimized (opt, default model.rxns)\n% params parameter structure as used by getMILPParams (opt)\n% scores vector of weights for the reactions. Negative scores\n% should not have flux. Positive scores are not possible in this\n% implementation, and they are changed to max(scores(scores<0)).\n% Must have the same dimension as toMinimize (find(toMinimize)\n% if it is a logical vector) (opt, default -1 for all reactions)\n%\n% x the corresponding fluxes for the full model\n% I the indexes of the reactions in toMinimize that were used\n% in the solution\n% exitFlag 1: optimal solution found\n% -1: no feasible solution found\n% -2: optimization time out\n%\n% NOTE: Uses 1000 mmol/gDW/h as an arbitary large flux. Could possibly\n% cause problems if the fluxes in the model are larger than that.\n%\n% Usage: [x,I,exitFlag]=getMinNrFluxes(model, toMinimize, params, scores)\n\nexitFlag=1;\n\nif nargin<2\n toMinimize=model.rxns;\nelseif ~islogical(toMinimize) && ~isnumeric(toMinimize)\n toMinimize=convertCharArray(toMinimize);\nelse\n toMinimize=model.rxns(toMinimize);\nend\n\n%For passing parameters to the solver\nif nargin<3\n params=struct();\nend\n\nif nargin<4\n %It says that the default is -1, but that is to fit with other code\n scores=ones(numel(toMinimize),1)*1;\nelse\n if numel(scores)~=numel(toMinimize)\n EM='The number of scores must be the same as the number of reactions to minimize';\n dispEM(EM);\n end\n \n %Change positive scores to have a small negative weight. This is a\n %temporary solution.\n scores(scores>=0)=max(scores(scores<0));\n \n %It says that the default is -1, but that is to fit with other code\n scores=scores*-1;\nend\n\n%Check if the model is in irreversible format\nif any(model.rev)\n %Convert the model to irreversible format\n irrevModel=convertToIrrev(model);\n \n %Find the indexes for the reactions in toMinimize\n [indexes, I]=ismember(strrep(irrevModel.rxns,'_REV',''),toMinimize);\nelse\n irrevModel=model;\n \n %Find the indexes for the reactions in toMinimize\n [indexes, I]=ismember(irrevModel.rxns,toMinimize);\nend\n\nindexes=find(indexes);\n%Adjust scores to fit with reversible\nscores=scores(I(indexes));\n\n%Add binary constraints in the following manner: - Add one unique\n%\"metabolite\" for each integer reaction as a substrate.\n% These metabolites can have net production\n%- Add reactions for the production of each of those metabolites. The\n% amount produced in one reaction unit must be larger than the largest\n% possible flux in the model (but not too large to avoid bad scaling)\n\n%Calculate a solution to the problem without any constraints. This is to\n%get an estimate about the magnitude of fluxes in the model and to get a\n%feasible start solution.\nsol=solveLP(irrevModel,1);\n\n%Return an empty solution if the non-constrained problem couldn't be solved\nif isempty(sol.x)\n x=[];\n I=[];\n exitFlag=-1;\n return;\nend\n\n%Take the maximal times 5 to have a safe margin. If it's smaller than 1000,\n%then use 1000 instead.\nmaxFlux=max(max(sol.x)*5,1000);\n\nintArray=speye(numel(irrevModel.rxns))*-1;\nintArray=intArray(indexes,:);\nprob.a=[irrevModel.S;intArray];\na=[sparse(numel(irrevModel.mets),numel(indexes));speye(numel(indexes))*maxFlux];\nprob.a=[prob.a a];\nprob.ints.sub=numel(irrevModel.rxns)+1:numel(irrevModel.rxns)+numel(indexes);\n\nprob.c=[zeros(numel(irrevModel.rxns),1);scores(:);zeros(size(prob.a,1),1)]; %Minimize the number of fluxes\nprob.A=[prob.a -speye(size(prob.a,1))];\nprob.blc=[irrevModel.b(:,1);zeros(numel(indexes),1)];\nif size(irrevModel.b,2)==2\n prob.buc=[irrevModel.b(:,2);inf(numel(indexes),1)];\nelse\n prob.buc=[irrevModel.b(:,1);inf(numel(indexes),1)];\nend\nprob.blx=[irrevModel.lb;zeros(numel(indexes),1)];\nprob.bux=[irrevModel.ub;ones(numel(indexes),1)];\nprob.lb = [prob.blx; prob.blc];\nprob.ub = [prob.bux; prob.buc];\nprob.osense=1;\nprob.csense=repmat('E', 1, size(prob.a,1),1);\nprob.b=zeros(size(prob.a,1), 1);\n\n%Use the output from the linear solution as starting point. Only the values\n%for the integer variables will be used, but all are supplied.\nprob.sol.int.xx=zeros(numel(prob.c),1);\nprob.sol.int.xx(prob.ints.sub(sol.x(indexes)>10^-12))=1;\nprob.x0=[];\nprob.vartype=repmat('C', size(prob.A,2), 1);\nprob.vartype(prob.ints.sub) = 'I'; % with .lb = 0 and .ub = 1, they are binary\n% integers (glpk in octave only allows 'continuous' or '', not 'binary')\nprob=rmfield(prob,{'blx','bux','blc','buc'});\n\n% Optimize the problem\nres = optimizeProb(prob,params);\nisFeasible=checkSolution(res);\n\nif ~isFeasible\n x=[];\n I=[];\n exitFlag=-1;\n return;\nend\n\nxx=res.full(1:numel(irrevModel.rxns));\nI=res.full(numel(xx)+1:end);\n\n%Check if Mosek aborted because it reached the time limit\n%TODO: modify for cobra/gurobi\n% if strcmp('MSK_RES_TRM_MAX_TIME',res.rcode)\n% exitFlag=-2;\n% end\n\n%Map back to original model from irrevModel\nx=xx(1:numel(model.rxns));\nif numel(irrevModel.rxns)>numel(model.rxns)\n x(model.rev~=0)=x(model.rev~=0)-xx(numel(model.rxns)+1:end);\nend\n\nI=ismember(toMinimize,strrep(irrevModel.rxns(indexes(I>10^-12)),'_REV',''));\nend\n", "meta": {"author": "SysBioChalmers", "repo": "RAVEN", "sha": "cf4d3e0be954fde96a1a09ae3353dd2ee46552ed", "save_path": "github-repos/MATLAB/SysBioChalmers-RAVEN", "path": "github-repos/MATLAB/SysBioChalmers-RAVEN/RAVEN-cf4d3e0be954fde96a1a09ae3353dd2ee46552ed/core/getMinNrFluxes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.46902481837669074}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Q = INVERSEKINEMATIC_KUKA_KR_30_L16_2(robot, T)\t\n% Solves the inverse kinematic problem for the KUKA KR5 ARC robot\n% where:\n% robot stores the robot parameters.\n% T is an homogeneous transform that specifies the position/orientation\n% of the end effector.\n%\n% A call to Q=INVERSEKINEMATIC_KUKA_KR_30_L16_2 returns 8 possible solutions, thus,\n% Q is a 6x8 matrix where each column stores 6 feasible joint values.\n%\n% \n% Example code:\n%\n% robot=load_robot('kuka', 'KR_30_L16_2');\n% q = [0 0 0 0 0 0];\t\n% T = directkinematic(robot, q);\n% %Call the inversekinematic for this robot\n% qinv = inversekinematic(robot, T);\n% check that all of them are feasible solutions!\n% and every Ti equals T\n% for i=1:8,\n% Ti = directkinematic(robot, qinv(:,i))\n% end\n%\tSee also DIRECTKINEMATIC.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n% Copyright (C) 2012, by Arturo Gil Aparicio\n%\n% This file is part of ARTE (A Robotics Toolbox for Education).\n% \n% ARTE is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% ARTE is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with ARTE. If not, see .\nfunction q = inversekinematic_kuka_kr20_3(robot, T)\n\n%initialize q,\n%eight possible solutions are generally feasible\nq=zeros(6,8);\n\n% %Evaluate the parameters\n% theta = eval(robot.DH.theta);\nd = eval(robot.DH.d);\nL6=abs(d(6));\n\n\n%T= [ nx ox ax Px;\n% ny oy ay Py;\n% nz oz az Pz];\nPx=T(1,4);\nPy=T(2,4);\nPz=T(3,4);\n\n%Compute the position of the wrist, being W the Z component of the end effector's system\nW = T(1:3,3);\n\n% Pm: wrist position\nPm = [Px Py Pz]' - L6*W; \n\n%first joint, two possible solutions admited: \n% if q(1) is a solution, then q(1) + pi is also a solution\nq1=atan2(Pm(2), Pm(1));\n\n\n%solve for q2\nq2_1=solve_for_theta2(robot, [q1 0 0 0 0 0 0], Pm);\n%the other possible solution is q1 + pi\nq2_2=solve_for_theta2(robot, [q1+pi 0 0 0 0 0 0], Pm);\n\n%solve for q3\nq3_1=solve_for_theta3(robot, [q1 0 0 0 0 0 0], Pm);\n%solver for q3 for both cases\nq3_2=solve_for_theta3(robot, [q1+pi 0 0 0 0 0 0], Pm);\n\n\n\n%the next matrix doubles each column. For each two columns, two different\n%configurations for theta4, theta5 and theta6 will be computed. These\n%configurations are generally referred as wrist up and wrist down solution\nq = [q1 q1 q1 q1 q1+pi q1+pi q1+pi q1+pi; \n q2_1(1) q2_1(1) q2_1(2) q2_1(2) q2_2(1) q2_2(1) q2_2(2) q2_2(2);\n q3_1(1) q3_1(1) q3_1(2) q3_1(2) q3_2(1) q3_2(1) q3_2(2) q3_2(2);\n 0 0 0 0 0 0 0 0;\n 0 0 0 0 0 0 0 0;\n 0 0 0 0 0 0 0 0];\n\n%leave only the real part of the solutions\n% q=real(q);\n% q = [pi/4 -pi/6 pi/4 0.1 0.1 0.1];\n% T = directkinematic(robot,q) \n% T = \n% -0.3864 -0.6500 0.6544 0.4980\n% -0.1062 0.7361 0.6685 0.5003\n% -0.9162 0.1888 -0.3535 1.0008\n% 0 0 0 1.0000\n%q =\n% 0.7854 -0.5236 0.7854 0.1000 0.1000 0.1000\n\n%Note that in this robot, the joint q3 has a non-simmetrical range. In this\n%case, the joint ranges from 60 deg to -219 deg, thus, the typical normalizing\n%step is avoided in this angle (the next line is commented). When solving\n%for the orientation, the solutions are normalized to the [-pi, pi] range\n%only for the theta4, theta5 and theta6 joints.\n\n%normalize q to [-pi, pi]\nq(1,:) = normalize(q(1,:));\nq(2,:) = normalize(q(2,:));\n\n% solve for the last three joints\n% for any of the possible combinations (theta1, theta2, theta3)\nfor i=1:2:size(q,2),\n qtemp = solve_spherical_wrist2(robot, q(:,i), T, 1,'geometric'); %wrist up\n qtemp(4:6)=normalize(qtemp(4:6));\n q(:,i)=qtemp;\n \n qtemp = solve_spherical_wrist2(robot, q(:,i), T, -1, 'geometric'); %wrist up\n qtemp(4:6)=normalize(qtemp(4:6));\n q(:,i+1)=qtemp;\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% solve for second joint theta2, two different\n% solutions are returned, corresponding\n% to elbow up and down solution\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction q2 = solve_for_theta2(robot, q, Pm)\n\n%Evaluate the parameters\ntheta = eval(robot.DH.theta);\nd = eval(robot.DH.d);\na = eval(robot.DH.a);\nalpha = eval(robot.DH.alpha);\n\n%See geometry\nL2=abs(a(2));\nL3=abs(d(4));\nA2 = (a(3));\n\n%See geometry of the robot\n%compute L4\nL4 = sqrt(A2^2 + L3^2);\n\n%The inverse kinematic problem can be solved as in the IRB 140 (for example)\n\n%given q1 is known, compute first DH transformation\nT01=dh(robot, q, 1);\n\n%Express Pm in the reference system 1, for convenience\np1 = inv(T01)*[Pm; 1];\n\nr = sqrt(p1(1)^2 + p1(2)^2);\n\nbeta = atan2(-p1(2), p1(1));\ngamma = real(acos((L2^2+r^2-L4^2)/(2*r*L2)));\n\n%return two possible solutions\n%elbow up and elbow down\n%the order here is important and is coordinated with the function\n%solve_for_theta3\nq2(1) = pi/2 - beta - gamma; %elbow up\nq2(2) = pi/2 - beta + gamma; %elbow down\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% solve for third joint theta3, two different\n% solutions are returned, corresponding\n% to elbow up and down solution\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction q3 = solve_for_theta3(robot, q, Pm)\n\n%Evaluate the parameters\ntheta = eval(robot.DH.theta);\nd = eval(robot.DH.d);\na = eval(robot.DH.a);\nalpha = eval(robot.DH.alpha);\n\n%See geometry\nL2=abs(a(2));\nL3=abs(d(4));\n\nA2 = (a(3));\n\n%See geometry of the robot\n%compute L4\nL4 = sqrt(A2^2 + L3^2);\n\n%the angle phi is fixed\nphi=acos((A2^2+L4^2-L3^2)/(2*A2*L4));\n\n%given q1 is known, compute first DH transformation\nT01=dh(robot, q, 1);\n\n%Express Pm in the reference system 1, for convenience\np1 = inv(T01)*[Pm; 1];\n\nr = sqrt(p1(1)^2 + p1(2)^2);\n\nbeta = real(acos((L2^2 + L4^2 - r^2)/(2*L2*L4)));\n\n%return two possible solutions\n%elbow up and elbow down solutions\n%the order here is important\nq3(1) = pi - phi - beta; \nq3(2) = pi - phi + beta; \n\n\n\n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/robots/KUKA/KR20_3/inversekinematic_kuka_kr20_3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.63341026367784, "lm_q1q2_score": 0.4688340450874562}}
{"text": "function om = add_quad_cost(om, name, idx, Q, c, k, varsets)\n%ADD_QUAD_COST Adds a set of user costs to the model.\n% OM.ADD_QUAD_COST(NAME, Q, C);\n% OM.ADD_QUAD_COST(NAME, Q, C, K);\n% OM.ADD_QUAD_COST(NAME, Q, C, K, VARSETS);\n% OM.ADD_QUAD_COST(NAME, IDX_LIST, Q, C);\n% OM.ADD_QUAD_COST(NAME, IDX_LIST, Q, C, K);\n% OM.ADD_QUAD_COST(NAME, IDX_LIST, Q, C, K, VARSETS);\n%\n% Adds a named block of quadratic costs to the model. Costs are of the\n% form\n% F(X) = 1/2 * X'*Q*X + C'*X + K\n% where Q is an NX x NX matrix (possibly sparse), C is an NX x 1 vector,\n% K is a scalar and NX is the number of elements in X. Here X is the vector\n% formed by combining the specified VARSETS (the full optimization vector\n% by default). Alternatively, if Q is an NX x 1 vector or empty, then F(X)\n% is also NX x 1, and K can be either NX + 1 or scalar.\n% F(X) = 1/2 * Q .* X.^2 + C .* X + K\n%\n% Indexed Named Sets\n% A cost set can be identified by a single NAME, as described\n% above, such as 'PgCost', or by a name that is indexed by one\n% or more indices, such as 'PgCost(3,4)'. For an indexed named\n% set, before adding the cost sets themselves, the dimensions\n% of the indexed set must be set by calling INIT_INDEXED_NAME.\n%\n% The constraints are then added using the following, where\n% all arguments are as described above, except IDX_LIST is a cell\n% array of the indices for the particular cost set being added.\n%\n% OM.ADD_QUAD_COST(NAME, IDX_LIST, Q, C, K);\n% OM.ADD_QUAD_COST(NAME, IDX_LIST, Q, C, K, VARSETS);\n%\n% Examples:\n% om.add_quad_cost('quad_cost1', Q1, c1, 0);\n% om.add_quad_cost('lin_cost2', [], c2, k2, {'Vm', 'Pg', 'z'});\n%\n% om.init_indexed_name('c', {2, 3});\n% for i = 1:2\n% for j = 1:3\n% om.add_quad_cost('c', {i, j}, Q{i,j}, ...);\n% end\n% end\n%\n% See also OPT_MODEL, PARAMS_QUAD_COST, EVAL_QUAD_COST.\n\n% MP-Opt-Model\n% Copyright (c) 2008-2020, Power Systems Engineering Research Center (PSERC)\n% by Ray Zimmerman, PSERC Cornell\n%\n% This file is part of MP-Opt-Model.\n% Covered by the 3-clause BSD License (see LICENSE file for details).\n% See https://github.com/MATPOWER/mp-opt-model for more info.\n\n%% initialize input arguments\nif iscell(idx) %% indexed named set\n if nargin < 7\n varsets = {};\n end\nelse %% simple named set\n if nargin < 6\n varsets = {};\n else\n varsets = k;\n end\n if nargin < 5\n k = 0;\n else\n k = c;\n end\n c = Q;\n Q = idx;\n idx = {};\nend\n\n%% convert varsets from cell to struct array if necessary\nvarsets = om.varsets_cell2struct(varsets);\nnv = om.varsets_len(varsets); %% number of variables\n\n%% check sizes\n[MQ, NQ] = size(Q);\n[Mc, Nc] = size(c);\nif MQ\n if NQ ~= MQ && NQ ~= 1\n error('@opt_model/add_quad_cost: Q (%d x %d) must be square or a column vector (or empty)', MQ, NQ);\n end\nend\nif Mc && Nc ~= 1\n error('@opt_model/add_quad_cost: c (%d x %d) must be a column vector (or empty)', Mc, Nc);\nend\nif MQ\n if Mc && Mc ~= MQ\n error('@opt_model/add_quad_cost: dimensions of Q (%d x %d) and c (%d x %d) are not compatible', MQ, NQ, Mc, Nc);\n end\n nx = MQ;\nelse\n if ~Mc\n error('@opt_model/add_quad_cost: Q and c cannot both be empty');\n end\n nx = Mc;\nend\nif nx ~= nv\n error('@opt_model/add_quad_cost: dimensions of Q (%d x %d) and c (%d x %d) do not match\\nnumber of variables (%d)\\n', MQ, NQ, Mc, Nc, nv);\nend\n\n%% size of named cost set\nif NQ == 1 || isempty(Q) %% if Q is a column vector or empty\n N = nx; %% cost is element-wise, i.e. a vector\nelse %% otherwise Q is a square matrix\n N = 1; %% cost is scalar\nend\n\n%% add the named quadratic cost set\nom.add_named_set('qdc', name, idx, N, Q, c, k, varsets);\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/mp-opt-model/lib/@opt_model/add_quad_cost.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631543, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4685544069345756}}
{"text": "function mpc = t_case3p_c\n%T_CASE3P_C Six bus hybrid test case, 2 single-phase buses, 4 3-phase buses.\n%\n% One bus is a hybrid PV bus (PV on single-phase side). Three phase bus\n% solution should match T_CASE3P_A\n\n%% MATPOWER Case Format : Version 2\nmpc.version = '2';\n\n%%----- Power Flow Data -----%%\n%% system MVA base\nmpc.baseMVA = 100;\n\n%% bus data\n%\tbus_i\ttype\tPd\tQd\tGs\tBs\tarea\tVm\tVa\tbaseKV\tzone\tVmax\tVmin\nmpc.bus = [\n\t1\t3\t0\t0\t0\t0\t1\t1\t0.20115203\t12.47\t1\t1.1\t0.9;\n% \t2\t2\t0\t0\t0\t0\t1\t1\t0\t12.47\t1\t1.1\t0.9;\n% \t3\t2\t0\t0\t0\t0\t1\t1\t0\t12.47\t1\t1.1\t0.9;\n\t4\t2\t0\t0\t0\t0\t1\t1\t0\t12.47\t1\t1.1\t0.9;\n% \t5\t1\t90\t30\t0\t0\t1\t1\t0\t12.47\t1\t1.1\t0.9;\n% \t6\t1\t0\t0\t0\t0\t1\t1\t0\t12.47\t1\t1.1\t0.9;\n% \t7\t1\t100\t35\t0\t0\t1\t1\t0\t12.47\t1\t1.1\t0.9;\n% \t8\t1\t0\t0\t0\t0\t1\t1\t0\t12.47\t1\t1.1\t0.9;\n% \t9\t1\t125\t50\t0\t0\t1\t1\t0\t12.47\t1\t1.1\t0.9;\n];\n\n%% generator data\n%\tbus\tPg\tQg\tQmax\tQmin\tVg\tmBase\tstatus\tPmax\tPmin\tPc1\tPc2\tQc1min\tQc1max\tQc2min\tQc2max\tramp_agc\tramp_10\tramp_30\tramp_q\tapf\nmpc.gen = [\n\t1\t72.3\t27.03\t300\t-300\t1.0024291384\t100\t1\t250\t10\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n\t4\t0\t0\t300\t-300\t1\t100\t1\t250\t10\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n% \t2\t163\t6.54\t300\t-300\t1.025\t100\t1\t300\t10\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n% \t3\t85\t-10.95\t300\t-300\t1.025\t100\t1\t270\t10\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n];\n\n%% branch data\n%\tfbus\ttbus\tr\tx\tb\trateA\trateB\trateC\tratio\tangle\tstatus\tangmin\tangmax\nmpc.branch = [\n\t1\t4\t0\t0.0576\t0\t250\t250\t250\t0\t0\t1\t-360\t360;\n% \t4\t5\t0.017\t0.092\t0.158\t250\t250\t250\t0\t0\t1\t-360\t360;\n% \t5\t6\t0.039\t0.17\t0.358\t150\t150\t150\t0\t0\t1\t-360\t360;\n% \t3\t6\t0\t0.0586\t0\t300\t300\t300\t0\t0\t1\t-360\t360;\n% \t6\t7\t0.0119\t0.1008\t0.209\t150\t150\t150\t0\t0\t1\t-360\t360;\n% \t7\t8\t0.0085\t0.072\t0.149\t250\t250\t250\t0\t0\t1\t-360\t360;\n% \t8\t2\t0\t0.0625\t0\t250\t250\t250\t0\t0\t1\t-360\t360;\n% \t8\t9\t0.032\t0.161\t0.306\t250\t250\t250\t0\t0\t1\t-360\t360;\n% \t9\t4\t0.01\t0.085\t0.176\t250\t250\t250\t0\t0\t1\t-360\t360;\n];\n\n%%----- OPF Data -----%%\n%% generator cost data\n%\t1\tstartup\tshutdown\tn\tx1\ty1\t...\txn\tyn\n%\t2\tstartup\tshutdown\tn\tc(n-1)\t...\tc0\nmpc.gencost = [\n\t2\t1500\t0\t3\t0.11\t5\t150;\n\t2\t1500\t0\t3\t0.11\t5\t150;\n% \t2\t2000\t0\t3\t0.085\t1.2\t600;\n% \t2\t3000\t0\t3\t0.1225\t1\t335;\n];\n\n\n%%----- 3 Phase Model Data -----%%\n%% system data\nmpc.freq = 60; %% frequency, Hz\nmpc.basekVA = 1000; %% system kVA base\n\n%% bus data\n%\tbusid\ttype\tbasekV\tVm1\tVm2\tVm3\tVa1\tVa2\tVa3\nmpc.bus3p = [\n\t1\t1\t12.47\t1\t1\t1\t0\t-120\t120;\n\t2\t1\t12.47\t1\t1\t1\t0\t-120\t120;\n\t3\t1\t4.16\t1\t1\t1\t0\t-120\t120;\n\t4\t1\t4.16\t1\t1\t1\t0\t-120\t120;\n];\n\n%% buslink data\n%\tlinkid\tbusid\tbus3pid\tstatus\nmpc.buslink = [\n\t1\t4\t1\t1;\n];\n\n%% branch data\n%\tbrid\tfbus\ttbus\tstatus\tlcid\tlen\nmpc.line3p = [\n\t1\t1\t2\t1\t1\t2000/5280;\n\t2\t3\t4\t1\t1\t2500/5280;\n];\n\n%% transformer\n%\txfid\tfbus\ttbus\tstatus\tR\tX\tbasekVA\tbasekV\nmpc.xfmr3p = [\n\t1\t2\t3\t1\t0.01\t0.06\t6000\t12.47;\n];\n\n%% load\n%\tldid\tldbus\tstatus\tPd1\tPd2\tPd3\tldpf1\tldpf2\tldpf3\nmpc.load3p = [\n\t1\t4\t1\t1275\t1800\t2375\t0.85\t0.9\t0.95;\n];\n\n%% gen\n%\tgenid\tgbus\tstatus\tVg1\tVg2\tVg3\tPg1\tPg2\tPg3\tQg1\tQg2\tQg3\nmpc.gen3p = [\n% \t1\t1\t1\t1\t1\t1\t2000\t2000\t2000\t0\t0\t0;\n];\n\n%% line construction\n%\tlcid\tR11\tR21\tR31\tR22\tR32\tR33\tX11\tX21\tX31\tX22\tX32\tX33\tC11\tC21\tC31\tC22\tC32\tC33\nmpc.lc = [\n\t1\t0.457541\t0.15594 \t0.153474\t0.466617\t0.157996\t0.461462\t1.078\t0.501648\t0.384909\t1.04813\t0.423624\t1.06502\t15.0671\t-4.86241\t-1.85323\t15.875\t-3.09098\t14.3254\n];\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/t/t_case3p_c.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.46855440693457556}}
{"text": "function [fileNameOut, extension] = lrsWriteRay(Q,modelName,vertexBool,param)\n% Outputs a file for lrs to convert an V-representation (vertex / ray) of a\n% polyhedron to a H-representation (half-space) via facet enumeration\n%\n% V-representation:\n% m is the number of input rows, each being a vertex, ray or line.\n% n is the number of input columns and d=n-1 is dimension of the input.\n% Each vertex is given in the form:\n% \n% 1 v_1 v_1 ... v_d\n% \n% Each ray is given in the form:\n% \n% 0 r_1 r_2... r_d\n% \n% where r_1 ... r_d is a point on the ray.\n% \n% There must be at least one vertex in each file. \n% For bounded polyhedra there will be no rays entered. \n% The coefficients can be entered as integers or rationals in the format x/y. \n% An input line can be specified as a ray and then included in the linearity option (see below).\n%\n% INPUT\n% Q m x n integer matrix where each row is a variable and each column is a vertex or ray\n% modelName string giving the prefix of the *.ext file that will contain the vertex representation\n% It is assumed the file is pwd/*.ine, otherwise provide the full path.\n%\n% OPTIONAL INPUT\n% vertexBool n x 1 Boolean vector indicating which columns of Q are vertices\n% By default, all columns of Q are assumed to be rays.\n%\n% param: parameter structure with the following fields:\n% *.positivity: if equals to 1, then positive orthant base\n% *.inequality: if equals to 1, then represent as two inequalities rather than a single equality\n% *.shellScript: if equals to 1, then lrs is run through a bash script\n% *.redund if equals to 0, then remove redundant linear equalities \n\n% Ronan Fleming 2021\n\n[nMonomial,nRay]=size(Q);\nif ~exist('vertexBool','var')\n fprintf('%s\\n',['Assuming ' int2str(nRay) ' rays']);\n vertexBool = zeros(nRay,1);\nend\n\nif ~exist('param','var')\n param = struct();\nend\nif ~isfield(param,'positivity')\n param.positivity = 0;\nend\nif ~isfield(param,'inequality')\n param.inequality = 0;\nend\nif ~isfield(param,'shellScript')\n param.shellScript = 0;\nend\nif ~isfield(param,'facetEnumeration')\n %assume vertex enumeration, unless specified that it is facet enumeration\n param.facetEnumeration = 1;\nend\nif ~isfield(param,'redund')\n param.redund = 1;\nend\n\nif param.redund ==0\n %remove all redundant halfspaces\n redundCmd = 'redund 0 0'; \nend\n\n%lrs wants each row to be a ray so transpose\nQ=Q';\n\nextension = '.ext';\nfileNameOut=[modelName extension];\nfid=fopen(fileNameOut,'w');\nfprintf(fid,'%s\\n%s\\n',modelName,'V-representation');\n\nif any(~vertexBool)\n ind = find(vertexBool);\n if ~isempty(ind)\n fprintf(fid,'%s%s','linearity ',int2str(nnz(vertexBool)));\n for j = 1:length(ind)\n fprintf(fid,'%s%s',' ',int2str(ind(j)));\n end\n fprintf(fid,'\\n');\n end\nend\n\nfprintf(fid,'%s\\n','begin');\n\nif ~any(vertexBool)\n fprintf(fid,'%s\\n',[int2str(nRay+1) ' ' int2str(nMonomial+1) ' integer']);\n %there must be at least one vertex\n for r=1:nRay+1\n if r==1\n for d=1:nMonomial+1\n if d==1\n fprintf(fid,'%s',[int2str(1)]);\n else\n fprintf(fid,'%s',[' ' int2str(0)]);\n end\n end\n else\n for d=1:nMonomial+1\n if d==1\n fprintf(fid,'%s',[int2str(0)]);\n else\n fprintf(fid,'%s',[' ' int2str(Q(r-1,d-1))]);\n end\n end\n end\n fprintf(fid,'\\n');\n end\nelse\n fprintf(fid,'%s\\n',[int2str(nRay) ' ' int2str(nMonomial+1) ' integer']);\n for r=1:nRay\n for d=1:nMonomial+1\n if d==1\n fprintf(fid,'%s',[int2str(vertexBool(r)+0)]);\n else\n fprintf(fid,'%s',[' ' int2str(Q(r,d-1))]);\n end\n end\n fprintf(fid,'\\n');\n end\nend\n\n%set of vertices specifying positive orthant\nif param.positivity\n for i=1:nMonomial\n fprintf(fid,'%s',int2str(1));\n for j=1:nMonomial\n if i==j\n fprintf(fid,'%s',[' ' int2str(1)]);\n else\n fprintf(fid,'%s',[' ' int2str(0)]);\n end\n end\n fprintf(fid,'\\n');\n end\nend\n\nfprintf(fid,'%s\\n','end');\nif param.redund==0\n %remove redundant halfspaces\n fprintf(fid,'%s\\n',redundCmd);\nend\nfclose(fid);\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/topology/extremeRays/lrs/lrsInterface/lrsWriteRay.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.6548947357776796, "lm_q1q2_score": 0.4685274007404433}}
{"text": "function [x,zo]=overlapadd(f,win,inc)\n%OVERLAPADD join overlapping frames together X=(F,WIN,INC)\n%\n% Usage for frequency-domain processing:\n% S=...; % input signal\n% OV=2; % overlap factor of 2 (4 is also often used)\n% INC=20; % set frame increment in samples\n% NW=INC*OV; % DFT window length\n% W=sqrt(hamming(NW,'periodic')); % omit sqrt if OV=4\n% W=W/sqrt(sum(W(1:INC:NW).^2)); % normalize window\n% F=rfft(enframe(S,W,INC),NW,2); % do STFT: one row per time frame, +ve frequencies only\n% ... process frames ...\n% X=overlapadd(irfft(F,NW,2),W,INC); % reconstitute the time waveform (omit \"X=\" to plot waveform)\n%\n% Inputs: F(NR,NW) contains the frames to be added together, one\n% frame per row.\n% WIN(NW) contains a window function to multiply each frame.\n% WIN may be omitted to use a default rectangular window\n% If processing the input in chunks, WIN should be replaced by\n% ZI on the second and subsequent calls where ZI is the saved\n% output state from the previous call.\n% INC gives the time increment (in samples) between\n% succesive frames [default = NW].\n%\n% Outputs: X(N,1) is the output signal. The number of output samples is N=NW+(NR-1)*INC. \n% ZO Contains the saved state to allow a long signal\n% to be processed in chunks. In this case X will contain only N=NR*INC\n% output samples. \n%\n\n%\t Copyright (C) Mike Brookes 2009\n% Version: $Id: overlapadd.m 2470 2012-11-02 15:27:24Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n[nr,nf]=size(f); % number of frames and frame length\nif nargin<2\n win=nf; % default increment\nend\nif isstruct(win)\n w=win.w;\n if ~numel(w) && length(w)~=nf\n error('window length does not match frames size');\n end\n inc=win.inc;\n xx=win.xx;\nelse\n if nargin<3\n inc=nf;\n end\n if numel(win)==1 && win==fix(win) && nargin<3 % win has been omitted\n inc=win;\n w=[];\n else\n w=win(:).';\n if length(w)~=nf\n error('window length does not match frames size');\n end\n if all(w==1)\n w=[];\n end\n end\n xx=[]; % partial output from previous call is null\nend\nnb=ceil(nf/inc); % number of overlap buffers\nno=nf+(nr-1)*inc; % buffer length\nz=zeros(no,nb); % space for overlapped output speech\nif numel(w)\n z(repmat(1:nf,nr,1)+repmat((0:nr-1)'*inc+rem((0:nr-1)',nb)*no,1,nf))=f.*repmat(w,nr,1);\nelse\n z(repmat(1:nf,nr,1)+repmat((0:nr-1)'*inc+rem((0:nr-1)',nb)*no,1,nf))=f;\nend\nx=sum(z,2);\nif ~isempty(xx)\n x(1:length(xx))=x(1:length(xx))+xx; % add on leftovers from previous call\nend\nif nargout>1 % check if we want to preserve the state\n mo=inc*nr; % completed output samples\n if nor',nf+(0:nr-1)*inc,x(nf+(0:nr-1)*inc),'3\n [lpyt,Eyt,Varyt] = gp.lik.fh.predy(gp.lik, Eft, Varft, y, z);\n end\n \n case 'cavity'\n % using EP equations\n\n % latent posterior\n [f, sigm2ii] = gpla_pred(gp, x, y, 'z', z, 'tstind', [], 'fcorr', fcorr);\n % remove the jitter variance (see sigm2_t below)\n sigm2ii = sigm2ii-gp.jitterSigma2;\n \n % \"site parameters\"\n W = -gp.lik.fh.llg2(gp.lik, y, f, 'latent', z);\n deriv = gp.lik.fh.llg(gp.lik, y, f, 'latent', z);\n % add the jitter variance (see sigm2ii above)\n sigm2_t = 1./W+gp.jitterSigma2;\n mu_t = f + sigm2_t.*deriv;\n \n % \"cavity parameters\"\n sigma2_i = 1./(1./sigm2ii-1./sigm2_t);\n myy_i = sigma2_i.*(f./sigm2ii-mu_t./sigm2_t);\n % check if cavity varianes are negative\n ii=find(sigma2_i<0);\n if ~isempty(ii)\n warning('gpla_loopred: some cavity variances are negative');\n sigma2_i(ii) = sigm2ii(ii);\n myy_i(ii) = f(ii);\n end\n \n % leave-one-out predictions\n Eft=myy_i;\n Varft=sigma2_i;\n\n if nargout==3\n lpyt = gp.lik.fh.predy(gp.lik, Eft, Varft, y, z);\n elseif nargout>3\n [lpyt,Eyt,Varyt] = gp.lik.fh.predy(gp.lik, Eft, Varft, y, z);\n end\n \n case 'inla'\n % Leonhard Held and Birgit Schrļæ½dle and Hļæ½vard Rue (2010)\n % Posterior and Cross-validatory Predictive Checks: A\n % Comparison of MCMC and INLA. In (eds) Thomas Kneib and\n % Gerhard Tutz, Statistical Modelling and Regression\n % Structures, pp. 91-110. Springer.\n \n % latent posterior\n [f, sigm2ii, lp] = gpla_pred(gp, x, y, 'z', z, 'tstind', [], 'fcorr', fcorr);\n \n Eft = zeros(tn,1);\n Varft = zeros(tn,1);\n lpyt = zeros(tn,1);\n minf = f-6.*sqrt(sigm2ii);\n maxf = f+6.*sqrt(sigm2ii);\n for i=1:tn\n if isempty(z)\n z1 = [];\n else\n z1 = z(i);\n end\n [m0, m1, m2] = quad_moments(@(x) norm_pdf(x, f(i), sqrt(sigm2ii(i)))./llvec(gp.lik,y(i),x,z1), minf(i), maxf(i));\n Eft(i) = m1;\n Varft(i) = m2-Eft(i)^2;\n lpyt(i) = -log(m0);\n end\n\n if nargout>3\n [tmp,Eyt,Varyt] = gp.lik.fh.predy(gp.lik, Eft, Varft, y, z);\n end\n if sum((abs(lpyt)./abs(lp) > 5) == 1) > 0.1*tn;\n warning('Very bad predictive densities, gpla_loopred might not be reliable, check results!');\n end\n \n end\n\nend\n\nfunction expll = llvec(gplik, y, f, z)\n for i=1:size(f,2)\n expll(i) = exp(gplik.fh.ll(gplik, y, f(i), z));\n end\nend\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/gp/gpla_loopred.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4681426590381211}}
{"text": "function [x,f,funEvals] = minConF_BC(funObj,x,LB,UB,options)\n% function [x,f] = minConF_BC(funObj,x,LB,UB,options)\n%\n% Function for using Two-Metric Projection to solve problems of the form:\n% min funObj(x)\n% s.t. LB_i <= x_i <= UB_i\n%\n% @funObj(x): function to minimize (returns gradient as second argument)\n%\n% options:\n% verbose: level of verbosity (0: no output, 1: final, 2: iter (default), 3:\n% debug)\n% optTol: tolerance used to check for progress (default: 1e-7)\n% maxIter: maximum number of calls to funObj (default: 250)\n% numDiff: compute derivatives numerically (0: use user-supplied\n% derivatives (default), 1: use finite differences, 2: use complex\n% differentials)\n% method: 'sd', 'lbfgs', 'newton'\n\nnVars = length(x);\n\n% Set Parameters\nif nargin < 5\n options = [];\nend\n[verbose,numDiff,optTol,maxIter,suffDec,interp,method,corrections,damped] = ...\n myProcessOptions(...\n options,'verbose',3,'numDiff',0,'optTol',1e-6,'maxIter',500,'suffDec',1e-4,...\n 'interp',1,'method','lbfgs','corrections',100,'damped',0);\n\n% Output Log\nif verbose >= 2\n fprintf('%10s %10s %15s %15s %15s\\n','Iteration','FunEvals','Step Length','Function Val','Opt Cond');\nend\n\n% Make objective function (if using numerical derivatives)\nfunEvalMultiplier = 1;\nif numDiff\n if numDiff == 2\n useComplex = 1;\n else\n useComplex = 0;\n end\n funObj = @(x)autoGrad(x,useComplex,funObj);\n funEvalMultiplier = nVars+1-useComplex;\nend\n\n% Evaluate Initial Point\nx = projectBounds(x,LB,UB);\nif strcmp(method,'newton')\n [f,g,H] = funObj(x);\n secondOrder = 1;\nelse\n [f,g] = funObj(x);\n secondOrder = 0;\nend\nfunEvals = 1;\nif verbose >= 1\n fprintf('Initial function value: %15.5e\\n', f);\nend\n\n% Compute Working Set\nworking = ones(nVars,1);\nworking((x < LB+optTol*2) & g >= 0) = 0;\nworking((x > UB-optTol*2) & g <= 0) = 0;\nworking = find(working);\n\n% Check Optimality\nif isempty(working)\n if verbose >= 1\n fprintf('All variables are at their bound and no further progress is possible at initial point\\n');\n end\n return;\nelseif norm(g(working)) <= optTol\n if verbose >=1\n fprintf('All working variables satisfy optimality condition at initial point\\n');\n end\n return;\nend\n\nif verbose >= 3\n switch method\n case 'sd'\n fprintf('Steepest Descent\\n');\n case 'lbfgs'\n fprintf('L-BFGS\\n');\n case 'bfgs'\n fprintf('BFGS\\n');\n case 'newton'\n fprintf('Newton\\n');\n end\nend\n\ni = 1;\nwhile funEvals <= maxIter\n\n % Compute Step Direction\n d = zeros(nVars,1);\n switch(method)\n case 'sd'\n d(working) = -g(working);\n case 'lbfgs'\n if i == 1\n d(working) = -g(working);\n old_dirs = zeros(nVars,0);\n old_stps = zeros(nVars,0);\n Hdiag = 1;\n else\n if damped\n [old_dirs,old_stps,Hdiag] = dampedUpdate(g-g_old,x-x_old,corrections,verbose==3,old_dirs,old_stps,Hdiag);\n else\n [old_dirs,old_stps,Hdiag] = lbfgsUpdate(g-g_old,x-x_old,corrections,verbose==3,old_dirs,old_stps,Hdiag);\n end\n curvSat = sum(old_dirs(working,:).*old_stps(working,:)) > 1e-10;\n d(working) = lbfgsC(-g(working),old_dirs(working,curvSat),old_stps(working,curvSat),Hdiag);\n end\n g_old = g;\n x_old = x;\n case 'bfgs'\n if i == 1\n d(working) = -g(working);\n B = eye(nVars);\n else\n y = g-g_old;\n s = x-x_old;\n\n ys = y'*s;\n\n if i == 2\n if ys > 1e-10\n B = ((y'*y)/(y'*s))*eye(nVars);\n end\n end\n if ys > 1e-10\n B = B + (y*y')/(y'*s) - (B*s*s'*B)/(s'*B*s);\n else\n if verbose == 2\n fprintf('Skipping Update\\n');\n end\n end\n d(working) = -B(working,working)\\g(working);\n end\n g_old = g;\n x_old = x;\n\n case 'newton'\n [R,posDef] = chol(H(working,working));\n \n if posDef == 0\n d(working) = -R\\(R'\\g(working));\n else\n if verbose == 3\n fprintf('Adjusting Hessian\\n');\n end\n H(working,working) = H(working,working) + eye(length(working)) * max(0,1e-12 - min(real(eig(H(working,working)))));\n d(working) = -H(working,working)\\g(working);\n end\n otherwise\n fprintf('Unrecognized Method: %s\\n',method);\n break;\n end\n\n % Check that Progress can be made along the direction\n f_old = f;\n gtd = g'*d;\n if gtd > -optTol\n if verbose >= 2\n fprintf('Directional Derivative below optTol\\n');\n end\n break;\n end\n\n % Select Initial Guess to step length\n if i == 1 && ~secondOrder\n t = min(1,1/sum(abs(g(working))));\n else\n t = 1;\n end\n\n % Evaluate the Objective and Projected Gradient at the Initial Step\n x_new = projectBounds(x+t*d,LB,UB);\n if secondOrder\n [f_new,g_new,H] = funObj(x_new);\n else\n [f_new,g_new] = funObj(x_new);\n end\n funEvals = funEvals+1;\n\n % Backtracking Line Search\n lineSearchIters = 1;\n while f_new > f + suffDec*g'*(x_new-x) || ~isLegal(f_new)\n temp = t;\n if interp == 0 || ~isLegal(f_new) || ~isLegal(g_new)\n if verbose == 3\n fprintf('Halving Step Size\\n');\n end\n t = .5*t;\n else\n if verbose == 3\n fprintf('Cubic Backtracking\\n');\n end\n t = polyinterp([0 f gtd; t f_new g_new'*d]);\n end\n\n % Adjust if change is too small\n if t < temp*1e-3\n if verbose == 3\n fprintf('Interpolated value too small, Adjusting\\n');\n end\n t = temp*1e-3;\n elseif t > temp*0.6\n if verbose == 3\n fprintf('Interpolated value too large, Adjusting\\n');\n end\n t = temp*0.6;\n end\n\n % Check whether step has become too small\n if sum(abs(t*d)) < optTol\n if verbose == 3\n fprintf('Line Search failed\\n');\n end\n t = 0;\n f_new = f;\n g_new = g;\n break;\n end\n\n % Evaluate New Point\n x_new = projectBounds(x+t*d,LB,UB);\n [f_new,g_new] = funObj(x_new);\n funEvals = funEvals+1;\n lineSearchIters = lineSearchIters+1;\n\n end\n\n % Take Step\n x = x_new;\n f = f_new;\n g = g_new;\n\n % Compute Working Set\n working = ones(nVars,1);\n working((x < LB+optTol*2) & g >= 0) = 0;\n working((x > UB-optTol*2) & g <= 0) = 0;\n working = find(working);\n\n % Output Log\n if verbose >= 2\n fprintf('%10d %10d %15.5e %15.5e %15.5e %15.5e\\n',i,funEvals*funEvalMultiplier,t,f,sum(abs(g(working))),norm(g(working)));\n end\n\n % Check Optimality\n if isempty(working)\n if verbose >= 1\n fprintf('All variables are at their bound and no further progress is possible\\n');\n end\n break;\n elseif norm(g(working)) <= optTol\n if verbose >=1\n fprintf('All working variables satisfy optimality condition\\n');\n end\n break;\n end\n\n % Check for lack of progress\n if sum(abs(t*d)) < optTol\n if verbose >= 1\n fprintf('Step size below optTol\\n');\n end\n break;\n end\n\n if abs(f-f_old) < optTol\n if verbose >= 1\n fprintf('Function value changing by less than optTol\\n');\n end\n break;\n end\n\n if funEvals*funEvalMultiplier > maxIter\n if verbose >= 1\n fprintf('Function Evaluations exceeds maxIter\\n');\n end\n break;\n end\n\n % If necessary, compute Hessian\n if secondOrder && lineSearchIters > 1\n [f_new,g_new,H] = funObj(x);\n end\n\n i = i + 1;\nend\nend\n\nfunction [x] = projectBounds(x,LB,UB)\nx(x < LB) = LB(x < LB);\nx(x > UB) = UB(x > UB);\nend\n", "meta": {"author": "rbgirshick", "repo": "voc-dpm", "sha": "c0b88564bd668bcc6216bbffe96cb061613be768", "save_path": "github-repos/MATLAB/rbgirshick-voc-dpm", "path": "github-repos/MATLAB/rbgirshick-voc-dpm/voc-dpm-c0b88564bd668bcc6216bbffe96cb061613be768/external/minConf/minConf/minConf_TMP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.46809724371790873}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%% %%%%%\n%%%% IEEE PES Power Grid Library - Optimal Power Flow - v21.07 %%%%%\n%%%% (https://github.com/power-grid-lib/pglib-opf) %%%%%\n%%%% Benchmark Group - Small Angle Difference %%%%%\n%%%% 29 - July - 2021 %%%%%\n%%%% %%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction mpc = pglib_opf_case5_pjm__sad\nmpc.version = '2';\nmpc.baseMVA = 100.0;\n\n%% area data\n%\tarea\trefbus\nmpc.areas = [\n\t1\t 4;\n];\n\n%% bus data\n%\tbus_i\ttype\tPd\tQd\tGs\tBs\tarea\tVm\tVa\tbaseKV\tzone\tVmax\tVmin\nmpc.bus = [\n\t1\t 2\t 0.0\t 0.0\t 0.0\t 0.0\t 1\t 1.00000\t 0.00000\t 230.0\t 1\t 1.10000\t 0.90000;\n\t2\t 1\t 300.0\t 98.61\t 0.0\t 0.0\t 1\t 1.00000\t 0.00000\t 230.0\t 1\t 1.10000\t 0.90000;\n\t3\t 2\t 300.0\t 98.61\t 0.0\t 0.0\t 1\t 1.00000\t 0.00000\t 230.0\t 1\t 1.10000\t 0.90000;\n\t4\t 3\t 400.0\t 131.47\t 0.0\t 0.0\t 1\t 1.00000\t 0.00000\t 230.0\t 1\t 1.10000\t 0.90000;\n\t5\t 2\t 0.0\t 0.0\t 0.0\t 0.0\t 1\t 1.00000\t 0.00000\t 230.0\t 1\t 1.10000\t 0.90000;\n];\n\n%% generator data\n%\tbus\tPg\tQg\tQmax\tQmin\tVg\tmBase\tstatus\tPmax\tPmin\nmpc.gen = [\n\t1\t 20.0\t 0.0\t 30.0\t -30.0\t 1.0\t 100.0\t 1\t 40.0\t 0.0;\n\t1\t 85.0\t 0.0\t 127.5\t -127.5\t 1.0\t 100.0\t 1\t 170.0\t 0.0;\n\t3\t 260.0\t 0.0\t 390.0\t -390.0\t 1.0\t 100.0\t 1\t 520.0\t 0.0;\n\t4\t 100.0\t 0.0\t 150.0\t -150.0\t 1.0\t 100.0\t 1\t 200.0\t 0.0;\n\t5\t 300.0\t 0.0\t 450.0\t -450.0\t 1.0\t 100.0\t 1\t 600.0\t 0.0;\n];\n\n%% generator cost data\n%\t2\tstartup\tshutdown\tn\tc(n-1)\t...\tc0\nmpc.gencost = [\n\t2\t 0.0\t 0.0\t 3\t 0.000000\t 14.000000\t 0.000000;\n\t2\t 0.0\t 0.0\t 3\t 0.000000\t 15.000000\t 0.000000;\n\t2\t 0.0\t 0.0\t 3\t 0.000000\t 30.000000\t 0.000000;\n\t2\t 0.0\t 0.0\t 3\t 0.000000\t 40.000000\t 0.000000;\n\t2\t 0.0\t 0.0\t 3\t 0.000000\t 10.000000\t 0.000000;\n];\n\n%% branch data\n%\tfbus\ttbus\tr\tx\tb\trateA\trateB\trateC\tratio\tangle\tstatus\tangmin\tangmax\nmpc.branch = [\n\t1\t 2\t 0.00281\t 0.0281\t 0.00712\t 400.0\t 400.0\t 400.0\t 0.0\t 0.0\t 1\t -1.33164584752\t 1.33164584752;\n\t1\t 4\t 0.00304\t 0.0304\t 0.00658\t 426.0\t 426.0\t 426.0\t 0.0\t 0.0\t 1\t -1.33164584752\t 1.33164584752;\n\t1\t 5\t 0.00064\t 0.0064\t 0.03126\t 426.0\t 426.0\t 426.0\t 0.0\t 0.0\t 1\t -1.33164584752\t 1.33164584752;\n\t2\t 3\t 0.00108\t 0.0108\t 0.01852\t 426.0\t 426.0\t 426.0\t 0.0\t 0.0\t 1\t -1.33164584752\t 1.33164584752;\n\t3\t 4\t 0.00297\t 0.0297\t 0.00674\t 426.0\t 426.0\t 426.0\t 0.0\t 0.0\t 1\t -1.33164584752\t 1.33164584752;\n\t4\t 5\t 0.00297\t 0.0297\t 0.00674\t 240.0\t 240.0\t 240.0\t 0.0\t 0.0\t 1\t -1.33164584752\t 1.33164584752;\n];\n\n% INFO : === Translation Options ===\n% INFO : Phase Angle Bound: 1.33164584752 (deg.)\n% INFO : \n% INFO : === Generator Bounds Update Notes ===\n% INFO : \n% INFO : === Base KV Replacement Notes ===\n% INFO : \n% INFO : === Transformer Setting Replacement Notes ===\n% INFO : \n% INFO : === Line Capacity Monotonicity Notes ===\n% INFO : \n% INFO : === Writing Matpower Case File Notes ===\n", "meta": {"author": "power-grid-lib", "repo": "pglib-opf", "sha": "01681386d084d8bd03b429abcd1ee6966f68b9a3", "save_path": "github-repos/MATLAB/power-grid-lib-pglib-opf", "path": "github-repos/MATLAB/power-grid-lib-pglib-opf/pglib-opf-01681386d084d8bd03b429abcd1ee6966f68b9a3/sad/pglib_opf_case5_pjm__sad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4680972367988685}}
{"text": "function [M,Minit,output] = cp_apr(X, R, varargin)\n%CP_APR Compute nonnegative CP with alternating Poisson regression.\n%\n% M = CP_APR(X, R) computes an estimate of the best rank-R\n% CP model of a tensor X using an alternating Poisson regression.\n% The input X can be a tensor, sptensor, ktensor, or ttensor. The\n% result P is a ktensor.\n%\n% M = CP_APR(X, R, 'param', value, ...) specifies optional parameters and\n% values. Valid parameters and their default values are:\n% 'tol' - Tolerance on the inner KKT violation {1.0e-4}\n% 'maxiters' - Maximum number of iterations {1000}\n% 'maxinneriters' = Maximum number of inner iterations {10}\n% 'init' - Initial guess [{'random'}|ktensor]\n% 'epsilon' - parameter to avoid divide by zero {100*eps}\n% 'kappatol' - tolerance on complementary slackness {100*eps}\n% 'kappa' - offset to fix complementary slackness {10*eps}\n% 'printitn' - Print every n outer iterations; 0 for no printing {1}\n% 'printinneritn' - Print every n inner iterations {0}\n%\n% [M,M0] = CP_APR(...) also returns the initial guess.\n%\n% [M,M0,out] = CP_APR(...) also returns additional output.\n% out.kktViolations - maximum kkt violation per iteration\n% out.nInnerIters - number of inner iterations per iteration\n% out.nViolations - number of factor matrices needing complementary\n% slackness adjustment per iteration\n% out.nTotalIters - total number of inner iterations\n%\n% REFERENCE: E. C. Chi and T. G. Kolda. On Tensors, Sparsity, and\n% Nonnegative Factorizations, arXiv:1112.2414 [math.NA], December 2011,\n% URL: http://arxiv.org/abs/1112.2414. Submitted for publication.\n%\n% See also CP_ALS, KTENSOR, TENSOR, SPTENSOR.\n%\n%MATLAB Tensor Toolbox.\n%Copyright 2012, Sandia Corporation.\n\n% This is the MATLAB Tensor Toolbox by T. Kolda, B. Bader, and others.\n% http://www.sandia.gov/~tgkolda/TensorToolbox.\n% Copyright (2012) Sandia Corporation. Under the terms of Contract\n% DE-AC04-94AL85000, there is a non-exclusive license for use of this\n% work by or on behalf of the U.S. Government. Export of this data may\n% require a license from the United States Government.\n% The full license terms can be found in the file LICENSE.txt\n\n%% Extract dimensions of X and number of dimensions of X.\nN = ndims(X);\n\n%% Set algorithm parameters from input or by using defaults.\nparams = inputParser;\nparams.addParamValue('epsilon',1e-10,@isscalar);\nparams.addParamValue('tol',1e-4,@isscalar);\nparams.addParamValue('maxiters',1000,@(x) isscalar(x) & x > 0);\nparams.addParamValue('init','random',@(x) (isa(x,'ktensor') || ismember(x,{'random'})));\nparams.addParamValue('printitn',1,@isscalar);\nparams.addParamValue('kappa',1e-2,@isscalar);\nparams.addParamValue('kappatol',1e-10,@isscalar);\nparams.addParamValue('maxinneriters',10,@isscalar);\nparams.addParamValue('printinneritn',0,@isscalar);\nparams.parse(varargin{:});\n\n\n%% Copy from params object.\nepsilon = params.Results.epsilon;\ntol = params.Results.tol;\nmaxOuterIters = params.Results.maxiters;\nMinit = params.Results.init;\nkappa = params.Results.kappa;\nkappaTol = params.Results.kappatol;\nmaxInnerIters = params.Results.maxinneriters;\nprintOuterItn = params.Results.printitn;\nprintInnerItn = params.Results.printinneritn;\nkktViolations = -ones(maxOuterIters,1);\nnInnerIters = zeros(maxOuterIters,1);\n\n%% Set up and error checking on initial guess for U.\nif isa(Minit,'ktensor')\n if ndims(Minit) ~= N\n error('Initial guess does not have the right number of dimensions');\n end\n \n if ncomponents(Minit) ~= R\n error('Initial guess does not have the right number of components');\n end\n \n for n = 1:N\n if size(Minit,n) ~= size(X,n)\n error('Dimension %d of the initial guess is the wrong size',n);\n end\n end\nelseif strcmp(Minit,'random')\n F = cell(N,1);\n for n = 1:N\n F{n} = rand(size(X,n),R);\n end\n Minit = ktensor(F);\nelse\n error('The selected initialization method is not supported');\nend\n\n\n%% Set up for iterations - initializing M and Phi.\nM = normalize(Minit,[],1);\nPhi = cell(N,1);\nkktModeViolations = zeros(N,1);\n\nif printOuterItn > 0\n fprintf('\\nCP_APR:\\n');\nend\n\nnViolations = zeros(maxOuterIters,1);\n\n%% Main Loop: Iterate until convergence.\nfor iter = 1:maxOuterIters\n \n isConverged = true; \n for n = 1:N\n\n % Make adjustments to entries of M{n} that are violating\n % complementary slackness conditions.\n if (iter > 1)\n V = (Phi{n} > 1) & (M{n} < kappaTol);\n if any(V(:)) \n nViolations(iter) = nViolations(iter) + 1;\n M{n}(V>0) = M{n}(V>0) + kappa;\n end\n end \n\n % Shift the weight from lambda to mode n\n M = redistribute(M,n);\n \n % Calculate product of all matrices but the n-th\n % (In sparse case, only calcuates entries corresponding to nonzeros in X.)\n Pi = calculatePi(X, M, R, n, N); \n \n % Do the multiplicative updates\n for i = 1:maxInnerIters\n\n % Count the inner iterations\n nInnerIters(iter) = nInnerIters(iter) + 1;\n \n % Calculate matrix for multiplicative update\n Phi{n} = calculatePhi(X, M, R, n, Pi, epsilon);\n \n % Check for convergence\n kktModeViolations(n) = max(abs(vec(min(M.U{n},1-Phi{n}))));\n if (kktModeViolations(n) < tol)\n break;\n else\n isConverged = false;\n end \n \n % Do the multiplicative update\n M{n} = M{n} .* Phi{n};\n \n % Print status\n if mod(i, printInnerItn)==0\n fprintf(' Mode = %1d, Inner Iter = %2d, KKT violation = %.6e\\n', n, i, kktModeViolations(n));\n end\n end\n \n % Shift weight from mode n back to lambda\n M = normalize(M,[],1,n);\n \n end\n\n kktViolations(iter) = max(kktModeViolations); \n\n if (mod(iter,printOuterItn)==0)\n fprintf(' Iter %4d: Inner Its = %2d KKT violation = %.6e, nViolations = %2d\\n', ...\n iter, nInnerIters(iter), kktViolations(iter), nViolations(iter)); \n end\n \n % Check for convergence\n if (isConverged)\n break;\n end \nend\n\n%% Clean up final result\nM = normalize(M,'sort',1);\n\nif printOuterItn>0\n normX = norm(X); \n normresidual = sqrt( normX^2 + norm(M)^2 - 2 * innerprod(X,M) );\n fit = 1 - (normresidual / normX); %fraction explained by model\n fprintf('===========================================\\n');\n fprintf(' Final log-likelihood = %e \\n', tt_loglikelihood(X,M));\n fprintf(' Final least squares fit = %e \\n', fit);\n fprintf(' Final KKT violation = %7.7e\\n', kktViolations(iter));\n fprintf(' Total inner iterations = %d\\n', sum(nInnerIters));\nend\n\noutput = struct;\noutput.params = params.Results;\noutput.kktViolations = kktViolations(1:iter);\noutput.nInnerIters = nInnerIters(1:iter);\noutput.nViolations = nViolations(1:iter);\noutput.nTotalIters = sum(nInnerIters);\n\n\nend\n\nfunction Pi = calculatePi(X, M, R, n, N)\n\nif (isa(X,'sptensor'))\n Pi = ones(nnz(X), R);\n for nn = [1:n-1,n+1:N]\n Pi = M{nn}(X.subs(:,nn),:).*Pi;\n end\nelse\n U = M.U;\n Pi = khatrirao(U{[1:n-1,n+1:N]},'r');\nend\n\nend\n\nfunction Phi = calculatePhi(X, M, R, n, Pi, epsilon)\n\nif (isa(X,'sptensor'))\n Phi = -ones(size(X,n),R);\n xsubs = X.subs(:,n);\n v = sum(M.U{n}(xsubs,:).*Pi,2);\n wvals = X.vals ./ max(v, epsilon);\n for r = 1:R\n Yr = accumarray(xsubs, wvals .* Pi(:,r), [size(X,n) 1]);\n Phi(:,r) = Yr;\n end \nelse\n Xn = double(tenmat(X,n));\n V = M.U{n}*Pi';\n W = Xn ./ max(V, epsilon);\n Y = W * Pi;\n Phi = Y;\nend\n\nend\n\nfunction y = vec(x)\ny = x(:);\nend\n", "meta": {"author": "andrewssobral", "repo": "mtt", "sha": "0152a77df09f24af4c294f46845931e4e0e63b55", "save_path": "github-repos/MATLAB/andrewssobral-mtt", "path": "github-repos/MATLAB/andrewssobral-mtt/mtt-0152a77df09f24af4c294f46845931e4e0e63b55/libs/tensor_toolbox_2.5/cp_apr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.46805994939737167}}
{"text": "classdef CurveBall < solvers.Solver\n % CurveBall - Newton solver variant\n %\n % This variant works by 2 gradient descent updates: one for the linear\n % system (inversion), and another for the main objective.\n %\n % Assumptions:\n % - Network's output is a single tensor of predictions (not loss).\n % - Forward pass was executed just before calling this solver's step().\n\n properties\n loss = 'logistic' % loss to use: 'ls' (least-squares), 'logistic' (softmax-log)\n\n lambda = 1 % Hessian regularization (0 = pure Newton)\n\n momentum = 0.9 % forget factor for linear system solution\n beta = 0.1 % learning rate for linear system GD step\n\n autoparam = true % adapt momentum and beta\n autoparam_interval = 1 % only run autoparam every N steps. NOTE: autolambda depends on autoparam running in the same step.\n autoparam_print = false % to print momentum/beta for debugging\n\n autolambda = true % adapt lambda\n autolambda_w1 = 0.999 % factor, how much to change lambda each time\n autolambda_interval = 5 % only run autolambda every N steps. NOTE: autolambda depends on autoparam running in the same step.\n autolambda_thresh = 0.5 % rho thresholds to trigger lambda change; [low, high] vector, or scalar T to use [T, 2 - T]\n\n labels % labels for this mini-batch (batch size assumed to be last dim.; cannot run with batch of 1)\n net % pointer to network object\n\n count = 0 % iteration count\n\n state % store for momentum (z)\n\n ratio = 0 % autolambda ratio is stored here for debugging\n last_loss % last computed loss value\n end\n\n methods\n function o = CurveBall(varargin)\n % parse generic Solver arguments\n % default weight decay is 0, but can override with name-value pair\n varargin = o.parseGenericArgs([{'weightDecay', 0}, varargin]);\n\n % parse arguments specific to this solver\n vl_parseprop(o, varargin, {'loss', 'lambda', 'beta', 'momentum', ...\n 'autoparam', 'autoparam_interval', 'autoparam_print', 'autolambda', ...\n 'autolambda_w1', 'autolambda_thresh', 'autolambda_interval'});\n % don't let parent class clear some parameters\n o.conserveMemory = false;\n o.state = {};\n end\n\n function w = gradientStep(o, w, ~, lr, decay)\n % store properties in local vars\n net = o.net; %#ok<*PROPLC>\n lambda = o.lambda;\n\n % initialize state if needed\n z = o.state;\n if isempty(z)\n z = cell(size(w));\n for i = 1:numel(w)\n z{i} = zeros(size(w{i}), 'like', w{i});\n end\n end\n\n use_decay = any(decay);\n assert(~use_decay, 'Not implemented.');\n \n\n %\n % do two GD steps. first update z (linear system state), then use the\n % result (whitened gradient estimate) to update the parameters w.\n %\n % zdelta = J' * Hl * J * z + lambda * z + J' * Jl'\n %\n % znew = momentum * z - beta * zdelta\n %\n % wnew = w + lr * znew\n %\n\n % compute factor Jz = J * z (for Hessian term)\n Jz = fmad(net, z);\n\n % evaluate loss, loss gradient Jl, and loss Hessian (Hl).\n % compute hessian_term = J' * Hl * Jz + Jl\n [Jz_, Jl, o.last_loss] = hessian_grad_loss(net, o.loss, o.labels, Jz);\n\n % backpropagate Jz_ + Jl\n hessian_term = backward(net, Jz_ + Jl);\n\n % compute z update (gradient descent on linear system)\n delta_z = cell(size(w));\n for i = 1:numel(w)\n delta_z{i} = hessian_term{i} + lambda * z{i};\n end\n\n \n %\n % automatic hyperparameters rho (momentum) and beta\n %\n\n if o.autoparam && rem(o.count, o.autoparam_interval) == 0\n % compute factor Jz = J * z (for Hessian term)\n Jdz = fmad(net, delta_z);\n\n % evaluate loss, loss gradient Jl, and loss Hessian (Hl).\n % compute hessian_term = J' * Hl * Jz\n Jdz_ = hessian_grad_loss(net, o.loss, o.labels, Jdz);\n\n % compute momentum and update by solving a 2x2 system A * x = b\n A11 = gather(Jdz(:)' * Jdz_(:));\n A12 = gather(Jz(:)' * Jdz_(:));\n A22 = gather(Jz(:)' * Jz_(:));\n\n b1 = gather(Jl(:)' * Jdz(:));\n b2 = gather(Jl(:)' * Jz(:));\n\n for i = 1:numel(w)\n % compute the system we want to invert\n z_vec = z{i}(:);\n dz_vec = delta_z{i}(:);\n\n % expand scalar if needed\n if isscalar(z_vec), z_vec(1:numel(dz_vec),1) = z_vec; end\n\n A11 = A11 + gather(dz_vec' * dz_vec) * lambda; % accumulating scalars is faster (JIT)\n A12 = A12 + gather(dz_vec' * z_vec) * lambda;\n A22 = A22 + gather(z_vec' * z_vec) * lambda;\n end\n\n % compute beta and momentum coefficient\n A = double([A11, A12; A12, A22]);\n b = double([b1; b2]);\n m_b = A \\ b;\n beta = m_b(1);\n momentum = -m_b(2);\n\n % sanity check\n if ~isfinite(momentum), momentum = 0; end\n if ~isfinite(beta), beta = 0; end\n\n % store values for next iterations if needed\n o.momentum = momentum;\n o.beta = beta;\n else\n momentum = o.momentum;\n beta = o.beta;\n end\n\n if o.autoparam_print\n fprintf('mom: %.1g beta: %.1g ', momentum, beta);\n end\n\n\n % update parameters with computed beta and momentum\n for i = 1:numel(w)\n % update linear system state\n z{i} = vl_taccum(momentum, z{i}, -beta, delta_z{i}) ;\n\n % update parameters (returned as this method's output)\n w{i} = vl_taccum(1, w{i}, lr(i), z{i}) ;\n end\n o.state = z;\n\n\n %\n % automatic lambda (trust region) hyperparameter\n %\n \n if o.autolambda && rem(o.count, o.autolambda_interval) == 0\n h_curr = o.last_loss ;\n M = -0.5 * m_b(:)' * b(:);\n\n % compute new value\n labels = o.labels;\n if isvector(labels) % categorical labels\n batch_size = numel(labels);\n else % regression targets, get last dimension\n batch_size = size(labels, ndims(labels));\n end\n\n % assign new parameter values now (don't wait for Solver.step)\n idx = [net.params.var];\n is_grad = ([net.params.trainMethod] == 1);\n net.setValue(idx(is_grad), w) ;\n\n % run network forward with new parameters\n net.eval({}, 'forward');\n\n % get value of last var (assumes only one output)\n pred = net.vars{end - 1};\n pred = reshape(pred, 1, 1, [], batch_size); % reshape to 4D tensor for vl_nnloss\n\n % compute loss value\n switch o.loss\n case 'logistic'\n loss_value = vl_nnloss(pred, labels, 'loss', 'softmaxlog');\n otherwise\n error('Loss not yet supported with autolambda');\n end\n\n h_new = loss_value;\n\n % ratio between true curvature and quadratic fit curvature\n ratio = (h_new - h_curr) / M;\n\n % increase or decrease lambda based on ratio\n w1 = o.autolambda_w1 ^ o.autolambda_interval;\n thresh = o.autolambda_thresh;\n if isscalar(thresh)\n thresh = [thresh, 2 - thresh];\n end\n assert(diff(thresh) >= 0);\n\n if ratio < thresh(1)\n lambda = lambda / w1;\n elseif ratio > thresh(2)\n lambda = lambda * w1;\n end\n o.lambda = lambda;\n o.ratio = ratio;\n end\n\n o.count = o.count + 1;\n\n end\n\n function s = saveobj(o)\n % serialize to struct (called by the built-in function SAVE)\n % transfer state to CPU first\n s = o.saveGeneric(); % call parent class\n s.last_loss = gather(o.last_loss);\n end\n end\n\n methods (Static)\n function o = loadobj(s)\n % deserialize from struct (called by the built-in function LOAD)\n o = solvers.CurveBall();\n o.last_loss = s.last_loss;\n o.loadGeneric(s); % call parent class\n\n % don't let parent class clear some parameters\n o.conserveMemory = false;\n end\n end\nend\n\n\n% computes the loss value, its gradient, and the hessian (multiplied by a\n% vector x).\nfunction [Hlx, Jl, loss_value] = hessian_grad_loss(net, loss, labels, x)\n if isvector(labels) % categorical labels\n batch_size = numel(labels);\n else % regression targets, get last dimension\n batch_size = size(labels, 4);\n end\n\n % get value of last var (assumes only one output)\n pred = net.vars{end - 1};\n pred = reshape(pred, 1, 1, [], batch_size); % reshape to 4D tensor for vl_nnloss\n\n switch loss\n case 'ls' % least-squares loss.\n % compute Hl * x. Hl = 2 / batch_size * I.\n Hlx = 2 / batch_size * x;\n\n % loss Jacobian, Jl\n assert(isequal(size(pred), size(labels)));\n Jl = 2 / batch_size * (pred - labels);\n\n % compute loss value\n loss_value = mean(sum((pred - labels).^2, 3), 4);\n\n case 'logistic' % logistic loss.\n % compute Hl * x. for a single sample, Hl = diag(p) - p * p', where p\n % is a column-vector. for many samples, p has one column per sample,\n % and Hl is a block-diag with each block as above (so one independent\n % matrix-vec product per sample). first compute p' * x for all samples\n\n p = vl_nnsoftmax(pred); % softmaxed probabilities\n\n if ismatrix(p)\n px = sum(p .* x, 1);\n else % 4D tensor\n px = sum(p .* x, 3);\n end\n\n % now finish computing Hl * x = diag(p) * x - p * p' * x for every sample.\n Hlx = p .* x - p .* px;\n Hlx = Hlx / batch_size;\n\n if nargout <= 1, return, end % early exit for single output\n\n\n % compute loss Jacobian, Jl. use backward pass of vl_nnloss\n Jl = vl_nnloss(pred, labels, single(1), 'loss', 'softmaxlog'); % loss gradient\n\n % compute loss value\n loss_value = vl_nnloss(pred, labels, 'loss', 'softmaxlog');\n\n otherwise\n error('Unknown loss.');\n end\nend\n\n", "meta": {"author": "jotaf98", "repo": "curveball", "sha": "1dc37325382c12e3fc9b2e7e27c47e6d7a17021a", "save_path": "github-repos/MATLAB/jotaf98-curveball", "path": "github-repos/MATLAB/jotaf98-curveball/curveball-1dc37325382c12e3fc9b2e7e27c47e6d7a17021a/CurveBall.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789040926008, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.46804781069435303}}
{"text": "function [ MRI_signal, bvalue ] = dt_from_smoldyn_pt2( positions, voxel_size, step_time, delta, Delta, gradient_directions, gradient_strength, bvalue )\n%DT_FROM_SMOLDYN_PT2 Calculates the MRI signal\n%\n% PART 2 OF THE CALCULATION OF THE DIFFUSION TENSOR FROM THE SMOLDYN MODEL DATA\n% This part calculates the diffusion MRI signal from the positions data.\n% Note that providing each set of positions data contains the same number\n% of molecules, the MRI signal from different sets of positions data can be\n% combined by just taking the mean.\n%\n% Inputs are:\n% positions: matrix of size no of molecules x 3 x no of timesteps generated\n% from the Smoldyn program and cut down in part 1\n% voxel_size: scalar. the total (isotropic) size of the volume simulated (um)\n% step_time: scalar. the time of each step as used to generate the Smoldyn diffusion (us)\n% delta: scalar. the gradient pulse time (us)\n% Delta: scalar. the time between gradient pulses (us)\n% gradient_directions: matrix of size no of directions x 3 which gives\n% the x,y,z components of the gradient directions\n% gradient_strength: IF UNKNOWN, SET TO 0 & IT WILL BE CALCULATED FROM\n% BVALUE. scalar. (T/um)\n% bvalue: IF UNKNOWN, SET TO 0 & IT WILL BE CALCULATED FROM\n% GRADIENT_STRENGTH. scalar. (um^2/us)\n%\n% Outputs are:\n% MRI_signal: relative signal for each of the gradient directions\n% bvalue: as input, included as an output as needed later\n\n% Author: Jo Bates \n% Copyright Ā© 2014 University of Oxford\n% \n% University of Oxford means the Chancellor, Masters and Scholars of\n% the University of Oxford, having an administrative office at\n% Wellington Square, Oxford OX1 2JD, UK. \n%\n% This file is part of Gerardus.\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details. The offer of this\n% program under the terms of the License is subject to the License\n% being interpreted in accordance with English Law and subject to any\n% action against the University of Oxford being under the jurisdiction\n% of the English Courts.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\nno_of_directions = size(gradient_directions,1);\nno_of_molecules = size(positions,1);\n% number of jumps\nno_of_timesteps = size(positions, 3);\n\n% define the gyromagnetic ratio of water (rad/us/T)\ngyro_ratio = 267.5;\n\n% calculate the bvalue or gradient_strength if required\nif bvalue == 0;\n bvalue = gradient_strength^2 * gyro_ratio^2 * delta^2 *(Delta - (delta/3));\nend\nif gradient_strength == 0;\n gradient_strength = sqrt(bvalue/(gyro_ratio^2 * delta^2 *(Delta - (delta/3))));\nend\n\n% resolution & range of the co-ordinates\nxres = 1; \nyres = 1;\nzres = 1;\nxmax = (voxel_size-1)/2;\nymax = (voxel_size-1)/2;\nzmax = (voxel_size-1)/2;\n\n% parameters independent of gradient direction or voxel\npulse_1_end_step = (delta/step_time) + 1;\npulse_2_start_step = (Delta/step_time)+1;\npulse_2_end_step = ((Delta+delta)/step_time) + 1;\n\n% calc parameters which are independent of voxel\nstart_corner = zeros(no_of_directions, 3);\nfor g = 1:no_of_directions \n % work out the starting corner of the image, where the MRI pulse with be 0\n sign_x = sign(gradient_directions(g,1));\n sign_y = sign(gradient_directions(g,2));\n sign_z = sign(gradient_directions(g,3));\n if sign_x < 0\n x_1 = xmax*2+1;\n else\n x_1 = 1;\n end\n if sign_y < 0\n y_1 = ymax*2+1;\n else\n y_1 = 1;\n end\n if sign_z < 0\n z_1 = zmax*2+1;\n else\n z_1 = 1;\n end\n start_corner (g,:) = [x_1, y_1, z_1];\nend\n\nMRI_signal = zeros(no_of_directions,1);\n% for every gradient direction\nfor g = 1:no_of_directions\n x_1 = start_corner (g,1);\n y_1 = start_corner (g,2);\n z_1 = start_corner (g,3);\n % for each molecule, for each position, the position in gradient\n % direction is the dot product of the position times the gradient\n % direction. since A.B = a1*b1 + a2*b2 + a3*b3, calculate like this as\n % need to include the potential for different resolutions in each\n % direction and can't seem to do dot product of correct parts for these\n % 2 matrices.\n\n x_pos = (positions(:,1,:)-x_1).*xres.*gradient_directions(g,1);\n y_pos = (positions(:,2,:)-y_1).*yres.*gradient_directions(g,2);\n z_pos = (positions(:,3,:)-z_1).*zres.*gradient_directions(g,3);\n position_grad_dirn = x_pos + y_pos + z_pos;\n\n % calculate phase shift for each molecule\n mol_pulse = zeros(size(position_grad_dirn));\n mol_pulse(:,:,1:pulse_1_end_step) = position_grad_dirn(:,:,1:pulse_1_end_step).*gradient_strength;\n mol_pulse(:,:,pulse_2_start_step:pulse_2_end_step) = -position_grad_dirn(:,:,pulse_2_start_step:pulse_2_end_step).*gradient_strength;\n molpulsesum = sum(mol_pulse,3);\n \n % calc MRI signal\n phasech = gyro_ratio*molpulsesum*step_time;\n cosphase = cos(phasech);\n MRI_signal(g) = mean(cosphase);\nend\n\nend\n\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/DiffusionMRIToolbox/dt_from_smoldyn_pt2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711870587667, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.46800039608728855}}
{"text": " function mse = ComputeMultiscaleEntropy(data, m, r, maxTau, maxVecSize,cg_moment,cg_method,constant_r)\n\n% mse = ComputeMultiscaleEntropy(data, m, r, max_tau,cg_moment)\n%\n% Overview\n%\tCalculates multiscale entropy on a vector of input data.\n%\n% Input\n%\tdata - data to analyze; vector of doubles\n% m - pattern length; int\n% r - radius of similarity (% of std); double\n% maxTau - maximum number of coarse-grainings; int\n% maxVecSize - optional, parameter to switch from SampEn to FastSempEn \n% cg_moment - optional, moment used to coarse-grain the time series,\n% by default use the mean 'mean'\n% Options: 'mean', 'varaince'\n% cg_method - [optional] - method use to generate the coarse-grain \n% time series. By default use the original method proposed\n% by Costa et al. ('fir' with mean).\n% Options: 'fir' [Costa et al.], 'butter' [Valencia et al.]\n% constant_r - [DEFAULT] 1 : use r as function of std of original time \n% series in this implementation correspond to zscore only \n% the original time series \n% - 0 : r as a function of scale factor (tau), i.e., \n% r(i)= r*std(ScaleData(i)), in this implementation it\n% corresponds to zscore each coarse-grain time siries\n% \n% \n% Output\n% mse - vector of [max_tau, 1] doubles\n%\n% Example\n% data = rand(1e4, 1); % generate random data\n% m = 2; % template length\n% r = 0.2; % radius of similarity\n% maxTau = 4; % calculate sample entropy over four coarse grainings\n% mse = multiscaleEntropy(data, m, r, maxTau, 'Fast','mean');\n% \n%\tREPO: \n% https://github.com/cliffordlab/PhysioNet-Cardiovascular-Signal-Toolbox\n%\n% Reference(s)\n% \n% Copyright (C) 2017 Erik Reinertsen \n% All rights reserved.\n%\n% \n% 08-23-2017 Modyfied by Giulia Da Poian to be inclused in the HRV Toolbox \n% for PhysioNet Cardiovascular Signal ToolboxToolbox \n% Removed the possibility to use different types of entropy, only\n% fastSampen method in this version\n%\n% 10-10-2017 Modyfied by Giulia Da Poian, use FastSampEn in series < 34000\n% otherwise use traditional SampEn that is faster for long series\n%\n% 10-23-2017 Modyfied by Giulia Da Poian, using scales like in Costa's\n% paper instead of Coarse-grain data using halving method.\n%\n% This software may be modified and distributed under the terms\n% of the BSD license. See the LICENSE file in this repo for details.\n\nif nargin<5 || isempty(maxVecSize)\n maxVecSize = 34000;\nend\nif nargin<6 || isempty(cg_moment)\n cg_moment = 'mean';\nend\nif nargin<7 || isempty(cg_method)\n cg_method = 'fir';\nend\nif nargin<8 || isempty(constant_r)\n constant_r = 0;\nend\n\n\ndata = zscore(data); % (introduced by GDP) normalization of the signal that \n % replace the common practice of expressing the \n % tolerance as r times the standard deviation\n \nmse = NaN(maxTau, 1); % Initialize output vector\n\nSampEnType = 'Maxim'; % Initialize default SampEn method \n\n% Check data length, if < 34000 use Fast Implementation (introduced GDP) \nif length(data) < maxVecSize\n SampEnType = 'Fast'; \nend\n\n\n% Loop through each window\n\n% Loop through each timescale\n% Note: i_tau == 1 is the original time series\nfor i_tau = 1:maxTau\n \n scaledData = coarsegrain(data,i_tau,cg_moment,cg_method); % Changed by GDP\n \n if ~constant_r\n scaledData = zscore(scaledData);\n end\n\n switch SampEnType\n case 'Fast'\n mse(i_tau) = fastSampen(scaledData, m, r);\n otherwise\n mse(i_tau) = sampenMaxim(scaledData, m, r); \n end\n\nend % end for loop\n\n\n\n\n\n\n% REFERENCES\n\n% Costa et al. \"Multiscale entropy analysis of complex physiologic time\n% series.\" Physical review letters 89.6 (2002): 068102\n\n% Valencia et al. \"Refined multiscale entropy: Application to 24-h holter \n% recordings of heart period variability in healthy and aortic stenosis\n% subjects.\" IEEE Transactions on Biomedical Engineering 56, no. 9 (2009).\n\n", "meta": {"author": "cliffordlab", "repo": "PhysioNet-Cardiovascular-Signal-Toolbox", "sha": "eec46e75e0b95c379ecb68cb0ebee0c4c9f54605", "save_path": "github-repos/MATLAB/cliffordlab-PhysioNet-Cardiovascular-Signal-Toolbox", "path": "github-repos/MATLAB/cliffordlab-PhysioNet-Cardiovascular-Signal-Toolbox/PhysioNet-Cardiovascular-Signal-Toolbox-eec46e75e0b95c379ecb68cb0ebee0c4c9f54605/Tools/Entropy_Tools/ComputeMultiscaleEntropy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.46793420837560384}}
{"text": "function [fProbability, fAICc] = calc_loglikelihood_nochange2(mCat1, mCat2)\n% function [fProbability, fAICc] = calc_loglikelihood_nochange2(mCat1, mCat2);\n% ----------------------------------------------------------------------------------------------\n% Calculate log-likelihood estimation of NO CHANGE between the two periods\n%\n% Incoming variable\n% mCat1 : EQ catalog period 1 (Catalog to be modified)\n% mCat2 : EQ catalog period 2 (Observed catalog)\n%\n% Outgoing variable\n% fProbability : log-likelihood probabilty\n% fAICc : Corrected Akaike Information Criterion\n%\n% Author: J. Woessner, woessner@seismo.ifg,.ethz.ch\n% last update: 26.11.02\n\nfBinning = 0.1;\n\n% Determine exact time period\nfPeriod1 = max(mCat1(:,3)) - min(mCat1(:,3));\nfPeriod2 = max(mCat2(:,3)) - min(mCat2(:,3));\n\n\n% Initialize values\nfMinMag = min([min(mCat1(:,6)) min(mCat2(:,6))]);\nfMaxMag = max([max(mCat1(:,6)) max(mCat2(:,6))]);\n\ntry\n %% Calculate model for best fiting Mc\n [mResult, fMls, fMc, fMu, fSigma, mDatPred, vPredBest, fBvalue] = calc_McCdfnormal(mCat1, fBinning);\n vPredFMD = mDatPred(:,1)'./fPeriod1;\n vMags = mDatPred(:,2)';\n % FMD to be modeled\n [vObsFMD,vBin2] = hist(mCat2(:,6),min(vMags):0.1:max(vMags));\n vObsFMD = ceil(vObsFMD./fPeriod2);\n % Calculate the likelihoods for both models\n vProb_ = calc_log10poisspdf2(vObsFMD', vPredFMD');\n % Sum the probabilities\n fProbability = (-1) * sum(vProb_);\n\n nDegFree = 0; % degree of freedom\n n_samples = length(mCat2(:,6));\n %% Corrected Akaike Information Criterion (AICc)\n fAICc = -2*(-fProbability)+2*nDegFree+2*nDegFree*(nDegFree+1)/(n_samples-nDegFree-1);\ncatch\n fAICc = nan;\n fProbability = nan;\nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/jochen/seisvar/calc/calc_loglikelihood_nochange2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.46793419387603324}}
{"text": "function [ n_data, n, a, x, fx ] = gegenbauer_poly_values ( n_data )\n\n%*****************************************************************************80\n%\n%% GEGENBAUER_POLY_VALUES returns some values of the Gegenbauer polynomials.\n%\n% Discussion:\n%\n% The Gegenbauer polynomials are also known as the \"spherical\n% polynomials\" or \"ultraspherical polynomials\".\n%\n% In Mathematica, the function can be evaluated by:\n%\n% GegenbauerC[n,m,x]\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Wolfram Media / Cambridge University Press, 1999.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA. The user sets N_DATA to 0 before the\n% first call. On each call, the routine increments N_DATA by 1, and\n% returns the corresponding data; when there is no more data, the\n% output value of N_DATA will be 0 again.\n%\n% Output, integer N, the order parameter of the function.\n%\n% Output, real A, the real parameter of the function.\n%\n% Output, real X, the argument of the function.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 38;\n\n a_vec = [ ...\n 0.5E+00, ...\n 0.5E+00, ...\n 0.5E+00, ...\n 0.5E+00, ...\n 0.5E+00, ...\n 0.5E+00, ...\n 0.5E+00, ...\n 0.5E+00, ...\n 0.5E+00, ...\n 0.5E+00, ...\n 0.5E+00, ...\n 0.0E+00, ...\n 1.0E+00, ...\n 2.0E+00, ...\n 3.0E+00, ...\n 4.0E+00, ...\n 5.0E+00, ...\n 6.0E+00, ...\n 7.0E+00, ...\n 8.0E+00, ...\n 9.0E+00, ...\n 10.0E+00, ...\n 3.0E+00, ...\n 3.0E+00, ...\n 3.0E+00, ...\n 3.0E+00, ...\n 3.0E+00, ...\n 3.0E+00, ...\n 3.0E+00, ...\n 3.0E+00, ...\n 3.0E+00, ...\n 3.0E+00, ...\n 3.0E+00, ...\n 3.0E+00, ...\n 3.0E+00, ...\n 3.0E+00, ...\n 3.0E+00, ...\n 3.0E+00 ];\n\n fx_vec = [ ...\n 1.0000000000E+00, ...\n 0.2000000000E+00, ...\n -0.4400000000E+00, ...\n -0.2800000000E+00, ...\n 0.2320000000E+00, ...\n 0.3075200000E+00, ...\n -0.0805760000E+00, ...\n -0.2935168000E+00, ...\n -0.0395648000E+00, ...\n 0.2459712000E+00, ...\n 0.1290720256E+00, ...\n 0.0000000000E+00, ...\n -0.3600000000E+00, ...\n -0.0800000000E+00, ...\n 0.8400000000E+00, ...\n 2.4000000000E+00, ...\n 4.6000000000E+00, ...\n 7.4400000000E+00, ...\n 10.9200000000E+00, ...\n 15.0400000000E+00, ...\n 19.8000000000E+00, ...\n 25.2000000000E+00, ...\n -9.0000000000E+00, ...\n -0.1612800000E+00, ...\n -6.6729600000E+00, ...\n -8.3750400000E+00, ...\n -5.5267200000E+00, ...\n 0.0000000000E+00, ...\n 5.5267200000E+00, ...\n 8.3750400000E+00, ...\n 6.6729600000E+00, ...\n 0.1612800000E+00, ...\n -9.0000000000E+00, ...\n -15.4252800000E+00, ...\n -9.6969600000E+00, ...\n 22.4409600000E+00, ...\n 100.8892800000E+00, ...\n 252.0000000000E+00 ];\n\n n_vec = [ ...\n 0, 1, 2, ...\n 3, 4, 5, ...\n 6, 7, 8, ...\n 9, 10, 2, ...\n 2, 2, 2, ...\n 2, 2, 2, ...\n 2, 2, 2, ...\n 2, 5, 5, ...\n 5, 5, 5, ...\n 5, 5, 5, ...\n 5, 5, 5, ...\n 5, 5, 5, ...\n 5, 5 ];\n\n x_vec = [ ...\n 0.20E+00, ...\n 0.20E+00, ...\n 0.20E+00, ...\n 0.20E+00, ...\n 0.20E+00, ...\n 0.20E+00, ...\n 0.20E+00, ...\n 0.20E+00, ...\n 0.20E+00, ...\n 0.20E+00, ...\n 0.20E+00, ...\n 0.40E+00, ...\n 0.40E+00, ...\n 0.40E+00, ...\n 0.40E+00, ...\n 0.40E+00, ...\n 0.40E+00, ...\n 0.40E+00, ...\n 0.40E+00, ...\n 0.40E+00, ...\n 0.40E+00, ...\n 0.40E+00, ...\n -0.50E+00, ...\n -0.40E+00, ...\n -0.30E+00, ...\n -0.20E+00, ...\n -0.10E+00, ...\n 0.00E+00, ...\n 0.10E+00, ...\n 0.20E+00, ...\n 0.30E+00, ...\n 0.40E+00, ...\n 0.50E+00, ...\n 0.60E+00, ...\n 0.70E+00, ...\n 0.80E+00, ...\n 0.90E+00, ...\n 1.00E+00 ];\n\n if ( n_data < 0 )\n n_data = 0;\n end\n\n n_data = n_data + 1;\n\n if ( n_max < n_data )\n n_data = 0;\n n = 0;\n a = 0.0;\n x = 0.0;\n fx = 0.0;\n else\n n = n_vec(n_data);\n a = a_vec(n_data);\n x = x_vec(n_data);\n fx = fx_vec(n_data);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_values/gegenbauer_poly_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741041, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4679264825075847}}
{"text": "%%******************************************************************\n%% mybicgstab\n%% \n%% [xx,resnrm,flag] = mybicgstab(A,b,M1,tol,maxit)\n%%\n%% iterate on bb - (M1)*AA*x\n%%\n%% r = b-A*xtrue; \n%%*****************************************************************\n%% SDPT3: version 4.0\n%% Copyright (c) 1997 by\n%% Kim-Chuan Toh, Michael J. Todd, Reha H. Tutuncu\n%% Last Modified: 16 Sep 2004\n%%*****************************************************************\n function [xx,resnrm,flag] = mybicgstab(A,b,M1,tol,maxit,printlevel)\n\n N = length(b); \n if (nargin < 6); printlevel = 1; end\n if (nargin < 5) | isempty(maxit); maxit = max(30,length(A.mat22)); end;\n if (nargin < 4) | isempty(tol); tol = 1e-10; end; \n tolb = min(1e-4,tol*norm(b));\n flag = 1;\n \n x = zeros(N,1); \n if (norm(x)) \n if isstruct(A); r = b-matvec(A,x); else; r = b-mexMatvec(A,x); end; \n else\n r =b; \n end\n err = norm(r); resnrm(1) = err; minresnrm = err; xx = x; \n %%if (err < 1e-3*tolb); return; end\n\n omega = 1.0;\n r_tld = r;\n%%\n%%\n%%\n breakyes = 0; \n smtol = 1e-40; \n for iter = 1:maxit, \n\n rho = (r_tld'*r); \n if (abs(rho) < smtol)\n flag = 2; \n if (printlevel); fprintf('*'); end;\n breakyes = 1; \n break; \n end\n if (iter > 1)\n beta = (rho/rho_1)* (alp/omega);\n p = r + beta*(p - omega*v);\n else\n p = r;\n end\n p_hat = precond(A,M1,p);\n if isstruct(A); v = matvec(A,p_hat); else; v = mexMatvec(A,p_hat); end;\n alp = rho / (r_tld'*v);\n s = r - alp*v; \n %%\n s_hat = precond(A,M1,s); \n if isstruct(A); t = matvec(A,s_hat); else; t = mexMatvec(A,s_hat); end;\n omega = (t'*s) / (t'*t);\n x = x + alp*p_hat + omega*s_hat; \n r = s - omega*t;\n rho_1 = rho;\n %%\n %% check convergence\n %%\n err = norm(r); resnrm(iter+1) = err; \n if (err < minresnrm); \n xx = x; minresnrm = err; \n end\n if (err < tolb)\n break; \n end\n if (err > 10*minresnrm) \n if (printlevel); fprintf('^'); end\n breakyes = 2; \n break; \n end \n if (abs(omega) < smtol)\n flag = 2; \n if (printlevel); fprintf('*'); end\n breakyes = 1; \n break; \n end\n end\n if (~breakyes) & (printlevel >=3); fprintf(' '); end\n%%\n%%*************************************************************************\n%%*************************************************************************\n%% precond: \n%%*************************************************************************\n\n function Mx = precond(A,L,x)\n\n m = L.matdim; m2 = length(x)-m;\n Mx = zeros(length(x),1); \n\n for iter = 1\n if norm(Mx); r = x - matvec(A,Mx); else; r = x; end\n if (m2 > 0)\n r1 = full(r(1:m)); \n else\n r1 = full(r); \n end\n if (m2 > 0)\n r2 = r(m+[1:m2]);\n w = linsysolvefun(L,r1); \n z = mexMatvec(A.mat12,w,1) - r2;\n z = L.Mu \\ (L.Ml \\ (L.Mp*z));\n r1 = r1 - mexMatvec(A.mat12,z); \n end\n d = linsysolvefun(L,r1); \n if (m2 > 0)\n d = [d; z];\n end\n Mx = Mx + d; \n end\n%%*************************************************************************\n%%*************************************************************************\n%% matvec: matrix-vector multiply.\n%% matrix = [A.mat11, A.mat12; A.mat12', A.mat22]\n%%*************************************************************************\n\n function Ax = matvec(A,x);\n\n m = length(A.mat11); m2 = length(x)-m; \n if issparse(x); x = full(x); end\n if (m2 > 0)\n x1 = x(1:m); \n else\n x1 = x; \n end\n Ax = mexMatvec(A.mat11,x1);\n if (m2 > 0)\n x2 = x(m+[1:m2]);\n Ax = Ax + mexMatvec(A.mat12,x2); \n Ax2 = mexMatvec(A.mat12,x1,1) + mexMatvec(A.mat22,x2);\n Ax = [full(Ax); full(Ax2)]; \n end\n%%*************************************************************************\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/SDPT3-4.0/SDPT3-4.0/Solver/mybicgstab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.46786698542691557}}
{"text": "function failed_tutorial_natmeg_beamforming\n\n% WALLTIME 00:20:00\n% MEM 8gb\n% DEPENDENCY\n\n% this script executes the MATLAB content from\n% http://www.fieldtriptoolbox.org/tutorial/natmeg/beamforming\n%\n% it corresponds to the wiki version of 7 October 2014\n\nclear all\nclose all\n\ncd(dccnpath('/home/common/matlab/fieldtrip/data/ftp/tutorial/natmeg'));\n\nload timefrequency/data_clean_MEG_responselocked.mat;\nload dipolefitting/headmodel_meg.mat;\n\n% Select time window of interest\ncfg = [];\ncfg.toilim = [0.35 0.85];\ndata_timewindow = ft_redefinetrial(cfg,data_clean_MEG_responselocked);\n\n% Freqanalysis for beamformer\ncfg = [];\ncfg.channel = {'MEG*2', 'MEG*3'};\ncfg.method = 'mtmfft';\ncfg.taper = 'dpss';\ncfg.output = 'powandcsd';\ncfg.keeptrials = 'no';\ncfg.foi = 18;\ncfg.tapsmofrq = 4;\n\n% for common filter over conditions\npowcsd_all = ft_freqanalysis(cfg, data_timewindow);\n\n% for conditions\ncfg.trials = find(data_timewindow.trialinfo(:,1) == 256);\npowcsd_left = ft_freqanalysis(cfg, data_timewindow);\ncfg.trials = find(data_timewindow.trialinfo(:,1) == 4096);\npowcsd_right = ft_freqanalysis(cfg, data_timewindow);\n\n% Create leadfield grid\ncfg = [];\ncfg.channel = {'MEG*2', 'MEG*3'};\ncfg.grad = powcsd_all.grad;\ncfg.headmodel = headmodel_meg;\ncfg.dics.reducerank = 2; % default for MEG is 2, for EEG is 3\ncfg.sourcemodel.resolution = 0.5; % use a 3-D grid with a 0.5 cm resolution\ncfg.sourcemodel.unit = 'cm';\ncfg.sourcemodel.tight = 'yes';\n[grid] = ft_prepare_leadfield(cfg);\n\ncfg = [];\ncfg.channel = {'MEG*2', 'MEG*3'};\ncfg.method = 'dics';\ncfg.frequency = 18;\ncfg.sourcemodel = grid;\ncfg.headmodel = headmodel_meg;\ncfg.senstype = 'MEG'; % Must me 'MEG', although we only kept MEG channels, information on EEG channels is still present in data\ncfg.dics.keepfilter = 'yes'; % We wish to use the calculated filter later on\ncfg.dics.projectnoise = 'yes';\ncfg.dics.lambda = '5%';\nsource_all = ft_sourceanalysis(cfg, powcsd_all);\n\ncfg = [];\ncfg.channel = {'MEG*2', 'MEG*3'};\ncfg.method = 'dics';\ncfg.frequency = 18;\ncfg.sourcemodel = grid;\ncfg.sourcemodel.filter = source_all.avg.filter;\ncfg.headmodel = headmodel_meg;\ncfg.senstype ='MEG';\n\nsource_left = ft_sourceanalysis(cfg, powcsd_left);\nsource_right = ft_sourceanalysis(cfg, powcsd_right);\n\nload dipolefitting/mri_realigned2.mat;\n\nmri_resliced = ft_volumereslice([], mri_realigned2);\n\ncfg = [];\ncfg.parameter = 'avg.pow';\nsource_left_int = ft_sourceinterpolate(cfg, source_left, mri_resliced);\nsource_right_int = ft_sourceinterpolate(cfg, source_right, mri_resliced);\n\nsource_diff_int = source_left_int;\nsource_diff_int.avg.pow = (source_left_int.avg.pow - source_right_int.avg.pow) ./ (source_left_int.avg.pow + source_right_int.avg.pow);\n\n% plot\ncfg = [];\ncfg.method = 'ortho';\ncfg.funparameter = 'avg.pow';\ncfg.funcolorlim = 'maxabs';\ncfg.opacitylim = [0 1e-4];\ncfg.opacitymap = 'rampup';\n\nft_sourceplot(cfg, source_left_int);\n\ncfg.location = [35 -13 76];\nft_sourceplot(cfg, source_diff_int);\n\nload dipolefitting/headmodel_eeg.mat\nload timefrequency/data_clean_EEG_responselocked.mat\n\n% select time window\ncfg = [];\ncfg.toilim = [0.35 0.85];\ndata_timewindow = ft_redefinetrial(cfg,data_clean_EEG_responselocked);\n\n% Freqanalysis for beamformer\ncfg = [];\ncfg.method = 'mtmfft';\ncfg.taper = 'dpss';\ncfg.output = 'powandcsd';\ncfg.keeptrials = 'no';\ncfg.foi = 18;\ncfg.tapsmofrq = 4;\n\n% for common filter over conditions and full duration\npowcsd_all = ft_freqanalysis(cfg, data_timewindow);\n\n% for conditions\ncfg.trials = find(data_timewindow.trialinfo(:,1) == 256);\npowcsd_left = ft_freqanalysis(cfg, data_timewindow);\ncfg.trials = find(data_timewindow.trialinfo(:,1) == 4096);\npowcsd_right = ft_freqanalysis(cfg, data_timewindow);\n\n% common grid/filter\ncfg = [];\ncfg.elec = powcsd_all.elec;\ncfg.headmodel = headmodel_eeg;\ncfg.reducerank = 3; % default is 3 for EEG, 2 for MEG\ncfg.sourcemodel.resolution = 0.5; % use a 3-D grid with a 0.5 cm resolution\ncfg.sourcemodel.unit = 'cm';\ncfg.sourcemodel.tight = 'yes';\n[grid] = ft_prepare_leadfield(cfg);\n\n% beamform common filter\ncfg = [];\ncfg.method = 'dics';\ncfg.frequency = 18;\ncfg.sourcemodel = grid;\ncfg.headmodel = headmodel_eeg;\ncfg.senstype = 'EEG'; % Remember this must be specified as either EEG, or MEG\ncfg.dics.keepfilter = 'yes';\ncfg.dics.lambda = '15%';\nsource_all = ft_sourceanalysis(cfg, powcsd_all);\n\n% beamform conditions\ncfg = [];\ncfg.method = 'dics';\ncfg.frequency = 18;\ncfg.sourcemodel = grid;\ncfg.sourcemodel.filter = source_all.avg.filter; % Use the common filter\ncfg.headmodel = headmodel_eeg;\ncfg.senstype = 'EEG';\n\nsource_left = ft_sourceanalysis(cfg, powcsd_left);\nsource_right = ft_sourceanalysis(cfg, powcsd_right);\n\ncfg = [];\ncfg.parameter = 'avg.pow';\nsource_left_int = ft_sourceinterpolate(cfg, source_left, mri_resliced);\nsource_right_int = ft_sourceinterpolate(cfg, source_right, mri_resliced);\n\nsource_diff_int = source_left_int;\nsource_diff_int.avg.pow = (source_left_int.avg.pow - source_right_int.avg.pow) ./ (source_left_int.avg.pow + source_right_int.avg.pow);\n\ncfg = [];\ncfg.method = 'ortho';\ncfg.funparameter = 'avg.pow';\ncfg.funcolorlim = 'maxabs';\n\nft_sourceplot(cfg, source_left_int);\n\ncfg.location = [-19.5 -18.5 70.5];\nft_sourceplot(cfg, source_diff_int);\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/failed_tutorial_natmeg_beamforming.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.46786697875216965}}
{"text": "function output=SSBerouti79(signal,fs,IS)\n\n% OUTPUT=SSBEROUTI79(S,FS,IS)\n% Nonlinear Spectral Subtraction based on Berouti 79. Power spectral\n% subtraction with adjusting subtraction factor. the adjustment is\n% according to local a postriori SNR.\n% S is the noisy signal, FS is the sampling frequency and IS is the initial\n% silence (noise only) length in seconds (default value is .25 sec)\n%\n% Required functions:\n% SEGMENT\n% VAD\n% Sep-04\n% Esfandiar Zavarehei\n\nif (nargin<3 | isstruct(IS))\n IS=.25; %seconds\nend\nW=fix(.025*fs); %Window length is 25 ms\nnfft=W;\nSP=.4; %Shift percentage is 40% (10ms) %Overlap-Add method works good with this value(.4)\nwnd=hamming(W);\n\n% IGNORE THIS SECTION FOR CAMPATIBALITY WITH ANOTHER PROGRAM FROM HERE.....\nif (nargin>=3 & isstruct(IS))%This option is for compatibility with another programme\n W=IS.windowsize\n SP=IS.shiftsize/W;\n nfft=IS.nfft;\n wnd=IS.window;\n if isfield(IS,'IS')\n IS=IS.IS;\n else\n IS=.25;\n end\nend\n% .......IGNORE THIS SECTION FOR CAMPATIBALITY WITH ANOTHER PROGRAM T0 HERE\n\nNIS=fix((IS*fs-W)/(SP*W) +1);%number of initial silence segments\nGamma=2;%Magnitude Power (1 for magnitude spectral subtraction 2 for power spectrum subtraction)\n%Change Gamma to 1 to get a completely different performance\ny=segment(signal,W,SP,wnd);\nY=fft(y,nfft);\nYPhase=angle(Y(1:fix(end/2)+1,:)); %Noisy Speech Phase\nY=abs(Y(1:fix(end/2)+1,:)).^Gamma;%Specrogram\nnumberOfFrames=size(Y,2);\nFreqResol=size(Y,1);\n\nN=mean(Y(:,1:NIS)')'; %initial Noise Power Spectrum mean\n\nNoiseCounter=0;\nNoiseLength=9;%This is a smoothing factor for the noise updating\n\nBeta=.03;\nminalpha=1;\nmaxalpha=3;\nminSNR=-5;\nmaxSNR=20;\nalphaSlope=(minalpha-maxalpha)/(maxSNR-minSNR);\nalphaShift=maxalpha-alphaSlope*minSNR;\n\nBN=Beta*N;\n\nfor i=1:numberOfFrames\n [NoiseFlag, SpeechFlag, NoiseCounter, Dist]=vad(Y(:,i).^(1/Gamma),N.^(1/Gamma),NoiseCounter); %Magnitude Spectrum Distance VAD\n if SpeechFlag==0\n N=(NoiseLength*N+Y(:,i))/(NoiseLength+1); %Update and smooth noise\n BN=Beta*N;\n end\n \n SNR=10*log(Y(:,i)./N);\n alpha=alphaSlope*SNR+alphaShift;\n alpha=max(min(alpha,maxalpha),minalpha);\n \n D=Y(:,i)-alpha.*N; %Nonlinear (Non-uniform) Power Specrum Subtraction\n \n X(:,i)=max(D,BN); %if BY>D X=BY else X=D which sets very small values of subtraction result to an attenuated \n %version of the input power spectrum.\nend\n\noutput=OverlapAdd2(X.^(1/Gamma),YPhase,W,SP*W);\n\n\n\nfunction ReconstructedSignal=OverlapAdd2(XNEW,yphase,windowLen,ShiftLen);\n\n%Y=OverlapAdd(X,A,W,S);\n%Y is the signal reconstructed signal from its spectrogram. X is a matrix\n%with each column being the fft of a segment of signal. A is the phase\n%angle of the spectrum which should have the same dimension as X. if it is\n%not given the phase angle of X is used which in the case of real values is\n%zero (assuming that its the magnitude). W is the window length of time\n%domain segments if not given the length is assumed to be twice as long as\n%fft window length. S is the shift length of the segmentation process ( for\n%example in the case of non overlapping signals it is equal to W and in the\n%case of %50 overlap is equal to W/2. if not givven W/2 is used. Y is the\n%reconstructed time domain signal.\n%Sep-04\n%Esfandiar Zavarehei\n\nif nargin<2\n yphase=angle(XNEW);\nend\nif nargin<3\n windowLen=size(XNEW,1)*2;\nend\nif nargin<4\n ShiftLen=windowLen/2;\nend\nif fix(ShiftLen)~=ShiftLen\n ShiftLen=fix(ShiftLen);\n disp('The shift length have to be an integer as it is the number of samples.')\n disp(['shift length is fixed to ' num2str(ShiftLen)])\nend\n\n[FreqRes FrameNum]=size(XNEW);\n\nSpec=XNEW.*exp(j*yphase);\n\nif mod(windowLen,2) %if FreqResol is odd\n Spec=[Spec;flipud(conj(Spec(2:end,:)))];\nelse\n Spec=[Spec;flipud(conj(Spec(2:end-1,:)))];\nend\nsig=zeros((FrameNum-1)*ShiftLen+windowLen,1);\nweight=sig;\nfor i=1:FrameNum\n start=(i-1)*ShiftLen+1;\n spec=Spec(:,i);\n sig(start:start+windowLen-1)=sig(start:start+windowLen-1)+real(ifft(spec,windowLen));\nend\nReconstructedSignal=sig;\n\nfunction [NoiseFlag, SpeechFlag, NoiseCounter, Dist]=vad(signal,noise,NoiseCounter,NoiseMargin,Hangover)\n\n%[NOISEFLAG, SPEECHFLAG, NOISECOUNTER, DIST]=vad(SIGNAL,NOISE,NOISECOUNTER,NOISEMARGIN,HANGOVER)\n%Spectral Distance Voice Activity Detector\n%SIGNAL is the the current frames magnitude spectrum which is to labeld as\n%noise or speech, NOISE is noise magnitude spectrum template (estimation),\n%NOISECOUNTER is the number of imediate previous noise frames, NOISEMARGIN\n%(default 3)is the spectral distance threshold. HANGOVER ( default 8 )is\n%the number of noise segments after which the SPEECHFLAG is reset (goes to\n%zero). NOISEFLAG is set to one if the the segment is labeld as noise\n%NOISECOUNTER returns the number of previous noise segments, this value is\n%reset (to zero) whenever a speech segment is detected. DIST is the\n%spectral distance. \n%Saeed Vaseghi\n%edited by Esfandiar Zavarehei\n%Sep-04\n\nif nargin<4\n NoiseMargin=3;\nend\nif nargin<5\n Hangover=8;\nend\nif nargin<3\n NoiseCounter=0;\nend\n \nFreqResol=length(signal);\n\nSpectralDist= 20*(log10(signal)-log10(noise));\nSpectralDist(find(SpectralDist<0))=0;\n\nDist=mean(SpectralDist); \nif (Dist < NoiseMargin) \n NoiseFlag=1; \n NoiseCounter=NoiseCounter+1;\nelse\n NoiseFlag=0;\n NoiseCounter=0;\nend\n\n% Detect noise only periods and attenuate the signal \nif (NoiseCounter > Hangover) \n SpeechFlag=0; \nelse \n SpeechFlag=1; \nend \n\nfunction Seg=segment(signal,W,SP,Window)\n\n% SEGMENT chops a signal to overlapping windowed segments\n% A= SEGMENT(X,W,SP,WIN) returns a matrix which its columns are segmented\n% and windowed frames of the input one dimentional signal, X. W is the\n% number of samples per window, default value W=256. SP is the shift\n% percentage, default value SP=0.4. WIN is the window that is multiplied by\n% each segment and its length should be W. the default window is hamming\n% window.\n% 06-Sep-04\n% Esfandiar Zavarehei\n\nif nargin<3\n SP=.4;\nend\nif nargin<2\n W=256;\nend\nif nargin<4\n Window=hamming(W);\nend\nWindow=Window(:); %make it a column vector\n\nL=length(signal);\nSP=fix(W.*SP);\nN=fix((L-W)/SP +1); %number of segments\n\nIndex=(repmat(1:W,N,1)+repmat((0:(N-1))'*SP,1,W))';\nhw=repmat(Window,1,N);\nSeg=signal(Index).*hw;\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/7653-berouti-spectral-subtraction/SSBerouti79.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4676812864961495}}
{"text": "function a = le( x, y )\n\n% Disciplined convex programming information for LE (<=):\n% The left-hand side of a less-than constraint must be convex. The\n% right-hand side must be concave. Of course, real constant and \n% affine expressions are both convex and concave and can be used on\n% either side as well.\n% \n% Disciplined geometric programming information for LE (<=):\n% The left-hand side of a less-than constraint must be log-convex,\n% including positive constants, monomials, posynomials, generalized\n% posynomials, and products thereof. The right-hand side must be \n% log-concave---including positive constants, monomials, \n% reciprocals of log-convex expressions, and products thereof.\n% \n% Note that CVX does not distinguish between strict less-than (<) and\n% less-than-or-equal (<=) constraints; they are treated identically. \n% Feasible interior-point solvers tend to return points which satisfy\n% strict inequality, but not all solvers do.\n\nb = newcnstr( evalin( 'caller', 'cvx_problem', '[]' ), x, y, '<=' );\nif nargout, a = b; end\n\n% Copyright 2005-2016 CVX Research, Inc.\n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/builtins/@cvxcnst/le.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4673417347142305}}
{"text": "function err = get_cross_entropy(model, data, l)\n% cross-entropy(reconstruction error, I use L2) of each layer. This is used\n% to monitor the pretraining progress.\n% data: can be real data(for rbm) or data filelist(crbm).\n\nglobal kConv_backward kConv_backward_c kConv_forward2 kConv_forward_c;\n\nfraction = 5;\nif l == 2\n n = length(data);\n batch_size = 32; batch_num = n / batch_size;\n assert(batch_num == floor(batch_num));\n stride = model.layers{l}.stride;\n \n batch_num = floor(batch_num / fraction); % evaluate 1/fraction% of data for speed\n shuffle_index = randperm(n);\n err = 0;\n for b = 1 : batch_num\n batch_index = shuffle_index((b-1)*batch_size + 1 : b * batch_size);\n batch = read_batch(model, data(batch_index), false);\n \n hidden_presigmoid = myConvolve2(kConv_forward2, batch, model.layers{l}.w, stride, 'forward');\n hidden_presigmoid = bsxfun(@plus, hidden_presigmoid, permute(model.layers{l}.c, [2,3,4,5,1]));\n hidden_prob = sigmoid(hidden_presigmoid);\n hidden_sample = single(hidden_prob > rand(size(hidden_prob)));\n \n visible_presigmoid = myConvolve(kConv_backward, hidden_sample, model.layers{l}.w, stride, 'backward');\n visible_presigmoid = bsxfun(@plus, visible_presigmoid, permute(model.layers{l}.b, [5,1,2,3,4]));\n visible_prob = sigmoid(visible_presigmoid);\n \n this_err = batch - visible_prob;\n err = err + sum(this_err(:).^2);\n end\n err = err / (batch_num * batch_size);\nelseif strcmp(model.layers{l}.type, 'convolution')\n n = length(data);\n batch_size = 32; batch_num = n / batch_size;\n assert(batch_num == floor(batch_num));\n stride = model.layers{l}.stride;\n \n batch_num = floor(batch_num / fraction); % evaluate 1/fraction% of data for speed\n shuffle_index = randperm(n);\n err = 0;\n for b = 1 : batch_num\n batch_index = shuffle_index((b-1)*batch_size + 1 : b * batch_size);\n batch = read_batch(model, data(batch_index), false);\n batch = propagate_batch(model, batch, l);\n \n hidden_presigmoid = myConvolve(kConv_forward_c, batch, model.layers{l}.w, stride, 'forward');\n hidden_presigmoid = bsxfun(@plus, hidden_presigmoid, permute(model.layers{l}.c, [2,3,4,5,1]));\n hidden_prob = sigmoid(hidden_presigmoid);\n hidden_sample = single(hidden_prob > rand(size(hidden_prob)));\n \n visible_presigmoid = myConvolve(kConv_backward_c, hidden_sample, model.layers{l}.w, stride, 'backward');\n visible_presigmoid = bsxfun(@plus, visible_presigmoid, permute(model.layers{l}.b, [5,1,2,3,4]));\n visible_prob = sigmoid(visible_presigmoid);\n \n this_err = batch - visible_prob;\n err = err + sum(this_err(:).^2);\n end\n err = err / (batch_num * batch_size);\nelseif model.classes > 0 && l == length(model.layers) % for the last layer\n n = size(data,1);\n batch_size = 32; batch_num = n / batch_size;\n err = 0;\n temp_w = model.layers{l}.w;\n temp_w(1:model.classes,:) = temp_w(1:model.classes,:) * model.duplicate;\n for b = 1 : batch_num\n batch = data((b-1)*batch_size + 1 : b * batch_size,:,:,:,:);\n hidden_presigmoid = bsxfun(@plus, ...\n\t\t\tbatch * temp_w, model.layers{l}.c);\n\t\thidden_prob = 1 ./ ( 1 + exp(- hidden_presigmoid) );\n\t\thidden_sample = single(hidden_prob > rand(size(hidden_prob)));\n \n visible_presigmoid = bsxfun(@plus, ...\n\t\t\t\t\thidden_sample * model.layers{l}.w', model.layers{l}.b);\n visible_prob_post = sigmoid(visible_presigmoid(:,model.classes+1:end));\n temp_exponential = exp(bsxfun(@minus,visible_presigmoid(:,1:model.classes),max(visible_presigmoid(:,1:model.classes),[],2)));\n visible_prob_pre = bsxfun(@rdivide, temp_exponential, sum(temp_exponential,2)); \n \n data_err = batch(:,model.classes+1:end) - visible_prob_post;\n label_err = batch(:, 1:model.classes) - visible_prob_pre;\n err = err + model.duplicate * sum(label_err(:).^2) + sum(data_err(:).^2);\n end\n err = err / n;\nelse % for original rbm\n n = size(data,1);\n batch_size = 32; batch_num = n / batch_size;\n err = 0;\n for b = 1 : batch_num\n batch = data((b-1)*batch_size + 1 : b * batch_size,:,:,:,:);\n hidden_presigmoid = bsxfun(@plus, ...\n\t\t\tbatch * model.layers{l}.w, model.layers{l}.c);\n\t\thidden_prob = 1 ./ ( 1 + exp(- hidden_presigmoid) );\n\t\thidden_sample = single(hidden_prob > rand(size(hidden_prob)));\n \n visible_presigmoid = bsxfun(@plus, ...\n\t\t\t\t\thidden_sample * model.layers{l}.w', model.layers{l}.b);\n visible_prob = 1 ./ ( 1 + exp(-visible_presigmoid) );\n \n this_err = batch - visible_prob;\n err = err + sum(this_err(:).^2);\n end\n err = err / n;\nend\n\nfunction y = sigmoid(x)\n y = 1 ./ ( 1 + exp(-x) );\n", "meta": {"author": "zhirongw", "repo": "3DShapeNets", "sha": "6a6cc71a9231051866092c94486ae967ac533d34", "save_path": "github-repos/MATLAB/zhirongw-3DShapeNets", "path": "github-repos/MATLAB/zhirongw-3DShapeNets/3DShapeNets-6a6cc71a9231051866092c94486ae967ac533d34/generative/get_cross_entropy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430311279739, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.46724908097514034}}
{"text": "function K = sdlfmaXsdlfmaKernComputeBlock(lfmKern1, lfmKern2, t1, t2, ...\n kyy, kyv, kvy, kvv, i, j, generalConst)\n\n% SDLFMAXSDLFMAKERNCOMPUTEBLOCK Computes SDLFM kernel matrix for block i,j\n% FORMAT\n% DESC computes the kernel matrix for the SDLFM kernel function in the\n% block specified at indeces i,j. It assumes the computation for functions\n% that describe accelerations (acceleration 1 and acceleration 2).\n% ARG lfmKern1 : structure containing parameters for the system 1\n% ARG lfmKern2 : structure containing parameters for the system 2\n% ARG t1 : times at which the system 1 is evaluated\n% ARG t2 : times at which the system 2 is evaluated\n% ARG kyy : covariance for the initial conditions between position 1 and\n% position 2 at block i,j\n% ARG kyv : covariance for the initial conditions between position 1 and\n% velocity 2 at block i,j\n% ARG kvy : covariance for the initial conditions between velocity 1 and\n% position 2 at block i,j\n% ARG kvv : covariance for the initial conditions between velocity 1 and\n% velocity 2 at block i,j\n% ARG i : interval to be evaluated for system 1\n% ARG j : interval to be evaluated for system 2\n% ARG generalConstant : constants evaluated with sdlfmKernComputeConstant.m\n% RETURN K : the kernel matrix portion of block i,j\n%\n% COPYRIGHT : Mauricio A. Alvarez, 2010.\n\n% KERN\n\nif nargin<11\n j = i;\n generalConst = [];\nend\n\na1 = sdlfmaMeanCompute(lfmKern1(1), t1, 'Pos');\nb1 = sdlfmaMeanCompute(lfmKern1(1), t1, 'Vel');\na2 = sdlfmaMeanCompute(lfmKern2(1), t2, 'Pos');\nb2 = sdlfmaMeanCompute(lfmKern2(1), t2, 'Vel');\n\nK = kyy*a1*a2.' + kyv*a1*b2.' + kvy*b1*a2.' + kvv*b1*b2.';\n\nif i==j\n for k=1:length(lfmKern1)\n K = K + lfmaXlfmaKernCompute(lfmKern1(k), lfmKern2(k), t1, t2);\n end\nelse \n if i>j\n AccelPos = zeros(1, length(t2));\n AccelVel = zeros(1, length(t2));\n for k=1:length(lfmKern1)\n AccelPos = AccelPos + lfmaXlfmKernCompute(lfmKern2(k), lfmKern1(k), t2, lfmKern2(k).limit).'; \n AccelVel = AccelVel + lfmaXlfmvKernCompute(lfmKern2(k), lfmKern1(k), t2, lfmKern2(k).limit).';\n end\n if isempty(generalConst{i,j})\n K = K + a1*AccelPos + b1*AccelVel; \n else\n K = K + (generalConst{i,j}(1,1)*a1 + generalConst{i,j}(2,1)*b1)*AccelPos + ...\n (generalConst{i,j}(1,2)*a1 + generalConst{i,j}(2,2)*b1)*AccelVel; \n end \n else\n AccelPos = zeros(length(t1),1);\n AccelVel = zeros(length(t1),1);\n for k =1:length(lfmKern1)\n AccelPos = AccelPos + lfmaXlfmKernCompute(lfmKern1(k), lfmKern2(k), t1, lfmKern1(k).limit);\n AccelVel = AccelVel + lfmaXlfmvKernCompute(lfmKern1(k), lfmKern2(k), t1, lfmKern1(k).limit);\n end\n if isempty(generalConst{i,j})\n K = K + AccelPos*a2.' + AccelVel*b2.';\n else\n K = K + AccelPos*(generalConst{i,j}(1,1)*a2.' + generalConst{i,j}(2,1)*b2.') + ...\n AccelVel*(generalConst{i,j}(1,2)*a2.' + generalConst{i,j}(2,2)*b2.');\n end\n end\nend\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/sdlfmaXsdlfmaKernComputeBlock.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4672183863314467}}
{"text": "function C = train_RSLDAshrink(xTr, yTr, sublab, varargin)\n% TRAIN_RSLDASHRINK - Relevance Subclass LDA with mean shrinkage to subclasses and automatic covariance shrinkage\n%\n%Synopsis:\n% C = train_RLSDAshrink(XTR, YTR, SUBLABELS)\n% C = train_RLSDAshrink(XTR, YTR, SUBLABELS, OPTS)\n%\n%Arguments:\n% XTR: DOUBLE [NxM] - Data matrix, with N feature dimensions, and M training points/examples. \n% YTR: INT [CxM] - Class membership labels of points in X_TR. C by M matrix of training\n% labels, with C representing the number of classes and M the number of training examples/points.\n% Y_TR(i,j)==1 if the point j belongs to class i.\n% SUBLABELS[Mx1] - Subclass membership for each data point\n% OPT: PROPLIST - Structure or property/value list of optional\n% properties. \n% 'Whitening' - BOOL (default 1): If true, mean shrinkage is performed\n% on whitened data. This is important for ERP data, as it has a\n% highly skewed eigenspectrum and the mean shrinkage is dominated by\n% directions of high variance.\n% 'ReturnRegularizationProfile' - BOOL (default 1): If true, returns regularization\n% profile as matrix MxM for both classes, with M being the number of\n% unique subclasses. \n%\n%Returns: \n% C: STRUCT - Trained classifier structure, with the subclassifier\n% hyperplanes given by fields C.subC{k}.w and C.subC{k}.b for each\n% subclass k\n% \n% C includes the fields:\n% 'sublab_unique' : unique subclass labels\n% 'pattern' : pattern (i.e. mu2-mu1) of each subclassifier\n% 'subC' : LDA classifiers (w and b) for each subclass\n% 'regularization_list': list of regularization weights for each class\n% and subclass, stacked for both classes \n% 'regularization_profile' : (optional) regularization profile as matrix\n%\n%Description:\n% TRAIN_RLSDA trains a Relevance Subclass LDA classifier on data X with \n% class labels given in LABELS and Subclass labels given in SUBLABELS. \n% The mean shrinkage parameter is selected by sotm and the covariance\n% shrinkage parameter is selected by the function clsutil_shrinkage.\n%\n%\n%Example 1:\n%%perform standard ERP analysis (loads data, subsampling and divide into epochs)\n% demo_analysis_ERPs\n% \n% \n%%only the last digit codes for the stimulus identity\n% subclass_lab = mod(epo.event.desc, 10);\n% \n%%extract features from the epochs by subsampling\n% ivals = [140:30:260 300:50:600; 170:30:300 350:50:650]';\n%%create features\n% fv = proc_flaten(proc_jumpingMeans(epo, ivals));\n%%train RSLDA\n% C = train_RSLDAshrink(fv.x, fv.y, subclass_lab);\n% \n%%Example 2: compare RSLDAshrink with LDAshrink\n% nfolds = 4;\n% [divTr, divTe] = sample_KFold(epo.y, nfolds);\n% loss_list_RSLDA = nan(1, nfolds);loss_list_RLDA = loss_list_RSLDA;\n% for kk = 1:nfolds\n% %generate training and test features\n% fvTr = proc_flaten(proc_jumpingMeans(proc_selectEpochs(epo, divTr{1}{kk}), ivals));\n% fvTe = proc_flaten(proc_jumpingMeans(proc_selectEpochs(epo, divTe{1}{kk}), ivals)); \n% %train cls on traing data\n% C_RSLDA = train_RSLDAshrink(fvTr.x, fvTr.y, subclass_lab(divTr{1}{kk}));\n% C_LDA = train_RLDAshrink(fvTr.x, fvTr.y);\n% %apply RSLDA on the test data\n% out_RSLDA = apply_RSLDAshrink(C_RSLDA, fvTe.x, subclass_lab(divTe{1}{kk}));\n% out_RLDA = apply_separatingHyperplane(C_LDA , fvTe.x);\n% \n% loss_list_RSLDA(kk) = loss_rocArea(fvTe.y,out_RSLDA);\n% loss_list_RLDA(kk) = loss_rocArea(fvTe.y,out_RLDA);\n% end\n%%compare loss for each fold\n% loss_list_RSLDA - loss_list_RLDA\n%%plot regularization profile for the last fold\n% figure, imagesc(C_RSLDA.regularization_profile{2})\n% \n%See also:\n% APPLY_SEPARATINGHYPERPLANE, CLSUTIL_MEANMTS, CLSUTIL_SHRINKAGE, TRAIN_RLDAshrink\n% TRAIN_LDA\n\n% 02-2015 Johannes Hoehne\nif size(yTr,1)==1, yTr= [yTr<0; yTr>0]; end\nyTr = logical(yTr);\nnClasses= size(yTr,1);\nprops= {'Whitening' 1 'BOOL'\n 'ReturnRegularizationProfile' 1 'BOOL'\n\t 'Prior' ones(nClasses, 1)/nClasses 'DOUBLE[- 1]'\n };\n \n% get props list of the subfunction\nprops_shrinkage= clsutil_meanMTS;\n\nif nargin==0,\n C= opt_catProps(props, props_shrinkage); \n return\nend\n\nopt= opt_proplistToStruct(varargin{:});\n[opt, isdefault]= opt_setDefaults(opt, props);\nopt_checkProplist(opt, props, props_shrinkage);\n\n% preprocessing of input\nyTr = logical(yTr);\nif size(sublab,2)==1 && size(sublab,1)>1\n sublab = sublab'; %sublab is expected to be a row-vector of \nend\n\n% empirical class priors as an option, if nan (I leave 1/nClasses as default)\nif isnan(opt.Prior)\n opt.Prior = sum(yTr, 2)/sum(sum(yTr));\nend\n\nC = {};\n\n%start func\nC.sublab_unique = unique(sublab);\n\n% get meanfree X (without considereing subclass labels)\n% compute Cov matrix\nif opt.Whitening\n M1 = mean(xTr(:, yTr(1,:)),2);\n M2 = mean(xTr(:,yTr(2,:)),2);\n M = repmat(M1, 1, size(yTr,2));\n M(:, yTr(2,:)) = repmat(M2, 1, sum(yTr(2,:)));\n Xmeanfree_dum = xTr - M;\n globalCov = clsutil_shrinkage(Xmeanfree_dum);\n [ Eigvec, Eigval ] = eig(globalCov);\n A_feat2white = Eigvec * (Eigval^-.5) * Eigvec;\n A_white2feat = inv(A_feat2white); \nelse %do not perform whitening \n% --> this leads to a poor performance for data with a skewed eigen spectrum\n A_feat2white = eye(size(xTr,2));\n A_white2feat = eye(size(xTr,2));\nend\nXwhite = A_feat2white' * xTr; \n\n\nkk = 0;\nM = nan(size(xTr)); %saves the classwise-shrinked means\nfor my_sublab = C.sublab_unique\n kk = kk+1;\n \n for ix_c = 1:nClasses %for each class\n %% estimate class means \n shrink_dat = {}; %initialize shrindat container\n shrink_dat.X = {Xwhite(:,((sublab == my_sublab) & yTr(ix_c,:)))' };\n\n %there might be sublabels without epoch in calss ix_c -> skip them as sublabel\n sublab_missing = []; \n for sublab_this = setdiff(C.sublab_unique, my_sublab)\n if sum((((sublab == sublab_this)) & yTr(ix_c,:)))>0\n shrink_dat.X{end+1} = Xwhite(:,(((sublab == sublab_this)) & yTr(ix_c,:)))';\n else\n sublab_missing(end+1) = sublab_this; %(only important for special cases)\n end\n end\n \n %PERFORM MULTI-TARGET SHINKAGE FOR CLASS 1\n % sublab=k & T sublab~=k & T\n [Mest(ix_c,:), gamma_tmp] = clsutil_meanMTS(shrink_dat, 'convex', 1, 'variablewise', 0, 'conservative', 1);\n\n % (only important for special cases) deal with the arrangement of missing subclass labels \n for xx = sublab_missing %put missing subclasses as zeros in gamma to maintain the correct size\n if xx>=length(gamma_tmp)+1, gamma_tmp = [gamma_tmp; 0]; %the last one was missing\n else gamma_tmp = [gamma_tmp(1:xx-1); 0; gamma_tmp(xx:end)]; %another one was missing\n end\n end \n gamma(ix_c,:) = gamma_tmp;\n \n %transform the Means back into feature space\n Mest_origSpace(ix_c,:) = A_white2feat' * Mest(ix_c,:)';\n \n % for each datapoint, save the dcorresponding subclass mean\n % --> build up Mean-template M with Target and NonTarget template \n M(:, find(yTr(ix_c,:) & sublab == my_sublab)) = repmat(Mest_origSpace(ix_c,:)', 1, length(find(yTr(ix_c,:) & sublab == my_sublab)));\n \n %save the mean estimators as we need them later to compute the cls\n list_M{kk}(ix_c,:) = Mest_origSpace(ix_c,:);\n end \n C.regularization_list(:,kk) = gamma(:);\nend\n\n\n%% estimate Cov with optimized means\nXmeanfree = xTr - M;\nCest = clsutil_shrinkage(Xmeanfree);\nC_invcov = pinv(Cest);\n\n%% finalize cls\nkk = 0;\nfor my_sublab = C.sublab_unique\n kk = kk+1;\n if nClasses>2\n C.subC{kk} = comp_reg_cls(C_invcov, list_M{kk}', opt.Prior) ; \n else\n % get the Target and NonTartget Means for each subclass\n M1est = list_M{kk}(1,:)';\n M2est = list_M{kk}(2,:)'; \n C.pattern(:,kk) = M2est - M1est;\n C.subC{kk} = comp_reg_cls2(C_invcov, M1est, M2est);\n end\n if ~isfinite(C.subC{kk}.b)\n error('sth went wrong')\n end\nend\n\nif opt.ReturnRegularizationProfile\n %reorganize the regularization_list such that we can interpret them\n% the regul parameters are reordered such that (dat)\n% l1 l2\n% l3 l4\n% l5 l6 \n% becomes a square Matrix A, which is better to interpret:\n% (1-l1-l2) l l\n% l3 (1-l3-l4) l4\n% l5 l6 (1-l5-l6)\n for i_class = 1:nClasses %for both classes \n nPara = size(C.regularization_list,1)/nClasses;\n dat = C.regularization_list((i_class-1)*nPara+1 : (i_class)*nPara,:)';\n A = zeros(size(dat,1));\n A(logical(eye(size(A)))) = 1-sum(dat,2);\n d = dat';\n A(~logical(eye(size(A)))) = d(:);\n C.regularization_profile{i_class} = A';\n end\nend\n\nreturn\n\nend\n\n\nfunction C = comp_reg_cls2(C_invcov, M1, M2)\nC = [];\nC.w= C_invcov*(M2 - M1);\nC.b= -0.5*C.w'*(M2 + M1);\nend\n\n\nfunction C = comp_reg_cls(C_invcov, C_mean, Prior)\nC = [];\nC.w= C_invcov*C_mean;\nC.b= -0.5*sum(C_mean.*C.w,1)' + log(Prior);\nend\n", "meta": {"author": "bbci", "repo": "bbci_public", "sha": "2e6fe9481537dcfee702e74544191dcf737f02ce", "save_path": "github-repos/MATLAB/bbci-bbci_public", "path": "github-repos/MATLAB/bbci-bbci_public/bbci_public-2e6fe9481537dcfee702e74544191dcf737f02ce/classification/train_RSLDAshrink.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.4671756526984476}}
{"text": "function [confusion_matrix, classes]=cosmo_confusion_matrix(ds, varargin)\n% Returns a confusion matrix\n%\n% Usage 1: mx=cosmo_confusion_matrix(ds)\n% Usage 2: mx=cosmo_confusion_matrix(targets, predicted)\n%\n%\n% Inputs:\n% targets Nx1 targets for N samples, or a dataset struct with\n% .sa.targets\n% predicted NxM predicted labels (from a classifier), for N samples and\n% M predictions per set of samples\n%\n% Returns:\n% mx PxPxM matrix assuming there are P unique targets.\n% mx(i,j,k)==c means that the i-th target class was classified\n% as the j-th target class c times for the k-th set of\n% samples.\n% classes Px1 class labels.\n%\n% Example:\n% ds=cosmo_synthetic_dataset('ntargets',3,'nchunks',4);\n% args=struct();\n% args.partitions=cosmo_nchoosek_partitioner(ds,1);\n% args.output='winner_predictions';\n% args.classifier=@cosmo_classify_lda;\n% pred_ds=cosmo_crossvalidation_measure(ds,args);\n% confusion=cosmo_confusion_matrix(pred_ds.sa.targets,pred_ds.samples);\n% cosmo_disp(confusion)\n% %|| [ 3 0 1\n% %|| 0 3 1\n% %|| 1 0 3 ]\n% confusion_alt=cosmo_confusion_matrix(pred_ds);\n% isequal(confusion,confusion_alt)\n% %|| true\n% %\n% % run a searchlight with tiny radius of 1 voxel (3 is more common)\n% nbrhood=cosmo_spherical_neighborhood(ds,'radius',1,'progress',false);\n% measure=@cosmo_crossvalidation_measure;\n% sl_ds=cosmo_searchlight(ds,nbrhood,measure,args,'progress',false);\n% %\n% % the confusion matrix is 3x3x6, that is 6 3x3 confusion\n% % matrices. Here the dataset is passed directly\n% sl_confusion=cosmo_confusion_matrix(sl_ds);\n% cosmo_disp(sl_confusion)\n% %|| @3x3x6\n% %|| (:,:,1) = [ 4 0 0\n% %|| 0 4 0\n% %|| 0 1 3 ]\n% %|| (:,:,2) = [ 4 0 0\n% %|| 0 4 0\n% %|| 0 1 3 ]\n% %|| (:,:,3) = [ 2 1 1\n% %|| 0 4 0\n% %|| 1 0 3 ]\n% %|| (:,:,4) = [ 4 0 0\n% %|| 0 3 1\n% %|| 0 1 3 ]\n% %|| (:,:,5) = [ 3 0 1\n% %|| 0 4 0\n% %|| 1 1 2 ]\n% %|| (:,:,6) = [ 3 0 1\n% %|| 0 4 0\n% %|| 1 1 2 ]\n%\n% % using samples that are not predictions gives an error\n% ds=cosmo_synthetic_dataset('ntargets',3,'nchunks',4);\n% confusion=cosmo_confusion_matrix(ds)\n% %|| error('72 predictions mismatch targets, first is (1,1)=2.211999e+00')\n%\n% Notes:\n% - this function counts the number of times each sample was classified\n% as any target\n%\n% # For CoSMoMVPA's copyright information and license terms, #\n% # see the COPYING file distributed with CoSMoMVPA. #\n\n [targets,predicted]=get_data(ds,varargin{:});\n\n % see which classes there are\n [class_indices,classes]=cosmo_index_unique(targets);\n nclasses=numel(class_indices);\n\n % allocate space for output\n nfeatures=size(predicted,2);\n confusion_matrix=zeros([nclasses,nclasses,nfeatures]);\n\n % keep track which predicted samples were in targets\n visited=false(size(predicted));\n % >@@>\n for k=1:nclasses\n % rows for k-th class\n idxs=class_indices{k};\n for j=1:nclasses\n match_msk=bsxfun(@eq,classes(j),predicted(idxs,:));\n confusion_matrix(k,j,:)=sum(match_msk,1);\n visited(idxs,:)=visited(idxs,:) | match_msk;\n end\n end\n\n % <@@<\n\n missing=~(visited | isnan(predicted));\n if any(missing(:))\n n=sum(missing(:));\n [i,j]=find(missing,1);\n error(['%d predictions mismatch targets, '...\n 'first is (%d,%d)=%d'],n,i,j,predicted(i,j));\n end\n\n\n\n\nfunction [targets,predicted]=get_data(ds, predicted)\n has_predicted=nargin>=2;\n is_ds=isstruct(ds);\n if is_ds\n if has_predicted\n error('Need exactly one argument when input is struct');\n end\n % input is a dataset\n cosmo_isfield(ds,'sa.targets',true);\n cosmo_isfield(ds,'samples',true);\n\n predicted=ds.samples;\n targets=ds.sa.targets;\n elseif isnumeric(ds)\n if ~has_predicted\n error('Need two arguments when first argument is numeric');\n end\n targets=ds;\n else\n error('Illegal input: need struct or numeric vector');\n end\n\n if ~isvector(targets) || size(targets,2)~=1\n error('targets must be column vector');\n end\n\n if numel(size(predicted))~=2\n error('predictions must be matrix');\n end\n\n nsamples=numel(targets);\n if size(predicted,1)~=nsamples\n error(['Size mismatch: predictions has %d values on first '...\n 'dimension, but targets has %d values'],...\n size(predicted,1),nsamples);\n end\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_confusion_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4671266161898023}}
{"text": "function p=drex_invlogit(a)\n%DREX subfunction \n%Written by Issam El Naqa 2003-2005\n%Extracted for generalized use 2005, AJH\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the DREES development team.\n% \n% This file is part of the Dose Response Explorer System (DREES).\n% \n% DREES development has been led by: Issam El Naqa, Aditya Apte, Gita Suneja, and Joseph O. Deasy.\n% \n% DREES has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% DREES is distributed under the terms of the Lesser GNU Public License. \n% \n% This version of DREES 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% DREES is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with DREES. If not, see .\n\np = 1 ./ (1 + exp(-a));\n\nreturn", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/MultivariableModeling/LogisticRegression/drxlr_invlogit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.467019999307424}}
{"text": "function x = proxTVSquare(x,lambda,alpha,varargin)\n\n[n,m] = size(x);\nlambda = alpha * lambda; % only the product matters\n\n% apply proxTV horizontally\nmMax = 2*floor((m+1)/2)-1; % round down to an odd number\n[x(:,2:2:mMax),x(:,3:2:mMax)] = proxTV(x(:,2:2:mMax),x(:,3:2:mMax),lambda,varargin{:});\n\nmMax = 2*floor(m/2); % round down to an even number\n[x(:,1:2:mMax),x(:,2:2:mMax)] = proxTV(x(:,1:2:mMax),x(:,2:2:mMax),lambda,varargin{:});\n\n% apply proxTV vertically\nnMax = 2*floor((n+1)/2)-1; % round down to an odd number\n[x(2:2:nMax,:),x(3:2:nMax,:)] = proxTV(x(2:2:nMax,:),x(3:2:nMax,:),lambda,varargin{:});\n\nnMax = 2*floor(n/2); % round down to an even number\n[x(1:2:nMax,:),x(2:2:nMax,:)] = proxTV(x(1:2:nMax,:),x(2:2:nMax,:),lambda,varargin{:});\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/EBSDAnalysis/EBSDSmoothing/@l1TVFilter/private/proxTVSquare.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.46698050862218626}}
{"text": "function box = mergeBoxes3d(box1, box2)\n%MERGEBOXES3D Merge 3D boxes, by computing their greatest extent.\n%\n% BOX = mergeBoxes3d(BOX1, BOX2);\n%\n% Example\n% box1 = [5 20 5 30 10 50];\n% box2 = [0 15 0 15 0 20];\n% mergeBoxes3d(box1, box2)\n% ans = \n% 0 20 0 30 0 50\n%\n%\n% See also\n% boxes3d, drawBox3d, intersectBoxes3d\n%\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2010-07-26, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2010 INRA - Cepia Software Platform.\n\n% unify sizes of data\nif size(box1,1) == 1\n box1 = repmat(box1, size(box2,1), 1);\nelseif size(box2, 1) == 1\n box2 = repmat(box2, size(box1,1), 1);\nelseif size(box1,1) ~= size(box2,1)\n error('Bad size for inputs');\nend\n\n% compute extreme coords\nmini = min(box1(:,1:2:end), box2(:,1:2:end));\nmaxi = max(box1(:,2:2:end), box2(:,2:2:end));\n\n% concatenate result into a new box structure\nbox = [mini(:,1) maxi(:,1) mini(:,2) maxi(:,2) mini(:,3) maxi(:,3)];\n\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_geom3d/geom3d/mergeBoxes3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.4668306059171906}}
{"text": "function M = femMultiplyCell(varargin)\n%+========================================================================+\n%| |\n%| OPENFEM - LIBRARY FOR FINITE ELEMENT METHOD |\n%| openFem is part of the GYPSILAB toolbox for Matlab |\n%| |\n%| COPYRIGHT : Matthieu Aussal & Francois Alouges (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%| francois.alouges@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 : femMultiplyCell.m |\n%| # | VERSION : 0.40 |\n%| _#_ | AUTHOR(S) : Matthieu Aussal & François Alouges |\n%| ( # ) | CREATION : 14.03.2017 |\n%| / 0 \\ | LAST MODIF : 14.03.2018 |\n%| ( === ) | SYNOPSIS : Multiply finite elements cells |\n%| `---' | |\n%+========================================================================+\n\nif (nargin == 1)\n M = varargin{1};\n \nelseif (nargin == 2)\n A = varargin{1};\n B = varargin{2};\n \n if iscell(A) && iscell(B)\n M = A{1} * B{1} + ...\n A{2} * B{2} + ...\n A{3} * B{3} ;\n \n elseif iscell(A) && ~iscell(B)\n M{1} = A{1} * B ;\n M{2} = A{2} * B ;\n M{3} = A{3} * B ;\n \n elseif ~iscell(A) && iscell(B)\n M{1} = A * B{1} ;\n M{2} = A * B{2} ;\n M{3} = A * B{3} ;\n \n elseif ~iscell(A) && ~iscell(B)\n M = A * B;\n \n else\n error('femMultiplyCell.m : unavailable case')\n end\n \nelseif (nargin == 3)\n A = varargin{1};\n B = varargin{2};\n C = varargin{3};\n \n if iscell(A) && iscell(B) && iscell(C)\n M = A{1} * B{2} * C{3} - ...\n A{1} * B{3} * C{2} + ...\n A{2} * B{3} * C{1} - ...\n A{2} * B{1} * C{3} + ...\n A{3} * B{1} * C{2} - ...\n A{3} * B{2} * C{1} ;\n \n elseif iscell(A) && iscell(B) && ~iscell(C)\n M = ( A{1} * B{1} + ...\n A{2} * B{2} + ...\n A{3} * B{3} ) * C;\n \n elseif iscell(A) && ~iscell(B) && iscell(C)\n M = A{1} * B * C{1} + ...\n A{2} * B * C{2} + ...\n A{3} * B * C{3} ;\n \n elseif ~iscell(A) && iscell(B) && iscell(C)\n M = A * ( B{1} * C{1} + ...\n B{2} * C{2} + ...\n B{3} * C{3} );\n \n elseif ~iscell(A) && ~iscell(B) && iscell(C)\n M{1} = A * B * C{1};\n M{2} = A * B * C{2};\n M{3} = A * B * C{3};\n \n elseif ~iscell(A) && iscell(B) && ~iscell(C)\n M{1} = A * B{1} * C;\n M{2} = A * B{2} * C;\n M{3} = A * B{3} * C;\n \n elseif iscell(A) && ~iscell(B) && ~iscell(C)\n M{1} = A{1} * B * C;\n M{2} = A{2} * B * C;\n M{3} = A{3} * B * C;\n \n elseif ~iscell(A) && ~iscell(B) && ~iscell(C)\n M = A * B * C;\n else\n error('femMultiplyCell.m : unavailable case')\n end\n \nelse\n error('femMultiplyCell.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/openFem/femMultiplyCell.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4668058508323266}}
{"text": "function [mResult, fMls, fMc, fMu, fSigma, mDatPredBest, vPredBest] = plot_McEMR(mCatalog, fBinning)\n% Same as calc_McCdfnormal with plotting the fitting steps and the final result\n%\n% [mResult, fMls, fMc, fMu, fSigma, mDatPredBest, vPredBest] = plot_McEMR(mCatalog, fBinning);\n% -----------------------------------------------------------------------------------------------------\n%\n% Incoming variables:\n% mCatalog : EQ catalog\n% fBinning : Binning interval, usually 0.1\n%\n% Outgoing variables:\n% mResult : Solution matrix including\n% vProbability: maximum likelihood score\n% vMc : Mc values\n% vX_res : mu (of normal CDF), sigma (of normal CDF), residuum, exitflag\n% vNmaxBest : Number of events in lowest magnitude bin considered complete\n% vABValue : a and b-value\n% fMls : likelihood score --> best Mc\n% fMc : Best estimated magnitude of completeness\n% mDatPredBest : Matrix of non-cumulative FMD [Prediction, magnitudes, original distribution]\n% vPredBest : Matrix of non-cumulative FMD below Mc [magnitude, prediction, uncertainty of prediction]\n%\n% J. Woessner: jochen.woessner@sed.ethz.ch\n% updated: 29.09.04\n\n% Initialize\nvProbability = [];\nvMc = [];\nvABValue =[];\nmFitRes = [];\nvX_res = [];\nvNCumTmp = [];\nmDataPred = [];\nvPredBest = [];\nvDeltaBest = [];\nvX_res = [];\nvNmaxBest = [];\nmResult=[];\nmDatPredBest = [];\n\n% Determine exact time period\nfPeriod1 = max(mCatalog.Date) - min(mCatalog.Date);\n\n% Determine max. and min. magnitude\nfMaxMag = ceil(10 * max(mCatalog.Magnitude)) / 10;\n\n% Set starting value for Mc loop and LSQ fitting procedure\nfMcTry= calc_Mc(mCatalog, McMethods.MaxCurvature);\nfSmu = abs(fMcTry/2);\nfSSigma = abs(fMcTry/4);\nif (fSmu > 1)\n fSmu = fMcTry/10;\n fSSigma = fMcTry/20;\nend\nfMcBound = fMcTry;\n\n% Calculate FMD for original catalog\n[vFMDorg, vNonCFMDorg, fmdbins] = calc_FMD(mCatalog.Magnitude);\n% convert answer back to this file's expectations...\nvFMDorg = [fmdbins'; vFMDorg'] % as rows\nvNonCFMDorg = [fmdbins'; vNonCFMDorg'];\n\nfMinMag = min(vNonCFMDorg(1,:));\n\n%% Shift to positive values\n% if fMinMag ~= 0\n% fMcBound = fMcTry-fMinMag;\n% end\n% Loop over Mc-values\nfor fMc = fMcBound-0.4:0.1:fMcBound+0.8\n fMc = round(fMc, -1);\n vFMD = vFMDorg;\n vNonCFMD = vNonCFMDorg;\n vNonCFMD = fliplr(vNonCFMD);\n % Select magnitudes to calculate b- anda-value\n vSel = mCatalog.Magnitude > fMc-fBinning/2;\n if sum(vSel) >= 20\n [ fBValue, fStdDev, fAValue] = calc_bmemag(mCatalog.Magnitude(vSel), fBinning);\n % Normalize to time period\n vFMD(2,:) = vFMD(2,:)./fPeriod1; % ceil taken out\n vNonCFMD(2,:) = vNonCFMD(2,:)./fPeriod1; % ceil removed\n % Compute quantity of earthquakes by power law\n fMaxMagFMD = max(vNonCFMD(1,:));\n fMinMagFMD = min(vNonCFMD(1,:));\n vMstep = [fMinMagFMD:0.1:fMaxMagFMD];\n vNCum = 10.^(fAValue-fBValue.*vMstep); % Cumulative number\n\n % Compute non-cumulative numbers vN\n fNCumTmp = 10^(fAValue-fBValue*(fMaxMagFMD+0.1));\n vNCumTmp = [vNCum fNCumTmp ];\n vN = abs(diff(vNCumTmp));\n\n % Normalize vN\n vN = vN./fPeriod1;\n % Data selection\n % mData = Non-cumulative FMD values from GR-law and original data\n mData = [vN' vNonCFMD'];\n vSel = (mData(:,2) >= fMc);\n mDataTest = mData(~vSel,:);\n mDataTmp = mData.subset(vSel);\n% % Check for zeros in observed data\n vSelCheck = (mDataTest(:,3) == 0);\n mDataTest = mDataTest(~vSelCheck,:);\n % Choices of normalization\n fNmax = mDataTmp(1,3); % Frequency of events in Mc bin\n %fNmax = max(mDataTest(:,3)); % Use maximum frequency of events in bins below Mc\n %fNmax = mDataTest(length(mDataTest(:,1)),3); % Use frequency of events at bin Mc-0.1 -> best fit\n if (~isempty(isempty(fNmax)) && ~isnan(fNmax) & fNmax ~= 0 & length(mDataTest(:,1)) > 4)\n mDataTest(:,3) = mDataTest(:,3)/fNmax; % Normalize datavalues for fitting with CDF\n % Move to M=0 to fit with lsq-algorithm\n fMinMagTmp = min(mDataTest(:,2));\n mDataTest(:,2) = mDataTest(:,2)-fMinMagTmp;\n % Curve fitting: Non cumulative part below Mc\n options = optimset;\n %options = optimset('Display','off','Tolfun',1e-7,'TolX',0.0001,'MaxFunEvals', 100000,'MaxIter',10000);\n options = optimset('Display','off','Tolfun',1e-5,'TolX',0.001,'MaxFunEvals', 1000,'MaxIter',1000);\n [vX, resnorm, resid, exitflag, output, lambda, jacobian]=lsqcurvefit(@calc_normalCDF,[fSmu fSSigma], mDataTest(:,2), mDataTest(:,3),[],[],options);\n mDataTest(:,1) = normcdf(mDataTest(:,2), vX(1), vX(2))*fNmax;\n if (length(mDataTest(:,2)) > length(vX(1,:)))\n %% Confidence interval determination\n % vPred : Predicted values of lognormal function\n % vPred+-delta : 95% confidence level of true values\n [vPred,delta] = nlpredci(@calc_normalCDF,mDataTest(:,2),vX, resid, jacobian);\n else\n vPred = NaN;\n delta = NaN;\n end % END: This section is due for errors produced with datasets less long than amount of parameters in vX\n % Results of fitting procedure\n mFitRes = [mFitRes; vX resnorm exitflag];\n % Move back to original magnitudes\n mDataTest(:,2) = mDataTest(:,2)+fMinMagTmp;\n % Set data together\n mDataTest(:,3) = mDataTest(:,3)*fNmax;\n mDataPred = [mDataTest; mDataTmp];\n % Denormalize to calculate probabilities\n mDataPred(:,1) = round(mDataPred(:,1).*fPeriod1);\n mDataPred(:,3) = mDataPred(:,3).*fPeriod1;\n vProb_ = calc_log10poisspdf2(mDataPred(:,3), mDataPred(:,1)); % Non-cumulative\n\n % Sum the probabilities\n fProbability = (-1) * sum(vProb_);\n vProbability = [vProbability; fProbability];\n % Move magnitude back\n mDataPred(:,2) = mDataPred(:,2)+fMinMag;\n vMc = [vMc; fMc];\n vABValue = [vABValue; fAValue fBValue];\n\n % Keep values\n vDeltaBest = [vDeltaBest; delta];\n vX_res = [vX_res; vX resnorm exitflag];\n vNmaxBest = [vNmaxBest; fNmax];\n\n % Keep best fitting model\n if (fProbability == min(vProbability))\n vDeltaBest = delta;\n vPredBest = [mDataTest(:,2) vPred*fNmax*fPeriod1 delta*fNmax*fPeriod1]; % Gives back uncertainty\n %fMc+fMinMag : Test procedure\n mDatPredBest = [mDataPred];\n end\n else\n %disp('Not enough data');\n % Setting values\n fProbability = NaN;\n fMc = NaN;\n vX(1) = NaN;\n vX(2) = NaN;\n resnorm = NaN;\n exitflag = NaN;\n delta = NaN;\n vPred = [NaN NaN NaN];\n fNmax = NaN;\n fAValue = NaN;\n fBValue = NaN;\n vProbability = [vProbability; fProbability];\n vMc = [vMc; fMc];\n vX_res = [vX_res; vX resnorm exitflag];\n% vDeltaBest = [vDeltaBest; NaN];\n% vPredBest = [vPredBest; NaN NaN NaN];\n vNmaxBest = [vNmaxBest; fNmax];\n vABValue = [vABValue; fAValue fBValue];\n end\n end\n\n\n % Clear variables\n vNCumTmp = [];\n mModelDat = [];\n vNCum = [];\n vSel = [];\n mDataTest = [];\n mDataPred = [];\nend % END of FOR fMc\n% Result matrix\nmResult = [mResult; vProbability vMc vX_res vNmaxBest vABValue];\n\n% Find best estimate, excluding the case of mResult all NAN\nif ~isempty(min(mResult))\n if ~isnan(min(mResult(:,1)))\n vSel = find(min(mResult(:,1)) == mResult(:,1));\n fMc = min(mResult(vSel,2));\n fMls = min(mResult(vSel,1));\n fMu = min(mResult(vSel,3));\n fSigma = min(mResult(vSel,4));\n fAvalue = min(mResult(vSel,8));\n fBvalue = min(mResult(vSel,9));\n else\n fMc = NaN;\n fMls = NaN;\n fMu = NaN;\n fSigma = NaN;\n fAvalue = NaN;\n fBvalue = NaN;\n end\nelse\n fMc = NaN;\n fMls = NaN;\n fMu = NaN;\n fSigma = NaN;\n fAvalue = NaN;\n fBvalue = NaN;\nend\n\ntry % Try catch block used as mDatPreBest not always calculated\n % Reconstruct vector of magnitudes from model for Period 1\n vMag = [];\n mModelFMD = [round(mDatPredBest(:,1)) mDatPredBest(:,2)];\n vSel = (mModelFMD(:,1) ~= 0); % Remove bins with zero frequency of zero events\n mData = mModelFMD(vSel,:);\n for nCnt=1:length(mData(:,1))\n fM = repmat(mData(nCnt,2),mData(nCnt,1),1);\n vMag = [vMag; fM];\n end\n % Calculate KS-Test\n [bH,fPval,fKsstat] = kstest2(roundn(mCatalog.Magnitude,-1),roundn(vMag,-1),0.05,0)\ncatch\n bH = NaN;\n fPval = NaN;\n fKsstat = NaN;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Plot result\n\n% Plot best fitting CDF vs. magnitude\nfigure_w_normalized_uicontrolunits('tag','best_cdfit','Name','CDF fit','Units','normalized','Nextplot','add',...\n 'Numbertitle','off','visible','on');\np1=plot(mDatPredBest(:,2), mDatPredBest(:,3),'Marker','d','MarkerEdgeColor',[0 0 0],'MarkerFaceColor',[0.4 0.4 0.4],'Markersize',8,'Linewidth',2,'Linestyle','none');\nset(gca,'NextPlot','add');\np2=plot(mDatPredBest(:,2),mDatPredBest(:,1),'Marker','o','MarkerEdgeColor',[0.25 0.25 0.25],'MarkerFaceColor',[0.75 0.75 0.75],'Markersize',8,'Linewidth',2,'Linestyle','none');\n%sTitlestr = ['mu = ' num2str(fMu) ', sigma = ' num2str(fSigma)];\n%title(sTitlestr)\np3=plot(vPredBest(:,1),vPredBest(:,2),'-','Color',[0.2 0.2 0.2],'Linewidth',2);\np4=plot(vPredBest(:,1),vPredBest(:,2)+vPredBest(:,3),'--','Color',[0.2 0.2 0.2],'Linewidth',2);\nplot(vPredBest(:,1),vPredBest(:,2)-vPredBest(:,3),'--','Color',[0.2 0.2 0.2],'Linewidth',2);\nxlabel('Magnitude','FontSize',14,'FontWeight','bold');\nylabel('Number of events','FontSize',14,'FontWeight','bold');\nxlim = ([min(mDatPredBest(:,2)) max(mDatPredBest(:,2))]);\nylim = ([0 max(mDatPredBest(:))]);\nhl1=legend([p1,p2,p3,p4],'Noncum. FMD','Noncum. model FMD ','Model','Model uncertainty');\nset(hl1,'FontWeight','bold','FontSize',12')\nset(gca,'visible','on','FontSize',12,'FontWeight','bold','LineWidth',2,'Box','on');\nset(gca,'NextPlot','replace');\n\n% Plot Non-/Cumulative distribution, original and predicted\nfigure_w_normalized_uicontrolunits('tag','ncumdist','Name','Best model','Units','normalized','Nextplot','add',...\n 'Numbertitle','off','visible','on');\np1 = semilogy(vNonCFMDorg(1,:)', vNonCFMDorg(2,:)', 'Marker','d','MarkerEdgeColor',[0 0 0],'MarkerFaceColor',[0.4 0.4 0.4],'Markersize',8,'Linewidth',2,'Linestyle','none');\nset(gca,'NextPlot','add');\np2 = semilogy(vFMDorg(1,:)', vFMDorg(2,:)', 'Marker','^','MarkerEdgeColor',[0 0 0],'MarkerFaceColor',[0.75 0.75 0.75],'Markersize',8,'Linewidth',2,'Linestyle','none');\n%p2=semilogy(vCFMD(1,:)', vNBest.*fPeriod1, '*',\np3=semilogy(mDatPredBest(:,2),mDatPredBest(:,1),'Marker','o','MarkerEdgeColor',[0.25 0.25 0.25],'MarkerFaceColor',[0.75 0.75 0.75],'Markersize',8,'Linewidth',2,'Linestyle','none');\n%fBvalue = mResult(vSel,9)\n%fAValue = mResult(vSel,8)\nvPoly = [-1*fBvalue fAvalue]\nvMagnitudes = [0:0.01:max(mDatPredBest(:,2))];\nfBFunc = 10.^(polyval(vPoly, vMagnitudes));\np4 = semilogy(vMagnitudes, fBFunc,'Linewidth',3,'Linestyle','--','Color',[0.4 0.4 0.4])\nxlim = ([min(mDatPredBest(:,2)) max(mDatPredBest(:,2))]);\nylim = ([0 100000]);\n%sTitlestr = ['Mc = ' num2str(fMc) ' using Normal CDF fitting'];\n%title(sTitlestr)\nsText1 = ['KS-Test: H = ' num2str(bH)];\nsText2 = ['Mc(EMR) = ' num2str(fMc)];\nhT1 = text(max(vFMDorg(1,:))-1, max(vFMDorg(2,:))*0.6,sText1);\nhT2 = text(max(vFMDorg(1,:))-1, max(vFMDorg(2,:))*0.4,sText2);\nset(hT1,'FontSize',12,'FontWeight','bold');\nset(hT2,'FontSize',12,'FontWeight','bold');\nxlabel('Magnitude','FontSize',14,'FontWeight','bold');\nylabel('Number of events','FontSize',14,'FontWeight','bold');\nhl1=legend([p1 p2 p3 p4],'Noncum. FMD','Cum. FMD','Noncum. model FMD','Cum. model FMD');\nset(hl1,'FontWeight','bold','FontSize',12')\nset(gca,'visible','on','FontSize',12,'FontWeight','bold','LineWidth',2,'Box','on');\n\n%%%% Plotting the likelihood scores\nfigure\n%vSel2 = (vMc >= 0.6 & vMc<= 2);\n%vMc = vMc(vSel2);\n%vProbability = vProbability(vSel2);\nplot(vMc, vProbability,'Marker','s','MarkerFaceColor',[0.5 0.5 0.5],'MarkerEdgeColor',[0 0 0],'Markersize',10','Linewidth',2,'Color',[0 0 0],'visible','on');%sTitlestr = ['mu = ' num2str(fMu) ', sigma = ' num2str(fSigma)];\nhl2=legend('MLE');\nset(hl2,'FontWeight','bold','FontSize',12');\nxlim = ([min(mDatPredBest(:,2)) max(mDatPredBest(:,2))]);\nset(gca,'visible','on','FontSize',12,'FontWeight','bold','LineWidth',2,'Box','on');\nxlabel('Magnitude','FontSize',14,'FontWeight','bold');\nylabel('Likelihood','FontSize',14,'FontWeight','bold');\n\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/jochen/plot/plot_McEMR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4667674580471897}}
{"text": "classdef FLEA < ALGORITHM\n% \n% Fast sampling based evolutionary algorithm\n\n%------------------------------- Reference --------------------------------\n% L. Li, C. He, R. Cheng, H. Li, L. Pan, and Y. Jin, A fast sampling based\n% evolutionary algorithm for million-dimensional multiobjective\n% optimization, Swarm and Evolutionary Computation, 2022, 75: 101181.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n% This function is written by Cheng He & Lianghao Li\n\n methods\n function main(Algorithm,Problem)\n %% Parameter setting\n Population = Problem.Initialization(); \n RN = ceil(sqrt(Problem.N));\t% Number of reference solutions\n \n %% Optimization\n while Algorithm.NotTerminated(Population)\n FrontNo = NDSort(Population.objs,Population.cons,inf);\n [Ref,Population] = RefSelection(Problem,Population,RN,(Problem.FE/Problem.maxFE)^2);\t% APD_Based_Selection\n [id_obj,id_dec] = Neighborhood_Association(Population,Ref); \n cm = 0.1*floor(10*(Problem.FE/Problem.maxFE));\t% Ratio of convergence population\n dirV_obj = Direction_Calculation(Problem,Population,Ref,id_obj,FrontNo);\n dirV_dec = Direction_Calculation(Problem,Population,Ref,id_dec,FrontNo);\n Offspring = Reproduction(Problem,Ref,cm,dirV_obj,dirV_dec);\n [Population,~,~] = EnvironmentalSelection([Population,Offspring],Problem.N);\n end\n end\n end\nend\n\nfunction [Ref,Population] = RefSelection(Problem,Population,RN,theta)\n% The environmental selection of RVEA\n [V,~] = UniformPoint(RN,Problem.M);\n V(1:RN,:) = V.*repmat(max(Population.objs,[],1)-min(Population.objs,[],1)+eps,size(V,1),1);\n PopObj = Population.objs;\n [N,M] = size(PopObj);\n NV = size(V,1);\n PopObj = PopObj - repmat(min(PopObj,[],1),N,1);\n cosine = 1 - pdist2(V,V,'cosine');\n cosine(logical(eye(length(cosine)))) = 0;\n gamma = min(acos(cosine),[],2);\n\n %% Associate each solution to a reference vector\n Angle = acos(1-pdist2(PopObj,V,'cosine'));\n Next = zeros(1,NV);\n for i = 1 : NV \n APD = (1+M*theta*Angle(:,i)/gamma(i)).*sqrt(sum(PopObj.^2,2));\n [~,Next(i)] = min(APD);\n Angle(Next(i),:) = inf;\n end\n % Population for next generation\n Ref = Population(Next);\n [~,order1] = sort(Ref.objs); \n Ref = Ref(order1(:,1));\nend\n\nfunction [OCid,DCid] = Neighborhood_Association(Population,Ref)\n % Neighborhood in objective space\n RefObj = Ref.objs; PopObj = Population.objs;\n Distance_Obj = pdist2(RefObj,PopObj,'chebychev'); \n [~,OCid] = min(Distance_Obj);\n % Neighborhood in decision space\n RefDec = Ref.decs; PopDec = Population.decs;\n Distance_Dec = pdist2(RefDec,PopDec,'chebychev');\n [~,DCid] = min(Distance_Dec);\nend\n\nfunction dirV = Direction_Calculation(Problem,Population,Ref,id,FrontNo)\n %Direction of convergence\n RefDec = Ref.decs; \n RN = length(Ref);\n dirV = zeros(size(RefDec));\n for i = 1:RN\n Neighbor = Population(id==i); \n F_Neighbor = FrontNo(id==i);\n if ~isempty(Neighbor) && min(F_Neighbor)>1\n dirV(i,:) = mean(Neighbor(F_Neighbor==min(F_Neighbor)).decs,1)-RefDec(i,:);\n elseif rand>0.5\n dirV(i,:) = (RefDec(i,:)-Problem.lower)./Problem.D;\n else\n dirV(i,:) = (Problem.upper-RefDec(i,:))./Problem.D;\n end\n end\nend\n\nfunction Offspring = Reproduction(Problem,Ref,cm,dirV_obj,dirV_dec)\n RefDec = Ref.decs; \n RN = length(Ref);\n CN = ceil(cm*0.5*Problem.N/RN); %Size of convergence population\n DN = Problem.N-CN*RN*2; %Size of diversity population\n OffDec = zeros(CN*RN*2+DN,Problem.D);\n for i = 1:RN\n mu = repmat(RefDec(i,:),CN,1); \n %% Convergence offsprings\n OffDec(1+(i-1)*CN:i*CN,:) = mu+repmat(randn(1,CN)',1,Problem.D).*repmat(dirV_obj(i,:),CN,1);\n OffDec(CN*RN+1+(i-1)*CN:CN*RN+i*CN,:) = mu+repmat(randn(1,CN)',1,Problem.D).*repmat(dirV_dec(i,:),CN,1);\n end\n %% Diversity offsprings\n x_1 = randi(RN,1,DN);x_2 = randi(RN,1,DN);\n dirV = Ref(x_1).decs-Ref(x_2).decs;\n OffDec(Problem.N-DN+1:end,:) = Ref(x_1).decs + randn(1,DN)'.*dirV;\n %% Evaluation\n Offspring = Problem.Evaluation(OffDec);\nend\n\nfunction [Population,FrontNo,CrowdDis] = EnvironmentalSelection(Population,N)\n% The environmental selection of NSGA-II\n %% Non-dominated sorting\n [FrontNo,MaxFNo] = NDSort(Population.objs,Population.cons,N);\n Next = FrontNo < MaxFNo;\n \n %% Calculate the crowding distance of each solution\n CrowdDis = CrowdingDistance(Population.objs,FrontNo);\n \n %% Select the solutions in the last front based on their crowding distances\n Last = find(FrontNo==MaxFNo);\n [~,Rank] = sort(CrowdDis(Last),'descend');\n Next(Last(Rank(1:N-sum(Next)))) = true;\n \n %% Population for next generation\n Population = Population(Next);\n FrontNo = FrontNo(Next);\n CrowdDis = CrowdDis(Next);\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Algorithms/Multi-objective optimization/FLEA/FLEA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.46667988992983644}}
{"text": "function gf=gradloglikGaP(x, varargin)\n% f=loglikGaP(x, varargin)\n% complete log likellihood of the GaP model \n% Vxt = varargin{1}; %data\n% sigpsf = varargin{2}; %std deviation of the PSF gaussian approx\n% alpha = varargin{3}; %parameters of the Gamma prior on the blinking\n% beta = varargin{4}; %parameters of the Gamma prior on the blinking\n% peval = varargin{5}; %parameters\n% x(1:end-2*peval.ncomp) is Hkt\n\n\nVxt = varargin{1}; %data\nsigpsf = varargin{2}; %std deviation of the PSF gaussian approx\nalpha = varargin{3}; %parameters of the Gamma prior on the blinking\nbeta = varargin{4}; %parameters of the Gamma prior on the blinking\npeval = varargin{5}; %parameters\n\n% % % Hkt_linear=x(1:end-peval.ncomp*2); % intensities\n% % % cx=x(end-peval.ncomp*2+1:end-peval.ncomp); %x-coordinates of the centers\n% % % cy=x(end-peval.ncomp+1:end); % y-coordinates of the centers\n% % %\nHkt_linear=x; % intensities\ncx=varargin{6};\ncy=varargin{7};\n% % %\n\nsigpsf_vec=repmat(sigpsf,peval.ncomp,1); %all psfs same sigma\ncxy_vec=[cx'+.5, cy'+.5];\na_vec=1./(sigpsf_vec*2*pi); % all normalised to 1\n\nHkt=reshape(Hkt_linear, peval.ncomp, peval.nt);\n% generate PSFs from given parameters:\nWxkpix=gauss2dmultislice([peval.nx, peval.ny, peval.ncomp], cxy_vec, sigpsf_vec, a_vec);\nWxkpix=normalizePSF(Wxkpix); %normalize PSFs to 1\nWxk=reshape(Wxkpix,peval.nx*peval.ny, peval.ncomp);\n% add the background component (just for muttiplication - in the gradient it should not matter): \n[Wxkbg,Hktbg]=addbg(Wxk, Hkt, peval.bg);\nP=Wxkbg*Hktbg; %current approximation\n\nxxvc = lineargrad([peval.nx, peval.ny, peval.ncomp], cx, 'xx'); %linera grasdient shifted by cx\nyyvc = lineargrad([peval.nx, peval.ny, peval.ncomp], cy, 'yy');\n\n% dW/dcx:\nWxtcx=1/sigpsf^2*xxvc.*Wxk; \n% dW/dcy:\nWxtcy=1/sigpsf^2*yyvc.*Wxk;\n\n% d(log(L))/dHkt:\n% % % gfHkt=(alpha-1)*1./Hkt - 1/beta + Wxk'*(Vxt./P-eye(peval.nx*peval.ny,peval.nt));\n% % % gfHkt= Wxk'*(Vxt./P-eye(peval.nx*peval.ny,peval.nt));\ngfHkt= Wxk'*(Vxt./P)-1; %without background\n% d(log(L))/dcx:\ngfcx=diag(Wxtcx'*(Vxt./P)*Hkt'); \n% d(log(L))/dcy:\ngfcy=diag(Wxtcy'*(Vxt./P)*Hkt'); \n\n% % % gf = [reshape(gfHkt',1,peval.nt*peval.ncomp), gfcx', gfcy'];\n% gf = [reshape(gfHkt(1:peval.ncomp, :),1,peval.nt*peval.ncomp)];\ngf = [reshape(gfHkt,1,peval.nt*peval.ncomp)];\n\nend\nfunction Wnorm=normalizePSF(W)\nsw=size(W);\nWr=reshape(W, sw(1)*sw(2),sw(3));\nq=squeeze(sum(Wr,1));\nWrnorm=Wr./repmat(q,sw(1)*sw(2),1);\nWnorm=reshape(Wrnorm,sw(1), sw(2), sw(3));\nend\nfunction xxvc = lineargrad(sizevec, cx, dir)\nswitch dir\n case 'xx'\n xxp=double(xx(sizevec, 'true')); %linear function - pixels\n case 'yy'\n xxp=double(yy(sizevec, 'true')); %linear function - pixels\n otherwise \n error('Wrong dir') \nend\n \nxxv=reshape(xxp,sizevec(1)*sizevec(2),sizevec(3)); %linear function - vector\nxxvc=xxv-repmat(cx,sizevec(1)*sizevec(2),1);\n% xxp=double(xx([peval.nx, peval.ny, peval.ncomp], 'true')); %linear function - pixels\n%yyp=double(yy([peval.nx, peval.ny, peval.ncomp], 'true'));\n% xxv=reshape(xxp,peval.nx*peval.ny,peval.ncomp); %linear function - vector\n%yyv=reshape(yyp,peval.nx*peval.ny,peval.ncomp);\n% xxvc=xxv-repmat(cx,peval.ncomp,1);\n%yyvc=yyv-repmat(cy,peval.ncomp,1);\nend", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/conjgradfunctions/tmp/gradloglikGaP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637397236824, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4666798801707522}}
{"text": "function [res,FLAG,RELRES,ITER,RESVEC,LSVEC] = cgNUSPIRiT(kData, x0, NUFFTOP, GOP, nIter, lambda)\n\n% Implementation of image-domain SPIRiT reconstruction from arbitrary\n% k-space. The function is based on Jeff Fessler's nufft code and LSQR \n% \n% Inputs: \n% kData - k-space data matrix it is 3D corresponding to [readout,interleaves,coils] \n% x0 - Initial estimate of the coil images\n% NUFFTOP - nufft operator (see @NUFFT class)\n% GOP - SPIRiT Operator (See @SPIRiT)\n% nIter - number of LSQR iterations\n% lambda - ratio between data consistency and SPIRiT consistency (1 is recommended)\n%\n% Outputs:\n% res - reconstructed coil images\n% FLAG,RELRES,ITER,RESVEC,LSVEC - See LSQR documentation\n%\n% See demo_nuSPIRiT for a demo on how to use this function.\n%\n% (c) Michael Lustig 2006, modified 2010\n\nN = prod(size(x0));\nimSize = size(x0);\ndataSize = [size(kData)];\n\nb = [kData(:) ; zeros(prod(imSize),1)];\n[res,FLAG,RELRES,ITER,RESVEC,LSVEC] = lsqr(@(x,tflag)afun(x,NUFFTOP,GOP,dataSize, imSize,lambda,tflag), b, [], nIter,speye(N,N),speye(N,N), x0(:));\n\nres = reshape(res,imSize);\n\n\n\n\n\nfunction [y, tflag] = afun(x,NUFFTOP,GOP,dataSize,imSize,lambda,tflag)\n\nif strcmp(tflag,'transp')\n x1 = reshape(x(1:prod(dataSize)),dataSize);\n x2 = reshape(x(prod(dataSize)+1:end),imSize);\n y = NUFFTOP'.*x1 + lambda*(GOP'*x2); \n y = y(:);\nelse\n \n x = reshape(x,imSize);\n y1 = NUFFTOP.*x;\n y2 = GOP*x;\n y = [y1(:); lambda*y2(:)];\nend\n\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/@SPIRiT_Wrapper/cgNUSPIRiT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4666798782189352}}
{"text": "function [x]=als_rake_solve(a,y,tol,varargin)\n%ALS-MINRES method for the solution of linear systems in QTT-Tucker format\n% [X]=ALS_RAKE_SOLVE(A,Y,TOL,VARARGIN) Attempts to solve the linear\n% system A*X = Y with accuracy EPS using the AMR iteration.\n% Matrix A has to be given in the QTT-Tucker, right-hand side Y should be\n% given in the QTT-Tucker format also. Options are provided in form\n% 'PropertyName1',PropertyValue1,'PropertyName2',PropertyValue2 and so\n% on. The parameters are set to default (in brackets in the following) \n% The list of option names and default values are:\n% o x0 - initial approximation [tensor of all ones] \n% o nswp - maximal number of AMR sweeps [10]\n% o verb - verbosity level, 0-silent, 1-sweep info, 2-block info [1]\n% o kickrank - rank-increasing parameter [5]\n% o max_full_size - maximal size of the local matrix to full solver \n% [2500]\n% o local_prec: Local preconditioner, '' - none\n% 'cjacobi' - block-Jacobi, diagonal over rank indices ['']\n% o local_iters - number of local gmres restarts [2]\n% o local_restart - dimension of local gmres [40]\n% o trunc_norm - truncation and stopping tolerance: 'resid' - the\n% residual norm is used, 'fro' - Frobenius (L2) ['resid']\n% o resid_damp - gap between the local solver and truncation. Larger\n% values help to filter some noise, but require more local\n% iterations [2]\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%---------------------------\n\nAu = [];\n\n% Inner parameters\nmax_full_size=2500;\n\nresid_damp = 2; % Truncation error to true residual treshold\nals_tol_high = 10;\nals_tol_low = 4;\nals_iters=2;\n\nnswp=10;\nlocal_restart=40;\nlocal_iters=2;\n\nlocal_prec = '';\n% local_prec_char = 0;\n% local_prec = 'jacobi';\n\nrmax=Inf;\ntrunc_norm = 'residual';\n% trunc_norm_char = 1;\n% trunc_norm = 'fro';\n\n% local_solver = 'gmres';\n% local_solver = 'pcg';\n\nverb=1;\nkickrank = 5;\nx=[];\n\nnswp_f = 1;\nnswp_c = 1;\n\nfor i=1:2:length(varargin)-1\n switch lower(varargin{i})\n case 'nswp'\n nswp=varargin{i+1};\n case 'rmax'\n rmax=varargin{i+1};\n case 'x0'\n x=varargin{i+1};\n case 'verb'\n verb=varargin{i+1};\n case 'local_prec'\n local_prec=varargin{i+1};\n case 'local_restart'\n local_restart=varargin{i+1};\n case 'local_iters'\n local_iters=varargin{i+1};\n% case 'local_solver'\n% local_solver=varargin{i+1}; \n case 'kickrank'\n kickrank=varargin{i+1};\n case 'als_tol_high'\n als_tol_high=varargin{i+1}; \n case 'als_tol_low'\n als_tol_low=varargin{i+1}; \n case 'als_iters'\n als_iters=varargin{i+1}; \n case 'max_full_size'\n max_full_size=varargin{i+1};\n% case 'step_dpow'\n% step_dpow=varargin{i+1};\n% case 'min_dpow'\n% min_dpow=varargin{i+1};\n case 'resid_damp'\n resid_damp = varargin{i+1};\n case 'trunc_norm'\n trunc_norm = varargin{i+1};\n% case 'bot_conv'\n% bot_conv=varargin{i+1};\n% case 'top_conv'\n% top_conv=varargin{i+1}; \n \n otherwise\n error('Unrecognized option: %s\\n',varargin{i});\n end\nend\n\ntol2 = tol;\n\nd = y.core.d;\nyc = core2cell(y.core);\nryc = y.core.r;\nn = cell(d,1);\nL = zeros(d,1);\nyf = cell(d,1);\nryf = cell(d,1);\nfor i=1:d\n n{i} = y.tuck{i}.n;\n L(i) = y.tuck{i}.d;\n ryf{i} = y.tuck{i}.r;\n ryf{i}(L(i)+2) = ryc(i+1);\n yf{i} = cell(L(i)+1,1);\n yf{i}(1:L(i)) = core2cell(y.tuck{i});\n yf{i}{L(i)+1} = yc{i};\nend;\n\nac = core2cell(a.core);\nrac = a.core.r;\naf = cell(d,1);\nraf = cell(d,1);\nfor i=1:d\n raf{i} = a.tuck{i}.r;\n raf{i}(L(i)+2) = rac(i+1); \n af{i} = cell(L(i)+1,1);\n af{i}(1:L(i)) = core2cell(a.tuck{i});\n af{i}{L(i)+1} = ac{i};\nend;\n\nxf = cell(d,1);\nrxf = cell(d,1);\nif (isempty(x))\n x = qtt_tucker;\n xc = tt_ones(1, d);\n x.core = xc;\n rxc = xc.r;\n xc = core2cell(xc);\n x.tuck = cell(d,1);\n for i=1:d\n rxf{i} = ones(L(i)+2,1);\n n{i}(L(i)+1) = 1;\n xf{i} = cell(L(i)+1,1);\n x.tuck{i} = tt_ones(n{i}(1:L(i)));\n xf{i}(1:L(i)) = core2cell(x.tuck{i});\n xf{i}{L(i)+1}=xc{i};\n end;\nelse\n xc = core2cell(x.core);\n rxc = x.core.r;\n for i=1:d\n rxf{i} = x.tuck{i}.r;\n rxf{i}(L(i)+2)=rxc(i+1);\n n{i}(L(i)+1) = rxc(i);\n xf{i} = cell(L(i)+1,1);\n xf{i}(1:L(i)) = core2cell(x.tuck{i});\n xf{i}{L(i)+1}=xc{i};\n end; \nend;\n\nmax_dx = 0;\nmax_res = 0;\n\nphiaf = cell(d,1);\nphiyf = cell(d,1);\nfor i=1:d\n phiaf{i} = cell(L(i)+2,1);\n phiaf{i}{1}=1;\n phiyf{i} = cell(L(i)+2,1);\n phiyf{i}{1}=1; \nend;\nphiac = cell(d+1,1); phiac{1}=1; phiac{d+1}=1;\nphiyc = cell(d+1,1); phiyc{1}=1; phiyc{d+1}=1;\n\nacp = cell(d,1);\nycp = cell(d,1);\n\n\nmax_res_prev = Inf;\nmax_dx_prev = Inf;\nmax_frank = 0;\nregurg_cnt = 0;\nlast_sweep = false;\n\nfor swp=1:nswp\n \n % Orthog + phi, Factors\n for i=1:d\n n{i}(L(i)+1)=rxc(i);\n rxf{i}(L(i)+2)=rxc(i+1); \n % Permute core blocks: rc1 is mode index now\n xf{i}{L(i)+1} = permute(xf{i}{L(i)+1}, [2,1,3]); % rxt,rxc1,rxc2\n for j=1:L(i)\n cr = xf{i}{j};\n cr = reshape(cr, rxf{i}(j)*n{i}(j), rxf{i}(j+1));\n [cr,rv]=qr(cr,0);\n cr2 = xf{i}{j+1};\n cr2 = reshape(cr2, rxf{i}(j+1), n{i}(j+1)*rxf{i}(j+2));\n cr2 = rv*cr2;\n rxf{i}(j+1) = size(cr, 2);\n cr = reshape(cr, rxf{i}(j), n{i}(j), rxf{i}(j+1));\n xf{i}{j} = cr;\n xf{i}{j+1} = reshape(cr2, rxf{i}(j+1), n{i}(j+1), rxf{i}(j+2));\n \n phiaf{i}{j+1} = compute_next_Phi(phiaf{i}{j}, cr, af{i}{j}, cr, 'lr');\n phiyf{i}{j+1} = compute_next_Phi(phiyf{i}{j}, cr, [], yf{i}{j}, 'lr');\n end;\n % core-projected matrix block\n acp{i} = permute(phiaf{i}{L(i)+1}, [2, 1, 3]);\n acp{i} = reshape(acp{i}, raf{i}(L(i)+1), rxf{i}(L(i)+1)*rxf{i}(L(i)+1));\n acp{i} = reshape(permute(af{i}{L(i)+1}, [1,3,2]), rac(i)*rac(i+1), raf{i}(L(i)+1)) * acp{i};\n acp{i} = reshape(acp{i}, rac(i), rac(i+1), rxf{i}(L(i)+1), rxf{i}(L(i)+1));\n acp{i} = permute(acp{i}, [1, 3, 4, 2]);\n % core-projected rhs block\n ycp{i} = phiyf{i}{L(i)+1}.';\n ycp{i} = reshape(permute(yf{i}{L(i)+1}, [1,3,2]), ryc(i)*ryc(i+1), ryf{i}(L(i)+1)) * ycp{i};\n ycp{i} = reshape(ycp{i}, ryc(i), ryc(i+1), rxf{i}(L(i)+1));\n ycp{i} = permute(ycp{i}, [1, 3, 2]);\n % return xf{i}{L{i}+1} to the core state\n xf{i}{L(i)+1} = permute(xf{i}{L(i)+1}, [2,1,3]); % rxc1,rxt,rxc2\n end;\n \n % ALS over core\n nc = zeros(d,1);\n for i=1:d\n nc(i)=rxf{i}(L(i)+1);\n end;\n for k=1:nswp_c\n% max_res_c = 0; \n % Orthog\n for i=1:d-1\n cr = xf{i}{L(i)+1};\n cr = reshape(cr, rxc(i)*nc(i), rxc(i+1));\n [cr,rv]=qr(cr,0);\n cr2 = xf{i+1}{L(i+1)+1};\n cr2 = reshape(cr2, rxc(i+1), nc(i+1)*rxc(i+2));\n cr2 = rv*cr2;\n rxc(i+1) = size(cr,2);\n % Update Factor-sizes too\n% n{i+1}(L(i+1)+1)=rxc(i+1);\n% rxf{i}(L(i)+2)=rxc(i+1);\n cr = reshape(cr, rxc(i), nc(i), rxc(i+1));\n xf{i}{L(i)+1} = cr;\n xf{i+1}{L(i+1)+1} = reshape(cr2, rxc(i+1), nc(i+1), rxc(i+2));\n \n phiac{i+1} = compute_next_Phi(phiac{i}, cr, acp{i}, cr, 'lr');\n phiyc{i+1} = compute_next_Phi(phiyc{i}, cr, [], ycp{i}, 'lr');\n end;\n % ALS\n for i=d:-1:1\n Phi1 = phiac{i};\n A1 = acp{i};\n Phi2 = phiac{i+1};\n \n sol_prev = reshape(xf{i}{L(i)+1}, rxc(i)*nc(i)*rxc(i+1), 1);\n \n dir = -1;\n if (i==1); dir=0; end;\n local_kickrank = kickrank;\n if (last_sweep); local_kickrank=0; end;\n if (verb>1); fprintf('\\t core %d\\n', i); end;\n [u,v,max_res,max_dx,flg]=local_solve(Phi1,A1,Phi2, phiyc{i},ycp{i},phiyc{i+1}, ...\n tol2/sqrt(sum(L+1))/resid_damp, resid_damp, trunc_norm, sol_prev, ...\n local_prec, local_restart, local_iters, max_full_size, max_res, max_dx, ...\n dir, rmax, local_kickrank, verb);\n \n if (flg>0); fprintf('-warn- local_solve did not converge at cb {%d}\\n', i); end;\n \n if (i>1)\n cr2 = xf{i-1}{L(i-1)+1};\n cr2 = reshape(cr2, rxc(i-1)*nc(i-1), rxc(i));\n cr2 = cr2*u;\n rxc(i) = size(v,2);\n % Update Factor-sizes\n% n{i}(L(i)+1)=rxc(i);\n% rxf{i-1}(L(i-1)+2)=rxc(i);\n v = reshape(v.', rxc(i), nc(i), rxc(i+1));\n xf{i}{L(i)+1} = v;\n xf{i-1}{L(i-1)+1} = reshape(cr2, rxc(i-1), nc(i-1), rxc(i));\n \n phiac{i} = compute_next_Phi(phiac{i+1}, v, acp{i}, v, 'rl');\n phiyc{i} = compute_next_Phi(phiyc{i+1}, v, [], ycp{i}, 'rl'); \n else\n v = u*(v.');\n xf{i}{L(i)+1} = reshape(v, rxc(i), nc(i), rxc(i+1));\n end;\n end;\n end;\n% max_res = max(max_res, max_res_c);\n \n \n % Optimization over factors\n for i=1:d\n % ALS L->1, the orth. holds\n % Copy the extended factor data to the current array\n curx = xf{i};\n % Last mode size <- largest core rank\n if (rxc(i)>rxc(i+1))\n % Reshape the core block to be the factor one\n curx{L(i)+1} = permute(curx{L(i)+1}, [2, 1, 3]); % rtx, rxc1, rxc2\n \n cura = af{i};\n % last block has to be convolved with phiac-left\n cura{L(i)+1} = permute(phiac{i}, [1,3,2]);\n cura{L(i)+1} = reshape(cura{L(i)+1}, rxc(i)*rxc(i), rac(i));\n cura{L(i)+1} = cura{L(i)+1}*reshape(af{i}{L(i)+1}, rac(i), raf{i}(L(i)+1)*rac(i+1));\n cura{L(i)+1} = reshape(cura{L(i)+1}, rxc(i), rxc(i), raf{i}(L(i)+1), rac(i+1));\n cura{L(i)+1} = permute(cura{L(i)+1}, [3, 1,2, 4]); % tucker rank is now the left\n \n cury = yf{i};\n cury{L(i)+1} = phiyc{i}*reshape(yf{i}{L(i)+1}, ryc(i), ryf{i}(L(i)+1)*ryc(i+1));\n cury{L(i)+1} = reshape(cury{L(i)+1}, rxc(i), ryf{i}(L(i)+1), ryc(i+1));\n cury{L(i)+1} = permute(cury{L(i)+1}, [2, 1, 3]); % tucker rank is now the left\n \n % The L+2-th phi comes from the core\n phiaf{i}{L(i)+2} = phiac{i+1}; % sizes rxc2,ra2,rxc2. rxc2 - our last \"rank\" index\n phiyf{i}{L(i)+2} = phiyc{i+1};\n \n n{i}(L(i)+1) = rxc(i);\n rxf{i}(L(i)+2) = rxc(i+1);\n else\n % Reshape the core block to be the factor one\n curx{L(i)+1} = permute(curx{L(i)+1}, [2, 3, 1]); % rtx, rxc2, rxc1\n \n cura = af{i};\n % last block has to be convolved with phiac-left\n cura{L(i)+1} = permute(phiac{i+1}, [2, 1,3]);\n cura{L(i)+1} = reshape(cura{L(i)+1}, rac(i+1), rxc(i+1)*rxc(i+1));\n cura{L(i)+1} = reshape(af{i}{L(i)+1}, rac(i)*raf{i}(L(i)+1), rac(i+1)) * cura{L(i)+1};\n cura{L(i)+1} = reshape(cura{L(i)+1}, rac(i), raf{i}(L(i)+1), rxc(i+1), rxc(i+1));\n cura{L(i)+1} = permute(cura{L(i)+1}, [2, 3,4, 1]); % tucker rank is now the left\n \n cury = yf{i};\n cury{L(i)+1} = reshape(yf{i}{L(i)+1}, ryc(i)*ryf{i}(L(i)+1), ryc(i+1)) * (phiyc{i+1}.');\n cury{L(i)+1} = reshape(cury{L(i)+1}, ryc(i), ryf{i}(L(i)+1), rxc(i+1));\n cury{L(i)+1} = permute(cury{L(i)+1}, [2, 3, 1]); % tucker rank is now the left\n \n % The L+2-th phi comes from the core\n phiaf{i}{L(i)+2} = phiac{i}; % sizes rxc2,ra2,rxc2. rxc2 - our last \"rank\" index\n phiyf{i}{L(i)+2} = phiyc{i}; \n \n n{i}(L(i)+1) = rxc(i+1);\n rxf{i}(L(i)+2) = rxc(i);\n end;\n \n for k=1:nswp_f\n% max_res_f = 0;\n % First, orthogonality L->1\n for j=(L(i)+1):-1:2\n cr = curx{j};\n cr = reshape(cr, rxf{i}(j), n{i}(j)*rxf{i}(j+1));\n [cr,rv]=qr(cr.',0);\n cr2 = curx{j-1};\n cr2 = reshape(cr2, rxf{i}(j-1)*n{i}(j-1), rxf{i}(j));\n cr2 = cr2*(rv.');\n rxf{i}(j) = size(cr, 2);\n cr = reshape(cr.', rxf{i}(j), n{i}(j), rxf{i}(j+1));\n curx{j} = cr;\n curx{j-1} = reshape(cr2, rxf{i}(j-1), n{i}(j-1), rxf{i}(j));\n \n phiaf{i}{j} = compute_next_Phi(phiaf{i}{j+1}, cr, cura{j}, cr, 'rl');\n phiyf{i}{j} = compute_next_Phi(phiyf{i}{j+1}, cr, [], cury{j}, 'rl');\n end;\n \n % Now, finally, the optimization itself\n% for j=(L(i)+1):-1:1\n for j=1:(L(i)+1)\n Phi1 = phiaf{i}{j};\n A1 = cura{j};\n Phi2 = phiaf{i}{j+1};\n \n sol_prev = reshape(curx{j}, rxf{i}(j)*n{i}(j)*rxf{i}(j+1), 1);\n \n dir = 1;\n if (j==(L(i)+1)); dir=0; end;\n local_kickrank = kickrank;\n if (last_sweep); local_kickrank=0; end;\n if (verb>1); fprintf('\\t factor {%d,%d}\\n', i, j); end;\n [u,v,max_res,max_dx,flg]=local_solve(Phi1,A1,Phi2, phiyf{i}{j},cury{j},phiyf{i}{j+1}, ...\n tol2/sqrt(sum(L+1))/resid_damp, resid_damp, trunc_norm, sol_prev, ...\n local_prec, local_restart, local_iters, max_full_size, max_res, max_dx, ...\n dir, rmax, local_kickrank, verb);\n \n if (flg>0); fprintf('-warn- local_solve did not converge at fb {%d}{%d}\\n', i, j); end;\n \n if (j<(L(i)+1))\n cr2 = curx{j+1};\n cr2 = reshape(cr2, rxf{i}(j+1), n{i}(j+1)*rxf{i}(j+2));\n cr2 = (v.')*cr2;\n rxf{i}(j+1) = size(u,2);\n max_frank = max(max_frank, rxf{i}(j+1));\n u = reshape(u, rxf{i}(j), n{i}(j), rxf{i}(j+1));\n curx{j} = u;\n curx{j+1} = reshape(cr2, rxf{i}(j+1), n{i}(j+1), rxf{i}(j+2));\n \n phiaf{i}{j+1} = compute_next_Phi(phiaf{i}{j}, u, cura{j}, u, 'lr');\n phiyf{i}{j+1} = compute_next_Phi(phiyf{i}{j}, u, [], cury{j}, 'lr');\n else\n u = u*(v.');\n curx{j} = reshape(u, rxf{i}(j), n{i}(j), rxf{i}(j+1));\n end;\n end;\n end;\n% max_res = max(max_res, max_res_f);\n \n if (ixc2 orth\n if (rxc(i)>rxc(i+1))\n cr = permute(curx{L(i)+1}, [2, 1, 3]); % now rc1,rt,rc2\n else \n cr = permute(curx{L(i)+1}, [3, 1, 2]); % now rc1,rt,rc2\n end;\n cr = reshape(cr, rxc(i)*rxf{i}(L(i)+1), rxc(i+1));\n [cr,rv]=qr(cr,0);\n cr2 = xf{i+1}{L(i+1)+1};\n cr2 = reshape(cr2, rxc(i+1), rxf{i+1}(L(i+1)+1)*rxc(i+2));\n cr2 = rv*cr2;\n rxc(i+1) = size(cr,2);\n % Update Factor-sizes too\n% n{i+1}(L(i+1)+1)=rxc(i+1);\n% rxf{i}(L(i)+2)=rxc(i+1);\n cr = reshape(cr, rxc(i), rxf{i}(L(i)+1), rxc(i+1));\n xf{i}{L(i)+1} = cr;\n xf{i+1}{L(i+1)+1} = reshape(cr2, rxc(i+1), rxf{i+1}(L(i+1)+1), rxc(i+2));\n \n % Update acp, ycp\n % core-projected matrix block\n acp{i} = permute(phiaf{i}{L(i)+1}, [2, 1, 3]);\n acp{i} = reshape(acp{i}, raf{i}(L(i)+1), rxf{i}(L(i)+1)*rxf{i}(L(i)+1));\n acp{i} = reshape(permute(af{i}{L(i)+1}, [1,3,2]), rac(i)*rac(i+1), raf{i}(L(i)+1)) * acp{i};\n acp{i} = reshape(acp{i}, rac(i), rac(i+1), rxf{i}(L(i)+1), rxf{i}(L(i)+1));\n acp{i} = permute(acp{i}, [1, 3, 4, 2]);\n % core-projected rhs block\n ycp{i} = phiyf{i}{L(i)+1}.';\n ycp{i} = reshape(permute(yf{i}{L(i)+1}, [1,3,2]), ryc(i)*ryc(i+1), ryf{i}(L(i)+1)) * ycp{i};\n ycp{i} = reshape(ycp{i}, ryc(i), ryc(i+1), rxf{i}(L(i)+1));\n ycp{i} = permute(ycp{i}, [1, 3, 2]);\n \n phiac{i+1} = compute_next_Phi(phiac{i}, cr, acp{i}, cr, 'lr');\n phiyc{i+1} = compute_next_Phi(phiyc{i}, cr, [], ycp{i}, 'lr');\n else\n xf{i}(1:L(i)) = curx(1:L(i));\n if (rxc(i)>rxc(i+1))\n xf{i}{L(i)+1} = permute(curx{L(i)+1}, [2, 1, 3]); % core block\n else\n xf{i}{L(i)+1} = permute(curx{L(i)+1}, [3, 1, 2]); % core block\n end;\n end;\n end;\n \n \n % Residual check, etc\n \n% x_old = x;\n% for i=1:d\n% x.tuck{i} = cell2core(x.tuck{i}, xf{i}(1:L(i)));\n% xc{i} = xf{i}{L(i)+1};\n% end;\n% x.core = cell2core(x.core, xc);\n \n if (verb>0)\n fprintf('=als_rake_solve= sweep %d, max_dx: %3.3e, max_res: %3.3e, mrank_c: %d, mrank_f: %d\\n', swp, max_dx, max_res, max(rxc), max_frank);\n end;\n \n if (last_sweep)\n break;\n end; \n \n if (kickrank<0)\n kickrank=kickrank-1;\n end; \n \n if (strcmp(trunc_norm, 'fro')) \n if (max_dxmax_dx_prev); regurg_cnt=regurg_cnt+1; fprintf('---- Regurgitation %d\\n', regurg_cnt); end; \n% kickrank = -1;\n% tol2=tol/4;\n end;\n if ((regurg_cnt>0)||(max_dx<=tol*als_tol_low))&&(kickrank>0); kickrank=-1; end;\n else\n% for i=1:d\n% x.tuck{i} = cell2core(x.tuck{i}, xf{i}(1:L(i)));\n% xc{i} = xf{i}{L(i)+1};\n% end;\n% x.core = cell2core(x.core, xc);\n% x.dphys = d;\n% Au = mvrk2(a, x, tol, 'y0', Au, 'verb', 0);\n% real_res = norm(Au-y)/norm(y);\n% fprintf('=als_rake_solve= sweep %d, \\t\\t\\t real_res: %3.3e\\n', swp, real_res);\n if (max_resmax_res_prev); regurg_cnt=regurg_cnt+1; fprintf('---- Regurgitation %d\\n', regurg_cnt); end;\n% if ((regurg_cnt>als_iters)||(max_res0)||(max_res<=tol*als_tol_low))&&(kickrank>0); kickrank=-1; end;\n% end; \n end;\n \n if (swp==nswp-1)||(regurg_cnt>2)\n last_sweep=true;\n% tol2 = tol;\n end;\n \n max_res_prev = max_res;\n max_dx_prev = max_dx;\n \n max_res = 0;\n max_dx = 0;\n max_frank=0;\nend;\n\n% Stuff back\nfor i=1:d\n x.tuck{i} = cell2core(x.tuck{i}, xf{i}(1:L(i)));\n xc{i} = xf{i}{L(i)+1}; \nend;\nx.core = cell2core(x.core, xc);\nx.dphys = d;\n% x.sz = n;\nend\n\n\n\nfunction [y]=bfun3(Phi1,B1,Phi2, x)\n% Computes (Phi1 * B1 * Phi2)*x\n% Phi1 is of sizes ry1, rB1, rx1\n% B1 is of sizes rB1, k1, m1, rB2\n% Phi2 is of sizes ry2, rB2, rx2\nry1 = size(Phi1,1); ry2 = size(Phi2,1);\nrx1 = size(Phi1,3); rx2 = size(Phi2,3);\nrb1=size(B1,1); rb2=size(B1,4); \nm1 = size(B1,3);\nk1 = size(B1,2);\n\ny = reshape(x, rx1, m1*rx2);\nPhi1 = reshape(Phi1, ry1*rb1, rx1);\ny = Phi1*y; % size ry1*rb1,m1*rx2 % cplx rb*rx^3*m^2\ny = reshape(y, ry1, rb1*m1, rx2);\ny = permute(y, [2, 1, 3]);\ny = reshape(y, rb1*m1, ry1*rx2);\nB1 = permute(B1, [2, 4, 1, 3]);\nB1 = reshape(B1, k1*rb2, rb1*m1);\ny = B1*y; % size k1*rb2, ry1*rx2 % cplx rb^2*rx^2*n^3\ny = reshape(y, k1, rb2, ry1, rx2);\ny = permute(y, [2, 4, 3, 1]);\ny = reshape(y, rb2*rx2, ry1*k1);\nPhi2 = reshape(Phi2, ry2, rb2*rx2);\ny = Phi2*y; % size ry2, ry1*k1 % cplx rb*rx^3*n^2\ny = y.';\ny = reshape(y, ry1*k1*ry2, 1);\nend\n\n\nfunction [u,v,max_res,max_dx,flg]=local_solve(Phi1,A1,Phi2, phiy1,y1,phiy2, tol, resid_damp, trunc_norm, sol_prev, local_prec, local_restart, local_iters, max_full_size, max_res, max_dx, dir, rmax, kickrank, verb)\nrx1 = size(Phi1,1);\nn = size(A1,2);\nrx2 = size(Phi2,1);\nra1 = size(Phi1,2);\nra2 = size(Phi2,2);\n\nry1 = size(phiy1,2);\nry2 = size(phiy2,2);\nif (dir>0)\n rhs = reshape(y1, ry1, n*ry2);\n rhs = phiy1*rhs;\n rhs = reshape(rhs, rx1*n, ry2);\n if (kickrank>0); y_save = rhs; end;\n rhs = rhs*(phiy2.');\nelse\n rhs = phiy2.';\n rhs = reshape(y1, ry1*n, ry2)*rhs;\n rhs = reshape(rhs, ry1, n*rx2);\n if (kickrank>0); y_save = rhs; end;\n rhs = phiy1*rhs;\nend;\nrhs = rhs(:);\n\nnorm_rhs = norm(rhs, 'fro');\n\nif (rx1*n*rx2tol)\n B2 = B+eye(rx1*n*rx2);\n sol_prev2 = sol_prev;\n for it=1:local_restart\n sol = B2 \\ sol_prev2;\n sol = sol/norm(sol);\n res_new = norm(B*sol);\n if (strcmp(trunc_norm, 'fro'))\n if (norm(sol-sol_prev2)tol)\n sol = B \\ rhs;\n % If the system was ill-conditioned\n % [sol,flg] = gmres(B, rhs, local_restart, real_tol, 2, [], [], sol);\n res_new = norm(B*sol-rhs)/norm_rhs;\n flg=0;\n if (res_new>tol); flg=1; end;\n else\n sol = sol_prev;\n res_new = res_prev;\n flg=0;\n end;\n end;\nelse\n if (norm_rhs==0.0)\n res_prev = norm(bfun3(Phi1, A1, Phi2, sol_prev));\n if (res_prev>tol)\n trunc_norm_char = 1;\n local_prec_char = 0;\n if ((strcmp(local_prec, 'cjacobi'))); local_prec_char = 1; end;\n if (strcmp(local_prec, 'ljacobi')); local_prec_char = 2; end;\n if (strcmp(local_prec, 'rjacobi')); local_prec_char = 3; end;\n \n Psi1 = zeros(rx1, rx1, ra1+1);\n Psi1(:,:,1:ra1) = permute(Phi1, [1,3,2]);\n Psi1(:,:,ra1+1) = eye(rx1);\n B1 = zeros(n, n, ra1+1, ra2+1);\n B1(:,:,1:ra1,1:ra2) = permute(A1, [2,3,1,4]);\n B1(:,:,ra1+1,ra2+1) = eye(n);\n B1 = permute(B1, [3,1,2,4]);\n Psi2 = zeros(rx2,rx2,ra2+1);\n Psi2(:,:,1:ra2) = permute(Phi2, [1,3,2]);\n Psi2(:,:,ra2+1) = eye(rx2);\n Psi2 = permute(Psi2, [2,3,1]);\n \n sol_prev2 = sol_prev;\n for it=1:local_restart\n sol = solve3d_2(Psi1, B1, Psi2, sol_prev2, tol, trunc_norm_char, sol_prev2, local_prec_char, local_restart, local_iters, 1);\n sol = sol/norm(sol);\n res_new = norm(bfun3(Phi1, A1, Phi2, sol));\n if (strcmp(trunc_norm, 'fro'))\n if (norm(sol-sol_prev2)tol); flg=1; end;\n else\n sol = sol_prev;\n res_new = res_prev;\n flg = 0;\n end;\n else\n res_prev = norm(bfun3(Phi1, A1, Phi2, sol_prev) - rhs)/norm_rhs;\n if (res_prev>tol)\n trunc_norm_char = 1;\n% if (strcmp(trunc_norm, 'fro')); trunc_norm_char = 0; end;\n local_prec_char = 0;\n if ((strcmp(local_prec, 'cjacobi'))); local_prec_char = 1; end;\n if (strcmp(local_prec, 'ljacobi')); local_prec_char = 2; end;\n if (strcmp(local_prec, 'rjacobi')); local_prec_char = 3; end;\n if (res_prev>1)\n sol_prev = zeros(rx1*n*rx2, 1);\n res_prev = 1;\n end;\n \n% sol = solve3d(permute(Phi1,[1,3,2]), A1, permute(Phi2, [1,3,2]), rhs, tol, trunc_norm_char, sol_prev, local_prec_char, local_restart, local_iters, 1);\n sol = solve3d_2(permute(Phi1,[1,3,2]), A1, permute(Phi2, [3,2,1]), rhs, tol, trunc_norm_char, sol_prev, local_prec_char, local_restart, local_iters, 0);\n \n res_new = norm(bfun3(Phi1, A1, Phi2, sol) - rhs)/norm_rhs;\n flg=0;\n if (res_new>tol); flg=1; end;\n else\n sol = sol_prev;\n res_new = res_prev;\n flg = 0;\n end;\n end;\nend;\n\nif (res_prev/res_newtol)\n fprintf('--warn-- the residual damp was smaller than in the truncation\\n');\nend;\n\n% if (flg>0)&&(kickrank==0)\n% sol = sol_prev;\n% res_new = res_prev;\n% end;\n\ndx = norm(sol-sol_prev)/norm(sol);\nmax_dx = max(max_dx, dx);\n\nmax_res = max(max_res, res_prev);\n\n\nif (norm_rhs==0.0)\n norm_rhs=1;\nend;\n\n% Truncation\nif (dir>=0) % left-to-right\n sol = reshape(sol, rx1*n, rx2);\nelse\n sol = reshape(sol, rx1, n*rx2);\nend;\n\nif (kickrank>=0)\n[u,s,v]=svd(sol, 'econ');\ns = diag(s);\n \nif (strcmp(trunc_norm, 'fro')) % We are happy with L2 truncation (when? but let it be) \n r = my_chop2(s, tol*resid_damp*norm(s));\nelse\n % Residual trunc; First, bin-search\n r1 = 1; r2 = numel(s); r = round((r1+r2)/2);\n while (r2-r1>1)\n cursol = u(:,1:r)*diag(s(1:r))*(v(:,1:r)');\n if (rx1*n*rx2=0)\n [u,v]=qr(sol, 0);\n v = v';\n r = size(u,2);\n s = ones(r,1);\n else\n [v,u]=qr(sol.', 0); \n u = u.';\n v = conj(v);\n r = size(v,2);\n s = ones(r,1); \n end;\nend;\n\nif (verb>1)\n fprintf('=als_rake_solve= dir %d, dx: %3.3e, res_prev: %3.3e, res_new: %3.3e r: %d\\n', dir, dx, res_prev, res_new, r);\nend;\n \n if (dir>0) % left-to-right, kickrank, etc\n u = u(:,1:r);\n v = conj(v(:,1:r))*diag(s(1:r));\n \n if (kickrank>0)\n % Smarter kick: low-rank PCA in residual\n % Matrix: Phi1-A{i}, rhs: Phi1-y{i}, sizes rx(i)*n - ra(i+1) \n leftresid = reshape(Phi1, rx1*ra1, rx1)*reshape(u*v.', rx1, n*rx2);\n leftresid = reshape(leftresid, rx1, ra1*n, rx2);\n leftresid = reshape(permute(leftresid, [2, 1, 3]), ra1*n, rx1*rx2);\n leftresid = reshape(permute(A1, [2,4,1,3]), n*ra2, ra1*n)*leftresid;\n leftresid = reshape(leftresid, n, ra2, rx1, rx2);\n leftresid = reshape(permute(leftresid, [3,1,2,4]), rx1*n, ra2*rx2);\n% leftA = permute(Phi1, [1, 3, 2]);\n% leftA = reshape(leftA, rx1*rx1, ra1);\n% leftA = leftA*reshape(A1, ra1, n*n*ra2);\n% leftA = reshape(leftA, rx1, rx1, n, n, ra2);\n% leftA = permute(leftA, [1, 3, 5, 2, 4]);\n% leftA = reshape(leftA, rx1*n*ra2, rx1*n);\n% leftresid = leftA*reshape(u*v.', rx1*n, rx2);\n% leftresid = reshape(leftresid, rx1*n, ra2*rx2);\n leftresid = [leftresid, -y_save];\n% \n% uk = zeros(rx1*n, min(kickrank,rx1*n));\n% for i=1:min(kickrank, rx1*n)\n% uk2 = uchol(leftresid.', 2);\n% uk(:,i) = uk2(:,end);\n% [uk(:,1:i),rv]=qr(uk(:,1:i), 0);\n% leftresid = leftA*uk(:,i);\n% leftresid = reshape(leftresid, rx1*n, ra2);\n% end;\n \n% % [uk,~,~]=svd(leftresid, 'econ');\n% % uk = uk(:,1:min(kickrank, size(uk,2)));\n uk = uchol(leftresid.', kickrank+1);\n uk = uk(:,size(uk,2):-1:max(size(uk,2)-kickrank+1,1));\n% leftresid = leftA*uk;\n% leftresid = reshape(leftresid, rx1*n, ra2*size(uk,2));\n% uk(:,size(uk,2)+1) = uchol(leftresid.', 1);\n% % uk = randn(rx1*n, kickrank);\n\n [u,rv]=qr([u,uk], 0);\n radd = size(uk,2);\n v = [v, zeros(rx2, radd)];\n v = v*(rv.');\n end;\n elseif (dir<0) % right-to-left\n u = u(:,1:r)*diag(s(1:r));\n v = conj(v(:,1:r));\n \n if (kickrank>0)\n % Smarter kick: low-rank PCA in residual\n % Matrix: Phi1-A{i}, rhs: Phi1-y{i}, sizes rx(i)*n - ra(i+1)\n rightresid = reshape(Phi2, rx2*ra2, rx2)*(reshape(u*v.', rx1*n, rx2).');\n rightresid = reshape(rightresid, rx2, ra2, rx1, n);\n rightresid = reshape(permute(rightresid, [4, 2, 3, 1]), n*ra2, rx1*rx2);\n rightresid = reshape(A1, ra1*n, n*ra2)*rightresid;\n rightresid = reshape(rightresid, ra1, n, rx1, rx2);\n rightresid = reshape(permute(rightresid, [2,4,1,3]), n*rx2, ra1*rx1); \n% rightA = permute(Phi2, [2, 1, 3]);\n% rightA = reshape(rightA, ra2, rx2*rx2);\n% rightA = reshape(A1, ra1*n*n, ra2)*rightA;\n% rightA = reshape(rightA, ra1, n, n, rx2, rx2);\n% rightA = permute(rightA, [2, 4, 1, 3, 5]);\n% rightA = reshape(rightA, n*rx2*ra1, n*rx2);\n% rightresid = rightA*(reshape(u*v.', rx1, n*rx2).');\n% rightresid = reshape(rightresid, n*rx2, ra1*rx1);\n rightresid = [rightresid, -(y_save.')];\n \n% uk = zeros(n*rx2, min(kickrank,n*rx2));\n% for i=1:min(kickrank, n*rx2)\n% uk2 = uchol(rightresid.', 2);\n% uk(:,i) = uk2(:,end);\n% [uk(:,1:i),rv]=qr(uk(:,1:i), 0);\n% rightresid = rightA*uk(:,i);\n% rightresid = reshape(rightresid, n*rx2, ra1);\n% end;\n\n% % [uk,~,~]=svd(rightresid, 'econ');\n% % uk = uk(:,1:min(kickrank, size(uk,2)));\n\n% % uk = randn(n*rx2, kickrank);\n uk = uchol(rightresid.', kickrank+1);\n uk = uk(:,size(uk,2):-1:max(size(uk,2)-kickrank+1,1));\n \n [v,rv]=qr([v,uk], 0);\n radd = size(uk,2);\n u = [u, zeros(rx1, radd)];\n u = u*(rv.');\n end;\n else\n % Just stuff back the last core\n u = u(:,1:r);\n v = conj(v(:,1:r))*diag(s(1:r));\n end;\n\nend\n\n\n\n\nfunction [Phi] = compute_next_Phi(Phi_prev, x, A, y, direction)\n% Performs the recurrent Phi (or Psi) matrix computation\n% Phi = Phi_prev * (x'Ay).\n% If direction is 'lr', computes Psi\n% if direction is 'rl', computes Phi\n% A can be empty, then only x'y is computed.\n\nif (strcmp(direction, 'rl'))\n % Revert ranks to perform the right-to-left recursion\n x = permute(x, [3, 2, 1]);\n y = permute(y, [3, 2, 1]);\n if (~isempty(A))\n A = permute(A, [4, 2, 3, 1]);\n end\nend\n\nrx1 = size(x,1); n = size(x,2); rx2 = size(x,3);\nry1 = size(y,1); m = size(y,2); ry2 = size(y,3);\nif (~isempty(A))\n ra1 = size(A,1); ra2 = size(A,4);\nelse\n ra1 = 1; ra2 = 1;\nend\n\nPhi = reshape(Phi_prev, [rx1*ra1, ry1]);\ny = reshape(y, [ry1, m*ry2]);\nPhi = Phi*y;\t% complexity §\\mcommentfont$\\mathcal{O}(n r_x r_A r_y^2)$§\nPhi = reshape(Phi, [rx1, ra1, m, ry2]);\nPhi = permute(Phi, [2, 3, 1, 4]);\nif (~isempty(A))\n Phi = reshape(Phi, [ra1*m, rx1*ry2]);\n A = permute(A, [4, 2, 1, 3]);\n A = reshape(A, [ra2*n, ra1*m]);\n Phi = A*Phi;\t% complexity §\\mcommentfont$\\mathcal{O}(n^2 r_x r_A^2 r_y)$§\n Phi = reshape(Phi, [ra2, n, rx1, ry2]);\nend\nPhi = permute(Phi, [3, 2, 1, 4]);\nPhi = reshape(Phi, [rx1*n, ra2*ry2]);\nx = reshape(x, [rx1*n, rx2]);\nPhi = (x')*Phi;\t% complexity §\\mcommentfont$\\mathcal{O}(n r_x^2 r_A r_y)$§\nif (~isempty(A))\n Phi = reshape(Phi, [rx2, ra2, ry2]);\nend\nend\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/solve/als_rake_solve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4666550652467602}}
{"text": "function [bFun, b0Fun, derFun] = conAffPoint2PlaneSimpleOLS(prm, cst, obs)\n\n% ------------------------------------------------------------------------------\n\nbFun = @(obs) bFunNested(obs);\n\n function bBlock = bFunNested(obs)\n \n bBlock = obs.dp;\n \n end\n\n% ------------------------------------------------------------------------------\n\nb0Fun = @(prm, cst) b0FunNested(prm, cst);\n \n function b0Block = b0FunNested(prm, cst)\n \n % Affine matrices\n A1 = [prm.a111 prm.a121 prm.a131\n prm.a211 prm.a221 prm.a231\n prm.a311 prm.a321 prm.a331];\n \n A2 = [prm.a112 prm.a122 prm.a132\n prm.a212 prm.a222 prm.a232\n prm.a312 prm.a322 prm.a332];\n \n % Homogeneous transformation matrix\n H1 = homotrafo(1, A1, [prm.tx1 prm.ty1 prm.tz1]);\n H2 = homotrafo(1, A2, [prm.tx2 prm.ty2 prm.tz2]);\n \n % Coordinates\n X1 = [cst.x1 cst.y1 cst.z1];\n X2 = [cst.x2 cst.y2 cst.z2];\n\n % Normal vector\n n1 = [cst.nx1 cst.ny1 cst.nz1];\n \n % Transformation from cartesian coord. to homogeneous coord.\n X1_h = homocoord(X1);\n X2_h = homocoord(X2);\n \n b0Block = dot((homocoord((H1 * X1_h')') - homocoord((H2 * X2_h')'))', n1')';\n \n end\n\n% Derivatives ------------------------------------------------------------------\n\nderFun.prm.a111 = @(prm, cst) derFunNested(prm, cst, 'prm_a111');\nderFun.prm.a121 = @(prm, cst) derFunNested(prm, cst, 'prm_a121');\nderFun.prm.a131 = @(prm, cst) derFunNested(prm, cst, 'prm_a131');\nderFun.prm.a211 = @(prm, cst) derFunNested(prm, cst, 'prm_a211');\nderFun.prm.a221 = @(prm, cst) derFunNested(prm, cst, 'prm_a221');\nderFun.prm.a231 = @(prm, cst) derFunNested(prm, cst, 'prm_a231');\nderFun.prm.a311 = @(prm, cst) derFunNested(prm, cst, 'prm_a311');\nderFun.prm.a321 = @(prm, cst) derFunNested(prm, cst, 'prm_a321');\nderFun.prm.a331 = @(prm, cst) derFunNested(prm, cst, 'prm_a331');\nderFun.prm.tx1 = @(prm, cst) derFunNested(prm, cst, 'prm_tx1');\nderFun.prm.ty1 = @(prm, cst) derFunNested(prm, cst, 'prm_ty1');\nderFun.prm.tz1 = @(prm, cst) derFunNested(prm, cst, 'prm_tz1');\n \nderFun.prm.a112 = @(prm, cst) derFunNested(prm, cst, 'prm_a112');\nderFun.prm.a122 = @(prm, cst) derFunNested(prm, cst, 'prm_a122');\nderFun.prm.a132 = @(prm, cst) derFunNested(prm, cst, 'prm_a132');\nderFun.prm.a212 = @(prm, cst) derFunNested(prm, cst, 'prm_a212');\nderFun.prm.a222 = @(prm, cst) derFunNested(prm, cst, 'prm_a222');\nderFun.prm.a232 = @(prm, cst) derFunNested(prm, cst, 'prm_a232');\nderFun.prm.a312 = @(prm, cst) derFunNested(prm, cst, 'prm_a312');\nderFun.prm.a322 = @(prm, cst) derFunNested(prm, cst, 'prm_a322');\nderFun.prm.a332 = @(prm, cst) derFunNested(prm, cst, 'prm_a332');\nderFun.prm.tx2 = @(prm, cst) derFunNested(prm, cst, 'prm_tx2');\nderFun.prm.ty2 = @(prm, cst) derFunNested(prm, cst, 'prm_ty2');\nderFun.prm.tz2 = @(prm, cst) derFunNested(prm, cst, 'prm_tz2');\n\n function derFunBlock = derFunNested(prm, cst, var)\n \n switch var\n \n % ------------------------------------------------------------------\n \n case 'prm_a111'\n \n derFunBlock = cst.x1 .* cst.nx1;\n \n % ------------------------------------------------------------------\n \n case 'prm_a121'\n \n derFunBlock = cst.y1 .* cst.nx1;\n \n % ------------------------------------------------------------------\n \n case 'prm_a131'\n \n derFunBlock = cst.z1 .* cst.nx1;\n \n % ------------------------------------------------------------------\n \n case 'prm_a211'\n \n derFunBlock = cst.x1 .* cst.ny1;\n \n % ------------------------------------------------------------------\n \n case 'prm_a221'\n \n derFunBlock = cst.y1 .* cst.ny1;\n \n % ------------------------------------------------------------------\n \n case 'prm_a231'\n \n derFunBlock = cst.z1 .* cst.ny1;\n \n % ------------------------------------------------------------------\n \n case 'prm_a311'\n \n derFunBlock = cst.x1 .* cst.nz1;\n \n % ------------------------------------------------------------------\n \n case 'prm_a321'\n \n derFunBlock = cst.y1 .* cst.nz1;\n \n % ------------------------------------------------------------------\n \n case 'prm_a331'\n \n derFunBlock = cst.z1.* cst.nz1;\n \n % ------------------------------------------------------------------\n \n case 'prm_a112'\n \n derFunBlock = - cst.x2 .* cst.nx1;\n \n % ------------------------------------------------------------------\n \n case 'prm_a122'\n \n derFunBlock = - cst.y2 .* cst.nx1;\n \n % ------------------------------------------------------------------\n \n case 'prm_a132'\n \n derFunBlock = - cst.z2 .* cst.nx1;\n \n % ------------------------------------------------------------------\n \n case 'prm_a212'\n \n derFunBlock = - cst.x2 .* cst.ny1;\n \n % ------------------------------------------------------------------\n \n case 'prm_a222'\n \n derFunBlock = - cst.y2 .* cst.ny1;\n \n % ------------------------------------------------------------------\n \n case 'prm_a232'\n \n derFunBlock = - cst.z2 .* cst.ny1;\n \n % ------------------------------------------------------------------\n \n case 'prm_a312'\n \n derFunBlock = - cst.x2 .* cst.nz1;\n \n % ------------------------------------------------------------------\n \n case 'prm_a322'\n \n derFunBlock = - cst.y2 .* cst.nz1;\n \n % ------------------------------------------------------------------\n \n case 'prm_a332'\n \n derFunBlock = - cst.z2.* cst.nz1;\n \n % ------------------------------------------------------------------\n \n case 'prm_tx1'\n\n derFunBlock = cst.nx1;\n \n % ------------------------------------------------------------------\n \n case 'prm_tx2'\n\n derFunBlock = - cst.nx1;\n \n % ------------------------------------------------------------------\n \n case 'prm_ty1'\n\n derFunBlock = cst.ny1;\n \n % ------------------------------------------------------------------\n \n case 'prm_ty2'\n\n derFunBlock = - cst.ny1;\n \n % ------------------------------------------------------------------\n \n case 'prm_tz1'\n\n derFunBlock = cst.nz1;\n \n % ------------------------------------------------------------------\n \n case 'prm_tz2'\n\n derFunBlock = - cst.nz1;\n \n end\n \n end\n\nend\n", "meta": {"author": "pglira", "repo": "Point_cloud_tools_for_Matlab", "sha": "4768f45e7d3527c52e911eb0450c31ca19b58f72", "save_path": "github-repos/MATLAB/pglira-Point_cloud_tools_for_Matlab", "path": "github-repos/MATLAB/pglira-Point_cloud_tools_for_Matlab/Point_cloud_tools_for_Matlab-4768f45e7d3527c52e911eb0450c31ca19b58f72/costfunctions/conAffPoint2PlaneSimpleOLS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.46647300751344023}}
{"text": "classdef prtClassRvm < prtClass\n % prtClassRvm Relevance vector machine classifier\n %\n % CLASSIFIER = prtClassRvm returns a relevance vector machine classifier\n %\n % CLASSIFIER = prtClassRvm(PROPERTY1, VALUE1, ...) constructs a\n % prtClassRvm object CLASSIFIER with properties as specified by\n % PROPERTY/VALUE pairs.\n %\n % A prtClassRvm object inherits all properties from the abstract class\n % prtClass. In addition is has the following properties:\n %\n % kernels - A cell array of prtKernel objects specifying\n % the kernels to use\n % verbosePlot - Flag indicating whether or not to plot during\n % training\n % verboseText - Flag indicating whether or not to output\n % verbose updates during training\n % learningMaxIterations - The maximum number of iterations\n %\n % A prtClassRvm also has the following read-only properties:\n %\n % learningConverged - Flag indicating if the training converged\n % beta - The regression weights, estimated during training\n % sparseBeta - The sparse regression weights, estimated during\n % training\n % sparseKernels - The sparse regression kernels, estimated during\n % training\n %\n % For information on relevance vector machines, please\n % refer to the following URL:\n %\n % http://en.wikipedia.org/wiki/Relevance_vector_machine\n %\n % By default, prtClassRvm uses the Laplacian approximation as found\n % in the paper:\n %\n % Michael E. Tipping. 2001. Sparse bayesian learning and the\n % relevance vector machine. J. Mach. Learn. Res. 1 (September 2001),\n %\n % The code is based on the algorithm in: \n %\n % Herbrich, Learning Kernel Classifiers, The MIT Press, 2002\n % http://www.learning-kernel-classifiers.org/\n %\n % A prtClassRvm object inherits the TRAIN, RUN, CROSSVALIDATE and\n % KFOLDS methods from prtAction. It also inherits the PLOT method\n % from prtClass.\n %\n % Example:\n %\n % TestDataSet = prtDataGenUnimodal; % Create some test and\n % TrainingDataSet = prtDataGenUnimodal; % training data\n % classifier = prtClassRvm; % Create a classifier\n % classifier = classifier.train(TrainingDataSet); % Train\n % classified = run(classifier, TestDataSet); % Test\n % % Plot the results\n % subplot(2,1,1);\n % classifier.plot;\n % subplot(2,1,2);\n % [pf,pd] = prtScoreRoc(classified,TestDataSet);\n % h = plot(pf,pd,'linewidth',3);\n % title('ROC'); xlabel('Pf'); ylabel('Pd');\n %\n % % Example 2, using a different kernel \n %\n % TestDataSet = prtDataGenUnimodal; % Create some test and\n % TrainingDataSet = prtDataGenUnimodal; % training data\n % classifier = prtClassRvm; % Create a classifier\n % \n % % Create a prtKernelSet object with a different pair of\n % % prtKernels and assign them to the classifier\n % kernSet = prtKernelDirect & prtKernelRbf;\n % classifier.kernels = kernSet;\n %\n % classifier = classifier.train(TrainingDataSet); % Train\n % classified = run(classifier, TestDataSet); % Test\n % % Plot\n % subplot(2,1,1);\n % classifier.plot;\n % subplot(2,1,2);\n % [pf,pd] = prtScoreRoc(classified,TestDataSet);\n % h = plot(pf,pd,'linewidth',3);\n % title('ROC'); xlabel('Pf'); ylabel('Pd');\n % \n % See also prtClass, prtClassLogisticDiscriminant, prtClassBagging,\n % prtClassMap, prtClassCap, prtClassBinaryToMaryOneVsAll, prtClassDlrt,\n % prtClassPlsda, prtClassFld, prtClassRvmFigueiredo, prtClassRvmSequential, prtClassGlrt, prtClass\n\n\n\n\n\n\n\n properties (SetAccess=private)\n name = 'Relevance Vector Machine' % Relevance Vector Machine\n nameAbbreviation = 'RVM' % RVM\n isNativeMary = false; % False\n end\n \n properties\n kernels = prtKernelDc & prtKernelRbfNdimensionScale; % The kernels to be used\n \n verboseText = false; % Whether or not to display text during training\n verbosePlot = false; % Whether or not to plot during training\n \n learningMaxIterations = 1000; % The maximum number of iterations\n learningConvergedTolerance = 1e-5; % Learning tolerance; \n % at iteration i, if ||if \\theta_{i}-\\theta_{i-1}|| / length(theta)\n % < learningConvergedTolerance, learning has converged\n \n learningRelevantTolerance = 1e-5; %Tolerance below which a kernel is marked as irrelevant and removed\n % Tolerance on \\theta; if \\theta is < learningConvergedTolerance, the kernel is irrelevant and can be ignored\n end\n \n % Estimated Parameters\n properties (GetAccess = public, SetAccess = protected)\n beta = []; % Regression weights\n sparseBeta = []; % Sparse Beta\n sparseKernels = {}; % Sparse Kernel array\n learningConverged = false; % Flag indicating whether or not training convereged\n end\n \n properties\n end\n \n methods\n \n function Obj = prtClassRvm(varargin)\n Obj = prtUtilAssignStringValuePairs(Obj,varargin{:});\n end\n \n function Obj = set.learningMaxIterations(Obj,val)\n if ~prtUtilIsPositiveInteger(val)\n error('prt:prtClassRvm:learningMaxIterations','learningMaxIterations must be a positive integer');\n end\n Obj.learningMaxIterations = val;\n end\n \n function Obj = set.learningConvergedTolerance(Obj,val)\n if ~prtUtilIsPositiveScalar(val)\n error('prt:prtClassRvm:learningConvergedTolerance','learningConvergedTolerance must be a positive scalar');\n end\n Obj.learningConvergedTolerance = val;\n end\n \n function Obj = set.learningRelevantTolerance(Obj,val)\n if ~prtUtilIsPositiveScalar(val)\n error('prt:prtClassRvm:learningRelevantTolerance','learningRelevantTolerance must be a positive scalar');\n end\n Obj.learningRelevantTolerance = val;\n end\n \n function Obj = set.kernels(Obj,val)\n assert(numel(val)==1 && isa(val,'prtKernel'),'prt:prtClassRvm:kernels','kernels must be a prtKernel');\n \n Obj.kernels = val;\n end\n \n function Obj = set.verbosePlot(Obj,val)\n assert(isscalar(val) && (islogical(val) || prtUtilIsPositiveInteger(val)),'prt:prtClassRvm:verbosePlot','verbosePlot must be a logical value or a positive integer');\n Obj.verbosePlot = val;\n end\n \n function Obj = set.verboseText(Obj,val)\n assert(isscalar(val) && islogical(val),'prt:prtClassRvm:verboseText','verboseText must be a logical value, but value provided is a %s',class(val));\n Obj.verboseText = val;\n end\n \n function varargout = plot(Obj)\n % plot - Plot output confidence of the prtClassRvm object\n %\n % CLASS.plot plots the output confidence of the prtClassRvm\n % object. The dimensionality of the dataset must be 3 or\n % less, and verboseStorage must be true.\n \n HandleStructure = plot@prtClass(Obj);\n \n holdState = get(gca,'nextPlot');\n hold on;\n Obj.sparseKernels.plot;\n set(gca, 'nextPlot', holdState);\n \n varargout = {};\n if nargout > 0\n varargout = {HandleStructure};\n end\n end\n \n end\n \n methods (Access=protected, Hidden = true)\n \n function Obj = trainAction(Obj,DataSet)\n %Rvm = trainAction(Rvm,DataSet) (Private; see prtClass\\train)\n % Implements Jefferey's prior based training of a relevance\n % vector machine. The Rvm output from this function contains\n % fields \"sparseBeta\" and \"sparseKernels\"\n %\n \n\n assert(DataSet.isBinary,'prtClassRvm Requires a binary dataset');\n \n warningState = warning;\n warning off MATLAB:nearlySingularMatrix\n \n %Note: do not assume that getTargets returns a double array or\n %values \"0\" and \"1\", instead use this:\n y = Obj.getMinusOneOneTargets(DataSet);\n y(y==-1) = 0;\n \n localKernels = Obj.kernels.train(DataSet);\n gram = localKernels.run_OutputDoubleArray(DataSet);\n \n theta = ones(size(gram,2),1);\n Obj.beta = zeros(size(theta));\n deltaThetaNorm = ones(Obj.learningMaxIterations,1)*nan;\n\n if Obj.verboseText\n fprintf('RVM training with %d possible vectors.\\n', size(gram,2));\n end\n \n for iteration = 1:Obj.learningMaxIterations\n \n %%%%\n %%See: Herbrich: Learning Kernel Classifiers, Algorithm 7, Page 328\n %%%%\n \n %check tolerance for basis removal\n cRelevant = theta > Obj.learningRelevantTolerance;\n \n Obj.beta(~cRelevant) = 0;\n\n cGram = gram(:,cRelevant);\n cTheta = theta(cRelevant);\n cThetaInv = diag(1./cTheta);\n \n if isempty(cGram)\n error('prt:prtClassRvm:noRelevantVectors','No relevant vectors were retained; this indicates a kernel that is scaled improperly with regards to the classification problem. Please try choosing a different kernel or modifying the kernel parameters');\n end\n [newBeta, SigmaInvChol] = prtUtilPenalizedIrls(y,cGram,Obj.beta(cRelevant),cThetaInv);\n \n Obj.beta(cRelevant) = newBeta;\n \n SigmaChol = inv(SigmaInvChol);\n sigma = SigmaChol*SigmaChol'; %#ok\n \n zeta = ones(size(diag(cThetaInv))) - (1./cTheta).*diag(sigma);\n\n previousTheta= theta;\n theta(cRelevant) = Obj.beta(cRelevant).^2./zeta;\n \n deltaThetaNorm(iteration) = norm(previousTheta-theta)./length(theta);\n\n if ~mod(iteration,Obj.verbosePlot)\n if DataSet.nFeatures == 2\n Obj.verboseIterationPlot(DataSet,cRelevant);\n elseif iteration == 1\n warning('prt:prtClassRvm','Learning iteration plot can only be produced for training Datasets with 2 features');\n end\n end\n \n \n if deltaThetaNorm(iteration) < Obj.learningConvergedTolerance && iteration > 1\n % Converged\n \n Obj.learningConverged = true;\n \n if Obj.verboseText\n fprintf('Convergence reached. Exiting...\\n\\n');\n end\n \n break;\n end\n \n if Obj.verboseText\n fprintf('\\t Iteration %d: %d RV''s, Convergence tolerance: %g \\n',iteration, sum(cRelevant), deltaThetaNorm(iteration));\n end\n \n end\n \n if Obj.verboseText && iteration == Obj.learningMaxIterations\n fprintf('Exiting...Convergence not reached before the maximum allowed iterations was reached.\\n\\n');\n end\n \n % Make sparse represenation\n Obj.sparseBeta = Obj.beta(cRelevant,1);\n Obj.sparseKernels = localKernels.retainKernelDimensions(cRelevant);\n \n % Very bad training\n if isempty(find(cRelevant,1));\n warning('prt:prtClassRvm:NoRelevantFeatures','No relevant features were found during training.');\n end\n \n % Reset warning\n warning(warningState);\n \n end\n \n function DataSet = runAction(Obj,DataSet)\n \n if isempty(Obj.sparseBeta)\n DataSet = DataSet.setObservations(nan(DataSet.nObservations,DataSet.nFeatures));\n return\n end\n \n n = DataSet.nObservations;\n \n largestMatrixSize = prtOptionsGet('prtOptionsComputation','largestMatrixSize');\n \n memChunkSize = max(floor(largestMatrixSize/length(Obj.sparseBeta)),1);\n \n OutputMat = zeros(n,1);\n for i = 1:memChunkSize:n\n cI = i:min(i+memChunkSize,n);\n cDataSet = prtDataSetClass(DataSet.X(cI,:));\n \n gram = Obj.sparseKernels.run(cDataSet);\n \n OutputMat(cI) = prtRvUtilNormCdf(gram.getObservations*Obj.sparseBeta);\n end\n \n DataSet.X = OutputMat;\n end\n end\n\n methods (Access=protected, Hidden = true)\n \n function y = getMinusOneOneTargets(Obj, DataSet) %#ok\n yMat = double(DataSet.getTargetsAsBinaryMatrix());\n y = nan(size(yMat,1),1);\n y(yMat(:,1) == 1) = -1;\n y(yMat(:,2) == 1) = 1;\n end\n \n function G = regularizeGramInnerProduct(Obj, gram)\n nBasis = size(gram,2);\n \n sigmaSquared = 1e-6;\n \n %Check to make sure the problem is well-posed. This can be fixed either\n %with changes to kernels, or by regularization\n G = gram'*gram;\n while rcond(G) < 1e-6\n if sigmaSquared == eps && Obj.verboseText\n %warning('prt:prtClassRvm:illConditionedG','RVM initial G matrix ill-conditioned; regularizing diagonal of G to resolve; this can be modified by changing kernel parameters\\n');\n fprintf('\\n\\tRegularizing Gram matrix...\\n');\n end\n G = (sigmaSquared*eye(nBasis) + gram'*gram);\n sigmaSquared = sigmaSquared*2;\n end\n \n end\n \n function verboseIterationPlot(Obj,DataSet,relevantIndices)\n DsSummary = DataSet.summarize;\n \n [linGrid, gridSize,xx,yy] = prtPlotUtilGenerateGrid(DsSummary.lowerBounds, DsSummary.upperBounds, Obj.plotOptions); %#ok\n \n localKernels = Obj.kernels.train(DataSet);\n cKernels = localKernels.retainKernelDimensions(relevantIndices);\n cPhiDataSet = cKernels.run(prtDataSetClass([xx(:),yy(:)]));\n cPhi = cPhiDataSet.getObservations;\n \n confMap = reshape(prtRvUtilNormCdf(cPhi*Obj.beta(relevantIndices)),gridSize);\n imagesc(xx(1,:),yy(:,1),confMap,[0,1])\n colormap(Obj.plotOptions.twoClassColorMapFunction());\n axis xy\n hold on\n plot(DataSet);\n cKernels.plot();\n hold off;\n \n set(gcf,'color',[1 1 1]);\n drawnow;\n end\n end\nend\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/class/prtClassRvm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4662763256872544}}
{"text": "function [emp_cov, dist] = empCov2(x_obs, y_obs, data_obs, n_classes)\n% SYNTAX:\n% [emp_cov, dist] = empCov2(x_obs, y_obs, data_obs, n_classes)\n%\n% DESCRIPTION:\n% return the array of the empirical covariance funtion\n%\n% EXAMPLE:\n% [emp_cov, dist] = empCov2(e_obs(id_td), n_obs(id_td), td_obs);\n% figure; plot(dist, emp_cov, 'b'); hold on;\n\n%--- * --. --- --. .--. ... * ---------------------------------------------\n% ___ ___ ___\n% __ _ ___ / __| _ | __|\n% / _` / _ \\ (_ | _|__ \\\n% \\__, \\___/\\___|_| |___/\n% |___/ v 1.0RC1\n%\n%--------------------------------------------------------------------------\n% Copyright (C) 2021 Geomatics Research & Development srl (GReD)\n% Written by: Andrea Gatti\n% Contributors: Andrea Gatti ...\n% A list of all the historical goGPS contributors is in CREDITS.nfo\n%--------------------------------------------------------------------------\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n%--------------------------------------------------------------------------\n% 01100111 01101111 01000111 01010000 01010011\n%--------------------------------------------------------------------------\n\n if nargin < 4\n n_classes = 50;\n end\n\n [x_mesh, y_mesh] = meshgrid(x_obs, y_obs);\n d_obs = sqrt(abs(x_mesh - x_mesh').^2 + abs(y_mesh - y_mesh').^2);\n classes = ceil(d_obs / max(d_obs(:)) * (n_classes-1))+1;\n\n emp_cov = zeros(max(classes(:)), size(data_obs,2));\n for i = 1 : size(data_obs,2)\n corr = (data_obs(:,i)-mean(data_obs(:,i))) * (data_obs(:,i)-mean(data_obs(:,i)))';\n for c = 1 : max(classes)\n emp_cov(c, i) = mean(corr(serialize(triu(classes)==c)));\n end\n end\n emp_cov = mean(emp_cov, 2);\n dist = (0 : (n_classes - 1))' * max(d_obs(:))/n_classes;\nend\n", "meta": {"author": "goGPS-Project", "repo": "goGPS_MATLAB", "sha": "30644df61d2459e3347ac5f3e31b71d9f69f4b01", "save_path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB", "path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB/goGPS_MATLAB-30644df61d2459e3347ac5f3e31b71d9f69f4b01/source/utility/empCov2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355188, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.46614086533854693}}
{"text": "function [ a, l, r ] = r8row_part_quick_a ( m, n, a )\n\n%*****************************************************************************80\n%\n%% R8ROW_PART_QUICK_A reorders the columns of an R8ROW.\n%\n% Discussion:\n%\n% An R8ROW is an M by N array of R8's, regarded as an array of M rows,\n% each of length N.\n%\n% The routine reorders the rows of A. Using A(1,1:N) as a\n% key, all entries of A that are less than or equal to the key will\n% precede the key, which precedes all entries that are greater than the key.\n%\n% Example:\n%\n% Input:\n%\n% M = 8, N = 2\n% A = ( 2 4\n% 8 8\n% 6 2\n% 0 2\n% 10 6\n% 10 0\n% 0 6\n% 5 8 )\n%\n% Output:\n%\n% L = 2, R = 4\n%\n% A = ( 0 2 LEFT\n% 0 6\n% ----\n% 2 4 KEY\n% ----\n% 8 8 RIGHT\n% 6 2\n% 10 6\n% 10 0\n% 5 8 )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 May 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the row dimension of A.\n%\n% Input, integer N, the column dimension of A.\n%\n% Input, real A(M,N). On input, the array to be checked.\n%\n% Output, real A(M,N), the reordered array.\n%\n% Output, integer L, R, the indices of A that define the three\n% segments. Let KEY = the input value of A(1:M,1). Then\n% I <= L A(I,1:N) < KEY;\n% L < I < R A(I,1:N) = KEY;\n% R <= I KEY < A(I,1:N).\n%\n if ( m < 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8ROWL_PART_QUICK_A - Fatal error!\\n' );\n fprintf ( 1, ' M < 1.\\n' );\n return\n end\n\n if ( m == 1 )\n l = 0;\n r = 2;\n return\n end\n\n key(1:n) = a(1,1:n);\n k = 1;\n%\n% The elements of unknown size have indices between L+1 and R-1.\n%\n l = 1;\n r = m + 1;\n\n for i = 2 : m\n\n if ( r8vec_gt ( n, a(l+1,1:n), key(1:n) ) )\n r = r - 1;\n vec = a(r,1:n);\n a(r,1:n) = a(l+1,1:n);\n a(l+1,1:n) = vec;\n elseif ( r8vec_eq ( n, a(l+1,1:n), key(1:n) ) )\n k = k + 1;\n vec = a(k,1:n);\n a(k,1:n) = a(l+1,1:n);\n a(l+1,1:n) = vec;\n l = l + 1;\n elseif ( r8vec_lt ( n, a(l+1,1:n), key(1:n) ) )\n l = l + 1;\n end\n\n end\n%\n% Shift small elements to the left.\n%\n for j = 1 : l - k\n a(j,1:n) = a(j+k,1:n);\n end\n%\n% Shift KEY elements to center.\n%\n for j = l - k + 1 : l\n a(j,1:n) = key(1:n);\n end\n%\n% Update L.\n%\n l = l - k;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8row_part_quick_a.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.4661408621689785}}
{"text": "function varargout = linearProgramming(maximizeFlag, f, A, b, lb, ub, constraintTypes, variableTypes, options)\n% Provides a common interface to several linear programming solvers.\n% Checks each solver for errors.\n%\n% That is it solves the problem:\n% max f'*x\n% subject to A*x~b, lb<=x<=ub\n% where \"~\" can be equality, or double or single-sided inequality\n% constraints if the chosen linear programming solver supports those\n% types of constraints. Additionally the variables, x, can, if the chosen\n% linear programming solver supports it, either continuous, integer, and\n% boolean valued.\n%\n% Constraint Types: etiher a single value, or a column vector or values:\n% 'F' Free (unbounded) variable (the constraint is ignored).\n% 'U' Variable with upper bound ( A(i,:)*x <= b(i)).\n% 'S' Fixed Variable (A(i,:)*x = b(i)).\n% 'L' Variable with lower bound (A(i,:)*x >= b(i)).\n% 'D' Double-bounded variable (A(i,:)*x >= -b(i) and A(i,:)*x <= b(i)).\n%\n% Variable Types: either a single value, or a column vector or values:\n% 'C' Continuous variable.\n% 'I' Integer variable\n% 'B' Binary variable\n%\n% Output\n% x\n% lambda, \n% fopt\n% errorFlag\n% errorMsg\n% extra\n%\n% Requirements: at least one of the following linear programing solvers\n% - glpk -- GNU Linear programming kit, to solve linear programming problems\n% http://sourceforge.net/projects/glpkmex/\n% - lp_solve -- open source solve linear programming solver\n% http://sourceforge.net/projects/lpsolve\n% - clp -- open source solve linear programming solver\n% http://control.ee.ethz.ch/~joloef/mexclp.zip\n% - bpmpd -- open source solve linear programming solver\n% http://www.pserc.cornell.edu/bpmpd/\n% - qsopt -- open source solve linear programming solver\n% http://control.ee.ethz.ch/~joloef/mexqsopt.msql\n% - Optimization Toolbox - has linprog, MATLAB's linear programming\n% solver. Note: linprog is not vevy good. We suggest you use another\n% solver instead.\n% http://www.mathworks.com/products/optimization/\n%\n% Author: Jonathan Karr\n% Affiliation: Covert Lab, Department of Bioengineering, Stanford University\n% Last updated: 10/31/2008\n\n%- A is non-empty\n%- b is real column vector of length ncols(A)\n%- lb, ub are real column vectors of length nrows(A)\nvalidateattributes(A, {'numeric'}, {'nonempty'});\nvalidateattributes(b, {'numeric'}, {'real', 'size', [size(A, 1) 1]});\nif isempty(lb)\n lb = -Inf(size(A, 2), 1);\nelse\n validateattributes(lb, {'numeric'}, {'real', 'size', [size(A, 2) 1]});\nend\nif isempty(ub)\n ub = -Inf(size(A, 2), 1);\nelse\n validateattributes(ub, {'numeric'}, {'real', 'size', [size(A, 2) 1]});\nend\n\n%error check length sizes of contraint and variable types, expand if\n%necessary\nif isscalar(constraintTypes)\n if ~ismembc(constraintTypes, 'DFLSUdflsu')\n throw(MException('ComputationUtil:LinearProgramming', 'linear programming: invalid constraints types'));\n end\n constraintTypes = constraintTypes(ones(length(b), 1), 1);\nelseif length(constraintTypes) ~= length(b)\n throw(MException('ComputationUtil:LinearProgramming', 'linear programming: invalid constraints types'));\nelseif ~all(ismembc(constraintTypes, 'DFLSUdflsu'))\n throw(MException('ComputationUtil:LinearProgramming', 'linear programming: invalid constraints types'));\nend\n\nif isscalar(variableTypes)\n if ~ismembc(variableTypes, 'BCIbci')\n throw(MException('ComputationUtil:LinearProgramming', 'linear programming: invalid variable types'));\n end\n variableTypes = variableTypes(ones(size(A, 2), 1), 1);\nelseif length(variableTypes) ~= length(lb)\n throw(MException('ComputationUtil:LinearProgramming', 'linear programming: invalid variable types'));\nelseif ~all(ismembc(variableTypes, 'BCIbci'))\n throw(MException('ComputationUtil:LinearProgramming', 'linear programming: invalid variable types'));\nend\n\n%compute sense from maximizeFlag\n%if maximize='maximize'->sense=-1\n%otherwise->sense=1\nsense = 1 - 2 *strcmp(maximizeFlag, 'maximize');\n\n%solver linear programming problem using chosen solver\nvarargout = cell(max(nargout, 1), 1);\nswitch options.solver(1:2)\n case 'gl'; [varargout{:}] = runglpk( f, A, b, lb, ub, sense, constraintTypes, variableTypes, options);\n case 'li'; [varargout{:}] = runlinprog(f, A, b, lb, ub, sense, constraintTypes, variableTypes, options); \n case 'bp'; [varargout{:}] = runbpmpd( f, A, b, lb, ub, sense, constraintTypes, variableTypes, options);\n case 'cl'; [varargout{:}] = runclp( f, A, b, lb, ub, sense, constraintTypes, variableTypes, options);\n case 'lp'; [varargout{:}] = runlpsolve(f, A, b, lb, ub, sense, constraintTypes, variableTypes, options);\n case 'qs'; [varargout{:}] = runqsopt( f, A, b, lb, ub, sense, constraintTypes, variableTypes, options);\n case 'to'; [varargout{:}] = runtomlab( f, A, b, lb, ub, sense, constraintTypes, variableTypes, options);\n case 'cp'; [varargout{:}] = runcplex( f, A, b, lb, ub, sense, constraintTypes, variableTypes, options);\n case 'gu'; [varargout{:}] = rungurobi( f, A, b, lb, ub, sense, constraintTypes, variableTypes, options);\n case 'mo'; [varargout{:}] = runmosek( f, A, b, lb, ub, sense, constraintTypes, variableTypes, options);\n otherwise; throw(MException('ComputationUtil:LinearProgramming', 'Support for %s not implemented', options.solver));\nend\n\nfunction [x, lambda, fopt, errorFlag, errorMsg, extra] = runlinprog(f, A, b, lb, ub, sense, constraintTypes, variableTypes, options)\n\n%setup equality, inequality constraints based on constraint types\nAeq = [];\nbeq = [];\nif sum(constraintTypes == 'S') == length(constraintTypes)\n Aeq = A;\n A = [];\n beq = b;\n b = [];\nelseif sum(constraintTypes == 'U') == length(constraintTypes)\nelseif sum(constraintTypes == 'L') == length(constraintTypes)\n A = -A;\n b = -b;\nelse\n throw(MException('ComputationUtil:LinearProgramming', 'linprog: constraint types invalid'));\nend\n\n%throw error if integer or boolean variable types requested, linprog\n%doesn't have this capability\nif sum(variableTypes == 'C') ~= length(variableTypes)\n throw(MException('ComputationUtil:LinearProgramming', 'linprog: variable types invalid'));\nend\n\n%linprog options\nif isfield(options.solverOptions, 'linprog')\n linprogoptions = options.solverOptions.linprog;\nelse\n linprogoptions = struct;\nend\n\ntry\n [x, fopt, exitflag, ~, lambda] = linprog(sense * f, A, b, Aeq, beq, lb, ub, [], linprogoptions);\n \n lambda = struct('reducedCosts', NaN(size(A, 2), 1), 'shadowPrices', lambda); \n fopt = fopt * sense;\n errorFlag = exitflag ~= 1;\n switch exitflag\n case 1; errorMsg = 'Function converged to a solution x.';\n case 0; errorMsg = 'Number of iterations exceeded options.MaxIter.';\n case -2; errorMsg = 'No feasible point was found.';\n case -3; errorMsg = 'Problem is unbounded.';\n case -4; errorMsg = 'NaN value was encountered during execution of the algorithm.';\n case -5; errorMsg = 'Both primal and dual problems are infeasible.';\n case -7; errorMsg = 'Search direction became too small. No further progress could be made.';\n end\ncatch exception\n errorFlag = 1;\n errorMsg = exception.message;\n x = NaN(size(lb));\n lambda = struct('reducedCosts', NaN(size(A, 2), 1), 'shadowPrices', NaN(size(A, 1), 1));\n fopt = NaN; \nend\n\nextra = struct;\n\nfunction [x, lambda, fopt, errorFlag, errorMsg, extra] = runglpk(f, A, b, lb, ub, sense, constraintTypes, variableTypes, options)\n\n%make structure of glpk options\nif isfield(options.solverOptions, 'glpk')\n glpkoptions = options.solverOptions.glpk;\nelse\n glpkoptions = struct;\nend\n\n%call glpk\ntry\n [x, fopt, status, extra] = glpkcc(f, A, b, lb, ub, constraintTypes, variableTypes, sense, glpkoptions);\n lambda = struct('reducedCosts', extra.redcosts, 'shadowPrices', extra.lambda);\n errorFlag = ~(status == 5 || status == 2);\n switch status\n %General Errors\n case 5; errorMsg = 'Solution is optimal';\n case 2; errorMsg = 'Solution is feasible';\n case 1; errorMsg = 'Solution is undefined';\n case 3; errorMsg = 'Solution is infeasible';\n case 4; errorMsg = 'No feasible solution exists';\n case 6; errorMsg = 'Solution is unbounded';\n \n %Simplex method Errors:\n case 101; errorMsg = 'Invalid basis';\n case 102; errorMsg = 'Singular matrix';\n case 103; errorMsg = 'Ill-conditioned matrix';\n case 104; errorMsg = 'Invalid bounds';\n case 105; errorMsg = 'Solver failed';\n case 106; errorMsg = 'Objective lower limit reached';\n case 107; errorMsg = 'Objective upper limit reached';\n case 108; errorMsg = 'Iteration limit exceeded';\n case 109; errorMsg = 'Time limit exceeded';\n case 110; errorMsg = 'No primal feasible solution';\n\n %Interior point method, mixed integer problem Errors:\n case 204; errorMsg = 'Unable to start the search.';\n case 205; errorMsg = 'Objective function lower limit reached.';\n case 206; errorMsg = 'Objective function upper limit reached.';\n case 207; errorMsg = 'Iterations limit exhausted.';\n case 208; errorMsg = 'Time limit exhausted.';\n case 209; errorMsg = 'No feasible solution.';\n case 210; errorMsg = 'Numerical instability.';\n case 211; errorMsg = 'Problems with basis matrix.';\n case 212; errorMsg = 'No convergence (interior).';\n case 213; errorMsg = 'No primal feasible solution (LP presolver).';\n case 214; errorMsg = 'No dual feasible solution (LP presolver).';\n \n otherwise, errorMsg = sprintf('Invalid error code %d', status);\n end\ncatch exception\n errorFlag = 1;\n errorMsg = exception.message;\n x = NaN(size(lb));\n lambda = struct('reducedCosts', NaN(size(A, 2), 1), 'shadowPrices', NaN(size(A, 1), 1));\n fopt = NaN;\nend\n\nextra = struct;\n\nfunction [x, lambda, fopt, errorFlag, errorMsg, extra] = runlpsolve(f, A, b, lb, ub, sense, constraintTypes, variableTypes, options)\n%options\nverbose = 3;\npresolve = 0; %none\nscaling = 4 + 64 + 128; %geometric + equilibrate + integers\nif isfield(options.solverOptions, 'lp_solve')\n if isfield(options.solverOptions.lp_solve, 'verbose'), verbose = options.solverOptions.lp_solve.verbose; end\n if isfield(options.solverOptions.lp_solve, 'presolve'), presolve = options.solverOptions.lp_solve.presolve; end\n if isfield(options.solverOptions.lp_solve, 'scaling'), scaling = options.solverOptions.lp_solve.scaling; end \nend\n\n%convert variable types to lp_solve format'\nif any(variableTypes == 'B'); throw(MException('ComputationUtil:LinearProgramming', 'lp_solve: boolean variables are not allowed')); end;\nxint = NaN(size(variableTypes));\nxint(variableTypes == 'I') = 1;\nxint(variableTypes == 'C') = 0;\n\n%convert constraints types to lp_solve format\nif any(constraintTypes == 'F'); throw(MException('ComputationUtil:LinearProgramming', 'lp_solve: free constraints are not allowed')); end;\nif any(constraintTypes == 'D'); throw(MException('ComputationUtil:LinearProgramming', 'lp_solve: double-sided constraints are not allowed')); end;\ncon_types = NaN(size(constraintTypes));\ncon_types(constraintTypes == 'L') = 2;\ncon_types(constraintTypes == 'S') = 3;\ncon_types(constraintTypes == 'U') = 1;\n\ntry\n lp = mxlpsolve('make_lp', size(A, 1), size(A, 2));\n mxlpsolve('set_verbose', lp, verbose);\n mxlpsolve('set_mat', lp, A);\n mxlpsolve('set_rh_vec', lp, b);\n mxlpsolve('set_obj_fn', lp, f);\n mxlpsolve('set_sense', lp, (sense == -1) + 0);\n mxlpsolve('set_constr_type', lp, con_types);\n mxlpsolve('set_bounds', lp, lb, ub);\n mxlpsolve('set_int', lp, xint); \n mxlpsolve('set_presolve', lp, presolve, mxlpsolve('get_presolveloops', lp));\n mxlpsolve('set_scaling', lp, scaling);\n \n status = mxlpsolve('solve', lp);\n errorFlag =~ status == 0 || status == 1 || status == 11 || status == 12;\n if ~errorFlag\n [fopt, x, duals] = mxlpsolve('get_solution', lp);\n reducedCosts = mxlpsolve('get_reduced_costs', lp);\n else\n fopt = NaN;\n x = NaN(size(lb));\n duals = NaN(size(A, 1), 1);\n reducedCosts = NaN(size(A, 2), 1); \n end\n \n extra = struct;\n if nargin >= 6\n tmpFileName = ['lpsolve.' datestr(now, 30) '.txt'];\n \n mxlpsolve('set_outputfile', lp, tmpFileName);\n mxlpsolve('print_scales', lp);\n \n fid = fopen(tmpFileName, 'r');\n fgetl(fid);\n fgetl(fid);\n line = fgetl(fid);\n extra.objScaling = str2double(line(32:end));\n extra.rowScaling = zeros(size(A, 1), 1);\n extra.colScaling = zeros(size(A, 2), 1);\n for i = 1:size(A, 1)\n line = fgetl(fid);\n extra.rowScaling(i) = str2double(line(32:end));\n end\n for i = 1:size(A, 2)\n line = fgetl(fid);\n extra.colScaling(i) = str2double(line(32:end));\n end\n fclose(fid); \n end\n \n mxlpsolve('delete_lp', lp);\n \n if nargin >= 6\n delete(tmpFileName);\n end\n \n lambda = struct('reducedCosts', reducedCosts, 'shadowPrices', duals);\n switch status\n case -2; errorMsg = 'Out of memory';\n case 0; errorMsg = 'An optimal solution was obtained';\n case 1; errorMsg = ['The model is sub-optimal. Only happens if there are integer variables and there is already an integer solution found. The solution is not guaranteed the most optimal one.\\n'...\n '* A timeout occured (set via set_timeout or with the -timeout option in lp_solve)\\n'...\n '* set_break_at_first was called so that the first found integer solution is found (-f option in lp_solve)\\n'...\n '* set_break_at_value was called so that when integer solution is found that is better than the specified value that it stops (-o option in lp_solve)\\n'...\n '* set_mip_gap was called (-g/-ga/-gr options in lp_solve) to specify a MIP gap\\n'...\n '* An abort function is installed (put_abortfunc) and this function returned TRUE\\n'...\n '* At some point not enough memory could not be allocated'];\n case 2; errorMsg = 'The model is infeasible';\n case 3; errorMsg = 'The model is unbounded';\n case 4; errorMsg = 'The model is degenerative';\n case 5; errorMsg = 'Numerical failure encountered';\n case 6; errorMsg = 'The abort routine returned TRUE. See put_abortfunc';\n case 7; errorMsg = 'A timeout occurred. A timeout was set via set_timeout';\n case 9; errorMsg = 'The model could be solved by presolve. This can only happen if presolve is active via set_presolve';\n case 10; errorMsg = 'The B&B routine failed';\n case 11; errorMsg = 'The B&B was stopped because of a break-at-first (see set_break_at_first) or a break-at-value (see set_break_at_value)';\n case 12; errorMsg = 'A feasible B&B solution was found';\n case 13; errorMsg = 'No feasible B&B solution found';\n end\ncatch exception\n errorFlag = 1;\n errorMsg = exception.message;\n x = NaN(size(lb));\n lambda = struct('reducedCosts', NaN(size(A, 2), 1), 'shadowPrices', NaN(size(A, 1), 1));\n fopt = NaN;\n extra = struct;\nend\n\nfunction [x, lambda, fopt, errorFlag, errorMsg, extra] = runqsopt(f, A, b, lb, ub, sense, constraintTypes, variableTypes, options)\n\n%setup equality, inequality constraints based on constraint types\nAeq = [];\nbeq = [];\nif sum(constraintTypes == 'S') == length(constraintTypes)\n Aeq = A;\n A = [];\n beq = b;\n b = [];\nelseif sum(constraintTypes == 'U') == length(constraintTypes)\nelseif sum(constraintTypes == 'L') == length(constraintTypes)\n A = -A;\n b = -b;\nelse\n throw(MException('ComputationUtil:LinearProgramming', 'qsopt: constraint types invalid'));\nend\n\n%throw error if integer or boolean variable types requested, qsopt\n%doesn't have this capability\nif sum(variableTypes == 'C') ~= length(variableTypes)\n throw(MException('ComputationUtil:LinearProgramming', 'qsopt: variable types invalid'));\nend\n\n%make structure of qsopt options\nqsoptoptions = struct;\nif isfield(options.solverOptions, 'qsopt')\n qsoptoptions = options.solverOptions.qsopt;\nend\n\ntry\n [x, dual, status] = qsopt(sense * f, A, b, Aeq, beq, lb, ub, qsoptoptions);\n lambda = struct('reducedCosts', NaN(size(A, 2), 1), 'shadowPrices', dual);\n fopt = f' * x;\n errorFlag = status ~= 1;\n switch status\n case 1; errorMsg = 'optimal';\n case 2; errorMsg = 'infeasible';\n case 3; errorMsg = 'unbounded';\n case 4; errorMsg = 'iteration limit';\n case 5; errorMsg = 'time limit';\n case 6; errorMsg = 'other problem';\n end\ncatch exception\n errorFlag = 1;\n errorMsg = exception.message;\n x = NaN(size(lb));\n lambda = struct('reducedCosts', NaN(size(A, 2), 1), 'shadowPrices', NaN(size(A, 1), 1));\n fopt = NaN;\nend\n\nextra = struct;\n\nfunction [x, lambda, fopt, errorFlag, errorMsg, extra] = runclp(f, A, b, lb, ub, sense, constraintTypes, variableTypes, options)\n\n%setup equality, inequality constraints based on constraint types\nAeq = [];\nbeq = [];\nif sum(constraintTypes == 'S') == length(constraintTypes)\n Aeq = A;\n A = [];\n beq = b;\n b = [];\nelseif sum(constraintTypes == 'U') == length(constraintTypes)\nelseif sum(constraintTypes == 'L') == length(constraintTypes)\n A = -A;\n b = -b;\nelse\n throw(MException('ComputationUtil:LinearProgramming', 'clp: constraint types invalid'));\nend\n\n%throw error if integer or boolean variable types requested, clp\n%doesn't have this capability\nif sum(variableTypes == 'C') ~= length(variableTypes)\n throw(MException('ComputationUtil:LinearProgramming', 'clp: variable types invalid'));\nend\n\n%make structure of clp options\nclpoptions = struct;\nif isfield(options.solverOptions, 'clp')\n clpoptions = options.solverOptions.clp;\nend\n\ntry\n [x, dual, status] = clp(zeros(length(f)), sense * f, A, b, Aeq, beq, lb, ub, clpoptions);\n lambda = struct('reducedCosts', NaN(size(A, 2), 1), 'shadowPrices', dual);\n fopt = f' * x;\n errorFlag = status ~= 0;\n switch status\n case 0; errorMsg = 'optimal';\n case 1; errorMsg = 'infeasible';\n case 2; errorMsg = 'unbounded';\n end\ncatch exception\n errorFlag = 1;\n errorMsg = exception.message;\n x = NaN(size(lb));\n lambda = struct('reducedCosts', NaN(size(A, 2), 1), 'shadowPrices', NaN(size(A, 1), 1));\n fopt = NaN;\nend\n\nextra = struct;\n\nfunction [x, lambda, fopt, errorFlag, errorMsg, extra] = runbpmpd(f, A, b, lb, ub, sense, constraintTypes, variableTypes, ~)\n\n%throw error if integer or boolean variable types requested, bpmpd\n%doesn't have this capability\nif sum(variableTypes == 'C') ~= length(variableTypes)\n throw(MException('ComputationUtil:LinearProgramming', 'bpmpd: variable types invalid'));\nend\n\n%convert constraints types to bpmpd format\nif any(constraintTypes == 'F'); throw(MException('ComputationUtil:LinearProgramming', 'bpmpd: free constraints are not allowed')); end;\nif any(constraintTypes == 'D'); throw(MException('ComputationUtil:LinearProgramming', 'bpmpd: double-sided constraints are not allowed')); end;\ne = NaN(size(constraintTypes));\ne(constraintTypes == 'L') = 1;\ne(constraintTypes == 'S') = 0;\ne(constraintTypes == 'U') = -1;\n\n%throw error if integer or boolean variable types requested, bpmpd\n%doesn't have this capability\nif sum(variableTypes == 'C') ~= length(variableTypes)\n throw(MException('ComputationUtil:LinearProgramming', 'bpmpd: variable types invalid'));\nend\n\ntry\n llist = (1:length(lb))';\n ulist = (1:length(ub))';\n [x, dual, ~, w, errorMsg] = bp(zeros(length(f)), A, b, sense * f, e, llist, lb, ulist, ub, bpopt,0);\n lambda = struct('reducedCosts', w, 'shadowPrices', dual);\n fopt = f' * x;\n errorFlag =~ strcmp(errorMsg, 'optimal solution');\ncatch exception\n errorFlag = 1;\n errorMsg = exception.message;\n x = NaN(size(lb));\n lambda = struct('reducedCosts', NaN(size(A, 2), 1), 'shadowPrices', NaN(size(A, 1), 1));\n fopt = NaN;\nend\n\nextra = struct;\n\nfunction [x, lambda, fopt, errorFlag, errorMsg, extra] = runtomlab( f, A, b, lb, ub, sense, constraintTypes, ~, options)\n\nb_L = -Inf(size(b));\nb_U = Inf(size(b));\nb_L(constraintTypes == 'L') = b(constraintTypes == 'L');\nb_U(constraintTypes == 'U') = b(constraintTypes == 'U');\nb_L(constraintTypes == 'S') = b(constraintTypes == 'S');\nb_U(constraintTypes == 'S') = b(constraintTypes == 'S');\nb_L(constraintTypes == 'D') = -b(constraintTypes == 'D');\nb_U(constraintTypes == 'D') = b(constraintTypes == 'D');\n\nprob = lpAssign(sense * f, A, b_L, b_U, lb, ub, [], [], [], [], [], [], [], [], []);\n\nsolver = 'minos';\nprob.optParam = struct();\nPriLev = 0;\nif isfield(options.solverOptions, 'tomlab')\n if isfield(options.solverOptions.tomlab, 'solver'), solver = options.solverOptions.tomlab.solver; end \n if isfield(options.solverOptions.tomlab, 'optParam'), prob.optParam = options.solverOptions.tomlab.optParam; end\n if isfield(options.solverOptions.tomlab, 'PriLev'), PriLev = options.solverOptions.tomlab.PriLev; end\nend\n\ntry \n result = tomRun(solver, prob, PriLev);\n errorFlag = result.ExitFlag ~= 0;\n errorMsg = result.ExitText;\n fopt = sense * result.f_k;\n x = result.x_k;\n lambda = struct('reducedCosts', NaN(size(A, 2), 1), 'shadowPrices', NaN(size(A, 1), 1));\ncatch exception\n errorFlag = 1;\n errorMsg = exception.message;\n x = NaN(size(lb));\n lambda = struct('reducedCosts', NaN(size(A, 2), 1), 'shadowPrices', NaN(size(A, 1), 1));\n fopt = NaN;\nend\n\nextra = struct;\n\nfunction [x, lambda, fopt, errorFlag, errorMsg, extra] = runcplex(f, A, b, lb, ub, sense, constraintTypes, variableTypes, options)\nconstraintTypes = upper(constraintTypes);\nif ~ismembc(constraintTypes, 'LSU')\n throw(MException('ComputationUtil:LinearProgramming', 'linear programming: invalid constraints types'));\nend\n\nAineq = [\n -A(constraintTypes == 'L', :)\n A(constraintTypes == 'U', :)\n ];\nbineq = [\n -b(constraintTypes == 'L', :)\n b(constraintTypes == 'U', :)\n ];\n \nAeq = A(constraintTypes == 'S', :);\nbeq = b(constraintTypes == 'S', :);\n\ntry\n [x, fopt, exitFlag, output] = cplexmilp(...\n sense * f, ...\n Aineq, bineq, ...\n Aeq, beq, ...\n [], [], [], lb, ub, variableTypes');\n errorFlag = exitFlag ~= 1;\n errorMsg = output.message;\ncatch exception\n errorFlag = 1;\n errorMsg = exception.message;\n x = NaN(size(lb));\n fopt = NaN;\nend\nlambda = struct('reducedCosts', NaN(size(A, 2), 1), 'shadowPrices', NaN(size(A, 1), 1));\n\nextra = struct('status', output.cplexstatus);\n\nfunction [x, lambda, fopt, errorFlag, errorMsg, extra] = rungurobi( f, A, b, lb, ub, sense, constraintTypes, variableTypes, options)\nb_L = -Inf(size(b));\nb_U = Inf(size(b));\nb_L(constraintTypes == 'L') = b(constraintTypes == 'L');\nb_U(constraintTypes == 'U') = b(constraintTypes == 'U');\nb_L(constraintTypes == 'S') = b(constraintTypes == 'S');\nb_U(constraintTypes == 'S') = b(constraintTypes == 'S');\nb_L(constraintTypes == 'D') = -b(constraintTypes == 'D');\nb_U(constraintTypes == 'D') = b(constraintTypes == 'D');\n\nxint = NaN(size(variableTypes));\nxint(variableTypes == 'I') = 1;\nxint(variableTypes == 'C') = 0;\n\nPriLev = 0;\ngrbControl = struct();\nif isfield(options.solverOptions, 'gurobi')\n if isfield(options.solverOptions.gurobi, 'PriLev'), PriLev = options.solverOptions.gurobi.PriLev; end\n if isfield(options.solverOptions.gurobi, 'grbControl'), grbControl = options.solverOptions.gurobi.grbControl; end\nend\n\ntry \n [x, ~, v, rc, fopt, ~, ~, status] = ...\n gurobi(sense * f, A, lb, ub, b_L, b_U, [], ...\n grbControl, PriLev, xint);\n fopt = fopt * sense;\n [errorMsg, exitFlag] = grbStatus(status);\n errorFlag = exitFlag ~= 0;\n lambda = struct('reducedCosts', rc, 'shadowPrices', v);\ncatch exception\n errorFlag = 1;\n errorMsg = exception.message;\n x = NaN(size(lb));\n lambda = struct('reducedCosts', NaN(size(A, 2), 1), 'shadowPrices', NaN(size(A, 1), 1));\n fopt = NaN;\nend\n\nextra = struct;\n\nfunction [x, lambda, fopt, errorFlag, errorMsg, extra] = runmosek( f, A, b, lb, ub, sense, constraintTypes, ~, options)\nif sense == 1\n cmd = 'minimize';\nelse\n cmd = 'maximize';\nend\n\nb_L = -Inf(size(b));\nb_U = Inf(size(b));\nb_L(constraintTypes == 'L') = b(constraintTypes == 'L');\nb_U(constraintTypes == 'U') = b(constraintTypes == 'U');\nb_L(constraintTypes == 'S') = b(constraintTypes == 'S');\nb_U(constraintTypes == 'S') = b(constraintTypes == 'S');\nb_L(constraintTypes == 'D') = -b(constraintTypes == 'D');\nb_U(constraintTypes == 'D') = b(constraintTypes == 'D');\n\nlb = max(lb, -1e7);\nub = min(ub, 1e7);\n\nopts = struct(...\n 'MSK_IPAR_LOG', 0, 'MSK_IPAR_MAX_NUM_WARNINGS', 1e5, ...\n 'MSK_IPAR_INTPNT_SCALING', 0, 'MSK_IPAR_SIM_SCALING', 0, 'MSK_IPAR_SIM_SCALING_METHOD', 1);\nif isfield(options.solverOptions, 'mosek')\n opts = options.solverOptions.mosek;\nend\n\ntry \n result = msklpopt(f, A, b_L, b_U, lb, ub, opts, cmd);\n fopt = result.sol.itr.pobjval;\n x = result.sol.itr.xx;\n errorFlag = result.rcode ~= 0;\n errorMsg = result.rmsg;\n lambda = struct(...\n 'reducedCosts', result.sol.itr.slx + result.sol.itr.sux, ...\n 'shadowPrices', result.sol.itr.slc + result.sol.itr.suc);\ncatch exception\n errorFlag = 1;\n errorMsg = exception.message;\n x = NaN(size(lb));\n lambda = struct('reducedCosts', NaN(size(A, 2), 1), 'shadowPrices', NaN(size(A, 1), 1));\n fopt = NaN;\nend\n\nextra = struct;", "meta": {"author": "CovertLab", "repo": "WholeCell", "sha": "6cdee6b355aa0f5ff2953b1ab356eea049108e07", "save_path": "github-repos/MATLAB/CovertLab-WholeCell", "path": "github-repos/MATLAB/CovertLab-WholeCell/WholeCell-6cdee6b355aa0f5ff2953b1ab356eea049108e07/src/+edu/+stanford/+covert/+util/@ComputationUtil/linearProgramming.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4661408526602731}}
{"text": "classdef ICMA < ALGORITHM\n% \n% Indicator-based constrained multi-objective algorithm\n\n%------------------------------- Reference --------------------------------\n% J. Yuan, H. Liu, Y. Ong, and Z. He, Indicator-based evolutionary\n% algorithm for solving constrained multi-objective optimization problems,\n% IEEE Transactions on Evolutionary Computation, 2022, 26(2): 379-391.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n% This function is written by Jiawei Yuan\n\n methods\n function main(Algorithm,Problem)\n %% Generate the random population\n Population = Problem.Initialization();\n Zmin = min(Population.objs,[],1);\n Fmin = min(Population(all(Population.cons<=0,2)).objs,[],1);\n Archive = Population;\n W = UniformPoint(Problem.N,Problem.M);\n Ra = 1;\n \n %% Optimization\n while Algorithm.NotTerminated(Archive)\n Nt = floor(Ra*Problem.N);\n MatingPool = [Population(randsample(Problem.N,Nt)),Archive(randsample(Problem.N,Problem.N-Nt))];\n \n [Mate1,Mate2,Mate3] = Neighbor_Pairing_Strategy(MatingPool,Zmin);\n if rand > 0.5\n Offspring = OperatorDE(Problem,Mate1,Mate2,Mate3);\n else\n Offspring = OperatorDE(Problem,Mate1,Mate2,Mate3,{0.5,0.5,0.5,0.75});\n end\n \n Fmin = min([Fmin;Offspring(all(Offspring.cons<=0,2)).objs],[],1);\n Zmin = min([Zmin;Offspring.objs],[],1);\n [Population,Archive] = ICMA_Update([Population,Offspring,Archive],Problem.N,W,Zmin,Fmin);\n \n Ra = 1 - Problem.FE/Problem.maxFE;\n end\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Algorithms/Multi-objective optimization/ICMA/ICMA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.615087848460224, "lm_q1q2_score": 0.46611011613162284}}
{"text": "% Author: Ricardo Baptista and Matthias Poloczek\n% Date: June 2018\n%\n% See LICENSE.md for copyright information\n%\n\nfunction particle_system = move_particles(particle_system)\n% MOVE_PARTICLES: Function moves the current particles according to an MCMC\n% kernel with an adaptive logistic regression proposal.\n\n% Extract function inputs\nn_vars = particle_system.n_vars;\nmodel_orig = particle_system.models;\nmodel_val = particle_system.model_val;\nrho = particle_system.rho;\nlogistic_A = particle_system.logistic_A;\n\n% Determine the number of current models, and dimensions\n[n_models, ~] = size(model_orig);\n\n% Compute the old particle diversity ratio\ndiversity_old = unique_particles(model_orig);\n\n% Declare vector for accept_ratios\nmh_accept_vect = [];\n\ntotal_fn_count = particle_system.total_fn_count(end);\n\niter_temp = 0;\nwhile(1)\n \n % Generate matrix to store new samples and data\n new_model = zeros(n_models, n_vars);\n new_mval = zeros(n_models, 1);\n\n % Declare vector to store acceptance ratio\n accept_ratio = 0;\n \n for i=1:n_models\n \n % Propose new model\n [prop_model, ~] = logistic_sample(n_vars, logistic_A);\n \n % Evaluate proposal density under both models\n q_new = evaluate_logit(particle_system, prop_model);\n q_old = evaluate_logit(particle_system, model_orig(i,:));\n\n % Evaluate probability function for both models\n total_fn_count = total_fn_count + 1;\n model_obj_new = particle_system.objective(prop_model);\n log_post_new = rho*model_obj_new;\n log_post_old = rho*model_val(i);\n\n % Compute acceptance probability\n accept_prob = exp(log_post_new - log_post_old)*(q_old/q_new);\n\n % Accept proposed sample/data or assign old values\n if rand < min(1,accept_prob)\n new_model(i,:) = prop_model;\n new_mval(i) = model_obj_new;\n accept_ratio = accept_ratio + 1;\n else\n new_model(i,:) = model_orig(i,:);\n new_mval(i) = model_val(i);\n end\n \n end\n\n %% Update Sample Information\n\n % Update variables\n model_orig = new_model;\n model_val = new_mval;\n mh_accept_vect = [mh_accept_vect, accept_ratio/n_models];\n\n % Compute the new particle diversity\n diversity_new = unique_particles(new_model);\n\n % Compare the diversity\n if (abs(diversity_new - diversity_old) < 0.02 || diversity_new > 0.95)\n break\n end\n\n % Update diversity_old\n diversity_old = diversity_new;\n\n iter_temp = iter_temp + 1;\n if iter_temp > 100\n break\n end\n\nend\n\n% Update particle_system\nparticle_system.models = model_orig;\nparticle_system.model_val = model_val;\nparticle_system.mh_accept = min(mh_accept_vect);\nparticle_system.total_fn_count = [particle_system.total_fn_count, total_fn_count];\n\nend\n", "meta": {"author": "baptistar", "repo": "BOCS", "sha": "fef0d4e34e376e8bb0dae9955d70c2155530b9eb", "save_path": "github-repos/MATLAB/baptistar-BOCS", "path": "github-repos/MATLAB/baptistar-BOCS/BOCS-fef0d4e34e376e8bb0dae9955d70c2155530b9eb/algorithms/SMC_Code/move_particles.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943603346811, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.46611010802042835}}
{"text": "function M = slpweval(X1, X2, f, varargin)\n%SLPWEVAL Perform pairwise computation\n%\n% $ Syntax $\n% - M = slpweval(X1, X2, f)\n% - M = slpweval(X1, X2, f, ...)\n%\n% $ Arguments $\n% - X1: the matrix of vectors serving as first argument of f\n% - X2: the matrix of vectors serving as second argument of f\n% - f: the function maps two vectors to a single scalar value\n% - M: the matrix of pairwise evaluaton results\n%\n% $ Description $\n% - M = slpweval(X1, X2, f) takes vector arguments from X1 and X2, and \n% computes the pairwise evaluation result with f. The vectors in X1\n% and X2 are stored in a column-wise manner. Suppose X1 and X2 have \n% m and n columns respectively, then the resultant matrix M would be\n% of size m x n, with the M(i, j) = f(X1(:,i), X2(:,j)). \n% \n% - M = slpweval(X1, X2, f, ...) conducts the computation with extra\n% parameters to f, i.e. M(i, j) = f(X1(:,i), X2(:,j), ...).\n%\n% $ Remarks $\n% - The vector length of the vectors in X1 and X2 are not necessarily\n% equal. The requirment on their dimensions depends on the callback\n% function f.\n% - For efficiency, the function would invoke f to evaluate in batch.\n% Thus f should support batch-evaluation. When the input arguments\n% to f have n columns, f should return an 1 x n row vector.\n%\n% $ History $\n% - Created by Dahua Lin on Apr 21, 2006\n% - Modified by Dahua Lin on Sep 10, 2006\n% - make some minor changes to suppress warnings\n%\n\n%% parse and verify input arguments\n\nif nargin < 3\n raise_lackinput('slpweval', 3);\nend\n[d1, n1] = size(X1);\n[d2, n2] = size(X2);\nslignorevars(d1, d2);\n\n%% compute\n\n% prepare output matrix\nM = zeros(n1, n2);\n\nif n1 > n2 % expand each column in X2 to n1 copies\n \n inds_e = ones(1, n1);\n for i = 1 : n2 \n x2 = X2(:, i);\n X2e = x2(:, inds_e); \n M(:, i) = feval(f, X1, X2e, varargin{:})'; \n end\n \nelse % expand each column in X1 to n2 copies\n \n inds_e = ones(1, n2);\n for i = 1 : n1\n x1 = X1(:, i);\n X1e = x1(:, inds_e);\n M(i, :) = feval(f, X1e, X2, varargin{:});\n end \n \nend\n\n", "meta": {"author": "lmthang", "repo": "nmt.hybrid", "sha": "50d5c025f18ed280ff0fd2e2adce327f4170a2c3", "save_path": "github-repos/MATLAB/lmthang-nmt.hybrid", "path": "github-repos/MATLAB/lmthang-nmt.hybrid/nmt.hybrid-50d5c025f18ed280ff0fd2e2adce327f4170a2c3/code/wordsim/code/sltoolbox_r101/sltoolbox_r101/sltoolbox/core/slpweval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.4659949078566215}}
{"text": "function blas1_d_test08 ( )\n\n%*****************************************************************************80\n%\n%% TEST08 tests DROTG.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 November 2006\n%\n% Author:\n%\n% John Burkardt\n%\n test_num = 5;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST08\\n' );\n fprintf ( 1, ' DROTG generates a real Givens rotation\\n' );\n fprintf ( 1, ' ( C S ) * ( A ) = ( R )\\n' );\n fprintf ( 1, ' ( -S C ) ( B ) ( 0 )\\n' );\n fprintf ( 1, '\\n' );\n\n seed = 123456789;\n\n for test = 1 : test_num\n\n [ a, seed ] = r8_uniform_01 ( seed );\n [ b, seed ] = r8_uniform_01 ( seed );\n\n [ c, s, r, z ] = drotg ( a, b );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' A = %f B = %f\\n', a, b );\n fprintf ( 1, ' C = %f S = %f\\n', c, s );\n fprintf ( 1, ' R = %f Z = %f\\n', r, z );\n fprintf ( 1, ' C*A+S*B = %f\\n', c * a + s * b );\n fprintf ( 1, ' -S*A+C*B = %f\\n', -s * a + c * b );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/blas1_d/blas1_d_test08.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.46599489422072743}}
{"text": "function inside = p15_inside ( m, n, point )\n\n%*****************************************************************************80\n%\n%% P15_INSIDE reports if a point is inside the region in problem 15.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer N, the number of points.\n%\n% Input, real POINT(M,N), the coordinates of the points.\n%\n% Output, logical INSIDE(N), is TRUE if the point is in the region.\n%\n inside(1:n) = ...\n ( -8.0 <= point(1,1:n) & point(1,1:n) <= 2.0 & ...\n -1.0 <= point(2,1:n) & point(2,1:n) <= 0.0 ) ...\n | ...\n ( -2.0 <= point(1,1:n) & point(1,1:n) <= 8.0 & ...\n 0.0 <= point(2,1:n) & point(2,1:n) <= 1.0 ); \n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_triangulation/p15_inside.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548511303336, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.46599488236438313}}
{"text": "function out = regress(dat, varargin)\n% Multiple regression with an fmri_data object (dat), predicting brain data with a design matrix stored in dat.X (or vice versa)\n%\n% Regress dat.X on dat.dat at each voxel, and return voxel-wise statistic\n% images. Each column of dat.X is a predictor in a multiple regression,\n% and the intercept is the last column. Intercept will automatically be\n% added if not detected unless 'nointercept' is specified.\n%\n% Key pointers:\n% - Output structure (regression_results_ols) contains beta and t images in statistic_image objects\n%\n% - If contrasts are entered, output structure contains contrast images and contrast t images in statistic_image objects\n%\n% - T images are thresholded, but beta/contrast images are not. These can be re-thresholded with the threshold( ) method\n%\n% - statistic_image objects can be visuallized with any CANlab display methods, e.g., surface( ), montage( ), and orthviews( )\n%\n% - Use the get_wh_image( ) method to select specific beta, t, contrast, contrast t images from statistic_image objects\n%\n% - Enter condition names and contrast names as cell vectors of strings Labels are saved in the .image_labels property in output objects\n%\n% - Some diagnostics, including VIFs and leverages, are automatically checked and returned\n%\n% - There is an option for robust regression, specified using the 'robust' flag\n%\n% - For first-level models (only), the grandmeanscale option is recommended to increase homogeneity in scale across participants\n%\n% - The regress( ) method does not use covariates field of fmri_data(). You must include covariates\n% manually in dat.X.\n%\n% - The regress( ) method can also create a map of brain regions that predict the dat.Y vector using the 'brainony' option. \n% This is essentially a univariate version of the 'predict' command. Warning: this is very slow as it loops\n% through all voxels.\n%\n% Creates thresholded plot by default\n%\n% :Usage:\n% ::\n%\n% out = regress(dat, varargin)\n%\n% :Inputs:\n% **dat:**\n% should be an fmri_data object with X field defined.\n% dat.X can be a design_matrix() object.\n%\n% :Optional Inputs:\n% **[threshold, 'unc']:**\n% p-value threshold string indicating threshold type\n% (see help statistic_image.threshold for options)\n%\n% **robust:**\n% Run a robust regression (default is OLS). Robust is considerably\n% slower than OLS\n%\n% **grandmeanscale:**\n% Scale overall grand mean to a value of 100. Intended to reduce inter-subject\n% variability in 1st-level analysis (single-subject) when doing\n% multi-subject group analyses on resulting contrasts/beta images.\n% Assumes mask and overall brain size are consistent across replicates (e.g., participants, in a first-level analysis) \n% Do not use for 2nd-level or standard single-level analyses.\n%\n% **C**\n% Followed by a contrast matrix, each column is a contrast across conditions/events\n% [k x c] matrix, where k = size(X, 2) and c is number of contrasts\n%\n% Note: k must be the number including the intercept. If your input\n% model X does not include an intercept, contrast matrix must have\n% one more element than input X has rows, to account for the added\n% intercept.\n%\n% **nointercept:**\n% Do not add intercept to model\n%\n% **display, display_results:**\n% Show thresholded results usin orthviews (if < 10 regressors)\n%\n% **nodisplay:**\n% Do not plot thresholded results using orthviews\n%\n% **brainony:**\n% univariate approach to predict obj.Y from brain data\n%\n% **residual:**\n% Output residual as fmri_data() object\n%\n% **noverbose:**\n% Suppress verbose outputs\n%\n% **variable_names:** (or 'names')\n% Followed by a cell array of variable/regressor names, for\n% non-intercept regressors\n% \n% **contrast_names:** \n% Followed by a cell array of contrast names\n% \n% **analysis_name:** \n% Followed by a string with a name/description for this analysis.\n% \n%\n% :Outputs:\n%\n% **out:**\n% A structure containing stats_img and fmri_data objects.\n% In addition to the main outputs below, the out structure also has\n% fields for input_parameters, the design matrix (X), variable\n% names, and warnings.\n%\n% **out.b:**\n% stats_img object of beta values estimated from regression\n%\n% **out.t:**\n% stats_img object of t-values with input threshold\n%\n% **out.df:**\n% fmri_data object of degrees of freedom\n%\n% **out.sigma:**\n% fmri_data object of variance of residual\n%\n% **out.residual:**\n% fmri_data object of residual data after model has been regressed out (optional).\n%\n% **out.diagnostics:***\n% A structure containing VIFs and leverage values for the design matrix\n% out.diagnostics.Variance_inflation_factors = VIFs\n% out.diagnostics.Leverages = leverage values\n%\n% :Examples:\n% ::\n%\n% % Run regression with liberal threshold\n% out = regress(dat, .05, 'unc');\n%\n% % Run regression with conservative threshold and save residual\n% out = regress(dat, .001, 'unc', 'residual);\n%\n% % Run robust regression with fdr threshold\n% out = regress(dat, .05, 'fdr','robust');\n%\n% % Run a regression predicting behavior from brain at liberal threshold\n% out = regress(data_comb, .05, 'unc', 'brainony')\n%\n% % Re-threshold at different values\n% out.t = threshold(out.t, .05, 'fdr');\n% out.t = threshold(out.t, .001, 'unc');\n%\n% % Re-display results of thresholding\n% orthviews(out.t);\n%\n% % Write out beta image to current directory\n% out.b.fullpath = fullfile(pwd,'beta.nii');\n% write(out)\n%\n% % Plot diagnostics\n% figure; subplot(1,2,1); title('VIFs')\n% plot(regression_results.diagnostics.Variance_inflation_factors);\n% subplot(1,2,2); title('Leverage of each observation')\n% plot(regression_results.diagnostics.Leverages);\n%\n% % Run with options:\n% regression_results = regress(dat, 'variable_names', names, 'analysis_name', 'Pinel localizer 1st-level GLM', 'noverbose');\n%\n% regression_results_ols = regress(dat, 'variable_names', names, ...\n% 'analysis_name', 'Pinel localizer 1st-level GLM', ...\n% 'C', C.weights, 'contrast_names', C.names);\n% \n% Show some results for selected individual conditions\n% % Thresholded t map for the first condition\n% t = get_wh_image(regression_results_ols.t, 1);\n% \n% create_figure('montage'); axis off\n% display_obj = montage(t);\n% \n% figure; surface(t);\n% \n% % Montages for thresholded t images, condition [2 4 6 8]\n% \n% t = get_wh_image(regression_results_ols.t, [2 4 6 8]);\n% \n% create_figure('montage2'); axis off\n% display_obj = montage(t);\n% Show results for contrasts\n% t = get_wh_image(regression_results_ols.con_t, 1:3);\n% \n% create_figure('montage3'); axis off\n% display_obj = montage(t);\n% \n% t = get_wh_image(regression_results_ols.con_t, 4:6);\n% \n% create_figure('montage4'); axis off\n% display_obj = montage(t);\n\n% ..\n% Copyright (c) 2015 Tor Wager & Luke Chang\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\n% in all copies or substantial portions of the Software.\n%\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n% OR 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\n% ..\n% Programmers' Notes:\n% c Tor Wager, Dec 2010\n% Edited by Luke Chang, 9/27/2012 to add optional input to reverse X & Y (i.e., create a map of voxels that predict the behavioral variable)\n% Edited by Luke Chang, 9/28/2012 to add optional input to run robust regression for brainony\n% Edited by Luke Chang, 10/24/2012 to save residuals (i.e., out.r), which is helpful for denoising an image\n% Edited by Luke Chang, 3/26/2013 to add optional input to not add an intercept - allows for more flexible modeling options\n% Code completely refactored by Luke Chang 2/24/25\n% Verbose option updated by Tor, 7/2015\n% Help, some outputs, robust % update: added by Tor, 5/2021\n% ..\n\n% ..\n% ---------------------------------------------------------------------\n% Defaults\n% ---------------------------------------------------------------------\n% ..\ninputargs = {.001, 'uncorrected'}; % default options for thresholding\ndo_display = false;\nbrain_is_outcome = 1; %else do brain on Y\ndo_robust = 0;\ndo_intercept = 1;\ndo_resid = 0;\ndoverbose = true;\nvariable_names = {};\ncontrast_names = {};\nanalysis_name = '';\nC = [];\ngrandmeanscale = false;\n\n% ---------------------------------------------------------------------\n% Parse Inputs\n% ---------------------------------------------------------------------\nfor varg = 1:length(varargin)\n \n if ischar(varargin{varg})\n % reserved keywords\n if strcmpi('unc',varargin{varg})\n inputargs = {varargin{varg-1}, 'uncorrected'};\n varargin{varg} = {}; varargin{varg - 1} = {};\n end\n if strcmpi('fdr',varargin{varg})\n inputargs = {varargin{varg-1}, 'fdr'};\n varargin{varg} = {}; varargin{varg - 1} = {};\n end\n \n if strcmpi('nodisplay',varargin{varg})\n do_display = 0;\n varargin{varg} = {};\n end\n \n if strcmpi('display',varargin{varg}) | strcmpi('display_results',varargin{varg})\n do_display = 0;\n varargin{varg} = {};\n end\n \n if strcmpi('robust',varargin{varg})\n do_robust = 1;\n varargin{varg} = {};\n end\n \n if strcmpi('brainony',varargin{varg}) | strcmpi('brain_is_predictor',varargin{varg}) %#ok<*OR2>\n brain_is_outcome = 0;\n varargin{varg} = {};\n end\n if strcmpi('nointercept',varargin{varg})\n do_intercept = 0;\n varargin{varg} = {};\n end\n if strcmpi('residual',varargin{varg})\n do_resid = 1;\n varargin{varg} = {};\n end\n if strcmpi('noverbose',varargin{varg})\n doverbose = false;\n varargin{varg} = {};\n end\n \n if strcmpi('names',varargin{varg}) | strcmpi('variable_names',varargin{varg})\n variable_names = varargin{varg + 1};\n varargin{varg} = {}; varargin{varg + 1} = {};\n end\n \n if strcmpi('C',varargin{varg}) | strcmpi('contrasts',varargin{varg})\n C = varargin{varg + 1};\n varargin{varg} = {}; varargin{varg + 1} = {};\n end\n \n if strcmpi('contrast_names',varargin{varg})\n contrast_names = varargin{varg + 1};\n varargin{varg} = {}; varargin{varg + 1} = {};\n end\n\n if strcmpi('analysis_name',varargin{varg})\n analysis_name = varargin{varg + 1};\n varargin{varg} = {}; varargin{varg + 1} = {};\n end\n \n if strcmpi('grandmeanscale',varargin{varg})\n grandmeanscale = true;\n varargin{varg} = {};\n end\n \n end % if ischar\nend\n\nif ~doverbose % add to pass into threshold( )\n inputargs{end+1} = 'noverbose';\nend\n \n% ---------------------------------------------------------------------\n% Check Data and Diagnostics\n% ---------------------------------------------------------------------\n\nmywarnings = {};\n\n\n% Check if fmri_data or image_vector\n% ---------------------------------------------------------------------\n\nif ~isa(dat,'fmri_data')\n error('dat input must be fmri_data object')\nend\n\n% Check data bit rate\n% ---------------------------------------------------------------------\n\nnuniquevals = length(unique(dat.dat(:)));\n\nif nuniquevals < 2^10\n mywarnings{end+1} = sprintf('Number of unique values in dataset is low (%d, %3.2f bits), indicating possible restriction of bit rate. For comparison, Int16 has 65,536 unique values', nuniquevals, log2(nuniquevals));\nend\n\n% Check of dat.X exists and is correct format\n% ---------------------------------------------------------------------\n\nif brain_is_outcome\n if isempty(dat.X)\n error('Make sure you include a design matrix in dat.X')\n end\n if size(dat.dat, 2) ~= size(dat.X, 1)\n error('dat.dat must have same number of columns as dat.X has rows.')\n end\n if isa(dat.X,'design_matrix')\n dat.X = dat.X.dat;\n end\nelse % Check if dat.Y exists and is in correct format if running brainony\n if isempty(dat.Y)\n error('Make sure you include a vector in dat.Y.')\n end\n if size(dat.dat, 2) ~= size(dat.Y, 1)\n error('dat.dat must have same number of columns as dat.Y has rows.')\n end\nend\n\n% Check if Rank Deficient\n% ---------------------------------------------------------------------\n\nif rank(dat.X) < size(dat.X,2)\n mywarnings{end+1} = 'Warning: dat.X is rank deficient.';\nend\n\nintercept_string = 'intercept is last';\n\n% Check if Intercept is in model or specified for x_on_brain default\n% ---------------------------------------------------------------------\n\nif do_intercept && brain_is_outcome\n wh_int = intercept(dat.X, 'which');\n \n if isempty(wh_int)\n % add intercept and update wh_int (used later)\n if doverbose, mywarnings{end+1} = 'No intercept detected, adding intercept to last column of design matrix'; end\n X = intercept(dat.X, 'add');\n variable_names{end + 1} = 'Intercept';\n% wh_int = intercept(X, 'which');\n \n else\n intercept_string = sprintf('Intercept detected in column %1.0f of dat.X', wh_int);\n\n if doverbose, mywarnings{end+1} = intercept_string; end\n X = dat.X;\n \n end\n \nelse\n % No intercept or exogenous variables are outcome\n\n X = dat.X;\nend\n\n% Predictor centering\n% ---------------------------------------------------------------------\n\nm = mean(X);\nwh_int = intercept(X, 'which');\nm(wh_int) = [];\nnon_centered = abs(m) > 100 * eps;\n\n% For effects-coded values [-1 1], ok, we want the intercept to reflect stats at average of 2 groups\niseffectcode = all(abs(X) == 1); % for each column\niseffectcode(wh_int) = [];\n\nif any(non_centered & iseffectcode) \n \n mywarnings{end+1} = 'Warning: Group sizes are unequal for effects-coded [1 -1] variable.';\n \nend\n\nif any(non_centered & ~iseffectcode) \n mywarnings{end+1} = 'Warning: Predictors are not centered -- intercept is not interpretable as stats for average subject'; \nend\n\n% Variance inflation\n% ---------------------------------------------------------------------\n\nvifs = getvif(X);\n\nif any(vifs > 4)\n \n mywarnings{end+1} = 'Warning!!! Design multicolinearity. Some regressors have variance inflation factors > 4. Check out.diagnostics';\n \nend\n\n% Leverages\n% ---------------------------------------------------------------------\n\nH = X*pinv(X);\n%H = X*inv(X'*X)*X' will be identical if not rank deficient\nleverages = diag(H);\n\nif any(abs(zscore(leverages)) >= 3)\n mywarnings{end+1} = 'Warning!!! Some observations have high leverage values relative to others, regression may be unstable. abs(z(leverage)) > 3';\nend\n\n% Names\n% ---------------------------------------------------------------------\n\nk = size(X, 2);\nif length(variable_names) < k\n if ~isempty(variable_names), mywarnings{end+1} = 'Warning!!! Too few variable names entered, less than size(X, 2). Names may be inaccurate.'; end % suppress warning if NO names entered\n \n for i = length(variable_names)+1:k %#ok<*FXUP>\n variable_names{i} = sprintf('R%d', i); %#ok<*AGROW>\n end\nend\n\nif length(variable_names) > k\n mywarnings{end+1} = 'Warning!!! Too many variable names entered, more than size(X, 2). Names may be inaccurate.';\n \n variable_names = variable_names(1:k);\nend\n \n% Check contrasts\n% ---------------------------------------------------------------------\n\nif ~isempty(C) && ~(size(C, 1) == size(X, 2))\n % Do this *after* adding intercept to X if needed\n \n disp('Contrasts entered, but size(C, 1) does not equal size(X, 2).');\n disp('Must have a contrast entry for each column of X (including the intercept)');\n error('Quitting.')\n \nend\n\n% Contrast names\n% ---------------------------------------------------------------------\n\nif ~isempty(C)\n \n kc = size(C, 2);\n \n if length(contrast_names) < kc\n if ~isempty(contrast_names), mywarnings{end+1} = 'Warning!!! Too few contrast names entered, less than size(C, 2). Names may be inaccurate.'; end % suppress warning if NO names entered\n \n for i = length(contrast_names)+1:kc\n contrast_names{i} = sprintf('Con%d', i); %#ok<*AGROW>\n end\n end\n \n if length(contrast_names) > kc\n mywarnings{end+1} = 'Warning!!! Too many contrast names entered, more than size(C, 2). Names may be inaccurate.';\n \n contrast_names = contrast_names(1:kc);\n end\n\nend\n\n% Enforce proper shape\nif ~iscolumn(variable_names), variable_names = variable_names'; end\nif ~isrow(contrast_names), contrast_names = contrast_names'; end\n\n% Enforce valid names: Eliminate special characters and leading numbers\n[variable_names, namewarnings] = format_text_letters_only(variable_names, 'numbers', 'cleanup', 'squeeze', 'underscore_ok');\nmywarnings = [mywarnings namewarnings];\nif ~isempty(namewarnings), mywarnings{end+1} = 'Enter valid variable_names'; end\n\nif ~isempty(C)\n \n [contrast_names, namewarnings] = format_text_letters_only(contrast_names, 'numbers', 'cleanup', 'squeeze', 'underscore_ok');\n mywarnings = [mywarnings namewarnings];\n if ~isempty(namewarnings), mywarnings{end+1} = 'Enter valid contrast_names'; end\n \nend\n\n% Data scaling and format\n% ---------------------------------------------------------------------\n\n% Enforce double-format (just in case)\ndat.dat = double(dat.dat);\n\nif grandmeanscale\n \n % Scale grand mean to 100; approximates what SPM and other packages do. Assumes mask and overall brain size are consistent across replicates (e.g., participants, in a first-level analysis \n dat.dat = dat.dat .* 100 / nanmean(dat.dat(:));\n \nend\n\n\nif doverbose\n \n fprintf('Analysis: %s\\n', analysis_name);\n disp('----------------------------------');\n \n nowarnings = all(cellfun(@isempty, mywarnings));\n \n disp('Design matrix warnings:');\n disp('----------------------------------');\n if nowarnings\n disp('None')\n \n else\n disp(char(mywarnings{:}))\n \n end\n \n disp(' ');\nend\n\n% ---------------------------------------------------------------------\n% Run Regression\n% ---------------------------------------------------------------------\n\ntic\nwarning off\n\nif brain_is_outcome\n % default is to regress dat.X on dat.dat (x on brain)\n % ---------------------------------------------------------------------\n \n % display info about regression\n if doverbose\n linestr = '______________________________________________________';\n disp(linestr);\n \n fprintf('Running regression: %3.0f voxels. Design: %3.0f obs, %3.0f regressors, %s\\n', size(dat.dat, 1), size(X, 1), size(X, 2), intercept_string);\n if brain_is_outcome\n fprintf('\\nPredicting exogenous variable(s) in dat.X using brain data as predictors, mass univariate');\n \n else % default\n fprintf('\\nPredicting Brain Activity from dat.X, mass univariate');\n end\n end\n \n if do_robust \n % Robust - Regress stim/behavior(X) on brain (Y)\n %need to loop through voxels - Slow!\n \n if doverbose\n fprintf('\\nRunning in Robust Mode ___%%');\n end\n \n v = size(dat.dat, 1);\n [n, k] = size(X);\n \n % Initialize outputs\n [b, t, stderr] = deal(zeros(k, v));\n p = ones(k, v);\n [dfe, sigma] = deal(zeros(1, v));\n \n for i = 1:v\n % For each voxel\n\n [bb,stats] = robustfit(X, dat.dat(i,:)', 'bisquare', [], 'off');\n \n b(:,i)=bb; %Betas\n t(:,i)=stats.t; %t-values\n p(:,i)=stats.p; %p-values\n dfe(:,i)=stats.dfe; %degrees of freedom\n stderr(:,i)=stats.se; %Standard Error\n sigma(:,i)=stats.robust_s; %robust estimate of sigma. LC not sure this is the best choice can switch to 'OLS_s','MAD_s', or 's'\n \n if doverbose && mod(i, 100) == 0\n fprintf('\\b\\b\\b\\b%03d%%', 100 * round(i/v))\n end\n end\n r = dat.dat' - X*b; %residual\n \n else\n % OLS - X predicting brain \n % - vectorized - Fast!\n \n if doverbose, fprintf('\\nRunning in OLS Mode'); end\n \n % Estimate Betas in vector\n\n \n b = pinv(X) * dat.dat';\n \n % Error\n r = dat.dat' - X*b;\n \n % Residual variance\n [stderr, sigma] = get_std_errors(r, X);\n \n % Inference\n [t,dfe,p,sigma] = param_t_test(X,b,stderr,sigma);\n \n end\n \nelse\n % Regress brain (X) on stim/behavior (Y) - loops through voxels, slow!\n % ---------------------------------------------------------------------\n \n if doverbose\n % display info about regression\n fprintf('regression > X: %3.0f voxels. Y: %3.0f obs, %3.0f regressors, %s\\n', size(dat.dat, 1), size(dat.Y, 2), intercept_string);\n fprintf('\\nPredicting dat.Y from Brain Activity');\n end\n \n if do_robust %need to loop through voxels - Slow!\n if doverbose\n fprintf('\\nRunning in Robust Mode ___%%');\n end\n \n v = size(dat.dat, 1);\n n = size(dat.dat, 2);\n k = 2; % one predictor (brain) and an intercept\n \n % Initialize outputs\n [b, t, stderr] = deal(zeros(k, v));\n p = ones(k, v);\n [dfe, sigma] = deal(zeros(1, v));\n \n for i = 1:v\n % Create X from brain Data\n if do_intercept\n X = intercept(dat.dat(i,:)','add');\n else\n X = dat.dat(i,:)';\n end\n\n [bb,stats] = robustfit(X, dat.Y, 'bisquare', [], 'off');\n \n b(:,i)=bb; %Betas\n t(:,i)=stats.t; %t-values\n p(:,i)=stats.p; %p-values\n dfe(:,i)=stats.dfe; %degrees of freedom\n stderr(:,i)=stats.se; %Standard Error\n sigma(:,i)=stats.robust_s; %robust estimate of sigma. LC not sure this is the best choice can switch to 'OLS_s','MAD_s', or 's'\n r(:,i) = dat.Y - X * b(:,i); %residual\n \n if doverbose && mod(i, 100) == 0\n fprintf('\\b\\b\\b\\b%03d%%', 100 * round(i/v))\n end\n \n end % voxel\n \n else\n % ---------------------------------------------------------------------\n %OLS -- Regress brain on Y\n \n if doverbose, fprintf('\\nRunning in OLS Mode'); end\n \n for i = 1:size(dat.dat,1)\n \n % Create X from brain Data\n if do_intercept\n X = intercept(dat.dat(i,:)','add');\n else\n X = dat.dat(i,:)';\n end\n \n % Estimate Betas in vector\n b(:,i) = pinv(X) * dat.Y;\n \n % Error\n r(:,i) = dat.Y - X * b(:,i);\n \n % sigma(i) = std(r(:,i)); % wrong\n % stderr(:,i) = ( diag(inv(X' * X)) .^ .5 ) * sigma(i); % params x voxels matrix of std. errors\n end\n \n % Residual variance - can do this at end because X is always the same size\n [stderr, sigma] = get_std_errors(r, X);\n \n % Inference\n [t,dfe,p,sigma] = param_t_test(X,b,stderr,sigma);\n \n end % dorobust\n \nend % brain_is_outcome or not\n\nstop = toc;\nif doverbose, fprintf('\\nModel run in %d minutes and %.2f seconds\\n',floor(stop/60),rem(stop,60)); end\n\n\n% ---------------------------------------------------------------------\n% Contrasts\n% ---------------------------------------------------------------------\n\nif ~isempty(C)\n\n con_vals = C' * b;\n\n % Contrast STE\n con_ste = diag(C' * inv(X' * X) * C) .^ .5 * sigma;\n \n [con_t, ~, con_p] = param_t_test(X, con_vals, con_ste, sigma);\n \nend\n\n\n% ---------------------------------------------------------------------\n% Create Output\n% ---------------------------------------------------------------------\n\nout = struct;\n\nout.analysis_name = analysis_name;\n\nout.input_parameters = struct( ...\n 'brain_is_predictor', brain_is_outcome, 'do_robust', do_robust, 'grandmeanscale', grandmeanscale, ...\n 'do_intercept', do_intercept, ...\n 'do_resid', do_resid, 'doverbose', doverbose, 'do_display', do_display);\n\nout.input_parameters.initial_statistical_threshold = inputargs;\n\nout.input_image_metadata.source_notes = dat.source_notes;\nout.input_image_metadata.history = dat.history;\nout.input_image_metadata.image_names = dat.image_names;\nout.input_image_metadata.fullpath = dat.fullpath;\n\n% design, contrasts, and diagnostics\n\nout.X = X;\nout.variable_names = variable_names;\nout.C = C;\nout.contrast_names = contrast_names;\n\nout.contrast_summary_table = table();\n\nif ~isempty(C)\n % Contrast summary table\n\n for i = 1:size(C, 2)\n out.contrast_summary_table(:, i) = table(C(:, i));\n end\n \n out.contrast_summary_table.Properties.RowNames = variable_names;\n out.contrast_summary_table.Properties.VariableNames = contrast_names;\n \n if doverbose\n fprintf('\\nSummary of conditions and contrasts\\n%s\\n', linestr);\n disp(out.contrast_summary_table);\n end\n\nend\n\nout.diagnostics = struct('Variance_inflation_factors', vifs, 'Leverages', leverages);\nout.warnings = mywarnings;\n\n% Create objects\nif doverbose\n fprintf('\\nCreating beta and t images, thresholding t images\\n%s\\n', linestr); \nend\n\n% Betas\nout.b = statistic_image;\nout.b.type = 'Beta';\nout.b.p = p';\nout.b.ste = stderr';\nout.b.N = n;\nout.b.dat = b';\nout.b.dat_descrip = sprintf('Beta Values from regression, intercept is column %d', wh_int);\nout.b.volInfo = dat.volInfo;\nout.b.removed_voxels = dat.removed_voxels;\nout.b.removed_images = false; % this image does not have the same dims as the original dataset\nout.b.image_labels = variable_names;\n\nout.b = enforce_variable_types(out.b);\n\n% - beta and contrast images are unthresholded, t images from both are thresholded\n% if doverbose, fprintf('Thresholding b images at %3.6f %s\\n', inputargs{1}, inputargs{2}); end\n% out.b = threshold(out.b, inputargs{:}, 'noverbose'); % Threshold image\n\n% T stats\nout.t = statistic_image;\nout.t.type = 'T';\nout.t.p = p';\nout.t.ste = stderr';\nout.t.N = n;\nout.t.dat = t';\nout.t.dat_descrip = sprintf('t-values from regression, intercept is column %d', wh_int);\nout.t.volInfo = dat.volInfo;\nout.t.removed_voxels = dat.removed_voxels;\nout.t.removed_images = false; % this image does not have the same dims as the original dataset\nout.t.image_labels = variable_names;\n\nout.t = enforce_variable_types(out.t);\n\nif doverbose\n fprintf('Thresholding t images at %3.6f %s\\n', inputargs{1}, inputargs{2}); \nend\nout.t = threshold(out.t, inputargs{:}); %Threshold image\n\n% DF as fmri_data\nout.df = dat;\nout.df.dat = dfe';\nout.df.dat_descrip = sprintf('Degrees of Freedom');\n\n% Sigma as fmri_data\nout.sigma = dat;\nout.sigma.dat = sigma';\nout.sigma.dat_descrip = sprintf('Sigma from Regression');\n\n% Residual as fmri_data\nif do_resid\n out.resid = dat;\n out.resid.dat = r';\n out.resid.dat_descrip = sprintf('Residual from Regression');\nend\n\nif ~isempty(C)\n \n if doverbose, fprintf('\\nCreating contrast and t images and thresholding t images\\n%s\\n', linestr); end\n\n % Contrast values\n out.contrast_images = statistic_image;\n out.contrast_images.type = 'Contrast';\n out.contrast_images.p = con_p';\n out.contrast_images.ste = stderr';\n out.contrast_images.N = n;\n out.contrast_images.dat = con_vals';\n out.contrast_images.dat_descrip = 'Contrast Values from regression';\n out.contrast_images.volInfo = dat.volInfo;\n out.contrast_images.removed_voxels = dat.removed_voxels;\n out.contrast_images.removed_images = false; % this image does not have the same dims as the original dataset\n out.contrast_images.image_labels = contrast_names;\n \n out.contrast_images = enforce_variable_types(out.contrast_images);\n\n% if doverbose, fprintf('Thresholding contrast images at %3.6f %s\\n', inputargs{1}, inputargs{2}); end\n% out.contrast_images = threshold(out.contrast_images, inputargs{:}, 'noverbose'); % Threshold image\n \n % T stats\n out.con_t = statistic_image;\n out.con_t.type = 'T';\n out.con_t.p = con_p';\n out.con_t.ste = con_ste';\n out.con_t.N = n;\n out.con_t.dat = con_t';\n out.con_t.dat_descrip = sprintf('t-values from regression, intercept is column %d', wh_int);\n out.con_t.volInfo = dat.volInfo;\n out.con_t.removed_voxels = dat.removed_voxels;\n out.con_t.removed_images = false; % this image does not have the same dims as the original dataset\n out.con_t.image_labels = contrast_names;\n \n out.con_t = enforce_variable_types(out.con_t);\n\n if doverbose\n fprintf('Thresholding t images at %3.6f %s\\n', inputargs{1}, inputargs{2}); \n \n end\n out.con_t = threshold(out.con_t, inputargs{:}); %Threshold image\n \nend\n\n\n% ---------------------------------------------------------------------\n% Plot Results\n% ---------------------------------------------------------------------\nif k < 10 && do_display\n \n orthviews(out.t);\n \nelseif do_display && doverbose\n disp('Warning: No display because >= 10 images.');\n \nend\n\nwarning on\n\n% ---------------------------------------------------------------------\n% Subfunctions\n% ---------------------------------------------------------------------\n\n\n\n function [stderr, sigma] = get_std_errors(r, X)\n \n [n, k] = size(X);\n v = size(dat.dat, 1);\n \n % We want diag(r' * r), but matrix size can be large\n % std(r) does not account for k parameters used, so is incorrect\n % residual std. not sqrt(var(resid)) -- we must account for k params used\n for i = 1:v\n sigma(1, i) = (r(:, i)' * r(:, i) ./ (n - k)) .^ .5;\n end\n \n stderr = ( diag(inv(X' * X)) .^ .5 ) * sigma; % params x voxels matrix of std. errors\n \n end\n\n \n function [t,dfe,p,sigma] = param_t_test(X,b,stderr,sigma)\n % test whether parameter is significantly different from zero\n %\n % Inputs:\n % X: design matrix\n % b: beta values\n % stderr: standard error of beta estimate\n % sigma: standard deviation of residual\n %\n % Returns:\n % t: t-value\n % dfe: degrees of freedom\n % p: p-value\n % sigma: standard deviation of residual\n \n [n, k] = size(X);\n t = b ./ stderr;\n dfe = n - k;\n p = 2 * (1 - tcdf(abs(t), dfe));\n \n sigma(sigma == 0) = Inf;\n t(isnan(t)) = 0;\n p(isnan(p)) = 0;\n dfe = repmat(dfe,1,size(t,2));\n end\n\nend % Main Function\n\n\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/@fmri_data/regress.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038221, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.4658969779216002}}
{"text": "function I = getPcontrolCurrentPack(t,t0,tf,x,param,extra)\n%\tgetPcontrolCurrentPack returns the value of the input current as a function of\n%\tthe time, states and parameters\n%\n% I = getPcontrolCurrentPack(t,t0,tf,y,param,extra)\n%\n% Inputs:\n% - t : value of the current time step\n% - t0 : initial integration time\n% - tf : final integration time\n% - x : contains the array of all the states\n% (differential and algebraic) at time t\n% - param : contains the parameters structure\n% - extra : extra parameters\n% Outputs:\n% - I : Applied current desnity [A/m^2]\n\n% This file is part of the LIONSIMBA Toolbox\n%\n%\tOfficial web-site: \thttp://sisdin.unipv.it/labsisdin/lionsimba.php\n% \tOfficial GitHUB: \thttps://github.com/lionsimbatoolbox/LIONSIMBA\n%\n% LIONSIMBA: A Matlab framework based on a finite volume model suitable for Li-ion battery design, simulation, and control\n% Copyright (C) 2016-2018 :Marcello Torchio, Lalo Magni, Davide Raimondo,\n% University of Pavia, 27100, Pavia, Italy\n% Bhushan Gopaluni, Univ. of British Columbia, \n% Vancouver, BC V6T 1Z3, Canada\n% Richard D. Braatz, \n% Massachusetts Institute of Technology, \n% Cambridge, Massachusetts 02142, USA\n% \n% Main code contributors to LIONSIMBA 2.0:\n% Ian Campbell, Krishnakumar Gopalakrishnan,\n% Imperial college London, London, UK\n%\n% LIONSIMBA is a free Matlab-based software distributed with an MIT\n% license.\n\n% This script provides the value of the applied current density as a\n% function of the voltage across the battery pack.\n\n% Firstly we extract the variables related to the first and second cell. To\n% this aim the field x_indices of the param structure contains the values\n% of the absolute positionong of the variables in the overall x array.\n% Indeed, when running simulations with multiple cells, the states array\n% (x) will contain as many rows - for a given time instant t - as the sum\n% of the states of all the cells involved in the simulation. x_indices\n% stores, for each cell, what are the indices of the overall x in which the\n% variables of a given cell are stored.\n\n% Extract the first cell variables\ncell1_variables = x(param{1}.x_index);\n% Extract the second cell variables\ncell2_variables = x(param{2}.x_index);\n\n% At this stage, since we have put the variables of the 2 cells into\n% cell1_variables and cell2_variables, use their relative indices to\n% extract the exact values.\n\n% Cell 1 voltage\nV_1 = cell1_variables(param{1}.Phis_indices(1))-cell1_variables(param{1}.Phis_indices(end));\n\n% Cell 2 voltage\nV_2 = cell2_variables(param{2}.Phis_indices(1))-cell2_variables(param{2}.Phis_indices(end));\n\n% Define the proportional action. Do not put extreme values, the simulator\n% could crash\nKp = 100;\n\n% Define the Voltage Setpoint\nV_ref = 8.2;\n% Define your linear or nonlinear function of t for evaluate the value\n% of I.\nI = Kp*(V_ref-(V_1+V_2));\n\nend", "meta": {"author": "lionsimbatoolbox", "repo": "LIONSIMBA", "sha": "d1cf29a4dcfa8e7824fc2416ac3e6ec760bb9b66", "save_path": "github-repos/MATLAB/lionsimbatoolbox-LIONSIMBA", "path": "github-repos/MATLAB/lionsimbatoolbox-LIONSIMBA/LIONSIMBA-d1cf29a4dcfa8e7824fc2416ac3e6ec760bb9b66/battery_model_files/external_functions/getPcontrolCurrentPack.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489892, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.46570683462172563}}
{"text": "function [ o, x, w ] = en_r2_09_1 ( n, option )\n\n%*****************************************************************************80\n%\n%% EN_R2_09_1 implements the Stroud rule 9.1 for region EN_R2.\n%\n% Discussion:\n%\n% The rule has order O = ( 2 * N^4 - 4 * N^3 + 22 * N^2 - 8 * N + 3 ) / 3.\n%\n% The rule has precision P = 9.\n%\n% EN_R2 is the entire N-dimensional space with weight function\n%\n% w(x) = exp ( - x1^2 - x2^2 ... - xn^2 ) \n%\n% There are two versions of each rule, chosen by setting the \n% OPTION variable to 1 or 2.\n%\n% The rule as tabulated by Stenger is available for N = 2 through 20.\n% This function accepts N = 3 through 6.\n%\n% N O\n% __ ___\n% 3 77\n% 4 193\n% 5 421\n% 6 825\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 January 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Arthur Stroud,\n% Approximate Calculation of Multiple Integrals,\n% Prentice Hall, 1971,\n% ISBN: 0130438936,\n% LC: QA311.S85.\n%\n% Parameters:\n%\n% Input, integer N, the spatial dimension.\n% 3 <= N <= 6.\n%\n% Input, integer OPTION, chooses rule option 1 or 2.\n%\n% Output, integer O, the order.\n%\n% Output, real X(N,O), the abscissas.\n%\n% Output, real W(O), the weights.\n%\n if ( n < 3 | 6 < n )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'EN_R2_09_1 - Fatal error!\\n' );\n fprintf ( 1, ' 3 <= N <= 6 required.\\n' );\n error ( 'EN_R2_09_1 - Fatal error!' )\n end\n\n if ( nargin < 2 )\n option = 1;\n end\n\n if ( option < 1 | 2 < option )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'EN_R2_09_1 - Fatal error!\\n' );\n fprintf ( 1, ' 1 <= OPTION <= 2 required.\\n' );\n error ( 'EN_R2_09_1 - Fatal error!' )\n end\n\n o = ( 2 * n^4 - 4 * n^3 + 22 * n^2 - 8 * n + 3 ) / 3;\n volume = sqrt ( pi^n );\n\n if ( n == 3 )\n u = 0.202018287045609E+01;\n v = 0.958572464613819E+00;\n b0 = 0.676448734429924E+00;\n b1 = 0.511989106291551E-02;\n b2 = 0.448595723493744E+00;\n b3 = 0.235223454595606E-03;\n b4 = 0.915390713080005E-01;\n b5 = 0.139208199920793E-01;\n b6 = 0.235223454595606E-03;\n b7 = 0.915390713080008E-01;\n b8 = 0.000000000000000E+00;\n elseif ( n == 4 & option == 1 )\n u = 0.202018287045609E+01;\n v = 0.958572464613819E+00;\n b0 = - 0.860452945007048E+00;\n b1 = - 0.405511998533795E-01;\n b2 = 0.107026475449715E+01;\n b3 = 0.138974239307092E-03;\n b4 = - 0.162248779448181E+00;\n b5 = 0.246740110027234E-01;\n b6 = 0.138974239307094E-03;\n b7 = 0.162248779448181E+00;\n b8 = 0.138974239307094E-03;\n elseif ( n == 4 & option == 2 )\n u = 0.958572464613819E+00;\n v = 0.202018287045609E+01;\n b0 = 0.265029088766810E-02;\n b1 = 0.637601342635332E+00;\n b2 = - 0.394394059389228E-01;\n b3 = 0.540829264827264E-01;\n b4 = - 0.416922717921281E-03;\n b5 = 0.246740110027234E-01;\n b6 = 0.540829264827270E-01;\n b7 = 0.416922717921281E-03;\n b8 = 0.540829264827269E-01;\n elseif ( n == 5 & option == 1 )\n u = 0.202018287045609E+01;\n v = 0.958572464613819E+00;\n b0 = - 0.827347006200826E+01;\n b1 = - 0.160820174530905E+00;\n b2 = 0.353499863758467E+01;\n b3 = 0.738976276909564E-03;\n b4 = - 0.862735421812943E+00;\n b5 = 0.437335458190621E-01;\n b6 = - 0.246325425636523E-03;\n b7 = 0.287578473937648E+00;\n b8 = 0.246325425636523E-03;\n elseif ( n == 5 & option == 2 )\n u = 0.958572464613819E+00;\n v = 0.202018287045609E+01;\n b0 = - 0.624416791055272E+00;\n b1 = 0.467494915583104E+00;\n b2 = - 0.152937760910536E+00;\n b3 = 0.287578473937646E+00;\n b4 = - 0.221692883072871E-02;\n b5 = 0.437335458190621E-01;\n b6 = - 0.958594913125490E-01;\n b7 = 0.738976276909568E-03;\n b8 = 0.958594913125492E-01;\n elseif ( n == 6 & option == 1 )\n u = 0.202018287045609E+01;\n v = 0.958572464613819E+00;\n b0 = - 0.361840434143098E+02;\n b1 = - 0.447936529138517E+00;\n b2 = 0.112077863004144E+02;\n b3 = 0.392940404320855E-02;\n b4 = - 0.254859786784158E+01;\n b5 = 0.775156917007496E-01;\n b6 = - 0.130980134773619E-02;\n b7 = 0.509719573568315E+00;\n b8 = 0.436600449245395E-03;\n elseif ( n == 6 & option == 2 )\n u = 0.958572464613819E+00;\n v = 0.202018287045609E+01;\n b0 = 0.448873836333650E+01;\n b1 = - 0.238473566140736E+01;\n b2 = - 0.413008493198885E+00;\n b3 = 0.152915872070494E+01;\n b4 = - 0.654900673868093E-02;\n b5 = 0.775156917007496E-01;\n b6 = - 0.509719573568314E+00;\n b7 = 0.130980134773618E-02;\n b8 = 0.169906524522772E+00;\n end\n\n x = zeros(n,o);\n w = zeros(o,1);\n\n k = 0;\n%\n% 1 point.\n%\n k = k + 1;\n% x(1:n,k) = 0.0;\n w(k) = b0;\n%\n% 2 * N points.\n%\n for i = 1 : n\n k = k + 1;\n x(i,k) = - u;\n w(k) = b1;\n k = k + 1;\n x(i,k) = + u;\n w(k) = b1;\n end\n%\n% 2 * N points.\n%\n for i = 1 : n\n k = k + 1;\n x(i,k) = - v;\n w(k) = b2;\n k = k + 1;\n x(i,k) = + v;\n w(k) = b2;\n end\n%\n% 4 * ( N * ( N - 1 ) / 2 ) points.\n%\n for i = 1 : n - 1\n for j = i + 1 : n\n k = k + 1;\n x(i,k) = - u;\n x(j,k) = - u;\n w(k) = b3;\n k = k + 1;\n x(i,k) = - u;\n x(j,k) = + u;\n w(k) = b3;\n k = k + 1;\n x(i,k) = + u;\n x(j,k) = - u;\n w(k) = b3;\n k = k + 1;\n x(i,k) = + u;\n x(j,k) = + u;\n w(k) = b3;\n end\n end\n%\n% 4 * ( N * ( N - 1 ) / 2 ) points.\n%\n for i = 1 : n - 1\n for j = i + 1 : n\n k = k + 1;\n x(i,k) = - v;\n x(j,k) = - v;\n w(k) = b4;\n k = k + 1;\n x(i,k) = - v;\n x(j,k) = + v;\n w(k) = b4;\n k = k + 1;\n x(i,k) = + v;\n x(j,k) = - v;\n w(k) = b4;\n k = k + 1;\n x(i,k) = + v;\n x(j,k) = + v;\n w(k) = b4;\n end\n end\n%\n% 4 * ( N * ( N - 1 ) ) points.\n%\n for i = 1 : n - 1\n for j = i + 1 : n\n k = k + 1;\n x(i,k) = - u;\n x(j,k) = - v;\n w(k) = b5;\n k = k + 1;\n x(i,k) = - u;\n x(j,k) = + v;\n w(k) = b5;\n k = k + 1;\n x(i,k) = + u;\n x(j,k) = - v;\n w(k) = b5;\n k = k + 1;\n x(i,k) = + u;\n x(j,k) = + v;\n w(k) = b5;\n k = k + 1;\n x(i,k) = - v;\n x(j,k) = - u;\n w(k) = b5;\n k = k + 1;\n x(i,k) = - v;\n x(j,k) = + u;\n w(k) = b5;\n k = k + 1;\n x(i,k) = + v;\n x(j,k) = - u;\n w(k) = b5;\n k = k + 1;\n x(i,k) = + v;\n x(j,k) = + u;\n w(k) = b5;\n end\n end\n%\n% 8 * ( N * ( N - 1 ) * ( N - 2 ) / 6 ) points.\n%\n for i = 1 : n - 2\n for j = i + 1 : n - 1\n for l = j + 1 : n\n k = k + 1;\n x(i,k) = - u;\n x(j,k) = - u;\n x(l,k) = - u;\n w(k) = b6;\n k = k + 1;\n x(i,k) = - u;\n x(j,k) = - u;\n x(l,k) = + u;\n w(k) = b6;\n k = k + 1;\n x(i,k) = - u;\n x(j,k) = + u;\n x(l,k) = - u;\n w(k) = b6;\n k = k + 1;\n x(i,k) = - u;\n x(j,k) = + u;\n x(l,k) = + u;\n w(k) = b6;\n k = k + 1;\n x(i,k) = + u;\n x(j,k) = - u;\n x(l,k) = - u;\n w(k) = b6;\n k = k + 1;\n x(i,k) = + u;\n x(j,k) = - u;\n x(l,k) = + u;\n w(k) = b6;\n k = k + 1;\n x(i,k) = + u;\n x(j,k) = + u;\n x(l,k) = - u;\n w(k) = b6;\n k = k + 1;\n x(i,k) = + u;\n x(j,k) = + u;\n x(l,k) = + u;\n w(k) = b6;\n end\n end\n end\n%\n% 8 * ( N * ( N - 1 ) * ( N - 2 ) / 6 ) points.\n%\n for i = 1 : n - 2\n for j = i + 1 : n - 1\n for l = j + 1 : n\n k = k + 1;\n x(i,k) = - v;\n x(j,k) = - v;\n x(l,k) = - v;\n w(k) = b7;\n k = k + 1;\n x(i,k) = - v;\n x(j,k) = - v;\n x(l,k) = + v;\n w(k) = b7;\n k = k + 1;\n x(i,k) = - v;\n x(j,k) = + v;\n x(l,k) = - v;\n w(k) = b7;\n k = k + 1;\n x(i,k) = - v;\n x(j,k) = + v;\n x(l,k) = + v;\n w(k) = b7;\n k = k + 1;\n x(i,k) = + v;\n x(j,k) = - v;\n x(l,k) = - v;\n w(k) = b7;\n k = k + 1;\n x(i,k) = + v;\n x(j,k) = - v;\n x(l,k) = + v;\n w(k) = b7;\n k = k + 1;\n x(i,k) = + v;\n x(j,k) = + v;\n x(l,k) = - v;\n w(k) = b7;\n k = k + 1;\n x(i,k) = + v;\n x(j,k) = + v;\n x(l,k) = + v;\n w(k) = b7;\n end\n end\n end\n%\n% 16 * ( N * ( N - 1 ) * ( N - 2 ) * ( N - 3 ) / 24 ) points.\n%\n for i = 1 : n - 3\n for j = i + 1 : n - 2\n for l = j + 1 : n - 1\n for m = l + 1 : n\n k = k + 1;\n x(i,k) = - u;\n x(j,k) = - u;\n x(l,k) = - u;\n x(m,k) = - u;\n w(k) = b8;\n k = k + 1;\n x(i,k) = - u;\n x(j,k) = - u;\n x(l,k) = - u;\n x(m,k) = + u;\n w(k) = b8;\n k = k + 1;\n x(i,k) = - u;\n x(j,k) = - u;\n x(l,k) = + u;\n x(m,k) = - u;\n w(k) = b8;\n k = k + 1;\n x(i,k) = - u;\n x(j,k) = - u;\n x(l,k) = + u;\n x(m,k) = + u;\n w(k) = b8;\n k = k + 1;\n x(i,k) = - u;\n x(j,k) = + u;\n x(l,k) = - u;\n x(m,k) = - u;\n w(k) = b8;\n k = k + 1;\n x(i,k) = - u;\n x(j,k) = + u;\n x(l,k) = - u;\n x(m,k) = + u;\n w(k) = b8;\n k = k + 1;\n x(i,k) = - u;\n x(j,k) = + u;\n x(l,k) = + u;\n x(m,k) = - u;\n w(k) = b8;\n k = k + 1;\n x(i,k) = - u;\n x(j,k) = + u;\n x(l,k) = + u;\n x(m,k) = + u;\n w(k) = b8;\n k = k + 1;\n x(i,k) = + u;\n x(j,k) = - u;\n x(l,k) = - u;\n x(m,k) = - u;\n w(k) = b8;\n k = k + 1;\n x(i,k) = + u;\n x(j,k) = - u;\n x(l,k) = - u;\n x(m,k) = + u;\n w(k) = b8;\n k = k + 1;\n x(i,k) = + u;\n x(j,k) = - u;\n x(l,k) = + u;\n x(m,k) = - u;\n w(k) = b8;\n k = k + 1;\n x(i,k) = + u;\n x(j,k) = - u;\n x(l,k) = + u;\n x(m,k) = + u;\n w(k) = b8;\n k = k + 1;\n x(i,k) = + u;\n x(j,k) = + u;\n x(l,k) = - u;\n x(m,k) = - u;\n w(k) = b8;\n k = k + 1;\n x(i,k) = + u;\n x(j,k) = + u;\n x(l,k) = - u;\n x(m,k) = + u;\n w(k) = b8;\n k = k + 1;\n x(i,k) = + u;\n x(j,k) = + u;\n x(l,k) = + u;\n x(m,k) = - u;\n w(k) = b8;\n k = k + 1;\n x(i,k) = + u;\n x(j,k) = + u;\n x(l,k) = + u;\n x(m,k) = + u;\n w(k) = b8;\n end\n end\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stroud/en_r2_09_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.46554047269810145}}
{"text": "function varargout = diff(varargin)\n%DIFF Derivative of a CHEBFUN2 object.\n% DIFF(F) is the derivative of F along the y direction.\n%\n% DIFF(F, N) is the Nth derivative of F in the y direction.\n%\n% DIFF(F, N, DIM) is the Nth derivative of F along the dimension DIM.\n% DIM = 1 (default) is the derivative in the y-direction.\n% DIM = 2 is the derivative in the x-direction.\n%\n% DIFF(F, [NX NY]) is the partial derivative of NX of F in the first variable,\n% and NY of F in the second derivative. For example, DIFF(F,[1 2]) is\n% d^3F/dxd^2y.\n%\n% See also GRADIENT, SUM, PROD.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n[varargout{1:nargout}] = diff@separableApprox(varargin{:});\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebfun2/diff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.4655041669377798}}
{"text": "function [z_irm,z_ibm,t] = applyIdealMasks(xt,xi,nfft,hop,fs)\n%APPLYIDEALMASKS Calculate and apply ideal masks via STFT\n% \n% Z_IRM = IOSR.BSS.APPLYIDEALMASKS(XT,XI) calculates the ideal ratio mask\n% (IRM) and applies it to the mixture XT+XI, where XT is the target\n% signal and XI is the interference signal. The IRM is calculated via the\n% STFT using 1024-point windows with 512-point overlap. Z_IRM, XT, and XI\n% are vectors. If XT and XI are of different lengths then the shorter\n% signal is zero-padded in order to make them the same length; Z_IRM is\n% the same length as XT and XI.\n% \n% Z_IRM = IOSR.BSS.APPLYIDEALMASKS(XT,XI,NFFT) uses NFFT-length segments\n% in the STFT.\n% \n% Z_IRM = IOSR.BSS.APPLYIDEALMASKS(XT,XI,WINDOW) uses\n% LENGTH(WINDOW)-length segments in the STFT and applies WINDOW to each\n% segment.\n% \n% Z_IRM = IOSR.BSS.APPLYIDEALMASKS(XT,XI,WINDOW,HOP) uses hop size HOP\n% for the STFT.\n% \n% [Z_IRM,Z_IBM] = IOSR.BSS.APPLYIDEALMASKS(...) calculates the ideal\n% binary mask (IBM) and applies it to the mixture, returning the result\n% to Z_IBM.\n% \n% [Z_IRM,Z_IBM,T] = IOSR.BSS.APPLYIDEALMASKS(XT,XI,WINDOW,HOP,FS) uses\n% sampling frequency FS to return the corresponding time T of each\n% element in Z_IRM and Z_IBM.\n% \n% See also IOSR.DSP.STFT, IOSR.DSP.ISTFT, IOSR.BSS.IDEALMASKS,\n% IOSR.BSS.APPLYMASKS.\n\n% Copyright 2016 University of Surrey.\n \n %% check input\n \n % check signals\n assert(isvector(xt) && numel(xt)>1, 'iosr:applyIdealMasks:invalidXt', 'XT must be a vector')\n assert(isvector(xi) && numel(xi)>1, 'iosr:applyIdealMasks:invalidXi', 'XI must be a vector')\n \n % make equal length\n maxlength = max([length(xi) length(xt)]);\n xt = pad(xt,maxlength);\n xi = pad(xi,maxlength);\n \n % check nfft\n if nargin<3\n nfft = 1024;\n end\n \n % determine window\n if numel(nfft)>1\n win = nfft;\n assert(isvector(win), 'iosr:applyIdealMasks:invalidWin', 'WINDOW must be a vector')\n nfft = length(win);\n else\n assert(round(nfft)==nfft && nfft>0, 'iosr:applyIdealMasks:invalidNfft', 'NFFT must be a positive integer')\n win = hamming(nfft);\n end\n \n % check x length\n assert(length(xt)>=nfft, 'iosr:applyIdealMasks:invalidXt', 'XT must have at least NFFT samples')\n assert(length(xi)>=nfft, 'iosr:applyIdealMasks:invalidXi', 'XI must have at least NFFT samples')\n \n % determine hop\n if nargin<4\n hop = fix(nfft/2);\n else\n assert(isscalar(hop) & round(hop)==hop, 'iosr:applyIdealMasks:invalidHop', 'HOP must be an integer')\n assert(hop<=nfft && hop>0, 'iosr:applyIdealMasks:invalidHop', 'HOP must be less than or equal to NFFT, and greater than 0')\n end\n \n % determine fs\n if nargin<5\n fs = 1;\n else\n assert(isscalar(fs), 'iosr:applyIdealMasks:invalidFs', 'FS must be an scalar')\n end\n \n %% calculate outputs\n \n % STFTs of signals and mixture\n st = iosr.dsp.stft(xt,win,hop);\n si = iosr.dsp.stft(xi,win,hop);\n mix = iosr.dsp.stft(xt+xi,win,hop);\n \n % return ideal masks\n [irm,ibm] = iosr.bss.idealMasks(st,si);\n \n % apply IRM\n z_irm = iosr.bss.applyMask(mix,irm,nfft,hop,fs);\n z_irm = pad(z_irm,maxlength);\n \n % apply IBM\n if nargout>1\n z_ibm = iosr.bss.applyMask(mix,ibm,nfft,hop,fs);\n z_ibm = pad(z_ibm,maxlength);\n end\n \n % calculate t\n if nargout>2\n t = (0:length(z_irm)-1)./fs;\n end\n \nend\n\nfunction y = pad(x,dur)\n%PAD Zero-pad a vector\n\n if length(x)\n% Pablo Arbelaez \n% June 2014\n% ------------------------------------------------------------------------ \n% This file is part of the MCG package presented in:\n% Arbelaez P, Pont-Tuset J, Barron J, Marques F, Malik J,\n% \"Multiscale Combinatorial Grouping,\"\n% Computer Vision and Pattern Recognition (CVPR) 2014.\n% Please consider citing the paper if you use this code.\n% ------------------------------------------------------------------------\nfunction [int_area, int_bbox] = boxes_intersection( bbox1, bbox2 )\n up1 = bbox1(1);\n left1 = bbox1(2);\n down1 = bbox1(3);\n right1 = bbox1(4);\n\n up2 = bbox2(1);\n left2 = bbox2(2);\n down2 = bbox2(3);\n right2 = bbox2(4);\n \n int_left = max(left1,left2);\n int_right = min(right1,right2);\n int_up = max(up1,up2);\n int_down = min(down1,down2);\n \n if (int_left<=int_right) && (int_up<=int_down)\n int_bbox = [int_up, int_left, int_down, int_right];\n int_area = box_area(int_bbox);\n else\n int_bbox = [];\n int_area = 0;\n end\nend\n\n", "meta": {"author": "s-gupta", "repo": "rcnn-depth", "sha": "7a7baf7dcccc6fdf6be7c13d16828064d89dff4e", "save_path": "github-repos/MATLAB/s-gupta-rcnn-depth", "path": "github-repos/MATLAB/s-gupta-rcnn-depth/rcnn-depth-7a7baf7dcccc6fdf6be7c13d16828064d89dff4e/mcg/src/bboxes/boxes_intersection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6187804267137441, "lm_q1q2_score": 0.46533065440704147}}
{"text": "%SerialLink.IKUNC Inverse manipulator by optimization without joint limits\n%\n% Q = R.ikunc(T, OPTIONS) are the joint coordinates (1xN) corresponding to\n% the robot end-effector pose T which is an SE3 object or homogenenous\n% transform matrix (4x4), and N is the number of robot joints. OPTIONS is\n% an optional list of name/value pairs than can be passed to fminunc.\n%\n% Q = robot.ikunc(T, Q0, OPTIONS) as above but specify the\n% initial joint coordinates Q0 used for the minimisation.\n%\n% [Q,ERR] = robot.ikunc(T,...) as above but also returns ERR which is the\n% scalar final value of the objective function.\n%\n% [Q,ERR,EXITFLAG] = robot.ikunc(T,...) as above but also returns the\n% status EXITFLAG from fminunc.\n%\n% [Q,ERR,EXITFLAG,OUTPUT] = robot.ikunc(T,...) as above but also returns the\n% structure OUTPUT from fminunc which contains details about the optimization.\n%\n% Trajectory operation::\n%\n% In all cases if T is a vector of SE3 objects (1xM) or a homogeneous transform\n% sequence (4x4xM) then returns the joint coordinates corresponding to\n% each of the transforms in the sequence. Q is MxN where N is the number\n% of robot joints. The initial estimate of Q for each time step is taken as\n% the solution from the previous time step.\n%\n% ERR and EXITFLAG are also Mx1 and indicate the results of optimisation\n% for the corresponding trajectory step.\n%\n% Notes::\n% - Requires fminunc from the MATLAB Optimization Toolbox.\n% - Joint limits are not considered in this solution.\n% - Can be used for robots with arbitrary degrees of freedom.\n% - In the case of multiple feasible solutions, the solution returned\n% depends on the initial choice of Q0\n% - Works by minimizing the error between the forward kinematics of the\n% joint angle solution and the end-effector frame as an optimisation.\n% The objective function (error) is described as:\n% sumsqr( (inv(T)*robot.fkine(q) - eye(4)) * omega )\n% Where omega is some gain matrix, currently not modifiable.\n%\n% Author::\n% Bryan Moutrie\n%\n% See also SerialLink.ikcon, fmincon, SerialLink.ikine, SerialLink.fkine.\n\n% Copyright (C) Bryan Moutrie, 2013-2015\n% Licensed under the GNU Lesser General Public License\n% see full file for full statement\n%\n% LICENSE STATEMENT:\n%\n% This file is part of pHRIWARE.\n% \n% pHRIWARE is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as \n% published by the Free Software Foundation, either version 3 of \n% the License, or (at your option) any later version.\n%\n% pHRIWARE 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 Lesser General Public \n% License along with pHRIWARE. If not, see .\n\n\nfunction [qstar, error, exitflag, output] = ikunc(robot, T, varargin)\n\n % check if Optimization Toolbox exists, we need it\n assert( exist('fminunc', 'file')>0, 'rtb:ikunc:nosupport', 'Optimization Toolbox required');\n \n if isa(T, 'SE3')\n T = T.T;\n end\n \n % create output variables\n T_sz = size(T,3);\n qstar = zeros(T_sz,robot.n);\n error = zeros(T_sz,1);\n exitflag = zeros(T_sz,1);\n \n problem.solver = 'fminunc';\n problem.x0 = zeros(1, robot.n);\n problem.options = optimoptions('fminunc', ...\n 'Algorithm', 'quasi-newton', ...\n 'Display', 'off'); % default options for ikunc\n \n if nargin > 2\n % check if there is a q0 passed\n if isnumeric(varargin{1}) && length(varargin{1}) == robot.n\n problem.x0 = varargin{1};\n varargin = varargin(2:end);\n end\n end\n if ~isempty(varargin)\n % if given, add optional argument to the list of optimiser options\n problem.options = optimoptions(problem.options, varargin{:});\n end\n \n reach = sum(abs([robot.a, robot.d]));\n omega = diag([1 1 1 3/reach]);\n \n for t = 1:T_sz\n problem.objective = ...\n @(x) sumsqr(((T(:,:,t) \\ robot.fkine(x).T) - eye(4)) * omega);\n \n [q_t, err_t, ef_t, out_t] = fminunc(problem);\n \n if ef_t ~= 1\n if T_sz > 1\n warning('step %d: errflag = %d, err = %f\\n', t, ef_t, err_t);\n else\n warning('errflag = %d, err = %f\\n', ef_t, err_t);\n out_t\n end\n end\n qstar(t,:) = q_t;\n error(t) = err_t;\n exitflag(t) = ef_t;\n output(t) = out_t;\n \n problem.x0 = q_t;\n end\n \nend\n\nfunction s = sumsqr(A)\n s = sum(A(:).^2);\nend\n\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/@SerialLink/ikunc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812554, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.46524885518117504}}
{"text": "function [sol,output] = sdf_nls(model,options)\n%SDF_NLS Structured data fusion by nonlinear least squares.\n% [sol,output] = sdf_nls(model) solves the data fusion problem described\n% by the structure model and returns the solution as the structure sol.\n% The model describes a data fusion problem with three fields:\n%\n% model.variables\n%\n% A structure or cell array of initializations for the variables in\n% the data fusion problem. Each field or cell in model.variables \n% represents a variable. A variable may be an array (such as\n% scalars, vectors, matrices and tensors) or a (nested) cell array\n% of arrays.\n%\n% model.factors\n%\n% A structure or cell array of factors. Each field or cell in\n% model.factors represents a factor. A factor is described by a\n% cell array of subfactors. After each subfactor has been\n% generated, the factor is constructed as the cell2mat of its\n% subfactors. A subfactor is a cell array in which the first\n% element is a reference to a variable, and the following elements\n% represent a sequence of transformations of that variable. If\n% model.variables is a structure, then a reference to a variable is\n% a string corresponding to the field name of the desired variable.\n% If model.variables is a cell array, then a reference to a\n% variable is the index of the cell containing the desired\n% variable. Transformations are supplied by functions which\n% describe their (linearized) behaviour. For example, the\n% transformation @struct_inv computes the factor as the matrix\n% inverse of the selected variable. All transformations must have\n% the function signature struct_mytrans(z,task). Instead of\n% supplying a reference to a variable, it is also possible to\n% supply a constant factor in the form of an array.\n% \n% model.factorizations\n% \n% A structure of data sets to jointly factorize. Each field in\n% model.factorizations represents a factorization. A factorization\n% is described by a structure containing two fields. The first\n% field has the field name 'data' and contains the (dense, sparse\n% or incomplete) array which is to be factorized. If the array\n% contains many zeros or a NaN, it is internally converted to a\n% sparse or incomplete tensor with fmt. The second field's \n% field name designates the type of factorization to compute of the\n% data set. Currently, two types are supported:\n%\n% 1. Canonical polyadic decomposition: a field 'cpd' should contain\n% a cell array of references to factors in model.factors. The\n% nth reference in the cell array corresponds to the nth factor\n% matrix of the CPD.\n%\n% 2. Block term decomposition: a field 'btd' should contain a cell\n% array of terms. Each term is itself a cell array containing\n% references to factors in model.factors. The nth reference in a\n% term corresponds to the nth factor matrix of that term. The\n% (N+1)th reference, where N is the number of dimensions of the\n% data set, in a term corresponds to the core tensor of that\n% term.\n%\n% Additionally, two types of regularization are available:\n%\n% 3. L2 regularization: a field 'regL2' should contain a cell array\n% of references to factors in model.factors. This appends a term\n% to the objective function of the form 0.5*norm(F(:)-D(:),2)^2,\n% where F(:) and D(:) are the serialized factors in regL2 and\n% the data field respectively. The data field may be omitted, in\n% which case it is an all-zero vector.\n%\n% 4. L1 regularization: a field 'regL1' should contain a cell array\n% of references to factors in model.factors. This appends a term\n% to the objective function which is a smooth approximation of\n% 0.5*norm(F(:)-D(:),1), where F(:) and D(:) are the serialized\n% factors in regL1 and the data field respectively. The data\n% field may be omitted, in which case it is an all-zero vector.\n%\n% The algorithm proceeds to compute the joint factorization of the data\n% sets provided by models.factorizations by minimizing the sum of square\n% magnitude residuals of these factorizations. The output sol contains\n% the optimized variables in sol.variables and the corresponding factors\n% in sol.factors.\n%\n% The structure output returns additional information:\n%\n% output.Name - The name of the selected algorithm.\n% output.<...> - The output of the selected algorithm.\n%\n% sdf_nls(model,options) may be used to set the following options:\n%\n% options.Algorithm = - The desired optimization method.\n% [@nls_gncgs| ...\n% {@nls_gndl}|@nls_lm]\n% options.PC = true - Whether or not to use a preconditioner, if\n% available, for computing the Gauss-Newton\n% step.\n% options.RelWeights = - By supplying relative weights, the weights\n% ones(1,F) options.Weights are computed as follows:\n% options.Weights(f) = options.RelWeights(f)/\n% (sum(options.RelWeights)*numel(data_f)) for\n% each of the F factorizations in the model.\n% options.Weights - The weight of the F factorizations in the\n% data fusion model. The SDF objective\n% function is \\sum_f 0.5*options.Weights(f)*\n% frob(model_f-data_f)^2, where model_f and\n% data_f are the fth factorization and\n% corresponding tensor. By default, weights\n% are provided by options.RelWeights, but\n% options.Weights has precedence if supplied.\n% options.<...> - Parameters passed to the selected method,\n% e.g., options.TolFun, options.TolX.\n% See also help [options.Algorithm].\n%\n% See also sdf_minf.\n\n% Authors: Laurent Sorber (Laurent.Sorber@cs.kuleuven.be)\n% Marc Van Barel (Marc.VanBarel@cs.kuleuven.be)\n% Lieven De Lathauwer (Lieven.DeLathauwer@kuleuven-kulak.be)\n%\n% References:\n% [1] L. Sorber, M. Van Barel, L. De Lathauwer, \"Structured data fusion,\"\n% ESAT-SISTA Internal Report 13-177, KU Leuven, 2013.\n\n% Check the options structure.\nif nargin < 2, options = struct; end\nisfunc = @(f)isa(f,'function_handle');\nxsfunc = @(f)isfunc(f)&&exist(func2str(f),'file');\nif ~isfield(options,'Algorithm')\n funcs = {@nls_gndl,@nls_gncgs,@nls_lm};\n options.Algorithm = funcs{find(cellfun(xsfunc,funcs),1)};\nend\nif ~isfield(options,'MaxIter'), options.MaxIter = 5000; end\nif ~isfield(options,'CGMaxIter'), options.CGMaxIter = 15; end\nif ~isfield(options,'Display'), options.Display = 0; end\nif ~isfield(options,'JHasFullRank'), options.JHasFullRank = false; end\nif ~isfield(options,'PC'), options.PC = true; end\nif ~isfield(options,'TolLargeScale'), options.TolLargeScale = 0.02; end\n\n% Convert model to internal format.\nif ~iscell(model.variables)\n cache.variables.names = fieldnames(model.variables);\n model.variables = reshape(struct2cell(model.variables),1,[]);\nelse\n model.variables = model.variables(:).';\nend\nif ~iscell(model.factors)\n cache.factors.names = fieldnames(model.factors);\n model.factors = reshape(struct2cell(model.factors),1,[]);\nelse\n model.factors = model.factors(:).';\nend\nif ~iscell(model.factorizations)\n cache.factorizations.names = fieldnames(model.factorizations);\n model.factorizations = reshape(struct2cell(model.factorizations),1,[]);\nelse\n model.factorizations = model.factorizations(:).';\nend\nfor I = 1:length(model.factors)\n if ~iscell(model.factors{I})\n model.factors{I} = model.factors(I);\n end\n if any(cellfun(@(f)isa(f,'function_handle'),model.factors{I}))\n model.factors{I} = model.factors(I);\n else\n for J = find(~cellfun(@iscell,model.factors{I}(:).'))\n model.factors{I}{J} = model.factors{I}(J);\n end\n end\nend\n\n% Set functions for saving state, computing the objective function,\n% gradient and fast matrix-vector products. New models need only implement\n% these four functions.\nfor I = 1:length(model.factorizations)\n fn = fieldnames(model.factorizations{I});\n model.factorizations{I}.type = find(~strcmp('data',fn));\n model.factorizations{I}.type = fn{model.factorizations{I}.type};\n model.factorizations{I}.factors = ...\n model.factorizations{I}.(model.factorizations{I}.type);\n model.factorizations{I} = ...\n rmfield(model.factorizations{I},model.factorizations{I}.type);\n switch model.factorizations{I}.type\n case 'cpd'\n model.factorizations{I}.state = @state_cpd;\n model.factorizations{I}.objfun = @objfun_cpd;\n model.factorizations{I}.grad = @grad_cpd;\n model.factorizations{I}.JHJx = @JHJx_cpd;\n case 'btd'\n model.factorizations{I}.state = @state_btd;\n model.factorizations{I}.objfun = @objfun_btd;\n model.factorizations{I}.grad = @grad_btd;\n model.factorizations{I}.JHJx = @JHJx_btd;\n case 'regL2'\n model.factorizations{I}.state = @state_regL2;\n model.factorizations{I}.objfun = @objfun_regL2;\n model.factorizations{I}.grad = @grad_regL2;\n model.factorizations{I}.JHJx = @JHJx_regL2;\n case 'regL1'\n model.factorizations{I}.state = @state_regL1;\n model.factorizations{I}.objfun = @objfun_regL1;\n model.factorizations{I}.grad = @grad_regL1;\n model.factorizations{I}.JHJx = @JHJx_regL1;\n otherwise\n error('sdf_nls:model','Model %s is not supported', ...\n model.factorizations{I}.type);\n end\nend\n\n% Fill in constants and dereference pointers from factors to variables.\ncache.factors.isconst = cell(1,length(model.factors));\nfor I = 1:length(model.factors)\n cache.factors.isconst{I} = ...\n cellfun(@(f)isnumeric(f{1})&&~isscalar(f{1}),model.factors{I});\n for J = 1:numel(model.factors{I})\n if cache.factors.isconst{I}(J)\n const = model.factors{I}{J}{1};\n for K = 2:length(model.factors{I}{J})\n const = model.factors{I}{J}{K}(const);\n end\n model.factors{I}{J} = {const};\n elseif ischar(model.factors{I}{J}{1})\n model.factors{I}{J}{1} = ...\n find(strcmp(model.factors{I}{J}{1},cache.variables.names));\n end\n end\nend\n\n% Dereference and flatten pointers from factorizations to factors.\nfor I = 1:length(model.factorizations)\n\tmodel.factorizations{I}.factors = ...\n deref(model.factorizations{I}.factors);\nend\nfunction array = deref(array)\n for i = 1:length(array)\n if iscell(array{i})\n array{i} = deref(array{i});\n elseif ischar(array{i})\n array{i} = find(strcmp(array{i},cache.factors.names));\n end\n end\nend\n\n% Convert full data to incomplete/sparse format where appropriate.\ncache.factorizations.isincomplete = false(1,length(model.factorizations));\ncache.factorizations.issparse = false(1,length(model.factorizations));\nfor I = 1:length(model.factorizations)\n if ~isfield(model.factorizations{I},'data') || ...\n iscell(model.factorizations{I}.data)\n continue;\n end\n model.factorizations{I}.data = ...\n fmt(model.factorizations{I}.data,true);\n if isstruct(model.factorizations{I}.data)\n cache.factorizations.isincomplete(I) = ...\n model.factorizations{I}.data.incomplete;\n cache.factorizations.issparse(I) = ...\n model.factorizations{I}.data.sparse;\n end\nend\n\n% Cache expansion of variables into factors.\ncache.factors.expanded = cell(size(model.factors));\ncache.factors.sequence = cell(size(model.factors));\ncache.factors.state = cell(size(model.factors));\nfor I = 1:length(model.factors)\n cache.factors.sequence{I} = cell(size(model.factors{I}));\n cache.factors.state{I} = cell(size(model.factors{I}));\n for J = 1:numel(model.factors{I})\n cache.factors.sequence{I}{J} = cell(1,length(model.factors{I}{J}));\n cache.factors.state{I}{J} = cell(1,length(model.factors{I}{J})-1);\n end\nend\nexpand(model.variables,'cache');\n\n% Cache factors' structure.\ncache.factors.structure = ...\n cellfun(@structure,cache.factors.sequence,'UniformOutput',false);\n\n% Cache offsets for variables and expanded factors.\ncache.variables.offset = ...\n cumsum([1 cellfun(@(v)numel(serialize(v)),model.variables)]);\ncache.factorizations.serialized = cell(size(model.factorizations));\ncache.factorizations.offset = cell(size(model.factorizations));\ncache.factorizations.suboffset = cell(size(model.factorizations));\nfor I = 1:length(model.factorizations)\n cache.factorizations.serialized{I} = ...\n serialize(model.factorizations{I}.factors).';\n cache.factorizations.offset{I} = ...\n cumsum([1 cellfun(@(v)numel(serialize(v)), ...\n cache.factors.expanded(cache.factorizations.serialized{I}))]);\n cum = cumsum([0 cellfun(@(f)sum(serialize( ...\n cellfun(@(s)numel(s{end}),f))),cache.factors.sequence( ...\n cache.factorizations.serialized{I}))]);\n fct = cellfun(@(f)cellfun(@(s)false(size(s{end})),f,'UniformOutput',...\n false),cache.factors.sequence( ...\n cache.factorizations.serialized{I}),'UniformOutput',false);\n cache.factorizations.suboffset{I} = cell(1,length(fct));\n for J = 1:length(fct)\n cache.factorizations.suboffset{I}{J} = cell(size(fct{J}));\n for K = 1:numel(fct{J})\n subfct = fct{J};\n subfct{K} = true(size(subfct{K}));\n subfct = find(cell2mat(subfct));\n if all(subfct(2:end) == subfct(1:end-1)+1)\n subfct = [subfct(1) subfct(end)];\n end\n cache.factorizations.suboffset{I}{J}{K} = subfct+cum(J);\n end\n end\nend\n\n% Set (relative) weights.\nif isfield(options,'RelWeights') && isfield(options,'Weights')\n warning('sdf_nls:weights',['Both relative and absolute weights ' ...\n 'are supplied, proceeding with absolute weights.']);\nend\nif ~isfield(options,'RelWeights')\n options.RelWeights = ones(1,length(model.factorizations));\nend\noptions.RelWeights = options.RelWeights./sum(options.RelWeights);\nif ~isfield(options,'Weights')\n for I = 1:length(model.factorizations)\n if isfield(model.factorizations{I},'data') && ...\n ~iscell(model.factorizations{I}.data)\n if isstruct(model.factorizations{I}.data)\n NUM = numel(model.factorizations{I}.data.val);\n else\n NUM = numel(model.factorizations{I}.data);\n end\n else\n NUM = cache.factorizations.offset{I}(end);\n end\n options.Weights(I) = 2*options.RelWeights(I)/NUM;\n end\nend\nif length(options.Weights) ~= length(model.factorizations)\n error('sdf_nls:weights',['The number of weights must equal the ' ...\n 'number of factorizations.']);\nend\n\n% Initialize each factorization's state.\ncache.factorizations.state = cell(size(model.factorizations));\nfor I = 1:length(model.factorizations)\n model.factorizations{I}.state(I,true);\nend\n\n% Run optimization algorithm.\ndF.JHF = @grad;\ndF.JHJx = @JHJx;\nif options.PC && isfield(options,'M') && isa(options.M,'function_handle')\n dF.M = options.M;\nend\n[z,output] = options.Algorithm(@objfun,dF,model.variables,options);\noutput.Name = func2str(options.Algorithm);\n\n% Return output.\nif isfield(cache.variables,'names')\n sol.variables = cell2struct(z(:),cache.variables.names);\nelse\n sol.variables = z;\nend\nif isfield(cache.factors,'names')\n sol.factors = cell2struct(reshape(expand(z),[],1),cache.factors.names);\nelse\n sol.factors = expand(z);\nend\n\nfunction x = expand(z,where)\n% Expands the variables into factors stored in the field factors.expanded,\n% and stores their computational state in the field factors.state.\n\n % Save some references for speed.\n factors = model.factors;\n isconst = cache.factors.isconst;\n \n % Expand into cache or into the output variable x.\n if nargin == 2 && ischar(where)\n \n % For each ith factor...\n for i = 1:length(factors)\n % For each jth subfactor...\n for j = 1:numel(factors{i})\n if isconst{i}(j)\n % Constant subfactor.\n cache.factors.sequence{i}{j}{1} = factors{i}{j}{1};\n else\n % For each kth transformation...\n cache.factors.sequence{i}{j}{1} = z{factors{i}{j}{1}};\n for k = 2:length(factors{i}{j})\n [cache.factors.sequence{i}{j}{k}, ...\n cache.factors.state{i}{j}{k-1}] = ...\n factors{i}{j}{k}( ...\n cache.factors.sequence{i}{j}{k-1},[]);\n end\n end\n end\n if numel(cache.factors.sequence{i}) == 1\n cache.factors.expanded{i} = ...\n cache.factors.sequence{i}{j}{end};\n else\n cache.factors.expanded{i} = ...\n cell2mat(cellfun(@(f)f{end}, ...\n cache.factors.sequence{i},'UniformOutput',false));\n end\n end\n \n else\n \n % For each ith factor...\n x = cell(size(factors));\n for i = 1:length(factors)\n % For each jth subfactor...\n sub = cell(size(factors{i}));\n for j = 1:numel(factors{i})\n if isconst{i}(j)\n % Constant subfactor.\n sub{j} = factors{i}{j}{1};\n else\n % For each kth transformation...\n sub{j} = z{factors{i}{j}{1}};\n for k = 2:length(factors{i}{j})\n sub{j} = factors{i}{j}{k}(sub{j},[]);\n end\n end\n end\n if numel(sub) == 1, x{i} = sub{1};\n else x{i} = cell2mat(sub);\n end\n end\n \n end\n \nend\n\nfunction x = derivexpand(r)\n% Linearly expand variables using their transformations' Jacobians.\n\n % Save some references for speed.\n factors = model.factors;\n voffset = cache.variables.offset;\n isconst = cache.factors.isconst;\n sequence = cache.factors.sequence;\n state = cache.factors.state;\n structure = cache.factors.structure;\n\n % For each ith factor...\n x = cell(size(factors));\n for i = 1:length(factors)\n % For each jth subfactor...\n sub = cell(size(factors{i}));\n for j = 1:numel(factors{i})\n if isconst{i}(j)\n % Constant subfactor.\n sub{j} = zeros(size(sequence{i}{j}{1}));\n else\n % For each kth transformation...\n seq = factors{i}{j};\n ftr = sequence{i}{j};\n stt = state{i}{j};\n dim = structure{i}{j}{1};\n sub{j} = r(voffset(seq{1}):voffset(seq{1}+1)-1);\n if isnumeric(dim)\n if ~isempty(dim), sub{j} = reshape(sub{j},dim); end\n else sub{j} = deserialize(sub{j},dim);\n end\n for k = 2:length(seq)\n task = stt{k-1};\n task.l = [];\n task.r = sub{j};\n sub{j} = seq{k}(ftr{k-1},task);\n end\n end\n\n end\n if numel(sub) == 1, x{i} = sub{1};\n else x{i} = cell2mat(sub);\n end\n end\n\nend\n\nfunction y = derivcontract(f,y,l)\n% Linearly contract factors using their transformations' Jacobians.\n\n % Save some references for speed.\n factors = model.factors;\n voffset = cache.variables.offset;\n isconst = cache.factors.isconst;\n sequence = cache.factors.sequence;\n state = cache.factors.state;\n structure = cache.factors.structure;\n serialized = cache.factorizations.serialized{f};\n soffset = cache.factorizations.suboffset{f};\n\n % Update y with Jacobian-contracted variables.\n for i = 1:length(serialized)\n % For each jth subfactor...\n idx = serialized(i);\n for j = 1:numel(factors{idx})\n \n % Skip this subfactor if it's constant.\n if isconst{idx}(j), continue; end\n\n % Apply sequence of Jacobian-vector products.\n seq = factors{idx}{j};\n ftr = sequence{idx}{j};\n stt = state{idx}{j};\n if size(soffset{i}{j},2) == 2\n sub = l(soffset{i}{j}(1):soffset{i}{j}(2));\n else\n sub = l(soffset{i}{j});\n end\n if length(seq) > 1\n dim = structure{idx}{j}{end};\n if isnumeric(dim)\n if ~isempty(dim), sub = reshape(sub,dim); end\n else sub = deserialize(sub,dim);\n end\n for k = length(seq):-1:2\n task = stt{k-1};\n task.l = sub;\n task.r = [];\n sub = seq{k}(ftr{k-1},task);\n end\n sub = serialize(sub);\n end\n \n % Update y.\n jdx = voffset(seq{1}):voffset(seq{1}+1)-1;\n y(jdx) = y(jdx)+sub;\n \n end\n end\n \nend\n\nfunction z = getfactors(f,x)\n% Retrieves factors of the fth factorization, given the factors x.\n \n % Deserialize the factors.\n z = deserialize_local(x,model.factorizations{f}.factors);\n function z = deserialize_local(x,dim)\n z = cell(size(dim));\n for i = 1:numel(dim)\n if iscell(dim{i})\n z{i} = deserialize_local(x,dim{i});\n else\n z{i} = x{dim{i}};\n end\n end\n end\n \nend\n\nfunction fval = objfun(z)\n \n % Expand the variables into factors.\n x = expand(z);\n \n % Compute objective function value.\n fval = 0;\n for i = find(options.Weights(:).' ~= 0)\n fval = fval+options.Weights(i)* ...\n model.factorizations{i}.objfun(i,getfactors(i,x));\n end\n \nend\n\nfunction grad = grad(z)\n \n % Expand the variables into factors.\n expand(z,'cache');\n \n % Let each factorization save intermediate computations in the cache.\n for i = 1:length(model.factorizations)\n model.factorizations{i}.state(i);\n end\n \n % Compute the gradient.\n grad = zeros(cache.variables.offset(end)-1,1);\n for i = find(options.Weights(:).' ~= 0)\n \n % Compute model's gradient.\n tmp = getfactors(i,cache.factors.expanded);\n JHF = model.factorizations{i}.grad(i,tmp);\n \n % Contract the factor matrices into variables.\n if i == 1\n grad = options.Weights(i)*derivcontract(i,grad,JHF);\n else\n grad = grad+options.Weights(i)*derivcontract(i,grad,JHF);\n end\n \n end\n \nend\n\nfunction y = JHJx(~,x)\n \n % Expand the variables into factors.\n x = derivexpand(x);\n \n % Compute (J(z)'*J(z))*x after expansion.\n y = zeros(cache.variables.offset(end)-1,1);\n for i = find(options.Weights(:).' ~= 0)\n \n % Apply fast matrix-vector product.\n tmpa = getfactors(i,cache.factors.expanded);\n tmpb = getfactors(i,x);\n JHJx = model.factorizations{i}.JHJx(i,tmpa,tmpb);\n \n % Contract the factor matrices into variables.\n if i == 1\n y = options.Weights(i)*derivcontract(i,y,JHJx);\n else\n y = y+options.Weights(i)*derivcontract(i,y,JHJx);\n end\n \n end\n \nend\n\nfunction [z,offset] = deserialize(z,dim,offset)\n if iscell(dim)\n v = z;\n z = cell(size(dim));\n if nargin < 3, offset = 0; end\n for i = 1:numel(z)\n if iscell(dim{i})\n [z{i},offset] = deserialize(v,dim{i},offset);\n else\n n = prod(dim{i}(:));\n z{i} = reshape(v(offset+(1:n)),dim{i});\n offset = offset+n;\n end\n end\n elseif ~isempty(dim)\n z = reshape(z,dim);\n end\nend\n\nfunction z = serialize(z)\n if iscell(z)\n for i = find(cellfun(@iscell,z(:).'))\n z{i} = serialize(z{i});\n end\n s = cellfun(@numel,z(:)); o = [0; cumsum(s)];\n c = z; z = zeros(o(end),1);\n for i = 1:length(s), z(o(i)+(1:s(i))) = c{i}(:); end\n else\n z = z(:);\n end\nend\n\nfunction dim = structure(z)\n if iscell(z)\n dim = cellfun(@size,z,'UniformOutput',false);\n for i = find(cellfun(@iscell,z(:).'))\n dim{i} = structure(z{i});\n end\n else\n dim = size(z);\n if numel(z) == dim(1), dim = []; end\n end\nend\n\n% Model: canonical polyadic decomposition ---------------------------------\n\nfunction state_cpd(f,firstrun)\n% Can read from model, cache and options, can save state by writing to the\n% structure cache.factorizations.state{f}.\n\n if nargin == 2 && firstrun\n \n % Store the fraction of known elements.\n if cache.factorizations.isincomplete(f)\n cache.factorizations.scale{f} = ...\n length(model.factorizations{f}.data.val)./...\n prod(model.factorizations{f}.data.size);\n end\n \n % Set Block-Jacobi preconditioner if\n % - the model is a single CPD and\n % - each factor consists of exactly one subfactor and\n % - no subfactor is transformed and\n % - every subfactor is a reference to a variable and\n % - all variable references are unique and\n % - all factor references are unique and\n % - an NLS algorithm is used.\n options.BJ = false;\n var = cellfun(@(v)v{1}{1},model.factors,'UniformOutput',false);\n ftr = cell2mat(model.factorizations{f}.factors);\n if options.PC && numel(model.factorizations) == 1 && ...\n all(cellfun(@(v)length(v) == 1,model.factors)) && ...\n all(cellfun(@(v)length(v{1}) == 1,model.factors)) && ...\n all(cellfun(@isscalar,var)) && ...\n length(unique(cell2mat(var))) == length(cell2mat(var))&&...\n length(unique(ftr)) == length(ftr) && ...\n ~isempty(strfind(func2str(options.Algorithm),'nls'))\n options.M = @pc_cpd;\n options.BJ = true;\n end\n \n end\n\n % Cache the factor matrices' Gramians.\n idx = cache.factorizations.serialized{f};\n N = length(idx);\n R = size(cache.factors.expanded{idx(1)},2);\n cache.factorizations.state{f}.UHU = zeros(N,R*R);\n for n = 1:N\n tmp = cache.factors.expanded{idx(n)};\n tmp = conj(tmp'*tmp);\n cache.factorizations.state{f}.UHU(n,:) = tmp(:);\n end\n \n % Optionally cache the inverses of the Gramians for the preconditioner.\n % In a faster language, this should be the Cholesky factor instead.\n if options.BJ\n cache.factorizations.state{f}.invW = cell(1,N);\n for n = 1:N\n tmp = cache.factorizations.state{f}.UHU([1:n-1 n+1:N],:);\n if N > 2, tmp = prod(tmp,1); end\n cache.factorizations.state{f}.invW{n} = ...\n inv(reshape(tmp,[R R]));\n end\n end\n \nend\n\nfunction fval = objfun_cpd(f,z)\n \n % CPD objective function.\n T = model.factorizations{f}.data;\n isincomplete = cache.factorizations.isincomplete(f);\n issparse = cache.factorizations.issparse(f);\n if ~isincomplete || length(T.ind)/prod(T.size) > options.TolLargeScale\n fval = z{1}*kr(z(end:-1:2)).';\n if isincomplete, fval = fval(T.ind)-T.val;\n elseif issparse\n if ~isempty(T.ind), fval(T.ind) = fval(T.ind)-T.val; end\n else fval = fval-reshape(T,size(fval));\n end\n else\n fval = -T.val;\n for r = 1:size(z{1},2)\n tmp = z{1}(T.sub{1},r);\n for n = 2:length(z), tmp = tmp.*z{n}(T.sub{n},r); end\n fval = fval+tmp;\n end\n end\n if isincomplete\n T.val = fval;\n if ~isempty(T.matrix)\n T.matrix = sparse(double(T.sub{1}), ...\n double(1+idivide(T.ind-1,int64(size(T.matrix,1)))), ...\n double(fval),size(T.matrix,1),size(T.matrix,2));\n end\n cache.factorizations.residual{f} = T;\n else\n if issparse, size_tens = T.size;\n else size_tens = size(T); end\n cache.factorizations.residual{f} = reshape(fval,size_tens);\n end\n fval = 0.5*(fval(:)'*fval(:));\n \nend\n\nfunction grad = grad_cpd(f,z)\n \n % CPD scaled conjugate cogradient.\n E = cache.factorizations.residual{f};\n offset = cache.factorizations.offset{f};\n grad = zeros(offset(end)-1,1);\n for n = 1:length(z)\n tmp = full(mtkrprod(E,z,n));\n grad(offset(n):offset(n+1)-1) = tmp(:);\n end\n \nend\n\nfunction y = JHJx_cpd(f,z,x)\n \n % CPD fast Jacobian's Gramian vector product.\n % Ignores the fact that the tensor might be incomplete.\n R = size(z{1},2);\n N = length(z);\n offset = cache.factorizations.offset{f};\n UHU = cache.factorizations.state{f}.UHU;\n XHU = zeros(R,R,N);\n y = zeros(offset(end)-1,1);\n for n = 1:N\n Wn = UHU([1:n-1 n+1:N],:);\n if N > 2, Wn = prod(Wn,1); end\n XHU(:,:,n) = conj(x{n}'*z{n});\n y(offset(n):offset(n+1)-1) = x{n}*reshape(Wn,[R R]);\n end\n for n = 1:N-1\n idxn = offset(n):offset(n+1)-1;\n Wn = zeros(R);\n for m = n+1:N\n idxm = offset(m):offset(m+1)-1;\n if N == 2\n Wn = Wn+XHU(:,:,m);\n JHJmnx = z{m}*XHU(:,:,n);\n else\n Wnm = UHU([1:n-1 n+1:m-1 m+1:N],:);\n if N > 3, Wnm = prod(Wnm,1); end\n Wnm = reshape(Wnm,[R R]);\n Wn = Wn+Wnm.*XHU(:,:,m);\n JHJmnx = z{m}*(Wnm.*XHU(:,:,n));\n end\n y(idxm) = y(idxm)+JHJmnx(:);\n end\n JHJnx = z{n}*Wn;\n y(idxn) = y(idxn)+JHJnx(:);\n end\n \n % If incomplete, approximate the effect of missing entries.\n if cache.factorizations.isincomplete(f)\n y = y*cache.factorizations.scale{f};\n end\n \nend\n\nfunction x = pc_cpd(~,b)\n\n % Solve M*x = b, where M is a block-diagonal approximation for JHJ.\n % Equivalent to simultaneous ALS updates for each of the factors.\n x = zeros(size(b));\n offset = cache.factorizations.offset{1};\n invW = cache.factorizations.state{1}.invW;\n for n = 1:length(offset)-1\n idx = offset(n):offset(n+1)-1;\n tmp = reshape(b(idx),[],size(invW{1},1))*invW{n};\n x(idx) = tmp(:);\n end\n x = x/options.Weights;\n \n % If incomplete, approximate the effect of missing entries.\n if cache.factorizations.isincomplete(1)\n x = x/cache.factorizations.scale{1};\n end\n \nend\n\n% Model: block term decomposition -----------------------------------------\n\nfunction state_btd(f,firstrun)\n% Can read from model, cache and options, can save state by writing to the\n% structure cache.factorizations.state{f}.\n \n if nargin == 2 && firstrun\n \n % Store the fraction of known elements.\n if cache.factorizations.isincomplete(f)\n cache.factorizations.scale{f} = ...\n length(model.factorizations{f}.data.val)./...\n prod(model.factorizations{f}.data.size);\n end\n \n % Set Block-Jacobi preconditioner if\n % - the model is a single BTD and\n % - each factor consists of exactly one subfactor and\n % - no subfactor is transformed and\n % - every subfactor is a reference to a variable and\n % - all variable references are unique and\n % - all factor references are unique and\n % - an NLS algorithm is used.\n options.BJ = false;\n var = cellfun(@(v)v{1}{1},model.factors,'UniformOutput',false);\n ftr = cache.factorizations.serialized{1};\n if options.PC && numel(model.factorizations) == 1 && ...\n all(cellfun(@(v)length(v) == 1,model.factors)) && ...\n all(cellfun(@(v)length(v{1}) == 1,model.factors)) && ...\n all(cellfun(@isscalar,var)) && ...\n length(unique(cell2mat(var))) == length(cell2mat(var))&&...\n length(unique(ftr)) == length(ftr) && ...\n ~isempty(strfind(func2str(options.Algorithm),'nls'))\n options.M = @pc_btd;\n options.BJ = true;\n end\n \n end\n \n % Cache the factor matrices' Gramians.\n U = getfactors(f,cache.factors.expanded);\n R = length(U);\n N = length(U{1})-1;\n [idx,jdx,kdx] = ndgrid(1:R,1:N,1:R);\n cache.factorizations.state{f}.UHU = ...\n arrayfun(@(i,n,j)U{i}{n}'*U{j}{n}, ...\n idx,jdx,kdx,'UniformOutput',false);\n \n % Optionally cache some results for the block-Jacobi preconditioner.\n if options.BJ\n [idx,jdx] = ndgrid(1:R,1:N);\n UHU = cache.factorizations.state{f}.UHU;\n cache.factorizations.state{f}.invSKS = arrayfun( ...\n @(r,n)inv(mtkronprod(U{r}{end},UHU(r,:,r),n)* ...\n conj(reshape(permute(U{r}{end},[1:n-1 n+1:N n]), ...\n [],size(U{r}{end},n)))),idx,jdx,'UniformOutput',false);\n cache.factorizations.state{f}.invUHU = arrayfun( ...\n @(r,n)inv(UHU{r,n,r}),idx,jdx,'UniformOutput',false);\n end\n\nend\n\nfunction fval = objfun_btd(f,z)\n \n % BTD objective function.\n T = model.factorizations{f}.data;\n isincomplete = cache.factorizations.isincomplete(f);\n issparse = cache.factorizations.issparse(f);\n if ~isincomplete || length(T.ind)/prod(T.size) > options.TolLargeScale\n fval = z{1}{1}*mtkronprod(z{1}{end},z{1}(1:end-1),1,'H');\n for r = 2:length(z)\n fval = fval+z{r}{1}*mtkronprod(z{r}{end},z{r}(1:end-1),1,'H');\n end\n if isincomplete, fval = fval(T.ind)-T.val;\n elseif issparse\n if ~isempty(T.ind), fval(T.ind) = fval(T.ind)-T.val; end\n else fval = fval-reshape(T,size(fval));\n end\n else\n fval = -T.val;\n for r = 1:length(z)\n size_core = cellfun('size',z{r}(1:end-1),2);\n idx = cell(1,length(size_core));\n S = z{r}{end};\n for i = 1:numel(S)\n [idx{:}] = ind2sub(size_core,i);\n tmp = S(idx{:})*z{r}{1}(T.sub{1},idx{1});\n for n = 2:length(size_core)\n tmp = tmp.*z{r}{n}(T.sub{n},idx{n});\n end\n fval = fval+tmp;\n end\n end\n end\n if isincomplete\n T.val = fval;\n if ~isempty(T.matrix)\n T.matrix = sparse(double(T.sub{1}), ...\n double(1+idivide(T.ind-1,int64(size(T.matrix,1)))), ...\n double(fval),size(T.matrix,1),size(T.matrix,2));\n end\n cache.factorizations.residual{f} = T;\n else\n if issparse, size_tens = T.size;\n else size_tens = size(T); end\n cache.factorizations.residual{f} = reshape(fval,size_tens);\n end\n fval = 0.5*(fval(:)'*fval(:));\n \nend\n\nfunction grad = grad_btd(f,z)\n \n % BTD scaled conjugate cogradient.\n N = length(z{1})-1;\n E = cache.factorizations.residual{f};\n offset = cache.factorizations.offset{f};\n grad = zeros(offset(end)-1,1);\n cnt = 1;\n for r = 1:length(z)\n U = z{r}(1:N);\n S = conj(z{r}{end});\n for n = 1:N\n tmp = full(mtkronprod(E,U,n))* ...\n reshape(permute(S,[1:n-1 n+1:N n]),[],size(S,n));\n grad(offset(cnt):offset(cnt+1)-1) = tmp(:);\n cnt = cnt+1;\n end\n tmp = full(mtkronprod(E,U,0));\n grad(offset(cnt):offset(cnt+1)-1) = tmp;\n cnt = cnt+1;\n end\n \nend\n\nfunction y = JHJx_btd(f,z,x)\n \n % BTD fast Jacobian's Gramian vector product.\n % Ignores the fact that the tensor might be incomplete.\n R = length(z);\n N = length(z{1})-1;\n offset = cache.factorizations.offset{f};\n UHU = cache.factorizations.state{f}.UHU;\n [idx,jdx,kdx] = ndgrid(1:R,1:N,1:R);\n XHU = arrayfun(@(i,n,j)x{i}{n}'*z{j}{n}, ...\n idx,jdx,kdx,'UniformOutput',false);\n y = zeros(offset(end)-1,1);\n cnt = 1;\n for ri = 1:R\n \n % Factor matrices.\n for ni = 1:N\n idx = offset(cnt):offset(cnt+1)-1;\n Sri = permute(z{ri}{end},[1:ni-1 ni+1:N ni]);\n Sri = conj(reshape(Sri,[],size(Sri,N)));\n for rj = 1:R\n Srj = z{rj}{end};\n tmp = mtkronprod(x{rj}{end},UHU(rj,:,ri),ni);\n for nj = [1:ni-1 ni+1:N]\n proj = UHU(rj,:,ri);\n proj{nj} = XHU{rj,nj,ri};\n tmp = tmp+mtkronprod(Srj,proj,ni);\n end\n tmp = z{rj}{ni}*(tmp*Sri);\n tmp = tmp+x{rj}{ni}* ...\n (mtkronprod(z{rj}{end},UHU(rj,:,ri),ni)*Sri);\n if rj == 1, y(idx) = tmp(:);\n else y(idx) = y(idx)+tmp(:); end\n end\n cnt = cnt+1;\n end\n \n % Core tensor.\n idx = offset(cnt):offset(cnt+1)-1;\n for rj = 1:R\n Srj = z{rj}{end};\n tmp = mtkronprod(x{rj}{end},UHU(rj,:,ri),0);\n for nj = 1:N\n proj = UHU(rj,:,ri);\n proj{nj} = XHU{rj,nj,ri};\n tmp = tmp+mtkronprod(Srj,proj,0);\n end\n if rj == 1, y(idx) = tmp(:);\n else y(idx) = y(idx)+tmp(:); end\n end\n cnt = cnt+1;\n \n end\n \n % If incomplete, approximate the effect of missing entries.\n if cache.factorizations.isincomplete(f)\n y = y*cache.factorizations.scale{f};\n end\n \nend\n\nfunction x = pc_btd(~,b)\n\n % Solve M*x = b, where M is a block-diagonal approximation for JHJ.\n x = zeros(size(b));\n R = length(model.factorizations{1}.factors);\n N = length(model.factorizations{1}.factors{1})-1;\n offset = cache.factorizations.offset{1};\n invSKS = cache.factorizations.state{1}.invSKS;\n invUHU = cache.factorizations.state{1}.invUHU;\n cnt = 1;\n for r = 1:R\n for n = 1:N\n idx = offset(cnt):offset(cnt+1)-1;\n tmp = reshape(b(idx),[],size(invSKS{r,n},1))*invSKS{r,n};\n x(idx) = tmp(:);\n cnt = cnt+1;\n end\n idx = offset(cnt):offset(cnt+1)-1;\n size_core = cellfun('size',invUHU(r,:),1);\n x(idx) = mtkronprod(reshape(b(idx),size_core),invUHU(r,:),0);\n cnt = cnt+1;\n end\n x = x/options.Weights;\n \n % If incomplete, approximate the effect of missing entries.\n if cache.factorizations.isincomplete(1)\n x = x/cache.factorizations.scale{1};\n end\n \nend\n\n% Model: L2 regularization ------------------------------------------------\n\nfunction state_regL2(f,firstrun)\n \n % Format right hand side, if available.\n if nargin == 2 && firstrun\n cache.factorizations.hasdata(f) = ...\n isfield(model.factorizations{f},'data');\n if cache.factorizations.hasdata(f) && ...\n ~iscell(model.factorizations{f}.data)\n model.factorizations{f}.data = ...\n {model.factorizations{f}.data};\n end\n if cache.factorizations.hasdata(f)\n model.factorizations{f}.data = cellfun(@(d)full(d), ...\n model.factorizations{f}.data,'UniformOutput',false);\n end\n end\n \nend\n\nfunction fval = objfun_regL2(f,z)\n % L2 regularization objective function.\n fval = 0;\n for i = 1:length(z)\n e = z{i}(:);\n if cache.factorizations.hasdata(f)\n e = e-model.factorizations{f}.data{i}(:);\n end\n fval = fval+(e'*e);\n end\n fval = 0.5*fval;\nend\n\nfunction grad = grad_regL2(f,z)\n % L2 regularization scaled conjugate cogradient.\n if cache.factorizations.hasdata(f)\n grad = cell2mat(cellfun(@(f,d)f(:)-d(:), ...\n z(:),model.factorizations{f}.data(:),'UniformOutput',false));\n else\n grad = cell2mat(cellfun(@(f)f(:),z(:),'UniformOutput',false));\n end\nend\n\nfunction y = JHJx_regL2(~,~,x)\n % L2 regularization Hessian vector product.\n y = cell2mat(cellfun(@(f)f(:),x(:),'UniformOutput',false));\nend\n\n% Model: L1 regularization ------------------------------------------------\n\nfunction state_regL1(f,firstrun)\n \n % Format right hand side, if available.\n if nargin == 2 && firstrun\n cache.factorizations.hasdata(f) = ...\n isfield(model.factorizations{f},'data');\n if cache.factorizations.hasdata(f) && ...\n ~iscell(model.factorizations{f}.data)\n model.factorizations{f}.data = ...\n {model.factorizations{f}.data};\n end\n if cache.factorizations.hasdata(f)\n model.factorizations{f}.data = cellfun(@(d)full(d), ...\n model.factorizations{f}.data,'UniformOutput',false);\n end\n if ~isfield(options,'mu')\n if cache.factorizations.hasdata(f)\n m = max(abs(serialize(model.factorizations{f}.data)));\n else\n m = 0;\n end\n options.Mu = max(m,1)/100;\n end\n end\n \nend\n\nfunction fval = objfun_regL1(f,z)\n % Approximate L1 regularization objective function.\n fval = 0;\n for i = 1:length(z)\n e = z{i}(:);\n if cache.factorizations.hasdata(f)\n e = e-model.factorizations{f}.data{i}(:);\n end\n far = abs(e) > options.Mu;\n e(far) = abs(e(far));\n e2 = e(~far);\n e2 = e2.*conj(e2);\n e(~far) = 2*options.Mu*e2./(e2+options.Mu^2);\n fval = fval+sum(e);\n end\n fval = 0.5*fval;\nend\n\nfunction grad = grad_regL1(f,z)\n % Approximate L1 regularization scaled conjugate cogradient.\n if cache.factorizations.hasdata(f)\n grad = cell2mat(cellfun(@(f,d)f(:)-d(:), ...\n z(:),model.factorizations{f}.data(:),'UniformOutput',false));\n else\n grad = cell2mat(cellfun(@(f)f(:),z(:),'UniformOutput',false));\n end\n far = abs(grad) > options.Mu;\n grad(far) = grad(far)./(2*abs(grad(far)));\n grad(~far) = 2*options.Mu^3*grad(~far)./ ...\n (grad(~far).*conj(grad(~far))+options.Mu^2).^2;\nend\n\nfunction y = JHJx_regL1(f,z,x)\n % Approximate L1 regularization Hessian vector product.\n if cache.factorizations.hasdata(f)\n hess = cell2mat(cellfun(@(f,d)f(:)-d(:), ...\n z(:),model.factorizations{f}.data(:),'UniformOutput',false));\n else\n hess = cell2mat(cellfun(@(f)f(:),z(:),'UniformOutput',false));\n end\n if ~isreal(hess)\n error('sdf_nls:regL1',['Please use sdf_minf when applying L1 ' ...\n 'regularization on complex factors.']);\n end\n far = abs(hess) > options.Mu;\n hess(far) = 0;\n if any(hess)\n hess(~far) = 2*options.Mu^3*(options.Mu^2-3*hess(~far).^2)./ ...\n (options.Mu^2+hess(~far).^2).^3;\n y = hess.*cell2mat(cellfun(@(f)f(:),x(:),'UniformOutput',false));\n else\n y = hess;\n end\nend\n\nend\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/libs/+tensorlab/sdf_nls.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4652136134620738}}
{"text": "% Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9)\n%\n% Copyright (C) 1993-2011, 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\nfunction qp = mtimes(q1, q2)\n%Quaternion.mtimes Multiply a quaternion object\n%\n% Q1*Q2 is a quaternion formed by Hamilton product of two quaternions.\n% Q*V is the vector V rotated by the quaternion Q\n% Q*S is the element-wise multiplication of quaternion elements by by the scalar S\n\n if isa(q1, 'Quaternion') & isa(q2, 'Quaternion')\n %QQMUL Multiply unit-quaternion by unit-quaternion\n %\n % QQ = qqmul(Q1, Q2)\n %\n % Return a product of unit-quaternions.\n %\n % See also: TR2Q\n\n\n % decompose into scalar and vector components\n s1 = q1.s; v1 = q1.v;\n s2 = q2.s; v2 = q2.v;\n\n % form the product\n qp = Quaternion([s1*s2-v1*v2' s1*v2+s2*v1+cross(v1,v2)]);\n\n elseif isa(q1, 'Quaternion') & isa(q2, 'double')\n\n %QVMUL Multiply vector by unit-quaternion\n %\n % VT = qvmul(Q, V)\n %\n % Rotate the vector V by the unit-quaternion Q.\n %\n % See also: QQMUL, QINV\n\n if length(q2) == 3\n\t\t\tqp = q1 * Quaternion([0 q2(:)']) * inv(q1);\n qp = qp.v(:);\n elseif length(q2) == 1\n qp = Quaternion(double(q1)*q2);\n else\n error('quaternion-vector product: must be a 3-vector or scalar');\n end\n\n elseif isa(q2, 'Quaternion') & isa(q1, 'double')\n if length(q1) == 3\n qp = q2 * Quaternion([0 q1(:)']) * inv(q2);\n qp = qp.v;\n elseif length(q1) == 1\n qp = Quaternion(double(q2)*q1);\n else\n error('quaternion-vector product: must be a 3-vector or scalar');\n end\n end\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/Octave/@Quaternion/mtimes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4650481036558553}}
{"text": "function Animate_Double_Pendulum(t,K,P)\n\n%FUNCTION:\n% This function is used to generate an animation of the double pendulum,\n% using precomputed values.\n%\n%INPUTS:\n% t = a vector of time, (tout, returned by ode45)\n% K = Kinematics struct, returned by Double_Pendulum_Kinematics.m\n% P = Parameters struct, returned by Set_Parameters.m\n%\n%OUTPUTS:\n% Figure 1 -- Animation of double pendulum\n%\n\n\n%Which figure to plopt on?\nfigure(1);\n\n%Get the various position vectors\nP1_x = K.r_P1_O(1,:);\nP1_y = K.r_P1_O(2,:);\nP2_x = K.r_P2_O(1,:);\nP2_y = K.r_P2_O(2,:);\n\n%Get the font sizes\n TitleFontSize = P.plot.TitleFontSize;\n LabelFontSize = P.plot.LabelFontSize;\n\n%Display a few things:\nParameters_to_Display = {...\n ['Slow Motion Factor: ' num2str(P.sim.slow_motion_factor)];...\n '';...\n ['Mass 1: ' num2str(P.dyn.m1,4) ' kg'];... \n ['Mass 2: ' num2str(P.dyn.m2,4) ' kg'];... \n ['Gravity: ' num2str(P.dyn.g,4) ' m/s^2'];...\n ['Length: ' num2str(P.dyn.L,4) ' m'];...\n};\n\ntic; %Start a timer\nLoop_Time = 0; %store how long has the simulation been running\ni=2; %Start at second index (for interpolation purposes)\nMax_i = length(t);\nT_end = t(end); %Ending time of one step\nL = P.dyn.L; %Leg length\nBounds = 1.1 * 2*L * [-1,1,-1,1];\n\nwhile Loop_Time < T_end; %Loop while the CPU time is less than the end of the simulation's time\n %The next few lines pull the time step that is closest to the real time\n Loop_Time = toc/P.sim.slow_motion_factor; %Get the current time (Taking slow motion into accunt if desired)\n while (i (t(i))) %While we are not at the end of the data and the CPU time is ahead of the simulation time\n i=i+1; %Go to the next time frame\n end\n %Now t(i-1) < Loop_Time < t(i) should be true\n \n %Linear interpolation scheme\n t_m = t(i-1);\n t_p = t(i);\n\n Pend_X_m = [0;P1_x(i-1); P2_x(i-1)];\n Pend_Y_m = [0;P1_y(i-1); P2_y(i-1)];\n\n Pend_X_p = [0;P1_x(i); P2_x(i)];\n Pend_Y_p = [0;P1_y(i); P2_y(i)];\n\n dPend_X = Pend_X_p - Pend_X_m;\n dPend_Y = Pend_Y_p - Pend_Y_m;\n \n dt = t_p - t_m;\n dt_cpu = Loop_Time - t_m;\n m = dt_cpu/dt;\n \n Pend_X = m*dPend_X + Pend_X_p;\n Pend_Y = m*dPend_Y + Pend_Y_p;\n \n clf\n plot(Pend_X,Pend_Y,'k-','LineWidth',6)\n hold on\n plot(Pend_X,Pend_Y,'b.','MarkerSize',50)\n plot(0,0,'ko','MarkerSize',40,'LineWidth',3)\n title(['Simulation Time: ' num2str(t(i)) ' seconds'],'FontSize',TitleFontSize)\n \n text(Bounds(2),mean(Bounds(3:4)),Parameters_to_Display,'FontSize',LabelFontSize);\n \n axis(Bounds); axis equal, axis manual; axis off;\n drawnow\n \nend\n\n\n\n\nend", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/DoublePendulum/Animate_Double_Pendulum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4650480903867935}}
{"text": "function [sMap, sTrain] = som_seqtrain(sMap, D, varargin)\n\n%SOM_SEQTRAIN Use sequential algorithm to train the Self-Organizing Map.\n%\n% [sM,sT] = som_seqtrain(sM, D, [[argID,] value, ...])\n% \n% sM = som_seqtrain(sM,D);\n% sM = som_seqtrain(sM,sD,'alpha_type','power','tracking',3);\n% [M,sT] = som_seqtrain(M,D,'ep','trainlen',10,'inv','hexa');\n%\n% Input and output arguments ([]'s are optional): \n% sM (struct) map struct, the trained and updated map is returned\n% (matrix) codebook matrix of a self-organizing map\n% size munits x dim or msize(1) x ... x msize(k) x dim\n% The trained map codebook is returned.\n% D (struct) training data; data struct\n% (matrix) training data, size dlen x dim\n% [argID, (string) See below. The values which are unambiguous can \n% value] (varies) be given without the preceeding argID.\n%\n% sT (struct) learning parameters used during the training\n%\n% Here are the valid argument IDs and corresponding values. The values which\n% are unambiguous (marked with '*') can be given without the preceeding argID.\n% 'mask' (vector) BMU search mask, size dim x 1\n% 'msize' (vector) map size\n% 'radius' (vector) neighborhood radiuses, length 1, 2 or trainlen\n% 'radius_ini' (scalar) initial training radius\n% 'radius_fin' (scalar) final training radius\n% 'alpha' (vector) learning rates, length trainlen\n% 'alpha_ini' (scalar) initial learning rate\n% 'tracking' (scalar) tracking level, 0-3 \n% 'trainlen' (scalar) training length\n% 'trainlen_type' *(string) is the given trainlen 'samples' or 'epochs'\n% 'train' *(struct) train struct, parameters for training\n% 'sTrain','som_train ' = 'train'\n% 'alpha_type' *(string) learning rate function, 'inv', 'linear' or 'power'\n% 'sample_order'*(string) order of samples: 'random' or 'ordered'\n% 'neigh' *(string) neighborhood function, 'gaussian', 'cutgauss',\n% 'ep' or 'bubble'\n% 'topol' *(struct) topology struct\n% 'som_topol','sTopo l' = 'topol'\n% 'lattice' *(string) map lattice, 'hexa' or 'rect'\n% 'shape' *(string) map shape, 'sheet', 'cyl' or 'toroid'\n%\n% For more help, try 'type som_seqtrain' or check out online documentation.\n% See also SOM_MAKE, SOM_BATCHTRAIN, SOM_TRAIN_STRUCT.\n\n%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% som_seqtrain\n%\n% PURPOSE\n%\n% Trains a Self-Organizing Map using the sequential algorithm. \n%\n% SYNTAX\n%\n% sM = som_seqtrain(sM,D);\n% sM = som_seqtrain(sM,sD);\n% sM = som_seqtrain(...,'argID',value,...);\n% sM = som_seqtrain(...,value,...);\n% [sM,sT] = som_seqtrain(M,D,...);\n%\n% DESCRIPTION\n%\n% Trains the given SOM (sM or M above) with the given training data\n% (sD or D) using sequential SOM training algorithm. If no optional\n% arguments (argID, value) are given, a default training is done, the\n% parameters are obtained from SOM_TRAIN_STRUCT function. Using\n% optional arguments the training parameters can be specified. Returns\n% the trained and updated SOM and a train struct which contains\n% information on the training.\n%\n% REFERENCES\n%\n% Kohonen, T., \"Self-Organizing Map\", 2nd ed., Springer-Verlag, \n% Berlin, 1995, pp. 78-82.\n% Kohonen, T., \"Clustering, Taxonomy, and Topological Maps of\n% Patterns\", International Conference on Pattern Recognition\n% (ICPR), 1982, pp. 114-128.\n% Kohonen, T., \"Self-Organized formation of topologically correct\n% feature maps\", Biological Cybernetics 43, 1982, pp. 59-69.\n%\n% REQUIRED INPUT ARGUMENTS\n%\n% sM The map to be trained. \n% (struct) map struct\n% (matrix) codebook matrix (field .data of map struct)\n% Size is either [munits dim], in which case the map grid \n% dimensions (msize) should be specified with optional arguments,\n% or [msize(1) ... msize(k) dim] in which case the map \n% grid dimensions are taken from the size of the matrix. \n% Lattice, by default, is 'rect' and shape 'sheet'.\n% D Training data.\n% (struct) data struct\n% (matrix) data matrix, size [dlen dim]\n% \n% OPTIONAL INPUT ARGUMENTS \n%\n% argID (string) Argument identifier string (see below).\n% value (varies) Value for the argument (see below).\n%\n% The optional arguments can be given as 'argID',value -pairs. If an\n% argument is given value multiple times, the last one is\n% used. The valid IDs and corresponding values are listed below. The values \n% which are unambiguous (marked with '*') can be given without the \n% preceeding argID.\n%\n% 'mask' (vector) BMU search mask, size dim x 1. Default is \n% the one in sM (field '.mask') or a vector of\n% ones if only a codebook matrix was given.\n% 'msize' (vector) map grid dimensions. Default is the one\n% in sM (field sM.topol.msize) or \n% 'si = size(sM); msize = si(1:end-1);' \n% if only a codebook matrix was given. \n% 'radius' (vector) neighborhood radius \n% length = 1: radius_ini = radius\n% length = 2: [radius_ini radius_fin] = radius\n% length > 2: the vector given neighborhood\n% radius for each step separately\n% trainlen = length(radius)\n% 'radius_ini' (scalar) initial training radius\n% 'radius_fin' (scalar) final training radius\n% 'alpha' (vector) learning rate\n% length = 1: alpha_ini = alpha\n% length > 1: the vector gives learning rate\n% for each step separately\n% trainlen is set to length(alpha)\n% alpha_type is set to 'user defined'\n% 'alpha_ini' (scalar) initial learning rate\n% 'tracking' (scalar) tracking level: 0, 1 (default), 2 or 3\n% 0 - estimate time \n% 1 - track time and quantization error \n% 2 - plot quantization error\n% 3 - plot quantization error and two first \n% components \n% 'trainlen' (scalar) training length (see also 'tlen_type')\n% 'trainlen_type' *(string) is the trainlen argument given in 'epochs'\n% or in 'samples'. Default is 'epochs'.\n% 'sample_order'*(string) is the sample order 'random' (which is the \n% the default) or 'ordered' in which case\n% samples are taken in the order in which they \n% appear in the data set\n% 'train' *(struct) train struct, parameters for training. \n% Default parameters, unless specified, \n% are acquired using SOM_TRAIN_STRUCT (this \n% also applies for 'trainlen', 'alpha_type',\n% 'alpha_ini', 'radius_ini' and 'radius_fin').\n% 'sTrain', 'som_train' (struct) = 'train'\n% 'neigh' *(string) The used neighborhood function. Default is \n% the one in sM (field '.neigh') or 'gaussian'\n% if only a codebook matrix was given. Other \n% possible values is 'cutgauss', 'ep' and 'bubble'.\n% 'topol' *(struct) topology of the map. Default is the one\n% in sM (field '.topol').\n% 'sTopol', 'som_topol' (struct) = 'topol'\n% 'alpha_type'*(string) learning rate function, 'inv', 'linear' or 'power'\n% 'lattice' *(string) map lattice. Default is the one in sM\n% (field sM.topol.lattice) or 'rect' \n% if only a codebook matrix was given. \n% 'shape' *(string) map shape. Default is the one in sM\n% (field sM.topol.shape) or 'sheet' \n% if only a codebook matrix was given. \n% \n% OUTPUT ARGUMENTS\n% \n% sM the trained map\n% (struct) if a map struct was given as input argument, a \n% map struct is also returned. The current training \n% is added to the training history (sM.trainhist).\n% The 'neigh' and 'mask' fields of the map struct\n% are updated to match those of the training.\n% (matrix) if a matrix was given as input argument, a matrix\n% is also returned with the same size as the input \n% argument.\n% sT (struct) train struct; information of the accomplished training\n% \n% EXAMPLES\n%\n% Simplest case:\n% sM = som_seqtrain(sM,D); \n% sM = som_seqtrain(sM,sD); \n%\n% To change the tracking level, 'tracking' argument is specified:\n% sM = som_seqtrain(sM,D,'tracking',3);\n%\n% The change training parameters, the optional arguments 'train', \n% 'neigh','mask','trainlen','radius','radius_ini', 'radius_fin', \n% 'alpha', 'alpha_type' and 'alpha_ini' are used. \n% sM = som_seqtrain(sM,D,'neigh','cutgauss','trainlen',10,'radius_fin',0);\n%\n% Another way to specify training parameters is to create a train struct:\n% sTrain = som_train_struct(sM,'dlen',size(D,1),'algorithm','seq');\n% sTrain = som_set(sTrain,'neigh','cutgauss');\n% sM = som_seqtrain(sM,D,sTrain);\n%\n% By default the neighborhood radius goes linearly from radius_ini to\n% radius_fin. If you want to change this, you can use the 'radius' argument\n% to specify the neighborhood radius for each step separately:\n% sM = som_seqtrain(sM,D,'radius',[5 3 1 1 1 1 0.5 0.5 0.5]);\n%\n% By default the learning rate (alpha) goes from the alpha_ini to 0\n% along the function defined by alpha_type. If you want to change this, \n% you can use the 'alpha' argument to specify the learning rate\n% for each step separately: \n% alpha = 0.2*(1 - log([1:100]));\n% sM = som_seqtrain(sM,D,'alpha',alpha);\n%\n% You don't necessarily have to use the map struct, but you can operate\n% directly with codebook matrices. However, in this case you have to\n% specify the topology of the map in the optional arguments. The\n% following commads are identical (M is originally a 200 x dim sized matrix):\n% M = som_seqtrain(M,D,'msize',[20 10],'lattice','hexa','shape','cyl');\n%\n% M = som_seqtrain(M,D,'msize',[20 10],'hexa','cyl');\n%\n% sT= som_set('som_topol','msize',[20 10],'lattice','hexa','shape','cyl');\n% M = som_seqtrain(M,D,sT);\n%\n% M = reshape(M,[20 10 dim]);\n% M = som_seqtrain(M,D,'hexa','cyl');\n%\n% The som_seqtrain also returns a train struct with information on the \n% accomplished training. This is the same one as is added to the end of the \n% trainhist field of map struct, in case a map struct is given.\n% [M,sTrain] = som_seqtrain(M,D,'msize',[20 10]);\n%\n% [sM,sTrain] = som_seqtrain(sM,D); % sM.trainhist{end}==sTrain\n%\n% SEE ALSO\n% \n% som_make Initialize and train a SOM using default parameters.\n% som_batchtrain Train SOM with batch algorithm.\n% som_train_struct Determine default training parameters.\n\n% Copyright (c) 1997-2000 by the SOM toolbox programming team.\n% http://www.cis.hut.fi/projects/somtoolbox/\n\n% Version 1.0beta juuso 220997\n% Version 2.0beta juuso 101199\n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Check arguments\n\nerror(nargchk(2, Inf, nargin)); % check the number of input arguments\n\n% map \nstruct_mode = isstruct(sMap);\nif struct_mode, \n sTopol = sMap.topol;\nelse \n orig_size = size(sMap);\n if ndims(sMap) > 2, \n si = size(sMap); dim = si(end); msize = si(1:end-1);\n M = reshape(sMap,[prod(msize) dim]);\n else\n msize = [orig_size(1) 1]; \n dim = orig_size(2);\n end\n sMap = som_map_struct(dim,'msize',msize);\n sTopol = sMap.topol;\nend\n[munits dim] = size(sMap.codebook);\n\n% data\nif isstruct(D), \n data_name = D.name; \n D = D.data; \nelse \n data_name = inputname(2); \nend\nD = D(find(sum(isnan(D),2) < dim),:); % remove empty vectors from the data\n[dlen ddim] = size(D); % check input dimension\nif dim ~= ddim, error('Map and data input space dimensions disagree.'); end\n\n% varargin\nsTrain = som_set('som_train','algorithm','seq','neigh', ...\n\t\t sMap.neigh,'mask',sMap.mask,'data_name',data_name);\nradius = [];\nalpha = [];\ntracking = 1;\nsample_order_type = 'random';\ntlen_type = 'epochs';\n\ni=1; \nwhile i<=length(varargin), \n argok = 1; \n if ischar(varargin{i}), \n switch varargin{i}, \n % argument IDs\n case 'msize', i=i+1; sTopol.msize = varargin{i}; \n case 'lattice', i=i+1; sTopol.lattice = varargin{i};\n case 'shape', i=i+1; sTopol.shape = varargin{i};\n case 'mask', i=i+1; sTrain.mask = varargin{i};\n case 'neigh', i=i+1; sTrain.neigh = varargin{i};\n case 'trainlen', i=i+1; sTrain.trainlen = varargin{i};\n case 'trainlen_type', i=i+1; tlen_type = varargin{i}; \n case 'tracking', i=i+1; tracking = varargin{i};\n case 'sample_order', i=i+1; sample_order_type = varargin{i};\n case 'radius_ini', i=i+1; sTrain.radius_ini = varargin{i};\n case 'radius_fin', i=i+1; sTrain.radius_fin = varargin{i};\n case 'radius', \n i=i+1; \n l = length(varargin{i}); \n if l==1, \n sTrain.radius_ini = varargin{i}; \n else \n sTrain.radius_ini = varargin{i}(1); \n sTrain.radius_fin = varargin{i}(end);\n if l>2, radius = varargin{i}; tlen_type = 'samples'; end\n end \n case 'alpha_type', i=i+1; sTrain.alpha_type = varargin{i};\n case 'alpha_ini', i=i+1; sTrain.alpha_ini = varargin{i};\n case 'alpha', \n i=i+1; \n sTrain.alpha_ini = varargin{i}(1);\n if length(varargin{i})>1, \n alpha = varargin{i}; tlen_type = 'samples'; \n sTrain.alpha_type = 'user defined'; \n end\n case {'sTrain','train','som_train'}, i=i+1; sTrain = varargin{i};\n case {'topol','sTopol','som_topol'}, \n i=i+1; \n sTopol = varargin{i};\n if prod(sTopol.msize) ~= munits, \n error('Given map grid size does not match the codebook size.');\n end\n % unambiguous values\n case {'inv','linear','power'}, sTrain.alpha_type = varargin{i}; \n case {'hexa','rect'}, sTopol.lattice = varargin{i};\n case {'sheet','cyl','toroid'}, sTopol.shape = varargin{i}; \n case {'gaussian','cutgauss','ep','bubble'}, sTrain.neigh = varargin{i};\n case {'epochs','samples'}, tlen_type = varargin{i};\n case {'random', 'ordered'}, sample_order_type = varargin{i}; \n otherwise argok=0; \n end\n elseif isstruct(varargin{i}) && isfield(varargin{i},'type'), \n switch varargin{i}(1).type, \n case 'som_topol', \n sTopol = varargin{i}; \n if prod(sTopol.msize) ~= munits, \n error('Given map grid size does not match the codebook size.');\n end\n case 'som_train', sTrain = varargin{i};\n otherwise argok=0; \n end\n else\n argok = 0; \n end\n if ~argok, \n disp(['(som_seqtrain) Ignoring invalid argument #' num2str(i+2)]); \n end\n i = i+1; \nend\n\n% training length\nif ~isempty(radius) || ~isempty(alpha), \n lr = length(radius);\n la = length(alpha);\n if lr>2 || la>1,\n tlen_type = 'samples';\n if lr> 2 && la<=1, sTrain.trainlen = lr;\n elseif lr<=2 && la> 1, sTrain.trainlen = la;\n elseif lr==la, sTrain.trainlen = la;\n else\n error('Mismatch between radius and learning rate vector lengths.')\n end\n end\nend\nif strcmp(tlen_type,'samples'), sTrain.trainlen = sTrain.trainlen/dlen; end \n\n% check topology\nif struct_mode, \n if ~strcmp(sTopol.lattice,sMap.topol.lattice) || ...\n\t~strcmp(sTopol.shape,sMap.topol.shape) || ...\n\tany(sTopol.msize ~= sMap.topol.msize), \n warning('Changing the original map topology.');\n end\nend\nsMap.topol = sTopol; \n\n% complement the training struct\nsTrain = som_train_struct(sTrain,sMap,'dlen',dlen);\nif isempty(sTrain.mask), sTrain.mask = ones(dim,1); end\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% initialize\n\nM = sMap.codebook;\nmask = sTrain.mask;\ntrainlen = sTrain.trainlen*dlen;\n\n% neighborhood radius\nif length(radius)>2,\n radius_type = 'user defined';\nelse\n radius = [sTrain.radius_ini sTrain.radius_fin]; \n rini = radius(1); \n rstep = (radius(end)-radius(1))/(trainlen-1);\n radius_type = 'linear';\nend \n\n% learning rate\nif length(alpha)>1, \n sTrain.alpha_type ='user defined';\n if ~(abs(length(alpha)-trainlen) < ...\n 1e4*eps(min(abs(length(alpha)),abs(trainlen)))),\n error('Trainlen and length of neighborhood radius vector do not match.')\n end\n if any(isnan(alpha)), \n error('NaN is an illegal learning rate.')\n end\nelse\n if isempty(alpha), alpha = sTrain.alpha_ini; end\n if strcmp(sTrain.alpha_type,'inv'), \n % alpha(t) = a / (t+b), where a and b are chosen suitably\n % below, they are chosen so that alpha_fin = alpha_ini/100\n b = (trainlen - 1) / (100 - 1);\n a = b * alpha;\n end\nend\n \n% initialize random number generator\nrand('state',sum(100*clock));\n\n% distance between map units in the output space\n% Since in the case of gaussian and ep neighborhood functions, the \n% equations utilize squares of the unit distances and in bubble case\n% it doesn't matter which is used, the unitdistances and neighborhood\n% radiuses are squared.\nUd = som_unit_dists(sTopol).^2;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Action\n\nupdate_step = 100; \nmu_x_1 = ones(munits,1);\nsamples = ones(update_step,1);\nr = samples; \nalfa = samples;\n\nqe = 0;\nstart = clock;\nif tracking > 0, % initialize tracking\n track_table = zeros(update_step,1);\n qe = zeros(floor(trainlen/update_step),1); \nend\n\nprintedbytes = 0;\n\nfor t = 1:trainlen, \n\n % Every update_step, new values for sample indeces, neighborhood\n % radius and learning rate are calculated. This could be done\n % every step, but this way it is more efficient. Or this could \n % be done all at once outside the loop, but it would require much\n % more memory.\n ind = rem(t,update_step); if ind==0, ind = update_step; end\n if ind==1, \n steps = [t:min(trainlen,t+update_step-1)];\n % sample order \n switch sample_order_type, \n case 'ordered', samples = rem(steps,dlen)+1;\n case 'random', samples = ceil(dlen*rand(update_step,1)+eps);\n end\n\n % neighborhood radius\n switch radius_type, \n case 'linear', r = rini+(steps-1)*rstep;\n case 'user defined', r = radius(steps); \n end \n r=r.^2; % squared radius (see notes about Ud above)\n r(r==0) = eps; % zero radius might cause div-by-zero error\n \n % learning rate\n switch sTrain.alpha_type,\n case 'linear', alfa = (1-steps/trainlen)*alpha;\n case 'inv', alfa = a ./ (b + steps-1);\n case 'power', alfa = alpha * (0.005/alpha).^((steps-1)/trainlen); \n case 'user defined', alfa = alpha(steps);\n end \n end\n \n % find BMU\n x = D(samples(ind),:); % pick one sample vector\n known = ~isnan(x); % its known components\n Dx = M(:,known) - x(mu_x_1,known); % each map unit minus the vector\n [qerr bmu] = min((Dx.^2)*mask(known)); % minimum distance(^2) and the BMU\n\n % tracking\n if tracking>0, \n track_table(ind) = sqrt(qerr);\n if ind==update_step, \n n = ceil(t/update_step); \n qe(n) = mean(track_table);\n printedbytes = trackplot(M,D,tracking,start,n,qe,printedbytes);\n end\n end\n \n % neighborhood & learning rate\n % notice that the elements Ud and radius have been squared!\n % (see notes about Ud above)\n switch sTrain.neigh, \n case 'bubble', h = (Ud(:,bmu)<=r(ind));\n case 'gaussian', h = exp(-Ud(:,bmu)/(2*r(ind))); \n case 'cutgauss', h = exp(-Ud(:,bmu)/(2*r(ind))) .* (Ud(:,bmu)<=r(ind));\n case 'ep', h = (1-Ud(:,bmu)/r(ind)) .* (Ud(:,bmu)<=r(ind));\n end \n h = h*alfa(ind); \n \n % update M\n M(:,known) = M(:,known) - h(:,ones(sum(known),1)).*Dx;\n\nend; % for t = 1:trainlen\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Build / clean up the return arguments\n\nif tracking, fprintf(1,'\\n'); end\n\n% update structures\nsTrain = som_set(sTrain,'time',datestr(now,0));\nif struct_mode, \n sMap = som_set(sMap,'codebook',M,'mask',sTrain.mask,'neigh',sTrain.neigh);\n tl = length(sMap.trainhist);\n sMap.trainhist(tl+1) = sTrain;\nelse\n sMap = reshape(M,orig_size);\nend\n\nreturn;\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% subfunctions\n\n%%%%%%%%\nfunction [count] = trackplot(M,D,tracking,start,n,qe, printedbytes)\n\n l = length(qe);\n elap_t = etime(clock,start); \n tot_t = elap_t*l/n;\n % Carriage return does not work as it should (even on UNIX) when printing\n % to screen, so let's do this instead\n fprintf(1, repmat('\\b', 1, printedbytes));\n count = fprintf(1,'Training: %3.0f/ %3.0f s',elap_t,tot_t); \n switch tracking\n case 1, \n case 2, \n plot(1:n,qe(1:n),(n+1):l,qe((n+1):l))\n title('Quantization errors for latest samples') \n drawnow\n otherwise,\n subplot(2,1,1), plot(1:n,qe(1:n),(n+1):l,qe((n+1):l))\n title('Quantization error for latest samples');\n subplot(2,1,2), plot(M(:,1),M(:,2),'ro',D(:,1),D(:,2),'b.'); \n title('First two components of map units (o) and data vectors (+)');\n drawnow\n end \n % end of trackplot\n\n", "meta": {"author": "ilarinieminen", "repo": "SOM-Toolbox", "sha": "f2597abc1ae33c2060e0443d49e854011ff21831", "save_path": "github-repos/MATLAB/ilarinieminen-SOM-Toolbox", "path": "github-repos/MATLAB/ilarinieminen-SOM-Toolbox/SOM-Toolbox-f2597abc1ae33c2060e0443d49e854011ff21831/som/som_seqtrain.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.4649650840729102}}
{"text": "% Version 1.000\n%\n% Code provided by Ruslan Salakhutdinov and Geoff Hinton\n%\n% Permission is granted for anyone to copy, use, modify, or distribute this\n% program and accompanying programs and documents for any purpose, provided\n% this copyright notice is retained and prominently displayed, along with\n% a note saying that the original programs are available from our\n% web page.\n% The programs and documents are distributed without any warranty, express or\n% implied. As the programs were written for research purposes only, they have\n% not been tested to the degree that would be advisable in any important\n% application. All use of these programs is entirely at the user's own risk.\n\n% This program fine-tunes an autoencoder with backpropagation.\n% Weights of the autoencoder are going to be saved in mnist_weights.mat\n% and trainig and test reconstruction errors in mnist_error.mat\n% You can also set maxepoch, default value is 200 as in our paper. \n\nmaxepoch=50;\nfprintf(1,'\\nFine-tuning deep autoencoder by minimizing cross entropy error. \\n');\n% fprintf(1,'60 batches of 1000 cases each. \\n');\n\nload mnistvh\nload mnisthp\nload mnisthp2\nload mnistpo \n\n% makebatches;\n[numcases numdims numbatches]=size(batchdata);\nN=numcases; \n\n%%%% PREINITIALIZE WEIGHTS OF THE AUTOENCODER %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nw1=[vishid; hidrecbiases];\nw2=[hidpen; penrecbiases];\n% w3=[hidpen2; penrecbiases2];\nw4=[hidtop; toprecbiases];\nw5=[hidtop'; topgenbiases]; \n% w6=[hidpen2'; hidgenbiases2]; \nw7=[hidpen'; hidgenbiases]; \nw8=[vishid'; visbiases];\n\n%%%%%%%%%% END OF PREINITIALIZATIO OF WEIGHTS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nl1=size(w1,1)-1;\nl2=size(w2,1)-1;\n% l3=size(w3,1)-1;\nl4=size(w4,1)-1;\nl5=size(w5,1)-1;\n% l6=size(w6,1)-1;\nl7=size(w7,1)-1;\nl8=size(w8,1)-1;\nl9=l1; \ntest_err=[];\ntrain_err=[];\n\n\nfor epoch = 1:maxepoch\n\n%%%%%%%%%%%%%%%%%%%% COMPUTE TRAINING RECONSTRUCTION ERROR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nerr=0; \n[numcases numdims numbatches]=size(batchdata);\nN=numcases;\n for batch = 1:numbatches\n data = [batchdata(:,:,batch)];\n data = [data ones(N,1)];\n w1probs = 1./(1 + exp(-data*w1)); w1probs = [w1probs ones(N,1)];\n w2probs = 1./(1 + exp(-w1probs*w2)); w2probs = [w2probs ones(N,1)];\n% w3probs = 1./(1 + exp(-w2probs*w3)); w3probs = [w3probs ones(N,1)];\n w4probs = w2probs*w4; w4probs = [w4probs ones(N,1)];\n w5probs = 1./(1 + exp(-w4probs*w5)); w5probs = [w5probs ones(N,1)];\n% w6probs = 1./(1 + exp(-w5probs*w6)); w6probs = [w6probs ones(N,1)];\n w7probs = 1./(1 + exp(-w5probs*w7)); w7probs = [w7probs ones(N,1)];\n dataout = 1./(1 + exp(-w7probs*w8));\n err= err + 1/N*sum(sum( (data(:,1:end-1)-dataout).^2 )); \n end\n train_err(epoch)=err/numbatches;\n\n%%%%%%%%%%%%%% END OF COMPUTING TRAINING RECONSTRUCTION ERROR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%%% DISPLAY FIGURE TOP ROW REAL DATA BOTTOM ROW RECONSTRUCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%\n% fprintf(1,'Displaying in figure 1: Top row - real data, Bottom row -- reconstructions \\n');\n% output=[];\n% for ii=1:15\n% output = [output data(ii,1:end-1)' dataout(ii,:)'];\n% end\n% if epoch==1 \n% close all \n% figure('Position',[100,600,1000,200]);\n% else \n% figure(1)\n% end \n% mnistdisp(output);\n% drawnow;\n\n%%%%%%%%%%%%%%%%%%%% COMPUTE TEST RECONSTRUCTION ERROR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n[testnumcases testnumdims testnumbatches]=size(testbatchdata);\nN=testnumcases;\nerr=0;\nfor batch = 1:testnumbatches\n data = [testbatchdata(:,:,batch)];\n data = [data ones(N,1)];\n w1probs = 1./(1 + exp(-data*w1)); w1probs = [w1probs ones(N,1)];\n w2probs = 1./(1 + exp(-w1probs*w2)); w2probs = [w2probs ones(N,1)];\n% w3probs = 1./(1 + exp(-w2probs*w3)); w3probs = [w3probs ones(N,1)];\n w4probs = w2probs*w4; w4probs = [w4probs ones(N,1)];\n w5probs = 1./(1 + exp(-w4probs*w5)); w5probs = [w5probs ones(N,1)];\n% w6probs = 1./(1 + exp(-w5probs*w6)); w6probs = [w6probs ones(N,1)];\n w7probs = 1./(1 + exp(-w5probs*w7)); w7probs = [w7probs ones(N,1)];\n dataout = 1./(1 + exp(-w7probs*w8));\n err = err + 1/N*sum(sum( (data(:,1:end-1)-dataout).^2 ));\n end\n test_err(epoch)=err/testnumbatches;\n fprintf(1,'Before epoch %d Train squared error: %6.3f Test squared error: %6.3f \\t \\t \\n',epoch,train_err(epoch),test_err(epoch));\n\n%%%%%%%%%%%%%% END OF COMPUTING TEST RECONSTRUCTION ERROR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n tt=0;\n for batch = 1:numbatches/10\n fprintf(1,'epoch %d batch %d\\r',epoch,batch);\n\n%%%%%%%%%%% COMBINE 10 MINIBATCHES INTO 1 LARGER MINIBATCH %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n tt=tt+1; \n data=[];\n for kk=1:10\n data=[data \n batchdata(:,:,(tt-1)*10+kk)]; \n end \n\n%%%%%%%%%%%%%%% PERFORM CONJUGATE GRADIENT WITH 3 LINESEARCHES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n max_iter=3;\n% VV = [w1(:)' w2(:)' w3(:)' w4(:)' w5(:)' w6(:)' w7(:)' w8(:)']';\n VV = [w1(:)' w2(:)' w4(:)' w5(:)' w7(:)' w8(:)']';\n Dim = [l1; l2; l4; l5; l7; l8; l9];\n\n [X, fX] = minimize(VV,'CG_MNIST',max_iter,Dim,data);\n\n w1 = reshape(X(1:(l1+1)*l2),l1+1,l2);\n xxx = (l1+1)*l2;\n w2 = reshape(X(xxx+1:xxx+(l2+1)*l3),l2+1,l3);\n xxx = xxx+(l2+1)*l3;\n% w3 = reshape(X(xxx+1:xxx+(l3+1)*l4),l3+1,l4);\n% xxx = xxx+(l3+1)*l4;\n w4 = reshape(X(xxx+1:xxx+(l4+1)*l5),l4+1,l5);\n xxx = xxx+(l4+1)*l5;\n w5 = reshape(X(xxx+1:xxx+(l5+1)*l6),l5+1,l6);\n xxx = xxx+(l5+1)*l6;\n% w6 = reshape(X(xxx+1:xxx+(l6+1)*l7),l6+1,l7);\n% xxx = xxx+(l6+1)*l7;\n w7 = reshape(X(xxx+1:xxx+(l7+1)*l8),l7+1,l8);\n xxx = xxx+(l7+1)*l8;\n w8 = reshape(X(xxx+1:xxx+(l8+1)*l9),l8+1,l9);\n\n%%%%%%%%%%%%%%% END OF CONJUGATE GRADIENT WITH 3 LINESEARCHES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n end\n\n save mnist_weights w1 w2 w4 w5 w7 w8 \n save mnist_error test_err train_err;\n\nend\n\n\n\n", "meta": {"author": "mars920314", "repo": "DeepFi", "sha": "9e7f99c181616d9aa4db18973c08675bdb714e8c", "save_path": "github-repos/MATLAB/mars920314-DeepFi", "path": "github-repos/MATLAB/mars920314-DeepFi/DeepFi-9e7f99c181616d9aa4db18973c08675bdb714e8c/Deep Belief Networks/backpropnew.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4649542495998386}}
{"text": "function [strika,dipa,rakea,dipdia,strikb,dipb,rakeb,dipdib,ierr] = pt2pl(trendp,plungp,trendt,plungt)\n \n % compute strike dip and rake (and dip direction) of two nodal planes from trend and plung of P and T axes\n %\n % usage:\n % call pt2pl(trendp,plungp,trendt,plungt,strika,dipa,rakea\n % 1,dipdia,strikb,dipb,rakeb,dipdib,ierr)\n %\n % arguments:\n % trendp trend of P axis in degrees (INPUT)\n % plungp plunge of P axis in degrees (INPUT)\n % trendt trend of P axis in degrees (INPUT)\n % plungt plunge of P axis in degrees (INPUT)\n % strika strike angle of first nodal plane in degrees (OUTPUT)\n % dipa dip angle of first nodal plane in degrees (OUTPUT)\n % rakea rake angle of first nodal plane in degrees (OUTPUT)\n % dipdia dip direction angle of first nodal plane in degrees (OUTPUT)\n % strikb strike angle of second nodal plane in degrees (OUTPUT)\n % dipb dip angle of second nodal plane in degrees (OUTPUT)\n % rakeb rake angle of second nodal plane in degrees (OUTPUT)\n % dipdib dip direction angle of second nodal plane in degrees (OUTPUT)\n % ierr error indicator (OUTPUT)\n %\n % errors:\n % 1 input TREND angle of P axis out of range\n % 2 input PLUNGE angle P axis out of range\n % 3 1+2\n % 4 input TREND angle of P axis out of range\n % 5 input PLUNGE angle P axis out of range\n % 6 4+5\n % 8,9,10 internal errors\n %\n % c\n % call fpsset\n amistr=-360.;\n amastr=360.;\n amidip=0.;\n amadip=90.;\n amirak=-360.;\n amarak=360.;\n amitre=-360.;\n amatre=360.;\n amiplu=0.;\n amaplu=90.;\n orttol=2.;\n ovrtol=0.001;\n tentol=0.0001;\n dtor=0.017453292519943296;\n c360=360.;\n c90=90.;\n c0=0.;\n c1=1.;\n c2=2.;\n c3=3.;\n % c\n % call ax2ca(trendp,plungp,px,py,pz,ierr)\n [px,py,pz,ierr] = focal_ax2ca(trendp,plungp);\n if (ierr ~= 0)\n disp(['PT2PL: ierr=' num2str(ierr)]);\n return;\n end\n \n % call ax2ca(trendt,plungt,tx,ty,tz,ierr)\n [tx,ty,tz,ierr] = focal_ax2ca(trendt,plungt);\n if (ierr ~= 0)\n ierr = ierr + 3;\n disp(['PT2PL: ierr=' num2str(ierr)]);\n return;\n end\n \n [anx,any,anz,dx,dy,dz,ierr] = focal_pt2nd(px,py,pz,tx,ty,tz);\n if (ierr ~= 0)\n ierr = 8;\n disp(['PT2PL: ierr=' num2str(ierr)]);\n return;\n end\n [strika,dipa,rakea,dipdia,ierr] = focal_nd2pl(anx,any,anz,dx,dy,dz);\n if (ierr ~= 0)\n ierr = 9;\n disp(['PT2PL: ierr=' num2str(ierr)]);\n return;\n end\n [strikb,dipb,rakeb,dipdib,ierr] = focal_nd2pl(dx,dy,dz,anx,any,anz);\n if (ierr ~= 0)\n ierr = 10;\n disp(['PT2PL: ierr=' num2str(ierr)]);\n return;\n end\nend", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/danijel/focal/focal_pt2pl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095992, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4647579484320551}}
{"text": "function dM = Bloch(t, M, Param, Pulse)\n%BLOCH Bloch-McConnell ordinary differential equations.\n% dM = Bloch(t, M, Param, Pulse)\n%\n% --args--\n% t: Function handle variable, represents the time.\n% M : magnetization vector [Mxf, Myf, Mzf, Mzr]\n% Param: Tissue parameter structure.\n%\n% -fields-\n% M0f: Free pool equilibrium magnetization.\n% M0r: Restricted pool equilibrium magnetization. (M0r = F*M0f)\n% R1f: Free pool longitudinal relaxation rate.\n% R1r: Restricted pool longitudinal relaxation rate.\n% R2f: Free pool transverse relaxation rate.\n% kf: Free pool magnetization exchange rate. \n% kr: Restricted pool magnetization exchange rate. (= kf/F)\n% G: Lineshape value of the restricted pool (generated by\n% computeG.m)\n%\n% Pulse: RF Pulse structure (generated by GetPulse.m).\n%\n% Reference: R. Mark Henkelman, Xuemei Huang, Qing-San Xiang, G. J. \n% Stanisz, Scott D. Swanson, Michael J. Bronskill. \n% Quantitative Interpretation of Magnetization Transfer,Mag. \n% Res. in Med., 29, 759-766, Eqs. 1-6, (1993)\n%\n%\n% See also COMPUTEG, GETPULSE, BLOCH, BLOCHNOMT.\n% \n\ndM = zeros(4,1);\n\nif (nargin < 4)\n omega = 0;\n omega2 = 0;\n delta = 0;\nelse\n omega = Pulse.omega(t);\n omega2 = Pulse.omega2(t);\n delta = Pulse.delta;\nend\n\nW = pi*Param.G.*omega2;\n\nif isfield(Param,'T2f')\n R2f = 1./Param.T2f;\nelse\n R2f = Param.R2f;\nend\n\nif isfield(Param,'F')\n kf = Param.kr*Param.F;\n M0r = Param.M0f*Param.F;\nelse\n kf = Param.kf;\n M0r = Param.M0r;\nend\n\ndM(1) = -R2f*M(1) - 2*pi*delta*M(2);\ndM(2) = -R2f*M(2) + 2*pi*delta*M(1) + omega*M(3);\ndM(3) = Param.R1f*(Param.M0f-M(3)) - kf*M(3) + Param.kr*M(4) - omega*M(2);\ndM(4) = Param.R1r*(M0r-M(4)) + kf*M(3) - Param.kr*M(4) - W*M(4);\n\nend\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/src/Common/sim/Bloch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545427, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.46465485920564825}}
{"text": "function eect2k = eect2000 (date1, date2)\n\n% equation of the equinoxes complementary terms, consistent with\n% iau 2000 resolutions.\n\n% annexe to iers conventions 2000, chapter 5\n\n% capitaine, n., wallace, p.t., & mccarthy, d.d. (2003). astron. &\n% astrophys. 406, pp. 1135-1149, table 3.\n% iers conventions (2010), chapter 5, p. 60, table 5.2e.\n% (table 5.2e presented in the printed publication is a truncated\n% series. the full series, which is used in novas, is available on\n% the iers conventions center website in file tab5.2e.txt.)\n% ftp://tai.bipm.org/iers/conv2010/chapter5/\n\n% input\n\n% date1, date2 = tt date (jd = date1 + date2)\n\n% output\n\n% eect2k = complementary terms (radians)\n\n% this revision: 2002 november 13\n% references updated 2010 november 26\n\n% ported from NOVAS 3.1\n\n%%%%%%%%%%%%%%%%%%%%%%%\n\n% 2 pi\n\nd2pi = 6.283185307179586476925287d0;\n\n% arc seconds to radians\n\ndas2r = 4.848136811095359935899141d-6;\n\n% reference epoch (j2000), jd\n\ndj0 = 2451545.0d0;\n\n% days per julian century\n\ndjc = 36525.0d0;\n\n% -----------------------------------------\n% the series for the ee complementary terms\n% -----------------------------------------\n\n% number of terms in the series\n\nne0 = 33;\n\nne1 = 1;\n\n% argument coefficients for t^0\n\nke0 = [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 0, 0, 2, -2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 0, 0, 2, -2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 0, 0, 2, -2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 0, 0, 2, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 0, 0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 1, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 0, 1, 2, -2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 0, 1, 2, -2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 0, 0, 4, -4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 0, 0, 1, -1, 1, 0, -8, 12, 0, 0, 0, 0, 0, 0;\n 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 0, 0, 2, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 1, 0, 2, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 1, 0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 0, 0, 2, -2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 0, 1, -2, 2, -3, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 0, 1, -2, 2, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 0, 0, 0, 0, 0, 0, 8,-13, 0, 0, 0, 0, 0, -1;\n 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 2, 0, -2, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 1, 0, 0, -2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 0, 1, 2, -2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 1, 0, 0, -2, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 0, 0, 4, -2, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 0, 0, 2, -2, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 1, 0, -2, 0, -3, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n 1, 0, -2, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0;];\n\n% transpose\n\nke0 = ke0';\n\n% argument coefficients for t^1\n\nke1 = [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n\n% transpose\n\nke1 = ke1';\n\n% sine and cosine coefficients for t^0\n\nse0 = [+2640.96d-6, -0.39d-6;\n +63.52d-6, -0.02d-6;\n +11.75d-6, +0.01d-6;\n +11.21d-6, +0.01d-6;\n -4.55d-6, +0.00d-6;\n +2.02d-6, +0.00d-6;\n +1.98d-6, +0.00d-6;\n -1.72d-6, +0.00d-6;\n -1.41d-6, -0.01d-6;\n -1.26d-6, -0.01d-6;\n -0.63d-6, +0.00d-6;\n -0.63d-6, +0.00d-6;\n +0.46d-6, +0.00d-6;\n +0.45d-6, +0.00d-6;\n +0.36d-6, +0.00d-6;\n -0.24d-6, -0.12d-6;\n +0.32d-6, +0.00d-6;\n +0.28d-6, +0.00d-6;\n +0.27d-6, +0.00d-6;\n +0.26d-6, +0.00d-6;\n -0.21d-6, +0.00d-6;\n +0.19d-6, +0.00d-6;\n +0.18d-6, +0.00d-6;\n -0.10d-6, +0.05d-6;\n +0.15d-6, +0.00d-6;\n -0.14d-6, +0.00d-6;\n +0.14d-6, +0.00d-6;\n -0.14d-6, +0.00d-6;\n +0.14d-6, +0.00d-6;\n +0.13d-6, +0.00d-6;\n -0.11d-6, +0.00d-6;\n +0.11d-6, +0.00d-6;\n +0.11d-6, +0.00d-6;];\n\nse0 = se0';\n\n% sine and cosine coefficients for t^1\n\nse1 = [-0.87d-6, +0.00d-6];\n\n% transpose\n\nse1 = se1';\n\n% interval between fundamental epoch j2000.0 and current date (jc)\n\nt = ((date1 - dj0) + date2) / djc;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% fundamental arguments (from iers conventions 2000)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% mean anomaly of the moon\n\nfa(1) = anmp ((485868.249036d0 + (715923.2178d0 + (31.8792d0 ...\n + (0.051635d0 + (-0.00024470d0) * t) * t) * t) * t) * das2r ...\n + mod (1325.0d0 * t, 1.0d0) * d2pi);\n\n% mean anomaly of the sun\n\nfa(2) = anmp ((1287104.793048d0 + (1292581.0481d0 + (-0.5532d0 ...\n + (+0.000136d0 + (-0.00001149d0) * t) * t) * t) * t) * das2r ...\n + mod (99.0d0 * t, 1.0d0) * d2pi);\n\n% mean longitude of the moon minus mean longitude of the ascending\n% node of the moon\n\nfa(3) = anmp (( 335779.526232d0 + (295262.8478d0 + (-12.7512d0 ...\n + (-0.001037d0 + (0.00000417d0) * t) * t) * t) * t) * das2r ...\n + mod (1342d0 * t, 1d0) * d2pi);\n\n% mean elongation of the moon from the sun\n\nfa(4) = anmp ((1072260.703692d0 + (1105601.2090d0 + (-6.3706d0 ...\n + (0.006593d0 + (-0.00003169d0) * t) * t) * t) * t) * das2r ...\n + mod (1236d0 * t, 1d0) * d2pi);\n\n% mean longitude of the ascending node of the moon\n\nfa(5) = anmp ((450160.398036d0 + (-482890.5431d0 + (7.4722d0 ...\n + (0.007702d0 + (-0.00005939d0) * t) * t) * t) * t) * das2r ...\n + mod (-5.0d0 * t, 1.0d0) * d2pi);\n\nfa(6) = anmp (4.402608842d0 + 2608.7903141574d0 * t);\nfa(7) = anmp (3.176146697d0 + 1021.3285546211d0 * t);\nfa(8) = anmp (1.753470314d0 + 628.3075849991d0 * t);\nfa(9) = anmp (6.203480913d0 + 334.0612426700d0 * t);\nfa(10) = anmp (0.599546497d0 + 52.9690962641d0 * t);\nfa(11) = anmp (0.874016757d0 + 21.3299104960d0 * t);\nfa(12) = anmp (5.481293872d0 + 7.4781598567d0 * t);\nfa(13) = anmp (5.311886287d0 + 3.8133035638d0 * t);\nfa(14) = (0.024381750d0 + 0.00000538691d0 * t) * t;\n\n% evaluate the ee complementary terms\n\ns0 = 0.0d0;\n\ns1 = 0.0d0;\n\nfor i = ne0: -1: 1\n\n a = 0.0d0;\n\n for j = 1:14\n\n a = a + ke0(j, i) * fa(j);\n\n end\n\n s0 = s0 + (se0(1, i) * sin(a) + se0(2, i) * cos(a));\n\nend\n\nfor i = ne1: -1: 1\n\n a = 0.0d0;\n\n for j = 1:14\n\n a = a + ke1(j, i) * fa(j);\n\n end\n\n s1 = s1 + (se1(1, i) * sin(a) + se1(2, i) * cos(a));\n\nend\n\neect2k = (s0 + s1 * t) * das2r;\n\n", "meta": {"author": "goGPS-Project", "repo": "goGPS_MATLAB", "sha": "30644df61d2459e3347ac5f3e31b71d9f69f4b01", "save_path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB", "path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB/goGPS_MATLAB-30644df61d2459e3347ac5f3e31b71d9f69f4b01/source/utility/sun_moon/novas/eect2000.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.46459755958580956}}
{"text": "function rayPlot(ray,ord)\n%+========================================================================+\n%| |\n%| OPENRAY - LIBRARY FOR TRI-DIMENSIONAL RAY TRACING |\n%| openRay 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 : rayPlot.m |\n%| # | VERSION : 0.41 |\n%| _#_ | AUTHOR(S) : Matthieu Aussal |\n%| ( # ) | CREATION : 14.03.2017 |\n%| / 0 \\ | LAST MODIF : 01.04.2018 |\n%| ( === ) | SYNOPSIS : Plot trajectory and last direction |\n%| `---' | |\n%+========================================================================+\n\n% Graphical configuration\nfigure(gcf)\noff = ~ishold;\nif off\n hold on\nend\n\n% Plot trajectory\nif (ord > -1)\n for i = 2:ord+1\n Pim1 = ray.pos{i-1};\n Pi = ray.pos{i};\n plot3([Pim1(:,1) Pi(:,1)]',[Pim1(:,2) Pi(:,2)]',[Pim1(:,3) Pi(:,3)]','o-b')\n end\nend\n\n% Plot direction\nif (ord == -1) || (length(ray.pos) == 1)\n P = ray.pos{end};\n U = ray.dir;\n quiver3(P(:,1),P(:,2),P(:,3),U(:,1),U(:,2),U(:,3),'r')\nend\n\n% Hold \nif off\n hold off\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/openRay/rayPlot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.46437787146436715}}
{"text": "function [fx,tx,pv,fv]=fxpefac(s,fs,tinc,m,pp)\n%FXPEFAC PEFAC pitch tracker [FX,TT,PV,FV]=(S,FS,TINC,M,PP)\n%\n% Input: s(ns) Speech signal\n% fs Sample frequency (Hz)\n% tinc Time increment between frames (s) [0.01]\n% or [start increment end]\n% m mode\n% 'g' plot graph showing waveform and pitch\n% 'G' plot spectrogram with superimposed pitch using\n% options pp.sopt [default: 'ilcwpf']\n% 'x' use external files for algorithm parameter\n% initialization: fxpefac_g and fxpefac_w\n% pp structure containing algorithm parameters\n%\n% Outputs: fx(nframe) Estimated pitch (Hz)\n% tx(nframe) Time at the centre of each frame (seconds).\n% pv(nframe) Probability of the frame of being voiced\n% fv structure containing feature vectors\n% fv.vuvfea(nframe,2) = voiced/unvoiced GMM features\n\n% References\n% [1] S.Gonzalez and M. Brookes,\n% A pitch estimation filter robust to high levels of noise (PEFAC), Proc EUSIPCO,Aug 2011.\n\n% Bugs/Suggestions\n% (1) do long files in chunks\n% (2) option of n-best DP\n\n%\t Copyright (C) Sira Gonzalez and Mike Brookes 2011\n% Version: $Id: fxpefac.m 3601 2013-10-11 15:27:30Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\npersistent w_u m_u v_u w_v m_v v_v dpwtdef\n% initialize persistent variables\nif ~numel(w_u)\n\n % voiced/unvoiced decision based on 2-element feature vector\n % (a) mean power of the frame's log-freq spectrum (normalized so its short-term average is LTASS)\n % (b) sum of the power in the first three peaks\n %===== VUV\n if nargin>3 && any(m=='x')\n fxpefac_g; % read in GMM parameters\n fxpefac_w; % read in Weights parameters\n else\n w_u=[0.1461799 0.3269458 0.2632178 0.02331986 0.06360947 0.1767271 ]';\n\n m_u=[13.38533 0.4199435 ;\n 12.23505 0.1496836 ;\n 12.76646 0.2581733 ;\n 13.69822 0.6893078 ;\n 9.804372 0.02786567 ;\n 11.03848 0.07711229 ];\n\n v_u=reshape([0.4575519 0.002619074 0.002619074 0.01262138 ;\n 0.7547719 0.008568089 0.008568089 0.001933864 ;\n 0.5770533 0.003561592 0.003561592 0.00527957 ;\n 0.3576287 0.01388739 0.01388739 0.04742106 ;\n 0.9049906 0.01033191 0.01033191 0.0001887114 ;\n 0.637969 0.009936445 0.009936445 0.0007082946 ]',[2 2 6]);\n\n w_v=[0.1391365 0.221577 0.2214025 0.1375109 0.1995124 0.08086066 ]';\n\n m_v=[15.36667 0.8961554 ;\n 13.52718 0.4809653 ;\n 13.95531 0.8901121 ;\n 14.56318 0.6767258 ;\n 14.59449 1.190709 ;\n 13.11096 0.2861982 ];\n\n v_v=reshape([0.196497 -0.002605404 -0.002605404 0.05495016 ;\n 0.6054919 0.007776652 0.007776652 0.01899244 ;\n 0.5944617 0.0485788 0.0485788 0.03511229 ;\n 0.3871268 0.0292966 0.0292966 0.02046839 ;\n 0.3377683 0.02839657 0.02839657 0.04756354 ;\n 1.00439 0.03595795 0.03595795 0.006737475 ]',[2 2 6]);\n end\n %===== PDP\n % dfm = -0.4238; % df mean\n % dfv = 3.8968; % df variance (although treated as std dev here)\n % delta = 0.15;\n % dflpso=[dfm 0.5/(log(10)*dfv^2) -log(2*delta/(dfv*sqrt(2*pi)))/log(10)]; % scale factor & offset for df pdf\n % dpwtdef=[1.0000, 0.8250, 1.3064, 1.9863]; % default DP weights\n dpwtdef=[1.0000, 0.8250, 0.01868, 0.006773, 98.9, -0.4238]; % default DP weights\n %===== END\n\nend\n% Algorithm parameter defaults\n\np.fstep=5; % frequency resolution of initial spectrogram (Hz)\np.fmax=4000; % maximum frequency of initial spectrogram (Hz)\np.fres = 20; % bandwidth of initial spectrogram (Hz)\np.fbanklo = 10; % low frequency limit of log filterbank (Hz)\np.mpsmooth = 21; % width of smoothing filter for mean power\n% p.maxtranf = 1000; % maximum value of tranf cost term\np.shortut = 7; % max utterance length to average power of entire utterance\np.pefact = 1.8; % shape factor in PEFAC filter\np.numopt = 3; % number of possible frequencies per frame\np.flim = [60 400]; % range of feasible fundamental frequencies (Hz)\np.w = dpwtdef; % DP weights\n% p.rampk = 1.1; % constant for relative-amplitude cost term\n% p.rampcz = 100; % relative amplitude cost for missing peak\np.tmf = 2; % median frequency smoothing interval (s)\np.tinc = 0.01; % default frame increment (s)\np.sopt = 'ilcwpf'; % spectrogram options\n\n% update parameters from pp argument\n\nif nargin>=5 && isstruct(pp)\n fnq=fieldnames(pp);\n for i=1:length(fnq)\n if isfield(p,fnq{i})\n p.(fnq{i})=pp.(fnq{i});\n end\n end\nend\n\n% Sort out input arguments\nif nargin>=3 && numel(tinc)>0\n p.tinc = tinc; % 0.01 s between consecutive time frames\nend\nif nargin<4\n m='';\nend\n\n% Spectrogram of the mixture\nfmin = 0; fstep = p.fstep; fmax = p.fmax;\nfres = p.fres; % Frequency resolution (Hz)\n[tx,f,MIX]=spgrambw(s,fs,fres,[fmin fstep fmax],[],p.tinc);\nnframes=length(tx);\ntxinc=tx(2)-tx(1); % actual frame increment\n% ==== we could combine spgrambw and filtbankm into a single call to spgrambw or use fft directly ====\n% Log-frequency scale\n[trans,cf]=filtbankm(length(f),2*length(f)-1,2*f(end),p.fbanklo,f(end),'usl');\nO = MIX*trans'; % Original spectrum in Log-frequency scale\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Amplitude Compression\n\n% Calculate alpha based on LTASS ratios\nltass = stdspectrum(6,'p',cf);\nauxf = [cf(1),(cf(1:end-1)+cf(2:end))./2,cf(end)];\nltass = ltass.*diff(auxf); % weight by bin width\n\n% estimated ltass\nO = O.*repmat(diff(auxf),nframes,1); % weight spectrum by bin width\nO1 = O;\n\nif tx(end)3*cf(1));\nsca = cf/cf(ini(1)); % bin frequencies start at approximately 0.33 with sca(ini(1))=1 exactly\n\n% Middle\nsca = sca(sca<10.5 & sca>0.5); % restrict to 0.5 - 10.5 times fundamental\n\nsca1 = sca;\nfilh = 1./(p.pefact-cos(2*pi*sca1));\nfilh = filh - sum(filh(1:end).*diff([sca1(1),(sca1(1:end-1)+sca1(2:end))./2,sca1(end)]))/sum(diff([sca1(1),(sca1(1:end-1)+sca1(2:end))./2,sca1(end)]));\n\nposit = find(sca>=1); % ==== this should just equal ini(1) ====\nnegat = find(sca<1);\nnumz = length(posit)-1-length(negat);\nfilh = filh./max(filh);\nfilh = [zeros(1,numz) filh]; % length is always odd with central value = 1\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Filter the log-frequency scaled spectrogram\nB = imfilter(O,filh); % does a convolution with zero lag at centre of filh\n\n% Feasible frequency range\nnumopt = p.numopt; % Number of possible fundamental frequencies per frame\nflim = p.flim;\npfreq = find(cf>flim(1) & cf0.6)); % calculate median frequency of first 2 seconds\nif isnan(mf)\n mf=median(fpos(pv(1:min(inmf,end))>0.5));\n if isnan(mf)\n mf=median(fpos(pv(1:min(inmf,end))>0.4));\n if isnan(mf)\n mf=median(fpos(pv(1:min(inmf,end))>0.3)); % ==== clumsy way of ensuring that we take the best frames ====\n if isnan(mf)\n mf=0;\n end\n end\n end\nend\nmedfx(1)=mf;\n\nfor i=2:nframes % main dynamic programming loop\n if i>inmf\n fpos = ff(i-inmf:i,1); % fpos is the highest peak in each frame\n mf=median(fpos(pv(1:inmf)>0.6)); % find median frequency over past 2 seconds\n if isnan(mf)\n mf=median(fpos(pv(1:inmf)>0.5));\n if isnan(mf)\n mf=median(fpos(pv(1:inmf)>0.4));\n if isnan(mf)\n mf=median(fpos(pv(1:inmf)>0.3));% ==== clumsy way of ensuring that we take the best frames ====\n if isnan(mf)\n mf=0;\n end\n end\n end\n end\n end\n medfx(i)=mf;\n % Frequency difference between candidates and cost\n df = dffact*(repmat(ff(i,:).',1,numopt) - repmat(ff(i-1,:),numopt,1))./(repmat(ff(i,:).',1,numopt) + repmat(ff(i-1,:),numopt,1));\n costdf=w(3)*min((df-w(6)).^2,w(4));\n\n % Cost related to the median pitch\n if mf==0 % this test was inverted in the original version\n costf = zeros(1,numopt);\n else\n costf = abs(ff(i,:) - mf)./mf;\n end\n [cost(i,:),prev(i,:)]=min(costdf + repmat(cost(i-1,:),numopt,1),[],2); % ==== should we allow the possibility of skipping frames ? ====\n cost(i,:)=cost(i,:)+w(2)*costf + w(1)*camp(i,:); % add on costs that are independent of previous path\n\nend\n\n% Traceback\n\nfx=zeros(nframes,1);\nax=zeros(nframes,1);\nbest = zeros(nframes,1);\n\nnose=find(cost(end,:)==min(cost(end,:))); % ==== bad method (dangerous) ===\nbest(end)=nose(1);\nfx(end)=ff(end,best(end));\nax(end)=amp(end,best(end));\nfor i=nframes:-1:2\n best(i-1)=prev(i,best(i));\n fx(i-1)=ff(i-1,best(i-1));\n ax(i-1)=amp(i-1,best(i-1));\nend\n\nif nargout>=4\n fv.vuvfea=vuvfea; % voiced-unvoiced features\n fv.best=best; % selected path\n fv.ff=ff; % pitch candidates\n fv.amp=amp; % pitch candidate amplitudes\n fv.medfx=medfx; % median pitch\n fv.w=w; % DP weights\n fv.dffact=dffact; % df scale factor\n fv.hist = [log(mean(O,2)) sum(amp,2)./((mean(O,2)))];\nend\n\nif ~nargout || any(m=='g') || any(m=='G')\n nax=0; % number of axes sets to link\n msk=pv>0.5; % find voiced frames as a mask\n fxg=fx;\n fxg(~msk)=NaN; % allow only good frames\n fxb=fx;\n fxb(msk)=NaN; % allow only bad frames\n if any(m=='G') || ~nargout && ~any(m=='g')\n clf;\n spgrambw(s,fs,p.sopt); % draw spectrogram with log axes\n hold on\n plot(tx,log10(fxg),'-b',tx,log10(fxb),'-r'); % fx track\n yy=get(gca,'ylim');\n plot(tx,yy(1)+yy*[-1;1]*(0.02+0.05*pv),'-k'); % P(V) track\n hold off\n nax=nax+1;\n axh(nax)=gca;\n if any(m=='g')\n figure; % need a new figure if plotting two graphs\n end\n end\n if any(m=='g')\n ns=length(s);\n [tsr,ix]=sort([(1:ns)/fs 0.5*(tx(1:end-1)+tx(2:end))']); % intermingle speech and frame boundaries\n jx(ix)=1:length(ix); % create inverse index\n sp2fr=jx(1:ns)-(0:ns-1); % speech sample to frame number\n spmsk=msk(sp2fr); % speech sample voiced mask\n sg=s;\n sg(~spmsk)=NaN; % good speech samples only\n sb=s;\n sb(spmsk)=NaN; % bad speech samples only\n clf;\n subplot(5,1,1);\n plot(tx,pv,'-b',(1:ns)/fs,0.5*mod(cumsum(fx(sp2fr)/fs),1)-0.6,'-b');\n nax=nax+1;\n axh(nax)=gca;\n ylabel('\\phi(t), P(V)');\n set(gca,'ylim',[-0.65 1.05]);\n subplot(5,1,2:3);\n plot((1:ns)/fs,sg,'-b',(1:ns)/fs,sb,'-r');\n nax=nax+1;\n axh(nax)=gca;\n subplot(5,1,4:5);\n plot(tx,fxg,'-b',tx,fxb,'-r');\n ylabel('Pitch (Hz)');\n % semilogy(tx,fxg,'-b',tx,fxb,'-r');\n % ylabel(['Pitch (' yticksi 'Hz)']);\n set(gca,'ylim',[min(fxg)-30 max(fxg)+30]);\n nax=nax+1;\n axh(nax)=gca;\n end\n if nax>1\n linkaxes(axh,'x');\n end\nend\n\nfunction y=smooth(x,n)\nnx=size(x,2);\nnf=size(x,1);\nc=cumsum(x,2);\ny=[c(:,1:2:n)./repmat(1:2:n,nf,1) (c(:,n+1:end)-c(:,1:end-n))/n (repmat(c(:,end),1,floor(n/2))-c(:,end-n+2:2:end-1))./repmat(n-2:-2:1,nf,1)];\n\nfunction y=timesm(x,n)\nif ~mod(n,2)\n n = n+1;\nend\nnx=size(x,2);\nnf=size(x,1);\nc=cumsum(x,1);\nmid = round(n/2);\ny=[c(mid:n,:)./repmat((mid:n).',1,nx); ...\n (c(n+1:end,:)-c(1:end-n,:))/n; ...\n (repmat(c(end,:),mid-1,1) - c(end-n+1:end-mid,:))./repmat((n-1:-1:mid).',1,nx)];\n", "meta": {"author": "covarep", "repo": "covarep", "sha": "5a2be5d6b776f14a0b275c69fde90eb13849e60d", "save_path": "github-repos/MATLAB/covarep-covarep", "path": "github-repos/MATLAB/covarep-covarep/covarep-5a2be5d6b776f14a0b275c69fde90eb13849e60d/external/voicebox/fxpefac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4639884408114674}}
{"text": "function FEP_fluctuations\n% This demonstration uses an ensemble of particles with intrinsic (Lorentz\n% attractor) dynamics and (Newtonian) short-range coupling. The focus of\n% this routine is to unpack the Bayesian perspective. We first simulate\n% dynamics to nonequilibrium steady-state, identify the Markov blanket and\n% then examine the encoding of external states by internal states; in terms\n% of their expected values.\n%\n% The crucial aspect of this implicit inference (and the basis of the free\n% energy principle) is the existence of a conditional synchronisation\n% manifold, when conditioning internal and external states on the Markov\n% blanket. This provides the basis for a mapping between internal and\n% external states that can be interpreted in terms of a probabilistic\n% representation or inference.\n%\n% This Bayesian perspective is illustrated in terms of a mapping between\n% the canonical modes of internal and external states (as approximated\n% with a polynomial expansion). The canonical modes her are evaluated\n% using an estimate of the conditional expectations based upon the\n% Euclidean proximity of Markov blanket states. The ensuing posterior over\n% external states is than illustrated, in relation to the actual external\n% states. We also simulate event related potentials by identifying\n% several points in time when the Markov blankets revisit the same\n% neighbourhood. Finally, to illustrate the underlying dynamics, the\n% Jacobians or coupling among internal and external states are\n% presented; using different orders of coupling (i.e., degrees of\n% separation)\n%\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: FEP_fluctuations.m 7163 2017-09-04 09:12:50Z karl $\n \n \n% default settings (GRAPHICS sets movies)\n%--------------------------------------------------------------------------\nrng('default')\nGRAPHICS = 1;\n \n% Demo of synchronization manifold using coupled Lorenz attractors\n%==========================================================================\nN = 128; % number of (Lorenz) oscillators\nT = 2048; % number of time bins\ndt = 1/32; % time interval\n \n% parameters\n%--------------------------------------------------------------------------\nP.k = 1 - exp(-rand(1,N)*4); % variations in temporal scale\nP.d = 1/8; % amplitude of random fluctuations\n \n% states\n%--------------------------------------------------------------------------\nx.p = randn(2,N)*4; % microstates (position)\nx.v = zeros(2,N); % microstates (velocity)\nx.q = randn(3,N)/32; % microstates (states)\nu = zeros(1,T); % exogenous fluctuations\n \n \n% generate an dynamics from initial conditions\n%==========================================================================\nspm_figure('GetWin','Markov blanket');clf\nif GRAPHICS\n subplot(2,2,1)\nelse\n subplot(2,1,1)\nend\n[Q,X,V,A,x] = spm_soup(x,u,P,T,dt,1);\n\n% States\n%--------------------------------------------------------------------------\n% Q - history of microstates (states)\n% X - history of microstates (position)\n% V - history of microstates (velocity)\n\nfor i = 1:size(X,3)\n S(:,:,i) = [Q(:,:,i);X(:,:,i);V(:,:,i)];\nend\n \n% Markov blanket - parents, children, and parents of children\n%==========================================================================\n\n% Adjacency matrix\n%--------------------------------------------------------------------------\nt = (T - 256):T; % final time indices\nL = sparse(double(any(A(:,:,t),3)))';\n \n% internal states (defined by principle eigenvector of Markov blanket)\n%--------------------------------------------------------------------------\nB = double((L + L' + L'*L));\nB = B - diag(diag(B));\nv = spm_svd(B*B',1);\n[v,j] = sort(abs(v(:,1)),'descend');\n \n% get Markov blanket and divide into sensory and active states\n%--------------------------------------------------------------------------\nm = j(1:8); % internal cluster\nmm = sparse(m,1,1,N,1); % internal states\nbb = B*mm & (1 - mm); % Markov blanket\nee = 1 - bb - mm; % external states\nb = find(bb);\ne = find(ee);\nm = find(mm);\ns = b(find( any(L(b,e),2)));\na = b(find(~any(L(b,e),2)));\n\n% adjacency matrix - with partition underneath (LL)\n%--------------------------------------------------------------------------\nk = [e; s; a; m];\nLL = L;\nLL(e,e) = LL(e,e) + 1/8;\nLL(s,s) = LL(s,s) + 1/8;\nLL(a,a) = LL(a,a) + 1/8;\nLL(m,m) = LL(m,m) + 1/8;\nLL = LL(k,k);\n \n% plot dynamics for the initial and subsequent time periods\n%--------------------------------------------------------------------------\nsubplot(4,1,3)\nr = 1:512;\nplot(r,squeeze(Q(1,e,r)),':c'), hold on\nplot(r,squeeze(Q(1,m,r)),' b'), hold off\naxis([r(1) r(end) -32 32])\nxlabel('Time','FontSize',12)\ntitle('Electrochemical dynamics','FontSize',16)\n \nsubplot(4,1,4)\nr = 1:T;\nplot(r,squeeze(V(1,e,r)),':c'), hold on\nplot(r,squeeze(V(1,m,r)),' b'), hold off\naxis([r(1) r(end) -32 32])\nxlabel('Time','FontSize',12)\ntitle('Newtonian dymanics','FontSize',16)\n \n \n% Markov blanket - self-assembly\n%==========================================================================\nsubplot(2,2,1)\nimagesc(1 - LL)\naxis square\nxlabel('Element','FontSize',12)\nxlabel('Element','FontSize',12)\ntitle('Adjacency matrix','FontSize',16)\n\n \n% follow self-assembly\n%--------------------------------------------------------------------------\nclear M\nfor i = (T - 512):T\n \n % plot positions\n %----------------------------------------------------------------------\n subplot(2,2,2),set(gca,'color','w')\n \n px = ones(3,1)*X(1,:,i) + Q([1 2 3],:,i)/16;\n py = ones(3,1)*X(2,:,i) + Q([2 3 1],:,i)/16;\n plot(px,py,'.b','MarkerSize',8), hold on\n px = X(1,e,i); py = X(2,e,i);\n plot(px,py,'.c','MarkerSize',24)\n px = X(1,m,i); py = X(2,m,i);\n plot(px,py,'.b','MarkerSize',24)\n px = X(1,s,i); py = X(2,s,i);\n plot(px,py,'.m','MarkerSize',24)\n px = X(1,a,i); py = X(2,a,i);\n plot(px,py,'.r','MarkerSize',24)\n \n xlabel('Position','FontSize',12)\n ylabel('Position','FontSize',12)\n title('Markov Blanket','FontSize',16)\n axis([-1 1 -1 1]*8)\n axis square, hold off, drawnow\n \n % save\n %----------------------------------------------------------------------\n if i > (T - 128) && GRAPHICS\n M(i - T + 128) = getframe(gca);\n end\n \nend\n \n% set ButtonDownFcn\n%--------------------------------------------------------------------------\nif GRAPHICS\n h = findobj(gca);\n set(h(1),'Userdata',{M,16})\n set(h(1),'ButtonDownFcn','spm_DEM_ButtonDownFcn')\n xlabel('Click for Movie','Color','r')\nend\n \n\n% illustrate the Bayesian perspective (predictability of external states)\n%==========================================================================\nspm_figure('GetWin','Bayesian perspective');clf\n\n% establish a statistical dependency between internal (dynamic) states (XQ)\n%--------------------------------------------------------------------------\nT = 512; % length of timeseries\nt = size(X,3) - T - 2;\nfor i = 1:T\n Xe(i,:) = spm_vec(V(:,e,i + t)); % external states\n Xb(i,:) = spm_vec(S(:,[a;s],i + t)); % Markov blanket\n Xm(i,:) = spm_vec(Q(:,m,i + t)); % internal states\nend\nxe = zeros(size(Xe));\nxm = zeros(size(Xm));\niC = inv(cov(Xb));\n\n% probabilistic proximity in the space of the Markov blanket\n%--------------------------------------------------------------------------\nfor i = 1:T\n for j = 1:T\n r = Xb(i,:) - Xb(j,:);\n w(i,j) = exp(-(r*iC*r')/128);\n end\nend\n\n% convert into proper probability distribution\n%--------------------------------------------------------------------------\nw = diag(sum(w,2))\\w;\n\n% mean\n%--------------------------------------------------------------------------\nfor i = 1:T\n for j = 1:T\n xe(i,:) = xe(i,:) + w(i,j)*Xe(j,:);\n xm(i,:) = xm(i,:) + w(i,j)*Xm(j,:);\n end\nend\n\n% covariance (not used)\n%--------------------------------------------------------------------------\n% ce = zeros(size(Xe,1),size(Xe,2),size(Xe,2));\n% for i = 1:T\n% for j = 1:T\n% ce(i,:,:) = squeeze(ce(i,:,:)) + w(i,j)*(Xe(i,:) - xe(i,:))'*(Xe(j,:) - xe(j,:));\n% end\n% end\n\n% normalise and identify canonical eigenvariates\n%--------------------------------------------------------------------------\nxe = spm_detrend(xe);\nxm = spm_detrend(xm);\nCVA = spm_cva(xe,xm);\n\n% show results - canonical vectors over elements (mode M)\n%--------------------------------------------------------------------------\nsubplot(3,2,1)\n\nM = 1;\nVe = CVA.V(:,M);\nVe = spm_unvec(Ve,V(:,e,1));\nve = sum(Ve.^2);\nve = ve/max(ve);\nfor k = 1:length(Ve)\n c = [0 1 1]*ve(k) + [1 1 1]*(1 - ve(k));\n plot(X(1,e(k),end),X(2,e(k),end),'.','MarkerSize',32,'Color',c), hold on\nend\n\n% overplot mode of motion\n%--------------------------------------------------------------------------\nquiver(X(1,e,end),X(2,e,end),Ve(1,:),Ve(2,:))\n\nVm = CVA.W(:,M);\nVm = spm_unvec(Vm,Q(:,m,1));\nvm = sum(Vm.^2);\nvm = vm/max(vm);\nfor k = 1:length(Vm)\n c = [0 0 1]*vm(k) + [1 1 1]*(1 - vm(k));\n plot(X(1,m(k),end),X(2,m(k),end),'.','MarkerSize',32,'Color',c), hold on\nend\nxlabel('Position', 'FontSize',12)\nylabel('Position','FontSize',12)\ntitle('Canonical mode','FontSize',16)\n\n% conditional synchronisation manifold (polynomial approximation)\n%==========================================================================\n\n% polynomial approximation\n%--------------------------------------------------------------------------\nxX = xm*CVA.W(:,M);\nXX = [xX.^0 xX.^1 xX.^2 xX.^3 xX.^4 xX.^5];\nbE = pinv(XX)*Xe*CVA.V(:,M);\nqE = XX*bE;\n\n% conditional expectation and variance\n%--------------------------------------------------------------------------\n% for i = 1:T\n% qC(i) = CVA.V(:,1)'*squeeze(ce(i,:,:))*CVA.V(:,1);\n% end\nqC = ones(size(qE));\nqC = abs(var(Xe*CVA.V(:,1) - qE)*qC/mean(qC));\n\n% show results - conditional synchronisation manifold\n%--------------------------------------------------------------------------\nsubplot(3,2,2)\nplot(CVA.w(:,1),Xe*CVA.V(:,1),'.c' ), hold on\nplot(CVA.w(:,1),qE,'.b' ), hold off\nxlabel('Internal mode', 'FontSize',12)\nylabel('External mode','FontSize',12)\ntitle('Synchronisation manifold','FontSize',16), spm_axis tight\n\n% show results - conditional distributions as a function of time\n%--------------------------------------------------------------------------\nsubplot(3,1,2)\nplot(Xe*CVA.V(:,1),'c' ), hold on\nspm_plot_ci(qE',qC(:)'), hold off\nxlabel('Time', 'FontSize',12)\nylabel('External states','FontSize',12)\ntitle('Inferred and real motion','FontSize',16), spm_axis tight\n\n\n% event related potentials\n%==========================================================================\n\n% identify points of interest using the external canonical variate\n%--------------------------------------------------------------------------\nu = CVA.v(:,1);\nue = [];\nfor i = 1:8\n [d,j] = max(u(33:end - 65));\n j = j + 32;\n % j = fix(rand*T); % random times\n k = (j - 32):(j + 64); % perstimulus time (around j)\n u((j - 8):(j + 8)) = -Inf; % eliminate from next max(u(:,1))\n ue(:,i) = Xe(k,:)*CVA.V(:,1);\n um(:,i) = Xm(k,:)*CVA.W(:,1);\n us(i) = j;\n \nend\nj = any(ue);\nus = us(j);\nue = spm_detrend(ue(:,j));\num = spm_detrend(um(:,j));\n\n% plot points of interest on conditional density\n%--------------------------------------------------------------------------\nsubplot(3,1,2)\nuy = get(gca,'Ylim'); hold on\nfor i = 1:length(us),plot([1 1]*us(i),uy,':'), end, hold off\n\n% show time locked (internal and external) fluctuations and their mean\n%--------------------------------------------------------------------------\nsubplot(3,2,5)\npst = (-32:64)*8;\nplot(pst,ue,'c:',pst,um,'b:'), hold on\nplot(pst,mean(ue,2),'c',pst,mean(um,2),'b'), hold on\nplot([0 0],get(gca,'YLim'),'--'), hold off, axis square\nxlabel('Time (milliseconds)', 'FontSize',12)\nylabel('Electrochemical response','FontSize',12)\ntitle('Simulated ERP','FontSize',16)\n\n% canonical correlations\n%--------------------------------------------------------------------------\nsubplot(3,2,6)\nbar(CVA.r,1/2,'c')\nxlabel('Mode', 'FontSize',12)\nylabel('Correlation','FontSize',12)\ntitle('Canonical correlations','FontSize',16), axis square\n\n\n\n% Jacobian's and generalised synchronisation\n%==========================================================================\nspm_figure('GetWin','Jacobians');clf\n\n% get Markov blanket indices the Jacobian\n%--------------------------------------------------------------------------\nxi = spm_zeros(x); xi.v(:,e) = 1; iXe = find(spm_vec(xi));\nxi = spm_zeros(x); xi.q(:,m) = 1; iXm = find(spm_vec(xi));\n\n% show results - Jacobians (of increasing order: 1 to n)\n%--------------------------------------------------------------------------\n[d,j] = max(CVA.v(:,1));\nj = j + (-8:8);\nJ = spm_soup(Q(:,:,j),X(:,:,j),V(:,:,j),P);\nJ = mean(J,3);\nj = [iXe;iXm];\n% q = 8;\n% U = blkdiag(CVA.V(:,1:q),CVA.W(:,1:q)); % eigenmodes (not used)\n\nn = 4;\nfor i = 1:n\n \n % all states\n %----------------------------------------------------------------------\n JJ = J^i;\n subplot(n,2,(i - 1)*2 + 1)\n spy(abs(JJ) > 1e-2,'k')\n title(sprintf('%i-order coupling',i),'FontSize',16)\n xlabel('All states','FontSize',12)\n ylabel('All states','FontSize',12)\n \n % Internal and external states\n %----------------------------------------------------------------------\n JJ = JJ(j,j); % JJ = pinv(U)*JJ(j,j)*U;\n subplot(n,2,(i - 1)*2 + 2)\n spy(abs(JJ) > 1e-2,'k')\n title(sprintf('%i-order coupling',i),'FontSize',16)\n xlabel('External and internal','FontSize',12)\n ylabel('External and internal','FontSize',12)\n \nend\n\n\nreturn\n \n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/DEM/FEP_fluctuations.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.46398843523014777}}
{"text": "classdef ParadigmSSRCSP < ParadigmBase\n % Selected-Subjects Regularized CSP (SSRCSP)\n %\n % This paradigm implements SSRCSP [1], which is a generalization of the Common Spatial Patterns\n % algorithms to calibration data comprising multiple subjects (or recordings). To train a model\n % for a particular \"goal\" (or target) subject using auxiliary data from other subjects, this\n % algorithm attempts to find a subset of other subjects such that, when data from those subjects\n % is combined with data from the goal subject, the performance on the goal subject's data is\n % optimal. The combination of data from multiple subjects and from the goal subject is done by\n % shrinking the goal-subject covariance matrix towards the average covariance matrix of the\n % other subjects (within each class), using a regularization parameter. The subset selection\n % algorithm employed is Sequential Floating Forward Selection (SFFS) [2].\n % \n % References:\n % [1] Lotte, F., & Guan, C. \n % \"Regularizing common spatial patterns to improve BCI designs: unified theory and new algorithms.\"\n % Biomedical Engineering, IEEE Transactions on, 58(2), 355-362, 2011.\n %\n % [2] Pudil, P., Ferri, F. J., Novovicova, J., & Kittler, J. \n % \"Floating search methods for feature selection with nonmonotonic criterion functions.\"\n % In Pattern Recognition, Proceedings of the 12th IAPR International. Conference on (Vol. 2, pp. 279-283). (1994)\n %\n % Name:\n % Selected-Subjects Regularized Common Spatial Patterns\n %\n % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD\n % 2014-02-06\n \n methods\n \n function defaults = preprocessing_defaults(self)\n defaults = {'FIRFilter',{'Frequencies',[6 8 28 32],'Type','minimum-phase'}, 'EpochExtraction',[0.5 3.5], 'Resampling',100};\n end\n \n function defaults = machine_learning_defaults(self)\n % set up the default parameters for machine learning\n defaults = {'lda',0.01,'regularization','shrinkage'};\n end\n \n function model = calibrate(self,varargin)\n % calibrate an SSRCSP model from a corpus of training sets\n args = arg_define(varargin, ...\n arg_norep({'collection','Collection'}), ...\n arg_norep({'goal_identifier','GoalIdentifier'}), ...\n arg({'patterns','PatternPairs'},3,uint32([1 1 64 10000]),'Number of CSP patterns (times two).'),...\n arg({'beta','CovarianceShrinkage'},0.5,[0 1],'Covariance shrinkage. This is the degree to which data from the goal subject is shrunken towards that of other subjects.'),...\n arg_sub({'flt','SignalProcessing'}, self.preprocessing_defaults(), @flt_pipeline, 'Signal processing stages. These parameters control filter stages that run on the signal level; they can be enabled, disabled and configured for the given paradigm. The prediction operates on the outputs of this stage.'), ...\n arg_sub({'ml','MachineLearning'},{'Learner',self.machine_learning_defaults()},@ml_train,'Machine learning stage of the paradigm. Operates on the feature vectors that are produced by the feature-extraction stage.'),...\n arg({'arg_dialogsel','ConfigLayout'},self.dialog_layout_defaults(),[],'Parameters displayed in the config dialog. Cell array of parameter names to display (dot-notation allowed); blanks are translated into empty rows in the dialog. Referring to a structure argument lists all parameters of that struture, except if it is a switchable structure - in this case, a pulldown menu with switch options is displayed.','type','cellstr','shape','row'));\n \n % get the data of the reference subject\n [reference,remaining] = utl_collection_closest(args.collection,args.goal_identifier); \n % preprocess each recording in the reference collection and concatenate them across epochs into a single set\n for r=1:length(reference)\n refsets{r} = exp_eval_optimized(flt_pipeline('signal',reference{r}.streams{1}, args.flt)); end\n refdata = exp_eval(set_joinepos(refsets{:}));\n\n % pre-process data of all other subjects\n otherdata = {};\n for s=1:length(remaining)\n if length(remaining{s}.streams) > 1\n disp_once('Note: ParadigmMKLCSP will use only the first data stream of a recording (no support for multi-modal data).'); end\n % preprocess\n otherdata{s} = exp_eval_optimized(flt_pipeline('signal',remaining{s}.streams{1}, args.flt)); %#ok<*NODEF>\n if otherdata{s}.nbchan < args.patterns\n error('CSP requires at least as many channels as you request output patterns. Please reduce the number of pattern pairs.'); end\n end\n \n % get the best subjects\n model.best_subjects = hlp_diskcache('featuremodels',@self.find_best_subjects,otherdata,refdata,args.patterns,args.ml);\n \n % calculate composite CSP\n covar = self.class_covariances(refdata);\n other_covar = self.class_covariances(exp_eval(set_joinepos(otherdata{model.best_subjects})));\n for k=1:2\n covar{k} = (1-args.beta)*covar{k} + args.beta*other_covar{k}; end\n [V,D] = eig(covar{1},covar{1}+covar{2}); P = inv(V); %#ok\n model.featuremodel.filters = V(:,[1:args.patterns end-args.patterns+1:end]);\n model.featuremodel.patterns = P([1:args.patterns end-args.patterns+1:end],:);\n \n % train predictive model\n model.predictivemodel = ml_train('data',{self.feature_extract(refdata,model.featuremodel),set_gettarget(refdata)}, args.ml);\n % set the filter graph based on the reference data\n model.tracking.filter_graph = refsets{end};\n % also store channel locations for model visualization\n model.chanlocs = refdata.chanlocs;\n end\n \n function predictions = predict(self,bundle,model)\n % extract features\n features = self.feature_extract(bundle.streams{1},model.featuremodel);\n % apply classifier\n predictions = ml_predict(features,model.predictivemodel);\n end\n \n function best_subjects = find_best_subjects(self,otherdata,refdata,patterns,ml)\n % find set of best subjects to include\n selected = {[]};\n remaining = {1:length(otherdata)};\n accuracy = {-Inf};\n n = 0;\n while n < length(otherdata)\n % find best subject to add\n best_accuracy = -Inf;\n best_index = NaN;\n for k = remaining{1+n}\n acc = self.evaluate_subset(otherdata([selected{1+n} k]),refdata,patterns,ml);\n if acc > best_accuracy\n best_accuracy = acc;\n best_index = k;\n end\n end\n selected{1+n+1} = [selected{1+n} best_index];\n remaining{1+n+1} = setdiff(remaining{1+n},best_index);\n accuracy{1+n+1} = best_accuracy;\n n = n+1;\n % remove subjects\n while n > 2\n % find best subject to remove\n best_accuracy = -Inf;\n best_index = NaN;\n for k=selected{1+n}\n acc = self.evaluate_subset(otherdata(setdiff(selected{1+n},k)),refdata,patterns,ml);\n if acc > best_accuracy\n best_accuracy = acc;\n best_index = k;\n end\n end\n if best_accuracy > accuracy{1+n-1}\n selected{1+n-1} = setdiff(selected{1+n},best_index);\n remaining{1+n-1} = [remaining{1+n} best_index];\n accuracy{1+n-1} = best_accuracy;\n n = n-1;\n else\n break;\n end\n end\n end\n best_n = argmax([accuracy{:}]);\n best_subjects = selected{best_n}; \n end\n \n function accuracy = evaluate_subset(self,trainset,testset,patterns,ml)\n % note: we are here implicitly weighting by the amount of training data per subject\n if iscell(trainset)\n trainset = exp_eval(set_joinepos(trainset{:})); end\n % train CSP on training set\n covar = self.class_covariances(trainset);\n [V,D] = eig(covar{1},covar{1}+covar{2}); %#ok\n featuremodel.filters = V(:,[1:patterns end-patterns+1:end]);\n % train classifier\n classifier = ml_train('data',{self.feature_extract(trainset,featuremodel),set_gettarget(trainset)},ml);\n % test on test set\n accuracy = -ml_calcloss('auto',set_gettarget(testset),ml_predict(self.feature_extract(testset,featuremodel),classifier));\n end\n \n function covar = class_covariances(self,dataset)\n % calculate per-class covariance matrices\n for k=1:2\n classdata = exp_eval(set_picktrials(dataset,'rank',k));\n covar{k} = (classdata.data(:,:) * classdata.data(:,:)') / (size(classdata.data,2)*size(classdata.data,3));\n covar{k}(~isfinite(covar{k})) = 0;\n end \n end\n \n function features = feature_extract(self,signal,featuremodel)\n % extract log-variance features from an epoched and preprocessed recording\n features = zeros(size(signal.data,3),size(featuremodel.filters,2));\n for t=1:size(signal.data,3)\n features(t,:) = sum((signal.data(:,:,t)'*featuremodel.filters).^2,1); end\n features = log(features/size(signal.data,2));\n end\n \n function visualize(self,varargin) %#ok<*INUSD>\n % visualize an mklCSP model\n args = arg_define(varargin, ...\n arg_norep({'model','Model'},[],[],'BCI Model to visualize.'), ...\n arg({'patterns','PlotPatterns'},true,[],'Plot patterns instead of filters. Whether to plot spatial patterns (forward projections) rather than spatial filters.'), ...\n arg({'paper','PaperFigure'},false,[],'Use paper-style font sizes. Whether to generate a plot with font sizes etc. adjusted for paper.'));\n\n f = figure; \n % get number of pairs, and index of pattern per subplot\n np = size(args.model.featuremodel.patterns,1)/2; \n idx = [1:np 2*np:-1:np+1];\n % for each CSP pattern...\n for p=1:np*2\n subplot(2,np,p,'Parent',f);\n if args.patterns\n topoplot(args.model.featuremodel.patterns(idx(p),:),args.model.featuremodel.chanlocs);\n else\n topoplot(args.model.featuremodel.filters(:,idx(p)),args.model.featuremodel.chanlocs);\n end\n t = title(['CSP Pattern ' num2str(idx(p))]);\n if args.paper\n set(t,'FontUnits','normalized');\n set(t,'FontSize',0.1); \n end\n end\n end\n \n function layout = dialog_layout_defaults(self)\n % define the default configuration dialog layout \n layout = {'SignalProcessing.Resampling.SamplingRate', 'SignalProcessing.FIRFilter.Frequencies', ...\n 'SignalProcessing.FIRFilter.Type', 'SignalProcessing.EpochExtraction', '', ...\n 'PatternPairs', 'CovarianceShrinkage', '', 'MachineLearning.Learner'};\n end\n \n end\nend\n \n% (turn off a few editor warnings because some actual implementations are missing in this file)\n%#ok<*INUSD,*STOUT,*MANU>\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/code/paradigms/in_development/ParadigmSSRCSP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.4638579103126611}}
{"text": "function f_x = ParFor10(in1)\n%PARFOR10\n% F_X = PARFOR10(IN1)\n\n% This function was generated by the Symbolic Math Toolbox version 8.2.\n% 31-Mar-2020 17:03:12\n\nr = in1(:,1);\ns = in1(:,13);\nu = in1(:,19);\nut = in1(:,20);\nux = in1(:,21);\nuxx = in1(:,22);\nuy = in1(:,23);\nuyy = in1(:,24);\nz = in1(:,7);\nt2 = u.^2;\nf_x = r.*-4.845016406907234+s.*6.96612441301113+ut.*5.457984690783633e-1-ux.*1.530748504418966e-2+uxx.*2.135644249305187-uy.*3.570878181824355e-2+uyy.*5.02823932467436-z.*1.323504040227272e2+r.*u.*6.191151455437648-s.*u.*9.105578580027213-t2.*u.*1.077295023277402e2+u.*ut.*5.65024831920482e-2+u.*ux.*1.830355084143775e-2-u.*uxx.*4.132096419489244+u.*uy.*4.442896435307375e-2-u.*uyy.*6.867807677976089+u.*z.*1.83605552916415e2+4.028421339788474e1;\n", "meta": {"author": "dynamicslab", "repo": "SINDy-PI", "sha": "42799b8e5a7585e400aa4bc3c83cfd659046cbb4", "save_path": "github-repos/MATLAB/dynamicslab-SINDy-PI", "path": "github-repos/MATLAB/dynamicslab-SINDy-PI/SINDy-PI-42799b8e5a7585e400aa4bc3c83cfd659046cbb4/Implicit-PDE/BZ_Reaction/TempFunctions/ParFor10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4638291502763339}}
{"text": "function ehmm = hsupdate_ehmm(Xi,Gamma,T,ehmm)\n%\n% updates hidden state parameters of an HMM\n%\n% INPUT:\n%\n% Xi probability of past and future state cond. on data\n% Gamma probability of current state cond. on data\n% T length of observation sequences\n% hmm single hmm data structure\n%\n% OUTPUT\n% hmm single hmm data structure with updated state model probs.\n%\n% Author: Diego Vidaurre, OHBA, University of Oxford\n\nK = ehmm.K;\n\nif isempty(Xi) % non-exact estimation\n order = (sum(T)-size(Gamma,1)) / length(T); \n Xi = zeros(sum(T-1-order),K,2,2);\n for j = 1:length(T)\n indG = (1:(T(j)-order)) + sum(T(1:j-1)) - (j-1)*order;\n indXi = (1:(T(j)-order-1)) + sum(T(1:j-1)) - (j-1)*(order+1);\n for k = 1:K\n g = [Gamma(indG,k) (1-Gamma(indG,k))];\n for t = 1:length(indXi)\n xi = g(t,:)' * g(t+1,:);\n xi = xi / sum(xi(:));\n Xi(indXi(t),k,:,:) = xi;\n end\n end\n end\nend\nif length(size(Xi))==4\n Xi = permute(sum(Xi),[2 3 4 1]);\nend\n\n% transitions\nfor k = 1:K\n ehmm.state(k).Dir2d_alpha = permute(Xi(k,:,:),[2 3 1]) ...\n + ehmm.state(k).prior.Dir2d_alpha;\n ehmm.state(k).P = zeros(2);\n for j = 1:2\n PsiSum = psi(sum(ehmm.state(k).Dir2d_alpha(j,:)));\n for j2 = 1:2\n ehmm.state(k).P(j,j2) = ...\n exp(psi(ehmm.state(k).Dir2d_alpha(j,j2))-PsiSum);\n end\n ehmm.state(k).P(j,:) = ehmm.state(k).P(j,:) ./ sum(ehmm.state(k).P(j,:));\n end\nend\n\n% initial state is always OFF for all chains\nend", "meta": {"author": "OHBA-analysis", "repo": "HMM-MAR", "sha": "bb0433b75482e473980791a2b30afe2012cf6578", "save_path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR", "path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR/HMM-MAR-bb0433b75482e473980791a2b30afe2012cf6578/episodic/hsupdate_ehmm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4638291393932732}}
{"text": "function [um] = au2um(au)\n% Convert length from astronomical units to microns.\n% Chad A. Greene 2012\num = au*1.49597870691e+17;", "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/35258-unit-converters/unit_converters/au2um.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7279754371026368, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.463742761026784}}
{"text": "%DIAGNOSTIC TOOLS (in the diag-folder):\n%\n% Convergence diagnostics\n% PSRF - Potential Scale Reduction Factor\n% CPSRF - Cumulative Potential Scale Reduction Factor\n% MPSRF - Multivariate Potential Scale Reduction Factor\n% CMPSRF - Cumulative Multivariate Potential Scale Reduction Factor\n% IPSRF - Interval-based Potential Scale Reduction Factor\n% CIPSRF - Cumulative Interval-based Potential Scale Reduction Factor\n% KSSTAT - Kolmogorov-Smirnov goodness-of-fit hypothesis test\n% HAIR - Brooks' hairiness convergence diagnostic\n% CUSUM - Yu-Mykland convergence diagnostic for MCMC\n% SCORE - Calculate score-function convergence diagnostic\n% GBINIT - Initial iterations for Gibbs iteration diagnostic\n% GBITER - Estimate number of additional Gibbs iterations\n%\n% Time series analysis\n% ACORR - Estimate autocorrelation function of time series using xcorr\n% ACORR2 - Estimate autocorrelation function of time series using fft\n% ACORRTIME - Estimate autocorrelation evolution of time series (simple)\n% GEYER_ICSE - Compute autocorrelation time tau using Geyer's\n% initial convex sequence estimator\n% (requires Optimization toolbox) \n% GEYER_IMSE - Compute autocorrelation time tau using Geyer's\n% initial monotone sequence estimator\n%\n% Survival model criteria\n% AUCS - Compute area under curve for survival model\n% AUCT - Compute area under curve for survival model at given time\n% EXT_AUC - Compute Extended AUC proposed by Chambless et al (2011)\n% HCS - Compute Harrell's C for survival model at given time\n% HCT - Compute Harrel's C for survival model at several time points\n% IDIS - Integrated Discrimination Improvement between two models\n% RSQR - R^2 statistic given probabilities at time point T\n%\n% Kernel density estimation etc.:\n% KERNEL1 - 1D Kernel density estimation of data\n% KERNELS - Kernel density estimation of independent components of data\n% KERNELP - 1D Kernel density estimation, with automatic kernel width\n% NDHIST - Normalized histogram of N-dimensional data\n% HPDI - Estimates the Bayesian HPD intervals\n%\n% Misc:\n% CUSTATS - Calculate cumulative statistics of data\n% GRADCHEK - Checks a user-defined gradient function using finite\n% differences.\n% DERIVATIVECHECK - Compare user-supplied derivatives to\n% finite-differencing derivatives.\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/diag/Contents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.4635895366907827}}
{"text": "function f = chebfun3double(f, op, dom, pref, isEqui)\n%CHEBFUN3DOUBLE CHEBFUN3 constructor for discrete tensor of values\n% This algorithm is equivalent to chebfun3classic for double inputs.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% The input is a discrete tensor of values.\npseudoLevel = pref.cheb3Prefs.chebfun3eps;\ntech = pref.tech();\n\nf = chebfun3();\nif ( ~isEqui && numel(op) == 1 )\n f = constructor(f, @(x,y,z) op + 0*x, dom);\n return;\nend\n\n% N.B. We cannot detect if MESHGRID was used to generate values unless we\n% know also the (x,y,z) points used to generate those values. If we knew\n% beforehand that ALL users WILL generate their tensor of values ONLY from\n% meshgrid pts, all we need is to say vals = permute(vals,[2 1 3]); to\n% generate a tensor corresponding to ''meshgrid'', in which case a copy of\n% ``tensorGrid`` should also be used accordingly. op = permute(op,[2 1 3]);\nif ( ~isEqui )\n m = size(op, 1);\n n = size(op, 2);\n p = size(op, 3);\n out = tech.tensorGrid([m, n, p], dom);\n xx = out{1};\n yy = out{2};\n zz = out{3};\nelse\n % Equispaced points from ndgrid, not meshgrid!\n x = linspace(dom(1), dom(2), size(op, 1));\n y = linspace(dom(3), dom(4), size(op, 2));\n z = linspace(dom(5), dom(6), size(op, 3));\n [xx, yy, zz] = ndgrid(x, y, z);\nend\n\n% Calculate a tolerance and find numerical rank to this tolerance: The\n% tolerance assumes the samples are generated by NDGRID from a function.\n% It depends on the size of the sample tensor, hscale of domain, vscale of\n% the samples, condition number of the function, and the accuracy target in\n% chebfun3 preferences.\n[relTol, absTol] = getTol3D(xx, yy, zz, op, max(size(op)), dom, pseudoLevel);\npref.chebfuneps = relTol;\n\n% Perform 3D ACA with complete pivoting:\nfactor = 0;\n[colsValues, rowsValues, pivotVals2D, ~, tubesValues, pivotVals3D, ~, ~, ...\n ~] = completeACA3D(op, absTol, factor, dom, pref);\n\nsepRank = numel(pivotVals3D); % first separation rank\ndiagValues2D = cell(sepRank, 1);\nfor k=1:sepRank\n diagValues2D{k} = diag(1./pivotVals2D{k});\nend\n\n% BTD ---> Tucker compression:\n[core, colsValues, rowsValues] = btd2tucker(colsValues, rowsValues, ...\n diagValues2D, pivotVals3D, absTol);\n\n% Construct a CHEBFUN3 object and call a sampleTest.\nif ( ~isEqui )\n f.cols = chebfun(colsValues, dom(1:2), pref);\n f.rows = chebfun(rowsValues, dom(3:4), pref);\n f.tubes = chebfun(tubesValues, dom(5:6), pref);\nelse\n f.cols = chebfun(colsValues, dom(1:2), 'equi', pref);\n f.rows = chebfun(rowsValues, dom(3:4), 'equi', pref);\n f.tubes = chebfun(tubesValues, dom(5:6), 'equi', pref);\nend\nf.core = core;\nf.domain = dom;\nreturn\n\nend\n\n%%\nfunction [relTol, absTol] = getTol3D(xx, yy, zz, vals, grid, dom, ...\n pseudoLevel)\n\nrelTol = 2*grid^(4/5) * pseudoLevel; % this should be vscale and hscale invariant\nvscale = max(abs(vals(:)));\n[m,n,p] = size(vals);\n% Remove some edge values so that df_dx, df_dy and df_dz have the same size. \n% xx changes in the first mode:\ndf_dx = diff(vals(:, 1:n-1, 1:p-1), 1, 1) ./ diff(xx(:, 1:n-1, 1:p-1), 1, 1);\n% yy changes row-wise (2nd mode):\ndf_dy = diff(vals(1:m-1, :, 1:p-1), 1, 2) ./ diff(yy(1:m-1, :, 1:p-1), 1, 2);\n% zz changes tube-wise (3rd mode):\ndf_dz = diff(vals(1:m-1, 1:n-1, :), 1, 3) ./ diff(zz(1:m-1, 1:n-1, :), 1, 3);\ngradNorms = [max(abs(df_dx(:))), max(abs(df_dy(:))), max(abs(df_dz(:)))];\n% A vector of gradient information over the domain.\nif ( isempty(gradNorms) )\n % This happens if the input in not a trivariate function in which case\n % we basically disable using gradient information:\n gradNorms = 1;\nend\ndomDiff = [diff(dom(1:2)) diff(dom(3:4)) diff(dom(5:6))];\nabsTol = max(max(gradNorms.*domDiff), vscale) * relTol;\n% absTol should depend on the vscale of the function while it also uses\n% derivative information to prevent issues like the one mentioned in\n% https://github.com/chebfun/chebfun/issues/1491.\n\nend\n\n%%\nfunction [colsBtd, rowsBtd, pivotValues2D, pivotIndices2D, fibers, ...\n pivotValues3D, pivotIndices3D, ifail3D, ifail2D] = completeACA3D(A, ...\n tol, factor, dom, pref)\n% Non-adaptive (fixed-size) MACA, i.e., a 3D analogue of Gaussian \n% elimination with complete pivoting.\n%\n% INPUTS: A: A given tensor of function values at 3D chebpts.\n%\n% tol: A given tolerance on the magnitude of the pivots.\n%\n% factor: The ratio between the width of A and the number \n% of iterations (rank) allowed in Gaussian elimination.\n%\n% OUTPUTS: colsBtd: A cell-array containing skeleton columns of slices \n% in block term decomposition.\n%\n% rowsBtd: A cell-array containing skeleton rows of slices in\n% block term decomposition.\n%\n% pivotValues2D: A cell array containing the values of pivots\n% in 2D ACAs.\n%\n% pivotIndices2D: A cell array containing indices i.e.,\n% locations of of 2D pivot points.\n%\n% fibers: A matrix of size n1 x ITER. Each of its columns\n% contains the values of the updated (residue) \n% tensor at the pivot fiber.\n%\n% pivotValues3D: A row vector containing the values of the \n% pivot entries during the iterations. \n%\n% pivotIndices3D: A matrix of size rank x 3, where rank = iter. \n% Each of its rows contain the index of one 3D pivotValues.\n%\n% ifail: We fail if iter >= (width/factor).\n\n% Developer Note: The output of this code should satisfy the following \n% slice decomposition:\n% AA \\approx temp, \n% where AA is a copy of A from input, and temp is computed as follows:\n% temp = zeros(size(A2)); \n% for i = 1:3, \n% temp = temp + chebfun3.outerProd(slices(:,:,i),fibers(:,i)./pivotValues3D(i));\n% end\n% norm(AA(:) - temp(:))\n%\n% An analogous BTD decomposotion should also hold.\n\npseudoLevel = pref.cheb3Prefs.chebfun3eps;\ntech = pref.tech();\n\n% Set up output variables.\n[n1, n2, n3] = size(A);\nwidth = min(n3, n1*n2); % Use to tell us how many pivots we can take\n % See Developer note in the following.\npivotValues3D = zeros(1); % Store an unknown number of Pivot values\npivotIndices3D = zeros(1, 3); % Store (col, row, tube) = entries of pivot location\nifail3D = 1; % Assume we fail in 3D ACA\nifail2D = 1; % Assume we also fail in the 2D ACAs\nglobalTol = [];\nsliceDim = [1 2]; % See Developer note in the following.\n\n% Main algorithm\niter = 0; % Count number of interpolated rows/slices.\n[infNorm, ind] = max(abs(reshape(A, numel(A), 1))); % Complete pivoting\n[col, row, tube] = ind2sub(size(A), ind);\n\nscl = infNorm;\n% If the function is the zero function.\nif ( scl == 0 )\n pivotValues3D = 0;\n fibers = 0;\n colsBtd{1} = 0;\n rowsBtd{1} = 0;\n pivotValues2D = 0;\n pivotIndices2D = [0 0];\n ifail3D = 0;\n ifail2D = 0;\nelse\n fibers(:,1) = zeros(size(A, 3), 1);\n colsBtd{1} = zeros(size(A, sliceDim(1)), 1);\n rowsBtd{1} = zeros(size(A, sliceDim(2)), 1);\n pivotValues2D{1} = 0;\n pivotIndices2D{1} = [0 0];\n slices(:,:,1) = zeros(size(A,sliceDim(1)), size(A, sliceDim(2)), 1);\nend\ndom2D = dom(1:4);\n\nwhile ( ( infNorm > tol ) && ( iter < width / factor) ...\n && ( iter < width ) )\n fibers(:, iter+1) = A(col, row, :); % Extract skeleton tubes. Each\n % column in \"fibers\" is N3 x 1.\n \n slices(:,:,iter+1) = A(:,:,tube); % Extract skeleton slices to be \n % decomposed further. Each slice in \"slices\" is N1 x N2.\n \n % Developer Note: As the above lines show, we are always separating the\n % last variable from the first two. The point is that the function \n % handle has already been permuted outside this subroutine and \n % therefore the tensor A here contains values of the permuted function.\n % In this sense, here we are in essense separating the variable chosen \n % by the dimension clustering step, and not necessarily the last \n % variable z.\n \n PivVal3D = A(col, row, tube); % = f(X(col), Y(row), Z(tube)) in\n % the 1st iteration.\n \n % Use the first slice to compute globalTol for 2D ACAs applied to all \n % slices.\n if ( iter == 0 )\n out = tech.tensorGrid([n1, n2], dom2D);\n xx2D = out{1};\n yy2D = out{2};\n globalTol = GetTol2D(xx2D, yy2D, slices(:,:,1), dom2D, pseudoLevel);\n end\n \n % Apply 2D ACA to each slice to form columns and rows in block term\n % decomposition:\n [colsBtd{iter+1}, pivotValues2D{iter+1}, rowsBtd{iter+1}, ...\n pivotIndices2D{iter+1}, ifail2DIter] = ...\n chebfun2ACA(slices(:, :, iter+1), globalTol, factor);\n \n % Developer Note: Since we use globalTol for slices after 1st \n % iteration, it might be that these 2D ACA's don't fail, while with a \n % localTol they would fail. So, it is auaully the 1st slice which shows\n % whether or not we got the 2D rank right. So, just use that one:\n if ( iter == 0 )\n ifail2D = ifail2DIter;\n end\n \n % Update the tensor, i.e., compute the residual tensor:\n A = A - chebfun3.outerProd(colsBtd{iter+1} * ...\n (diag(1./(pivotValues2D{iter+1}))) * (rowsBtd{iter+1}.'), ...\n fibers(:,iter+1) ./ PivVal3D);\n % Equivalently, we have: \n % A = A - chebfun3.outerProd(slices(:,:,iter+1),fibers(:,iter+1)./PivVal3D);\n \n % Keep track of progress in 3D ACA:\n iter = iter + 1; % One more fiber and slice are removed from A\n pivotValues3D(iter) = PivVal3D; % Store pivot value in 3D ACA\n pivotIndices3D(iter, :)=[col row tube]; % Store pivot location in 3D ACA\n \n % Find next 3D pivot value and its location:\n [infNorm, ind] = max(abs(A(:)));\n [col, row, tube] = ind2sub(size(A), ind);\nend\n\nif ( ( iter > 0 ) && ( all(pivotValues2D{iter} == 0) ) )\n % If the last 2D pivot was zero, remove it\n colsBtd=colsBtd(1:iter-1);\n rowsBtd=rowsBtd(1:iter-1);\n pivotValues2D = pivotValues2D(1:iter-1);\n pivotIndices2D = pivotIndices2D(1:iter-1);\n fibers = fibers(:, 1:iter-1);\n pivotValues3D = pivotValues3D(1:iter-1);\n pivotIndices3D=pivotIndices3D(1:iter-1,:);\n infNorm = 0; % If the last 2D pivot was zero, infNorm will be NaN and \n % it makes the next statement result in ifail3D \\neq 0; So, put it 0 to\n % get ifail3D = 0;\nend\n\nif ( infNorm <= tol )\n ifail3D = 0; % We didn't fail in 3D ACA.\n if ( iter == 0 )\n ifail2D = 0; \n end\nend\nif ( iter > width/factor )\n ifail3D = 1; % We did fail in 3D ACA.\nend\n\nend\n%%\n\n%%\nfunction absTol = GetTol2D(xx, yy, vals, dom, pseudoLevel)\n% GETTOL2D Calculate a tolerance for the Chebfun2 constructor.\n%\n% This is the 2D analogue of the tolerance employed in the chebtech\n% constructors. It is based on a finite difference approximation to the\n% gradient, the size of the approximation domain, the internal working\n% tolerance, and an arbitrary (4/5) exponent. \n\n[m, n] = size(vals); \ngrid = max(m, n);\nrelTol = grid^(4/5) * pseudoLevel; % this should be vscale and hscale invariant\n\n% Remove some edge values so that df_dx and df_dy have the same size. \n% xx is generated by ndgrid, i.e., xx changes in the first mode:\ndfdx = diff(vals(:, 1:n-1), 1, 1) ./ diff(xx(:, 1:n-1), 1, 1);\n% yy is generated by ndgrid, i.e., yy changes row-wise (2nd mode):\ndfdy = diff(vals(1:m-1, :), 1, 2) ./ diff(yy(1:m-1, :), 1, 2);\ngradNorms = [max(abs(dfdx(:))), max(abs(dfdy(:)))];\n% A vector of gradient information over the domain.\nif ( isempty(gradNorms) )\n % This happens if the input in not a trivariate function.\n gradNorms = 1;\nend\n\nvscale = max(abs(vals(:)));\ndomDiff = [diff(dom(1:2)) diff(dom(3:4))];\nabsTol = max(max(gradNorms.*domDiff), vscale) * relTol;\nend\n\n%%\nfunction [col, pivotVals, row, pivotLoc, ifail2D] = chebfun2ACA(op, ...\n tol, factor)\n% Perform GE with complete pivoting:\n\nif ( factor ~= 0 )\n % FACTOR in the 3D steps is either 0 (in case of constructionFromDoubles) \n % or 2sqrt(2) otherwise. For 2D steps however, we are happy with \n % FACTOR = 0 or 2 as in Chebfun2. This IF conditional, makes it\n % possible to rewrite FACTOR in 2D steps, but at the same time keeping \n % it zero fro constructionFromDoubles.\n factor = 2;\nend\n[pivotVals, pivotLoc, row, col, ifail2D] = completeACA2D(op, tol, factor); \nend\n\n\n%%\nfunction [pivotValue, pivotElement, rows, cols, ifail2D] = ...\n completeACA2D(A, tol, factor) \n% 2D ACA with complete pivoting which is the continuous analogue of \n% Gaussian elimination with complete pivoting.\n% We attempt to adaptively find the numerical rank of function in the 2D\n% level. This is _almost_ the same as the one in chebfun2/constructor.\n\n\n% Set up output variables.\n[nx, ny] = size(A);\nwidth = min(nx, ny); % Use to tell us how many pivots we can take.\npivotValue = zeros(1); % Store an unknown number of Pivot values.\npivotElement = zeros(1, 2); % Store (j,k) entries of pivot location.\nifail2D = 1; % Assume we fail.\n\n% Main algorithm\nzRows = 0; % count number of zero cols/rows.\n[infNorm, ind] = max(abs(reshape(A, numel(A), 1)));\n[row, col] = chebfun3.myind2sub(size(A) , ind);\n\n% Bias toward diagonal for square matrices (see reasoning below):\nif ( ( nx == ny ) && ( max(abs(diag(A))) - infNorm) > -tol )\n [infNorm, ind] = max(abs(diag(A)));\n row = ind;\n col = ind;\nend\n\nscl = infNorm;\n% If the function is the zero function\nif ( scl == 0 )\n pivotValue = 0;\n cols = 0;\n rows = 0;\n ifail2D = 0;\nelse\n cols(:,1) = zeros(size(A, 1), 1);\n rows(1,:) = zeros(1, size(A, 2));\nend\n\nwhile ( ( infNorm > tol ) && ( zRows < width / factor) ...\n && ( zRows < min(nx, ny) ) )\n\n cols(:, zRows+1) = A(:, col); % Extract skeleton columns\n rows(zRows+1, :) = A(row, :); % Extract skeleton rows\n PivVal = A(row, col);\n A = A - cols(:, zRows+1)*(rows(zRows+1,:)./PivVal); % One step of GE\n \n % Keep track of progress.\n zRows = zRows + 1; % One more row is interpolated\n pivotValue(zRows) = PivVal; % Store value of 2D pivot\n pivotElement(zRows, :)=[row col]; % Store index of 2D pivot\n \n % Find value and index of next 2D pivot\n [infNorm, ind] = max(abs(A(:))); % Slightly faster\n [row, col] = chebfun3.myind2sub(size(A), ind);\n \n % Have a bias towards the diagonal of A, so that it can be used as a test\n % for nonnegative definite functions. (Complete GE and Cholesky are the\n % same as nonnegative definite functions have an absolute maximum on the\n % diagonal, except there is the possibility of a tie with an off-diagonal\n % absolute maximum. Bias toward diagonal maxima to prevent this.)\n if ( ( nx == ny ) && ( max(abs(diag(A))) - infNorm) > -tol )\n [infNorm, ind] = max(abs(diag(A)));\n row = ind;\n col = ind;\n end\nend\n\nif ( infNorm <= tol )\n ifail2D = 0; % We didn't fail in 2D ACA\nend\nif ( zRows >= (width/factor) )\n ifail2D = 1; % We did fail in 2D ACA\nend\n\nrows = rows.'; % To unify all the columns, \n % rows and tubes, store \n % skeleton rows also as column \n % vectors.\nend\n\n%%\nfunction [core, colsTucker, rowsTucker] = btd2tucker(colsValues, ...\n rowsValues, diagValues2D, pivotVals3D, absTol)\nallCols = []; \nallRows = []; \nallDiags = [];\nnn = numel(pivotVals3D);\nsizeIndex = zeros(nn, 1);\n\nfor kkk = 1:nn\n sizeIndex(kkk) = size(rowsValues{kkk}, 2);\n allCols = [allCols, colsValues{kkk}];\n allRows = [allRows, rowsValues{kkk}];\n allDiags = [allDiags; diag(diagValues2D{kkk})];\nend\nsizeIndex = cumsum([0; sizeIndex]);\n \n% Compress allCols and allRows:\nif ( size(allCols, 2) > 1 )\n [Su, ~, Vu, colsTucker] = completeACA2D(allCols, absTol, 0);\n % factor = 0, because we want the ACA to be applied even if op is not \n % low-rank. In contrast to Chebfun2, we now have \n % allCols = colsTucker * diag(1./Su) * Vu'.\n % Moreover, we use the same absTol to chop columns, the same tolerance\n % used to chop fibers so that ranks are less inconsistent for symmetric\n % functions.\n Vu = Vu*diag(1./Su);\nelse\n colsTucker = allCols; \n Vu = 1;\nend\n\nif ( size(allRows, 2) > 1 )\n [Sv, ~, Vv, rowsTucker] = completeACA2D(allRows, absTol, 0);\n Vv = Vv*diag(1./Sv);\nelse\n rowsTucker = allRows; \n Vv = 1;\nend\n\n% Form the core tensor:\ncore = zeros(size(colsTucker, 2), size(rowsTucker, 2), nn);\nfor kkk = 1:nn\n core(:,:,kkk) = Vu(sizeIndex(kkk)+1:sizeIndex(kkk+1), :).' * ...\n diag(allDiags(sizeIndex(kkk)+1:sizeIndex(kkk+1))) * ...\n Vv(sizeIndex(kkk)+1:sizeIndex(kkk+1), :)./pivotVals3D(kkk);\nend\n\nif ( (max(abs(allCols(:))) == 0) || (max(abs(allRows(:))) == 0) ) \n % zero input\n core = 0;\nend\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebfun3/chebfun3double.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.4635895366438769}}
{"text": "function [res,qualMeasOut]=MLEM(proj,geo,angles,niter,varargin)\n%MLEM solves the tomographic problem by using Maximum Likelihood Expectation\n% Maximisation algorithm. \n%\n% MLEM(PROJ,GEO,ALPHA,NITER,opt) solves the reconstruction problem\n% using the projection data PROJ taken over ALPHA angles, corresponding\n% to the geometry described in GEO, using NITER iterations.\n%\n% 'verbose': Get feedback or not. Default: 1\n%\n% 'init': Describes different initialization techniques.\n% ⢠'none' : Initializes the image to ones (default)\n% ⢠'FDK' : Initializes image to FDK reconstruction\n%\n% 'QualMeas': Asks the algorithm for a set of quality measurement\n% parameters. Input should contain a cell array of desired\n% quality measurement names. Example: {'CC','RMSE','MSSIM'}\n% These will be computed in each iteration.\n%\n% 'groundTruth': An image as ground truth, to be used if quality measures\n% are requested, to plot their change w.r.t. this known\n% data.\n%--------------------------------------------------------------------------\n%--------------------------------------------------------------------------\n% This file is part of the TIGRE Toolbox\n% \n% Copyright (c) 2015, University of Bath and \n% CERN-European Organization for Nuclear Research\n% All rights reserved.\n%\n% License: Open Source under BSD. \n% See the full license at\n% https://github.com/CERN/TIGRE/blob/master/LICENSE\n%\n% Contact: tigre.toolbox@gmail.com\n% Codes: https://github.com/CERN/TIGRE/\n% Coded by: Ander Biguri \n%--------------------------------------------------------------------------\n[verbose,res,QualMeasOpts,gpuids,gt]=parse_inputs(proj,geo,angles,varargin);\nmeasurequality=~isempty(QualMeasOpts) | ~any(isnan(gt(:)));\nif ~any(isnan(gt(:)))\n QualMeasOpts{end+1}='error_norm';\n res_prev=gt;\n clear gt\nend\nif nargout<2 && measurequality\n warning(\"Image metrics requested but none caught as output. Call the algorithm with 3 outputs to store them\")\n measurequality=false;\nend\nqualMeasOut=zeros(length(QualMeasOpts),niter);\n\n\nres = max(res,0);\n\n% Back-projection weight, V\nV = Atb(ones(size(proj),'single'),geo,angles,'matched','gpuids',gpuids);\nV(V<=0.) = inf;\n\nfor ii=1:niter\n if measurequality && ~strcmp(QualMeasOpts,'error_norm')\n res_prev = res; % only store if necessary\n end\n if (ii==1);tic;end\n\n den = Ax(res,geo,angles,'gpuids',gpuids);\n den(den<=0.)=inf;\n \n imgupdate = Atb(proj./den, geo,angles,'matched','gpuids',gpuids)./V;\n res = max(res.*imgupdate,0.);\n \n if measurequality\n qualMeasOut(:,ii)=Measure_Quality(res_prev,res,QualMeasOpts);\n end\n \n if (ii==1)&&(verbose==1)\n expected_time=(toc)*niter;\n disp('MLEM');\n disp(['Expected duration : ',secs2hms(expected_time)]);\n disp(['Expected finish time: ',datestr(datetime('now')+seconds(expected_time))]);\n disp('');\n end\n\nend\nend\n\n%% Parse inputs\nfunction [verbose,f0,QualMeasOpts,gpuids,gt]=parse_inputs(proj,geo,angles,argin)\nopts = {'verbose','init','qualmeas','gpuids','groundtruth'};\ndefaults=ones(length(opts),1);\n% Check inputs\nnVarargs = length(argin);\nif mod(nVarargs,2)\n error('TIGRE:MLEM:InvalidInput','Invalid number of inputs')\nend\n\n% check if option has been passed as input\nfor ii=1:2:nVarargs\n ind=find(ismember(opts,lower(argin{ii})));\n if ~isempty(ind)\n defaults(ind)=0;\n else\n error('TIGRE:MLEM:InvalidInput',['Optional parameter \"' argin{ii} '\" does not exist' ]);\n end\nend\n\nfor ii=1:length(opts)\n opt=opts{ii};\n default=defaults(ii);\n % if one option is not default, then extract value from input\n if default==0\n ind=double.empty(0,1);jj=1;\n while isempty(ind)\n ind=find(isequal(opt,lower(argin{jj})));\n jj=jj+1;\n end\n if isempty(ind)\n error('TIGRE:MLEM:InvalidInput',['Optional parameter \"' argin{jj} '\" does not exist' ]);\n end\n val=argin{jj};\n end\n \n switch opt\n % % % % % % % Verbose\n case 'verbose'\n if default\n verbose=1;\n else\n verbose=val;\n end\n if ~is2014bOrNewer\n warning('TIGRE: Verbose mode not available for older versions than MATLAB R2014b');\n verbose=false;\n end\n % Initial image\n % =========================================================================\n case 'init'\n if default || strcmp(val,'none')\n f0=ones(geo.nVoxel','single');\n else\n if strcmp(val,'FDK')\n f0=FDK(proj, geo, angles);\n else\n error('TIGRE:MLEM:InvalidInput','Invalid init')\n end\n end\n % Image Quality Measure\n % =========================================================================\n case 'qualmeas'\n if default\n QualMeasOpts={};\n else\n if iscellstr(val)\n QualMeasOpts=val;\n else\n error('TIGRE:MLEM:InvalidInput','Invalid quality measurement parameters');\n end\n end\n % GPUIDS\n % =========================================================================\n case 'gpuids'\n if default\n gpuids = GpuIds();\n else\n gpuids = val;\n end\n case 'groundtruth'\n if default\n gt=nan;\n else\n gt=val;\n end\n otherwise\n error('TIGRE:MLEM:InvalidInput',['Invalid input name:', num2str(opt),'\\n No such option in MLEM()']);\n end\nend\nend\n\n", "meta": {"author": "CERN", "repo": "TIGRE", "sha": "8df632662228d1b1c52afd95c90d0f7a9f8dc4b3", "save_path": "github-repos/MATLAB/CERN-TIGRE", "path": "github-repos/MATLAB/CERN-TIGRE/TIGRE-8df632662228d1b1c52afd95c90d0f7a9f8dc4b3/MATLAB/Algorithms/MLEM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.46354034648601694}}
{"text": "function Dual_TVL1_optic_flow( I0,I1, u1, u2, nx, ny, tau, lambda, theta, warps, epsilon,verbose,iflagMedian)\nsize = round(nx * ny);\nl_t = lambda * theta;\nif isa(u1,'cell') && isa(u2,'cell')\n u1 = cell2mat(u1);\n u2 = cell2mat(u2);\nend\nMAX_ITERATIONS= 300;\nPRESMOOTHING_SIGMA =0.8;\nGRAD_IS_ZERO = 1E-10;\n[I1x, I1y] = centered_gradient(I1, 0, 0, nx, ny);\n for i = 1: size \n p11(i) =0.0; \n p12(i) = 0.0;\n p21(i) =0.0;\n p22(i) = 0.0;\n end\n rho_c = zeros(1,size);\n grad = zeros(1,size);\n for warpings = 1: warps\n I1w = bicubic_interpolation_warp(I1, u1, u2, 0, nx, ny, 1);\n I1wx = bicubic_interpolation_warp(I1x, u1, u2, 0, nx, ny, 1);\n I1wy = bicubic_interpolation_warp(I1y, u1, u2, 0, nx, ny, 1);\n for i = 1:size\n Ix2 = I1wx(i) * I1wx(i);\n Iy2 = I1wy(i) * I1wy(i);\n\n \n grad(i) = (Ix2 + Iy2);\n sizes = [length(u2),length(I1w),length(I1wx),length(u1),length(I1wy),length(I0)];\nif i <= min(sizes)\n rho_c(i) = (I1w(i) - I1wx(i) * u1(i)- I1wy(i) * u2(i) - I0(i));\nend\n end\n n = 0;\n error = Inf;\n while (error > epsilon * epsilon && n < MAX_ITERATIONS) \n n = n +1;\n \n\n for i = 1 : size\n sizes = [length(u2),length(I1w),length(I1wx),length(u1),length(I1wy),length(I0)];\nif i <= min(sizes)\n rho = rho_c(i)+ (I1wx(i) * u1(i) + I1wy(i) * u2(i));\n\n d1 = 0.0; d2 = 0.0;\n\n if (rho < - l_t * grad(i)) \n d1 = l_t * I1wx(i);\n d2 = l_t * I1wy(i);\n else \n if (rho > l_t * grad(i)) \n d1 = -l_t * I1wx(i);\n d2 = -l_t * I1wy(i);\n else \n if (grad(i) < GRAD_IS_ZERO)\n d1 = 0;\n d2 = 0;\n else \n fi = -rho/grad(i);\n d1 = fi * I1wx(i);\n d2 = fi * I1wy(i);\n end\n \n end\n end\nend\nif(i <= length(u1))\n v1(i) = u1(i) + d1;\nend\nif(i <= length(u2))\n v2(i) = u2(i) + d2;\nend\n end\n div_p1 = divergence(p11, p12, 0, nx ,ny);\n div_p2 = divergence(p21, p22, 0, nx ,ny);\n error = 0.0;\n\n\n for i = 1: size-1\n if(i <= length(u1))\n u1k = u1(i);\n u2k = u2(i);\n\n u1(i) = v1(i) + theta * div_p1(i);\n u2(i) = v2(i) + theta * div_p2(i);\n\n error = error + (u1(i) - u1k) * (u1(i) - u1k) +(u2(i) - u2k) * (u2(i) - u2k);\n end\n end\n error = error / size;\n [u1x, u1y ] = forward_gradient(u1, 0, 0, nx ,ny);\n [u2x, u2y] = forward_gradient(u2, 0, 0, nx ,ny);\n for (i = 1: size-1) \n taut = tau / theta;\n if i < length(u1x)\n g1 = hypot(u1x(i), u1y(i));\n g2 = hypot(u2x(i), u2y(i));\n end\n ng1 = 1.0 + taut * g1;\n ng2 = 1.0 + taut * g2;\n\n p11(i) = (p11(i) + taut * u1x(i)) / ng1;\n p12(i) = (p12(i) + taut * u1y(i)) / ng1;\n p21(i) = (p21(i) + taut * u2x(i)) / ng2;\n p22(i) = (p22(i) + taut * u2y(i)) / ng2;\n end\n\n end\n \n %applay the filter and continue \nend", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/å»åŖē®ę³/SPTWO_matlab-master/Dual_TVL1_optic_flow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.46351540624317344}}
{"text": "function [Y, optinf] = bpdngrp(D, S, lambda, mu, g, opt)\n\n% bpdngrp -- Basis Pursuit DeNoising with l2,1 group sparsity\n%\n% argmin_x (1/2)||D*x - s||_2^2 + lambda*||x||_1 +\n% mu * \\sum_l ||G_l(x)||_2\n%\n% The solution is computed using the ADMM approach (see\n% boyd-2010-distributed for details).\n%\n% Usage:\n% [Y, optinf] = bpdngrp(D, S, lambda, mu, g, opt)\n%\n% Input:\n% D Dictionary matrix\n% S Signal vector (or matrix)\n% lambda Regularization parameter\n% mu l2,1 regularization parameter\n% g Vector containing index values indicating the\n% group number for each dictionary element. The\n% first group index is 1 (0 indicates no group).\n% Numbers must be contiguous. Overlapping groups\n% are not supported.\n% opt Options/algorithm parameters structure (see below)\n%\n% Output:\n% Y Dictionary coefficient vector (or matrix)\n% optinf Details of optimisation\n%\n%\n% Options structure fields:\n% Verbose Flag determining whether iteration status is displayed.\n% Fields are iteration number, functional value,\n% data fidelity term, l1 regularisation term, l2,1\n% regularisation term, and primal and dual residuals\n% (see Sec. 3.3 of boyd-2010-distributed). The value of\n% rho is also displayed if options request that it is\n% automatically adjusted.\n% MaxMainIter Maximum main iterations\n% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of\n% boyd-2010-distributed)\n% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of\n% boyd-2010-distributed)\n% Y0 Initial value for Y\n% U0 Initial value for U\n% rho ADMM penalty parameter\n% AutoRho Flag determining whether rho is automatically updated\n% (see Sec. 3.4.1 of boyd-2010-distributed)\n% AutoRhoPeriod Iteration period on which rho is updated\n% RhoRsdlRatio Primal/dual residual ratio in rho update test\n% RhoScaling Multiplier applied to rho when updated\n% AutoRhoScaling Flag determining whether RhoScaling value is\n% adaptively determined (see wohlberg-2015-adaptive). If\n% enabled, RhoScaling specifies a maximum allowed\n% multiplier instead of a fixed multiplier.\n% RhoRsdlTarget Residual ratio targeted by auto rho update policy.\n% StdResiduals Flag determining whether standard residual definitions\n% (see Sec 3.3 of boyd-2010-distributed) are used instead\n% of normalised residuals (see wohlberg-2015-adaptive)\n% RelaxParam Relaxation parameter (see Sec. 3.4.3 of\n% boyd-2010-distributed)\n% AuxVarObj Flag determining whether objective function is computed\n% using the auxiliary (split) variable\n%\n%\n% Author: Brendt Wohlberg