{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% evalIFGT Evaluate the density estimate using the \"improved\" Fast Gauss Transform\n%\n% [e,b] = evalIFGT(X,Y,N [,Nc,rC]) -- eval likelihood (\"e\") of the points Y under\n% the density estimate X using N coefficients of the\n% \"improved\" Fast Gauss Transform; the value \"b\" is the bound\n% on the (absolute) error which could arise.\n%\n% Optional arguments:\n% Nc -- # of clusters to use for \"X\", default is sqrt(Npoints) \n% rC -- Cutoff radius (in std deviations) to exclude contributions, default 3\n%\n% See: Yang, Duraiswami, Gumerov; \"Improved Fast Gauss Transform\", submitted to \n% the Siam Journal of Scientific Computing, 2004\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [estimate,errbound] = evalIFGT(pp,q,Ncoeff,Nclusters,rCutoff)\n p = kde(pp);\t% copy constructor to dodge later rescaling...\n if (p.type ~= 0) \n error('Sorry -- FGT = fast Gauss transform; it needs Gaussian kernels');\n end;\n if (size(p.bandwidth,2)>2*p.N)\n error('Sorry -- IFGT currently supports only uniform bandwidths');\n end;\n if (nargin<4) Nclusters = round(sqrt(getNpts(p))); end;\n if (nargin<5) rCutoff = 3; end; \n if (isa(q,'kde')) qpts = getPoints(q); else qpts = q; end;\n \n BW = getBW(p,1); BWorig = BW;\n if (any( BW - BW(1) )) % CONVERT TO SINGLE, SCALAR BW:\n p = rescale(p, 1./BW); % if differ in dimensions, need to rescale\n qpts = qpts .* repmat(1./BW,[1,size(qpts,2)]);\n BW = 1;\n else BW = BW(1); % already scalar; can just drop other dim's\n end;\n\n [c,cPts,cWts,cWt,cRad] = fpClusterK(p,Nclusters);\n %[c,cPts,cWts,cWt,cRad] = fpClusterR(p,sqrt(2)*BW);\n coeff = findCoeff(c,cPts,cWts,cRad,BW,Ncoeff);\n [estimate,errbound] = evalCoeff( qpts, c,coeff,Ncoeff,cWt,BW,cRad,rCutoff);\n\n % Change norm. constant (due to rescaling operation)\n scale = p.D*log(BW) - sum(log(BWorig));\n estimate = estimate * exp(scale); errbound = errbound * exp(scale);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% fpCluster -- fast, \"farthest point\" clustering method\n% cluster points of \"p\" into K clusters, described by \"centers\",\n% \"clusters\" (cell array of pts to each cluster),\n% cWeight (weight per cluster), and maximum radius of any cluster.\n%\nfunction [centers, clusters, weights, cWeight, radius] = fpClusterK(p, K)\n points = getPoints(p); wts = getWeights(p);\n [D,N] = size(points);\n centers = zeros(D,K); clusters = cell(1,K); weights = cell(1,K);\n assign = ones(1,N); dmin = zeros(1,N)+inf;\n next = fix(rand(1)*N)+1; % choose 1st center at random\n for i=1:K\n centers(:,i) = points(:, next);\n d = points - repmat(centers(:,i),[1,N]);\n d = sqrt(sum(d.^2,1));\n F=find(d rMax),\n i=i+1; centers(:,i) = points(:, next);\n d = points - repmat(centers(:,i),[1,N]);\n d = sqrt(sum(d.^2,1));\n F=find(d= rCutoff^2);\n\n start = 0; startNew = 1;\n terms = zeros(length(PTS),size(coeffI,2));\n terms(:,start+1) = exp( - distance2(PTS) )';\n pos = ones(1,D); \n for j=2:Nterms\n Nprev = startNew - start;\n\tNadd = sum(Nprev-pos+1); \n\tm=1; posNew(1)=m;\n\tfor k=1:D\n\t for l=pos(k):Nprev\n\t terms(:,startNew+m) = vals(k,PTS)' .* terms(:,start+l);\n\t m = m+1;\n\t end;\n\t if (k~=D) posNew(k+1) = m; end;\n\tend;\n\tpos = posNew; start = startNew; startNew = start+Nadd;\n end;\n est(PTS) = est(PTS) + (coeffI * terms');\n\n % error bound addition for included points... + Qin * 2^p/p! rhox^p rhoy^p\n err(PTS)=err(PTS) + cWt(i)*exp( Nterms*log(2*rCutoff)- sum(log(1:Nterms)) + Nterms*log(cRad/h) );\n\n % error bound addition for excluded points... + Qin * exp(-rhoy^2+rhox^2)\n err(PTSN)=err(PTSN) + cWt(i)*exp( - rCutoff^2 + (cRad/h)^2 );\n\n end; \n h = h / sqrt(2);\n \n est = est ./ (2*pi*h^2)^(D/2);\n err = err ./ (2*pi*h^2)^(D/2);\n\n", "meta": {"author": "ShapeNet", "repo": "RenderForCNN", "sha": "c0bee04aad3dc2f0ae5de71daf6d51664ce02e76", "save_path": "github-repos/MATLAB/ShapeNet-RenderForCNN", "path": "github-repos/MATLAB/ShapeNet-RenderForCNN/RenderForCNN-c0bee04aad3dc2f0ae5de71daf6d51664ce02e76/render_pipeline/kde/matlab_kde_package/evalIFGT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127492339909, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5998993833664229}} {"text": "classdef factorize\n%FACTORIZE an object-oriented method for solving linear systems\n% and least-squares problems, and for representing operations with the\n% inverse of a square matrix or the pseudo-inverse of a rectangular matrix.\n%\n% F = factorize(A) returns an object F that holds the factorization of a\n% non-singular matrix A. x=F\\b then solves a linear system or a\n% least-squares problem. S=inverse(F) or S=inverse(A) returns a factorized\n% representation of the inverse of A so that inverse(A)*b is mathematically\n% equivalent to inv(A)*b, but the former does not actually compute the\n% inverse of A.\n%\n% Example\n%\n% F = factorize(A) ; % LU, QR, or Cholesky factorization of A\n% x = F\\b ; % solve A*x=b; same as x=A\\b\n% S = inverse (F) ; % S represents the factorization of inv(A)\n% x = S*b ; % same as x = A\\b.\n% S = A-B*inverse(D)*C % efficiently computes the Schur complement\n% S = A-B*inv(D)*C % bad method for computing the Schur complement\n% S = inverse(A) ; S(:,1) % compute just the first column of inv(A),\n% % without computing inv(A)\n%\n% If A is square, symmetric (Hermitian for the complex case), and has a\n% real positive diagonal, then use F=factorize(A,1). If you know\n% otherwise, use F=factorize(A,0). Using this option improves performance,\n% since otherwise this condition must be checked to choose between a\n% Cholesky or LU factorization. The option is ignored if A is rectangular.\n%\n% For more details, type \"help factorize1\".\n% For a demo type \"fdemo\" or see the html/ directory.\n%\n% See also inverse, factorize1, mldivide, mrdivide, inv, pinv, linsolve\n\n% Copyright 2009, Timothy A. Davis, University of Florida\n\n properties (SetAccess = protected)\n % The factorize object holds a QR, LU, Cholesky factorization:\n A = [ ] ; % a copy of the input matrix\n L = [ ] ; % lower-triangular factor for LU and Cholesky\n U = [ ] ; % upper-triangular factor for LU\n Q = [ ] ; % Q factor for dense QR\n R = [ ] ; % R factor for QR\n p = [ ] ; % sparse row permutation matrix\n q = [ ] ; % sparse column permutation matrix\n is_inverse = false ; % F represents the factorization of A or inv(A)\n kind = 0 ; % F is one of 8 kinds of factorizations\n end\n\n methods\n\n function F = factorize (A,try_chol)\n\n % factorize constructor: compute a factorization of A\n\n if (ndims (A) > 2)\n error ('Matrix must be 2D.') ;\n end\n [m n] = size (A) ;\n F.A = A ;\n\n if (m > n)\n\n % QR factorization of A\n if (issparse (A))\n % Q-less econonmy sparse QR: (A*q)'*(A*q) = R'*R\n q = sparse (colamd (A), 1:n, 1) ;\n R = qr (A*q, 0) ;\n F.q = q ;\n F.kind = 1 ;\n else\n % dense economy QR factorization: A = Q*R\n [Q R] = qr (A,0) ;\n F.Q = Q ;\n F.kind = 2 ;\n end\n ok = (nnz (diag (R)) == n) ;\n F.R = R ;\n\n elseif (m < n)\n\n % QR factorization of A'\n if (issparse (A))\n % Q-less economy sparse QR: (p*A)*(p*A)' = R'*R\n C = A' ;\n p = sparse (1:m, colamd (C), 1) ;\n R = qr (C*p', 0) ;\n F.p = p ;\n F.kind = 3 ;\n else\n % dense economy LQ factorization: A' = Q*R\n [Q R] = qr (A',0) ;\n F.Q = Q ;\n F.kind = 4 ;\n end\n ok = (nnz (diag (R)) == m) ;\n F.R = R ;\n\n else\n\n % Cholesky or LU factorization of A\n g = 1 ;\n if (nargin == 1)\n % This is an expensive test, so skip it if the caller\n % already knows the matrix is a candidate for Cholesky.\n d = diag (A) ;\n try_chol = (all (d > 0) && nnz (imag (d)) == 0 && ...\n nnz (A-A') == 0) ;\n end\n if (try_chol)\n if (issparse (A))\n % sparse Cholesky factorization: q'*A*q = L*L'\n [L g q] = chol (A, 'lower') ;\n else\n % dense Cholesky factorization: A = R'*R\n [R g] = chol (A) ;\n end\n end\n % do an LU factorization if Cholesky failed or was skipped\n ok = (g == 0) ;\n if (ok)\n % Cholesky was successful\n if (issparse (A))\n F.L = L ;\n F.q = q ;\n F.kind = 5 ;\n else\n F.R = R ;\n F.kind = 6 ;\n end\n else\n % need an LU factorization\n if (issparse (A))\n % sparse LU factorization: p*A*q = L*U\n [L U p q] = lu (A) ;\n F.q = q ;\n F.kind = 7 ;\n else\n % dense LU factorization: p*A = L*U\n [L U p] = lu (A, 'vector') ;\n p = sparse (1:n, p, 1) ;\n F.kind = 8 ;\n end\n F.L = L ;\n F.U = U ;\n F.p = p ;\n ok = (nnz (diag (U)) == n) ;\n end\n end\n\n if (~ok)\n error ('Matrix is rank deficient.') ;\n end\n end\n end\nend\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/SuiteSparse/MATLAB_Tools/Factorize/@factorize/factorize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5998993752469844}} {"text": "function [textures] = getGLSZMtextures_temp(GLSZM)\n% -------------------------------------------------------------------------\n% function [textures] = getGLSZMtextures_temp(GLSZM)\n% -------------------------------------------------------------------------\n% DESCRIPTION:\n% This function computes texture features from an input Gray-Level Size\n% Zone Matrix (GLSZM).\n% -------------------------------------------------------------------------\n% REFERENCES:\n% [1] Galloway, M. M. (1975). Texture analysis using gray level run lengths. \n% Computer Graphics and Image Processing, 4(2), 172–179.\n% [2] Chu, A., Sehgal, C. M., & Greenleaf, J. F. (1990). Use of gray value \n% distribution of run lengths for texture analysis. Pattern Recognition\n% Letters, 11(6), 415-419.\n% [3] Dasarathy, B. V., & Holder, E. B. (1991). Image characterizations \n% based on joint gray level-run length distributions. Pattern \n% Recognition Letters, 12(8), 497-502.\n% [4] Thibault, G., Fertil, B., Navarro, C., Pereira, S., Cau, P., Levy, \n% N., Mari, J.-L. (2009). Texture Indexes and Gray Level Size Zone \n% Matrix. Application to Cell Nuclei Classification. In Pattern \n% Recognition and Information Processing (PRIP) (pp. 140–145).\n% -------------------------------------------------------------------------\n% INPUTS:\n% - GLSZM: Gray-Level Size Zone Matrix.\n%\n% ** 'GLSZM' should be the output from 'getGLSZM.m' **\n% -------------------------------------------------------------------------\n% OUTPUTS:\n% - textures: Struture specifying the values of different GLSZM texture\n% features as defined below.\n% -------------------------------------------------------------------------\n% AUTHOR(S): Martin Vallieres \n% -------------------------------------------------------------------------\n% HISTORY:\n% - Creation: January 2013\n% - Revision: May 2015\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%\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% USEFUL MATRICES, VECTORS AND QUANTITIES\nsz = size(GLSZM); % Size of GLSZM\nnRuns = sum(GLSZM(:));\ncVect = 1:sz(2); rVect = 1:sz(1);% Row and column vectors\n[cMat,rMat] = meshgrid(cVect,rVect); % Column and row indicators for each entry of the GLSZM\npg = sum(GLSZM,2)'; % Gray-Level Run-Number Vector\npr = sum(GLSZM); % Run-Length Run-Number Vector\n\n\n% COMPUTATION OF TEXTURE FEATURES\n% 1. Small Zone Emphasis (SZE), Ref.[1,4]\ntextures.SZE = (pr*(cVect.^(-2))')/nRuns;\n\n% 2. Large Zone Emphasis (LZE), Ref.[1,4]\ntextures.LZE = (pr*(cVect.^2)')/nRuns;\n\n% 3. Gray-Level Nonuniformity (GLN), adapted from Ref.[1,4]\ntextures.GLN = sum(pg.^2)/nRuns;\n\n% 4. Zone-Size Nonuniformity (ZSN), adapted from Ref.[1,4]\ntextures.ZSN = sum(pr.^2)/nRuns;\n\n% 5. Zone Percentage (ZP), adapted from Ref.[1,4]\ntextures.ZP = nRuns/(pr*cVect');\n\n% 6. Low Gray-Level Zone Emphasis (LGZE), Ref.[2,4]\ntextures.LGZE = (pg*(rVect.^(-2))')/nRuns;\n\n% 7. High Gray-Level Zone Emphasis (HGZE), Ref.[2,4]\ntextures.HGZE = (pg*(rVect.^2)')/nRuns;\n\n% 8. Small Zone Low Gray-Level Emphasis (SZLGE), Ref.[3,4]\ntextures.SZLGE = sum(sum(GLSZM.*(rMat.^(-2)).*(cMat.^(-2))))/nRuns;\n\n% 9. Small Zone High Gray-Level Emphasis (SZHGE), Ref.[3,4]\ntextures.SZHGE = sum(sum(GLSZM.*(rMat.^2).*(cMat.^(-2))))/nRuns;\n\n% 10. Large Zone Low Gray-Level Emphasis (LZLGE), Ref.[3,4]\ntextures.LZLGE = sum(sum(GLSZM.*(rMat.^(-2)).*(cMat.^2)))/nRuns;\n\n% 11. Large Zone High Gray-Level Emphasis (LZHGE), Ref.[3,4]\ntextures.LZHGE = sum(sum(GLSZM.*(rMat.^2).*(cMat.^2)))/nRuns;\n\n\n% New features according to Ref.[4]\n% GLSZM = GLSZM./nRuns; % In the future, this operation will be applied at the beginning of the function\n% pg=sum(GLSZM,2)'; pr=sum(GLSZM);\nug = (pg*rVect')/(sz(1)*sz(2));\nur = (pr*cVect')/(sz(1)*sz(2));\n\n% 12. Gray-Level Variance (GLV), adapted from Ref.[4]\nGLV = 0;\nfor g = 1:sz(1)\n for r = 1:sz(2)\n GLV = GLV + (GLSZM(g,r)*g-ug)^2;\n end\nend\ntextures.GLV = GLV/(sz(1)*sz(2));\n\n% 13. Zone-Size Variance (ZSV), adapted from Ref.[4]\nZSV = 0;\nfor g = 1:sz(1)\n for r = 1:sz(2)\n ZSV = ZSV + (GLSZM(g,r)*r-ur)^2;\n end\nend\ntextures.ZSV = ZSV/(sz(1)*sz(2));\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/FEATURES_COMPUTATIONS/getGLSZMtextures_temp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5998993752469843}} {"text": "%PARZENML Optimum smoothing parameter in Parzen density estimation.\n% \n% H = PARZENML(A)\n% \n% INPUT\t\n% A Input dataset\n%\n% OUTPUT\n% H Scalar smoothing parameter (in case of crisp labels)\n% Vector with smoothing parameters (in case of soft labels)\n%\n% DESCRIPTION\n% Maximum likelihood estimation for the smoothing parameter H in the \n% Parzen denstity estimation of the data in A. A leave-one out \n% maximum likelihood estimation is used. \n%\n% The dataset A can either be crisp or soft labeled. In case of crisp\n% labeling the class information is not used and a single smoothing \n% parameter is estimated. In case of soft labels a smoothing parameter\n% for every class is estimated and objects are weighted in relation to\n% their class weigthts (soft label value). \n% It may be profitable to scale the data before calling it. eg. \n% WS = SCALEM(A,'variance'); A = A*WS.\n% \n% SEE ALSO (PRTools Guide)\n% DATASETS, MAPPINGS, SCALEM, SELDAT, PARZENM, PARZENDC, PRPROGRESS\n\n% Copyright: R.P.W. Duin, r.p.w.duin@37steps.com\n% Faculty EWI, Delft University of Technology\n% P.O. Box 5031, 2600 GA Delft, The Netherlands\n\n% $Id: parzenml.m,v 1.11 2010/03/25 15:39:46 duin Exp $\n\nfunction h = parzenml(A,fid)\n\n\t\t\n\tif nargin < 2, fid = []; end\n\n\tif isdouble(A), A = prdataset(A); end\n\t\n\tA = testdatasize(A);\n\tA = testdatasize(A,'objects');\n\n\tif islabtype(A,'crisp')\n\t\th = parzenmlc(A,fid);\n\telseif islabtype(A,'soft')\n\t\th = parzenmls(A,fid);\n\telse\n\t\terror('Label type should be either ''crisp'' or ''soft''')\n\tend\n\t\n\treturn\n\t\nfunction h = parzenmlc(A,fid) %crisp version\n\n\t[m,k] = size(A);\n\tDD= distm(+A) + diag(1e70*ones(1,m));\n\tE = min(DD);\n\t\n\th1 = sqrt(max(E)); % initial estimate of h\n\tF1 = derlc(DD,E,h1,k); % derivative\n\n\tprprogress(fid,'parzenml:\\n');\n\tprprogress(fid,' %6.4f %6.3e\\n',h1,F1);\n\tif abs(F1) < 1e-70 \n\t\th = h1;\n\t\tprwarning(4,'jump out\\n');\n\t\treturn;\n\tend\n\t\n\ta1 = (F1+m*k)*h1*h1;\n\th2 = sqrt(a1/(m*k)); % second guess\n\tF2 = derlc(DD,E,h2,k); % derivative\n\n\tprprogress(fid,' %6.4f %6.3e\\n',h2,F2);\n\tif (abs(F2) < 1e-70) | (abs(1e0-h1/h2) < 1e-6) \n\t\th = h2;\n\t\tprwarning(4,'jump out\\n');\n\t\treturn\n\tend\n\t\n\t% find zero-point of derivative to optimize h^2\n\t% stop if improvement is small, or h does not change significantly\n\t\n\talf = 1;\n\tprwaitbar(100,'parzenml: Optimizing smoothing parameter',m > 100)\n\titer = 0;\n\twhile abs(1e0-F2/F1) > 1e-4 & abs(1e0-h2/h1) > 1e-3 & abs(F2) > 1e-70\n\t\titer = iter+1;\n\t\th3 = (h1*h1*h2*h2)*(F2-F1)/(F2*h2*h2-F1*h1*h1);\n\t\tif h3 < 0 % this should not happen\n\t\t\th3 = sqrt((F2+m*k)*h2*h2/(m*k));\n\t\telse\n\t\t\th3 = sqrt(h3);\n\t\tend\n\t\tprwaitbar(100,100-100*exp(-iter/10));\n\t\th3 = h2 +alf*(h3-h2);\n\t\tF3 = derlc(DD,E,h3,k);\n\t\tprprogress(fid,' %6.4f %6.3e\\n',h3,F3);\n\t\tF1 = F2; F2 = F3;\n\t\th1 = h2; h2 = h3;\n\t\talf = alf*0.99; % decrease step size\n\tend\n\th = h2;\n\tprwaitbar(0);\n\nreturn\n\nfunction F = derlc(DD,E,h,k) % crisp version\n\t% computation of the likelihood derivative for Parzen density\n\t% given distances D and their object minima E (for increased accuracy)\n\tm = size(DD,1);\n\twarning off MATLAB:divideByZero;\n\t\tY = (DD-repmat(E,m,1))/(2*h*h); % correct for minimum distance to save accuracy\n\twarning on MATLAB:divideByZero;\n\tIY = find(Y<20); % take small distance only, others don't contribute\n\tP = zeros(m,m);\n\tP(IY) = exp(-Y(IY));\n\tPP = sum(P,2)';\n\tFU = repmat(realmax,1,m);\n\tJ = find(PP~=0); \n\tFU(J) = 1./PP(J);\n\tFF = sum(DD.*P,2);\n\twarning off MATLAB:divideByZero;\n\t\tF = (FU*FF)./(h*h) - m*k;\n\twarning on MATLAB:divideByZero;\nreturn\n\nfunction h = parzenmls(A,fid) %soft version\n\n\tSS = gettargets(setlabtype(A,'soft'));\n\t[m,k,c] = getsize(A);\n\tDD= distm(+A) + diag(1e70*ones(1,m));\n\tE = min(DD);\n\th = zeros(c,1);\n\th0 = sqrt(max(E)); % initial estimate of h\n\t\n\t\n\ts = sprintf('parzenml: runover classes');\n\tprwaitbar(c,s,m > 100);\n\titer = 0;\n\t\n\tfor j=1:c\n\t\tprwaitbar(c,j)\n\t\tS = SS(:,j);\n\t\th1 = h0;\n\t\tF1 = derls(DD,E,h1,k,S); % derivative\n\n\t prprogress(fid,'parzenml: class %i : \\n',j);\n\t\tprprogress(fid,' %6.4f %6.3e\\n',h1,F1);\n\t\tif abs(F1) < 1e-70 \n\t\t\th(j) = h1;\n\t\t\tprwarning(4,'jump out\\n');\n\t\t\tbreak;\n\t\tend\n\t\n\t\ta1 = (F1+m*k)*h1*h1;\n\t\th2 = sqrt(a1/(m*k)); % second guess\n\t\tF2 = derls(DD,E,h2,k,S); % derivative\n\n\t\tprprogress(fid,' %6.4f %6.3e\\n',h2,F2);\n\t\tif (abs(F2) < 1e-70) | (abs(1e0-h1/h2) < 1e-6) \n\t\t\th(j) = h2;\n\t\t\tprwarning(4,'jump out\\n');\n\t\t\tbreak;\n\t\tend\n\t\n\t\t% find zero-point of derivative to optimize h^2\n\t\t% stop if improvement is small, or h does not change significantly\n\t\n\t\t\n\t\tprwaitbar(100,'parzenml: Optimizing smoothing parameter',m > 100)\n\t\titer = 0;\n\t\talf = 1;\n\t\twhile abs(1e0-F2/F1) > 1e-4 & abs(1e0-h2/h1) > 1e-3 & abs(F2) > 1e-70\n\t\t\titer = iter+1;\n\t\t\tprwaitbar(100,100-100*exp(-iter/10));\n\t\t\th3 = (h1*h1*h2*h2)*(F2-F1)/(F2*h2*h2-F1*h1*h1);\n\t\t\tif h3 < 0 % this should not happen\n\t\t\t\th3 = sqrt((F2+m*k)*h2*h2/(m*k));\n\t\t\telse\n\t\t\t\th3 = sqrt(h3);\n\t\t\tend\n\t\t\th3 = h2 +alf*(h3-h2);\n\t\t\tF3 = derls(DD,E,h3,k,S);\n\t\t\tprprogress(fid,' %6.4f %6.3e\\n',h3,F3);\n\t\t\tF1 = F2; F2 = F3;\n\t\t\th1 = h2; h2 = h3;\n\t\t\talf = alf*0.99; % decrease step size\n\t\tend\n\t\tprwaitbar(0)\n\t\th(j) = h2;\n\tend\n prwaitbar(0)\nreturn\n\nfunction F = derls(DD,E,h,k,S) %soft version\n\t% computation of the likelihood derivative for Parzen density\n\t% given distances D and their object minima E (for increased accuracy)\n\t% S are the object weigths\n\tc = size(S,2); % number of classes\n\tm = size(DD,1);\n\tY = (DD-repmat(E,m,1))/(2*h*h); % correct for minimum distance to save accuracy\n\tIY = find(Y<20); % take small distance only, others don't contribute\n\tF = 0;\n\tfor j=1:c\n\t\tP = zeros(m,m);\n\t\tP(IY) = exp(-Y(IY));\n\t\tPP = S(:,j)'*P';\n\t\tFU = repmat(realmax,1,m);\n\t\tJ = find(PP~=0); \n\t\tFU(J) = S(J,j)'./PP(J);\n\t\tK = find(S(:,j)==0);\n\t\tFU(K) = zeros(1,length(K));\n\t\tFF = (DD.*P)*S(:,j);\n\t\tF = F + (FU*FF)./(h*h);\n\tend\n\tF = F - sum(S(:))*k;\nreturn\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/prtools/parzenml.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681013541611, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5997981317391337}} {"text": "function [ Q, sumQ] = OffpolicyQlearning150816( qldata3 , gamma, alpha, numtraces)\n% OFF POLICY Q LEARNING\n\n%initialisation of variables\nsumQ=zeros(numtraces,1); %record sum of Q after each iteration\nnact=numel(unique(qldata3(:,3)))-1; %nr of actions\nncl=numel(unique(qldata3(:,2)));\nQ=zeros (ncl, nact); \nmaxavgQ=1;\nmodu=100;\nlisti=find(qldata3(:,1)==1); %position of 1st step of each episodes in dataset\nnrepi=numel(listi); %nr of episodes in the dataset\njj=1;\n\n for j=1:numtraces\n \n \n i=listi(floor(rand()*(nrepi-2))+1); %pick one episode randomly (not the last one!)\n trace = [];\n \n while qldata3(i+1,1)~=1 \n S1=qldata3(i+1,2);\n a1=qldata3(i+1,3);\n r1=qldata3(i+1,4);\n step = [ r1, S1, a1 ];\n trace = [trace ; step];\n i=i+1;\n end\n\n tracelength = length(trace(:,1));\n return_t = trace(tracelength,1); % get last reward as return for penultimate state and action.\n \n for t=tracelength-1:-1:1 %Step through time-steps in reverse order\n s = trace(t,2); % get state index from trace at time t\n a = trace(t,3); % get action index\n Q(s,a) = (1-alpha)*Q(s,a) + alpha*return_t; % update Q.\n return_t = return_t*gamma + trace(t,1); % return for time t-1 in terms of return and reward at t\n end\n \n sumQ(jj,1)=sum(sum(Q));\n jj=jj+1;\n \n if mod(j,500*modu)==0 %check if can stop iterating (when no more improvement is seen)\n% sumQ(jj,1)=sum(sum(Q));\n% jj=jj+1;\n s=mean(sumQ(j-49999:j));\n d=(s-maxavgQ)/maxavgQ;\n if abs(d)<0.001\n break %exit routine\n end\n maxavgQ=s;\n end\n \n\n end\n\n sumQ(jj:end)=[];\n \n \nend\n\n", "meta": {"author": "matthieukomorowski", "repo": "AI_Clinician", "sha": "0669f8907e65503641857ca76aa46938641e513f", "save_path": "github-repos/MATLAB/matthieukomorowski-AI_Clinician", "path": "github-repos/MATLAB/matthieukomorowski-AI_Clinician/AI_Clinician-0669f8907e65503641857ca76aa46938641e513f/OffpolicyQlearning150816.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424450764199, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.5997893900427607}} {"text": "function cond = condition_linpack ( n, a )\n\n%*****************************************************************************80\n%\n%% CONDITION_LINPACK estimates the L1 condition number of a matrix.\n%\n% Discussion:\n%\n% The R8GE storage format is used for a general M by N matrix. A storage \n% space is made for each logical entry. The two dimensional logical\n% array is mapped to a vector, in which storage is by columns.\n%\n% For the system A * X = B, relative perturbations in A and B\n% of size EPSILON may cause relative perturbations in X of size\n% EPSILON*RCOND.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 March 2004\n%\n% Author:\n%\n% Original FORTRAN77 version by Dongarra, Bunch, Moler, Stewart.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Dongarra, Bunch, Moler, Stewart,\n% LINPACK User's Guide,\n% SIAM, 1979\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix A.\n%\n% Input, real A(N,N), a matrix to be factored.\n%\n% Output, real COND, an estimate of the condition number of A.\n%\n\n%\n% Compute the L1 norm of A.\n%\n anorm = norm ( a, 1 );\n%\n% Compute the LU factorization.\n%\n [ a_lu, pivot, info ] = r8ge_fa ( n, a );\n%\n% COND = norm(A) * (estimate of norm(inverse(A))) \n%\n% estimate of norm(inverse(A)) = norm(Z) / norm(Y)\n%\n% where\n% A * Z = Y\n% and\n% A' * Y = E\n%\n% The components of E are chosen to cause maximum local growth in the\n% elements of W, where U'*W = E. The vectors are frequently rescaled\n% to avoid overflow.\n%\n% Solve U' * W = E.\n%\n ek = 1.0;\n z(1:n,1) = 0.0;\n\n for k = 1 : n\n\n if ( z(k,1) ~= 0.0 )\n ek = - r8_sign ( z(k,1) ) * abs ( ek );\n end\n\n if ( abs ( a_lu(k,k) ) < abs ( ek - z(k,1) ) )\n s = abs ( a_lu(k,k) ) / abs ( ek - z(k,1) );\n z(1:n,1) = s * z(1:n,1);\n ek = s * ek;\n end\n\n wk = ek - z(k,1);\n wkm = -ek - z(k,1);\n s = abs ( wk );\n sm = abs ( wkm );\n\n if ( a_lu(k,k) ~= 0.0 )\n wk = wk / a_lu(k,k);\n wkm = wkm / a_lu(k,k);\n else\n wk = 1.0;\n wkm = 1.0;\n end\n\n if ( k + 1 <= n )\n\n for j = k + 1 : n\n sm = sm + abs ( z(j,1) + wkm * a_lu(k,j) );\n z(j,1) = z(j,1) + wk * a_lu(k,j);\n s = s + abs ( z(j,1) );\n end\n\n if ( s < sm )\n t = wkm - wk;\n wk = wkm;\n z(k+1:n,1) = z(k+1:n,1) + t * a_lu(k,k+1:n)';\n end\n\n end\n\n z(k,1) = wk;\n\n end\n\n t = sum ( abs ( z(1:n,1) ) );\n z(1:n,1) = z(1:n,1) / t;\n%\n% Solve L' * Y = W\n%\n for k = n : -1 : 1\n\n z(k,1) = z(k,1) + a_lu(k+1:n,k)' * z(k+1:n,1);\n\n t = abs ( z(k,1) );\n\n if ( 1.0 < t )\n z(1:n,1) = z(1:n,1) / t;\n end\n\n l = pivot(k);\n\n t = z(l,1);\n z(l,1) = z(k,1);\n z(k,1) = t;\n\n end\n\n z(1:n,1) = z(1:n,1) / sum ( abs ( z(1:n,1) ) );\n\n ynorm = 1.0;\n%\n% Solve L * V = Y.\n%\n for k = 1 : n\n\n l = pivot(k);\n\n t = z(l,1);\n z(l,1) = z(k,1);\n z(k,1) = t;\n\n z(k+1:n,1) = z(k+1:n,1) + t * a_lu(k+1:n,k);\n\n if ( 1.0 < abs ( z(k,1) ) )\n ynorm = ynorm / abs ( z(k,1) );\n z(1:n) = z(1:n) / abs ( z(k,1) );\n end\n\n end\n\n s = sum ( abs ( z(1:n,1) ) );\n z(1:n,1) = z(1:n,1) / s;\n ynorm = ynorm / s;\n%\n% Solve U * Z = V.\n%\n for k = n : -1 : 1\n\n if ( abs ( a_lu(k,k) ) < abs ( z(k,1) ) )\n s = abs ( a_lu(k,k) ) / abs ( z(k,1) );\n z(1:n,1) = s * z(1:n,1);\n ynorm = s * ynorm;\n end\n\n if ( a_lu(k,k) ~= 0.0 )\n z(k,1) = z(k,1) / a_lu(k,k);\n else\n z(k,1) = 1.0;\n end\n\n z(1:k-1,1) = z(1:k-1,1) - a_lu(1:k-1,k) * z(k,1);\n\n end\n%\n% Normalize Z in the L1 norm.\n%\n s = 1.0 / sum ( abs ( z(1:n,1) ) );\n z(1:n,1) = s * z(1:n,1);\n ynorm = s * ynorm;\n\n cond = anorm / ynorm;\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/condition/condition_linpack.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5997893738262565}} {"text": "function [F,F_r,F_u] = odo3(F,u)\n\n% ODO3 3D Odometry evolution.\n% F = ODO3(F,U) performs one step on the pose F of a vehicle, given\n% odometry increments U=[DX;DV] in robot frame.\n% - F is a frame structure (see FRAME).\n% - Position increment DX is given in robot frame F.\n% - Orientation increment DV is given as a Rotation Vector in robot frame F.\n%\n% [F,F_r,F_u] = ODO3(F,U) gives the full Jacobians wrt state and odometry\n% inputs.\n%\n% See also FRAME, V2Q, QPROD, QUATERNION.\n\n% Copyright 2005-2009 Joan Sola @ LAAS-CNRS.\n\ndv = u(4:6);\ndx = u(1:3);\n\nif nargout == 1\n\n x = fromFrame(F,dx); % Position update\n\n q = F.x(4:end);\n q2 = qProd(q,v2q(dv)); % quaternion update\n\n F.x = [x;q2]; % frame update\n\n\nelse % Jacobians\n\n [x,X_r,X_dx] = fromFrame(F,dx); % Position update and jacobians\n\n q = F.x(4:end);\n [dq,DQ_dv] = v2q(dv);\n [q2,Q2_q,Q2_dq] = qProd(q,dq); % quaternion update\n Q2_dv = Q2_dq*DQ_dv;\n\n F.x = [x;q2]; % frame update\n\n F_r = [X_r;zeros(4,3) Q2_q];\n F_u = [X_dx zeros(3,3);zeros(4,3) Q2_dv];\nend\n\nF = updateFrame(F);\n\nreturn\n\n%% Jacobians\n\nsyms x y z a b c d real\nsyms dx dy dz dp dq dr real\nFi.x=[x;y;z;a;b;c;d];\nDx = [dx;dy;dz];\nDv = [dp;dq;dr];\nu = [Dx;Dv];\n\nFi = updateFrame(Fi);\n\n[F,F_r,F_u] = odo3(Fi,u);\n\nF_rs = jacobian(F.x,Fi.x);\nF_us = jacobian(F.x,[Dx;Dv]);\n\nsimplify(F_r-F_rs)\nsimplify(F_u-F_us)\n\n\n\n% ========== End of function - Start GPL license ==========\n\n\n% # START GPL LICENSE\n\n%---------------------------------------------------------------------\n%\n% This file is part of SLAMTB, a SLAM toolbox for Matlab.\n%\n% SLAMTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% SLAMTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with SLAMTB. If not, see .\n%\n%---------------------------------------------------------------------\n\n% SLAMTB is Copyright:\n% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,\n% Copyright (c) 2010-2013, Joan Sola,\n% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,\n% SLAMTB is Copyright 2009 \n% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol\n% @ LAAS-CNRS.\n% See on top of this file for its particular copyright.\n\n% # END GPL LICENSE\n\n", "meta": {"author": "joansola", "repo": "slamtb", "sha": "b4767f6bf38bceed205abb85f1aed12422c9a972", "save_path": "github-repos/MATLAB/joansola-slamtb", "path": "github-repos/MATLAB/joansola-slamtb/slamtb-b4767f6bf38bceed205abb85f1aed12422c9a972/Kinematics/odo3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5997893634236229}} {"text": "function pde = hyperIntf(am,ap,bm,bp,r,x0,y0,z0)\n%% USAGE: polynomial solution for Poisson equation\n% Last Modified: 02/21/2020 by Xu Zhang\n\n%% PDE Structure\npde = struct('intf',@intf,...\n 'exactu1',@exactu1,'exactu2',@exactu2,'exactu3',@exactu3,...\n 'um1',@um1,'um2',@um2,'um3',@um3,'up1',@up1,'up2',@up2,'up3',@up3,...\n 'Dxu',@Dxu,'Dxum',@Dxum,'Dxup',@Dxup,'Dyu',@Dyu,...\n 'Dyum',@Dyum,'Dyup',@Dyup,'Dzu',@Dzu,'Dzum',@Dzum,'Dzup',@Dzup,...\n 'f1',@f1,'f2',@f2,'f3',@f3,...\n 'fm1',@fm1,'fm2',@fm2,'fm3',@fm3,...\n 'fp1',@fp1,'fp2',@fp2,'fp3',@fp3,...\n 'A',@A,'Am',@Am,'Ap',@Ap,'one',@one,...\n 'B',@B,'Bm',@Bm,'Bp',@Bp);\n\npde.am = am;\npde.ap = ap;\npde.bm = bm;\npde.bp = bp;\n%% interface function\n function u = intf(x,y,z)\n u = ((x-x0).^2 + (y-y0).^2 - (z-z0).^2)-r;\n end\n\n%% exact solution\n function u = exactu1(x,y,z)\n u = um1(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = up1(x(id),y(id),z(id));\n end\n function u = exactu2(x,y,z)\n u = um2(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = up2(x(id),y(id),z(id));\n end\n function u = exactu3(x,y,z)\n u = um3(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = up3(x(id),y(id),z(id));\n end\n coef1 = 1; coef2 = 0; coef3 = 1;\n function u = um1(x,y,z)\n u = coef1*(z-z0) + coef3*(x-x0)/bm + coef2*intf(x,y,z).*(x-x0)/am;\n end\n function u = um2(x,y,z)\n u = coef3*(y-y0)/bm + coef2*intf(x,y,z).*(y-y0)/am;\n end\n function u = um3(x,y,z)\n u = coef1*(x-x0) - coef3*(z-z0)/bm + coef2*intf(x,y,z).*(z-z0)/am;\n end\n function u = up1(x,y,z)\n u = coef1*(z-z0) + coef3*(x-x0)/bp + coef2*intf(x,y,z).*(x-x0)/ap;\n end\n function u = up2(x,y,z)\n u = coef3*(y-y0)/bp + coef2*intf(x,y,z).*(y-y0)/ap;\n end\n function u = up3(x,y,z)\n u = coef1*(x-x0) - coef3*(z-z0)/bp + coef2*intf(x,y,z).*(z-z0)/ap;\n end\n%% Boundary Function\n function u = gD1(x,y,z)\n u = exactu1(x,y,z);\n end\n function u = gD2(x,y,z)\n u = exactu2(x,y,z);\n end\n function u = gD3(x,y,z)\n u = exactu3(x,y,z);\n end\n%% Derivative of the exact solution\n function u = Dxu(x,y,z)\n u = Dxum(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = Dxup(x(id),y(id),z(id));\n end\n function u = Dyu(x,y,z)\n u = Dyum(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = Dyup(x(id),y(id),z(id));\n end\n function u = Dzu(x,y,z)\n u = Dzum(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = Dzup(x(id),y(id),z(id));\n end\n function u = Dxum(x,y,z)\n u = 4*(y-y0).*(z-z0)/am*coef2;\n end\n function u = Dyum(x,y,z)\n u = -4*(x-x0).*(z-z0)/am*coef2;\n end\n function u = Dzum(x,y,z)\n u = zeros(size(x));\n end\n function u = Dxup(x,y,z)\n u = 4*(y-y0).*(z-z0)/ap*coef2;\n end\n function u = Dyup(x,y,z)\n u = -4*(x-x0).*(z-z0)/ap*coef2;\n end\n function u = Dzup(x,y,z)\n u = zeros(size(x));\n end\n\n%% right hand side function\n function u = f1(x,y,z)\n u = fm1(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = fp1(x(id),y(id),z(id));\n end\n function u = f2(x,y,z)\n u = fm2(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = fp2(x(id),y(id),z(id));\n end\n function u = f3(x,y,z)\n u = fm3(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = fp3(x(id),y(id),z(id));\n end\n\n function u = fm1(x,y,z)\n u = 4*(x-x0)*coef2 + bm*um1(x,y,z);\n end\n function u = fm2(x,y,z)\n u = 4*(y-y0)*coef2 + bm*um2(x,y,z);\n end\n function u = fm3(x,y,z)\n u = -8*(z-z0)*coef2 + bm*um3(x,y,z);\n end\n function u = fp1(x,y,z)\n u = 4*(x-x0)*coef2 + bp*up1(x,y,z);\n end\n function u = fp2(x,y,z)\n u = 4*(y-y0)*coef2 + bp*up2(x,y,z);\n end\n function u = fp3(x,y,z)\n u = -8*(z-z0)*coef2 + bp*up3(x,y,z);\n end\n\n%% Diffusion coefficient function\n function u = A(x,y,z)\n u = Am(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = Ap(x(id),y(id),z(id));\n end\n function u = Am(x,y,z)\n u = am*ones(size(x));\n end\n function u = Ap(x,y,z)\n u = ap*ones(size(x));\n end\n\n%% Mass coefficient function\n function u = B(x,y,z)\n u = Bm(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = Bp(x(id),y(id),z(id));\n end\n function u = Bm(x,y,z)\n u = bm*ones(size(x));\n end\n function u = Bp(x,y,z)\n u = bp*ones(size(x));\n end\n\n%% Other function\n function u = one(x,y,z)\n u = ones(size(x));\n end\nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/IVEM/hyperIntf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424256566558, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5997893606698259}} {"text": "function a_inverse = r8ge_inverse ( n, a_lu, pivot )\n\n%*****************************************************************************80\n%\n%% R8GE_INVERSE computes the inverse of a matrix factored by R8GE_FA.\n%\n% Discussion:\n%\n% The R8GE storage format is used for a general M by N matrix. A storage \n% space is made for each logical entry. The two dimensional logical\n% array is mapped to a vector, in which storage is by columns.\n%\n% R8GE_INVERSE is a simplified standalone version of the LINPACK routine\n% R8GEDI.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 March 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix A.\n%\n% Input, real A_LU(N,N), the factor information computed by R8GE_FA.\n%\n% Input, integer PIVOT(N), the pivot vector from R8GE_FA.\n%\n% Output, real A_INVERSE(N,N), the inverse matrix.\n%\n a_inverse(1:n,1:n) = a_lu(1:n,1:n);\n%\n% Compute Inverse(U).\n%\n for k = 1 : n\n\n a_inverse(k,k) = 1.0E+00 / a_inverse(k,k);\n a_inverse(1:k-1,k) = -a_inverse(1:k-1,k) * a_inverse(k,k);\n\n for j = k + 1 : n\n\n temp = a_inverse(k,j);\n a_inverse(k,j) = 0.0E+00;\n a_inverse(1:k,j) = a_inverse(1:k,j) + a_inverse(1:k,k) * temp;\n\n end\n\n end\n%\n% Form Inverse(U) * Inverse(L).\n%\n for k = n - 1 : -1 : 1\n\n work(k+1:n) = a_inverse(k+1:n,k);\n a_inverse(k+1:n,k) = 0.0E+00;\n\n for j = k + 1 : n\n a_inverse(1:n,k) = a_inverse(1:n,k) + a_inverse(1:n,j) * work(j);\n end\n\n if ( pivot(k) ~= k )\n\n for i = 1 : n\n t = a_inverse(i,k);\n a_inverse(i,k) = a_inverse(i,pivot(k));\n a_inverse(i,pivot(k)) = t;\n end\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/linplus/r8ge_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959545, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.5997881359282241}} {"text": "% MATLAB computation of pulse transformer model - DS Method\n% File: c:\\M_files\\shortcuts\\xfrmrds2.m\n% 9/19/02; 4/17/04; 2/15/07\n% \ntic;clc;clear;\nK=1e3;pF=1e-12;mH=1e-3;uH=1e-6;ns=1e-9;ps=1e-12; % unit suffixes\n%\n% Components\n%\nR1=10;R2=1.5;R3=20*K;R4=1.5;R5=1*K;R6=0.5;R7=1;\nC1=20*pF;C2=5*pF;C3=20*pF;L1=1*uH;L2=2*mH;L3=1*uH;\n%\n% Get A, B, D, & E arrays; this function called only once.\n%\nNom=[R1 R2 R3 R4 R5 R6 R7 C1 C2 C3 L1 L2 L3];\n[A,B,D,E,I]=tfrmr2(Nom);\n%\n% * * * * * * * * * * * * Frequency response * * * * * * * * * * * *\n%\nEin=10; % Change Ein from 1V to 10V.\n%\nBF=2;ND=6;PD=50;NP=ND*PD+1;L=linspace(BF,BF+ND,NP);\n%\n% Since the output is vC3, we dont need the D and E arrays. \n% The cv output below is [vC1 vC2 vC3 iL1 iL2 iL3]'\n% (a column vector). Hence we need vC3 or cv(3).\n%\nfor i=1:NP\n F=10^L(i);s=2*pi*F*j;\n cx=(s*I-A)\\B*Ein;\n% cy=D*cx+E*Ein; % cy not used \n Vo=abs(cx(3)); % vC3 = Vo\n Vf(i)=20*log10(Vo); \nend\n%\n% * * * * * * * * * * * * * Transient response * * * * * * * * * * * \n%\nTx=1/max(max(abs(A)));\ndisp('Shortest circuit time constant');Tx\n%Per=input('Sweep time? (sec)');\n% set Sweep time to 200ns = 200e-9 to match Spice run.\nPer=200*ns;\nkmax=1e5; % kmax increased due to fast time constant Tx\ndt = 2*ps\nN=6;\n%dt=Per/kmax;N=6;\nt1=linspace(0,Per,kmax);IV=zeros(N,kmax);\n%\n% input ramp parameters\n%\np=Ein/(5*dt);b=6*dt;pw=5e4*dt;c=pw+6*dt;d=pw+11*dt;\nEa1=ramp1(p,t1(1),dt)-ramp1(p,t1(1),b)-ramp1(p,t1(1),c)+ramp1(p,t1(1),d);\n% initialize k = 1\nIV(:,1)=B*Ea1*dt;\n%\n% iterate for k = 2,3,...kmax\n%\nfor k=2:kmax\n Eak=ramp1(p,t1(k),dt)-ramp1(p,t1(k),b)-ramp1(p,t1(k),c)+ramp1(p,t1(k),d);\n IV(:,k)=A*IV(:,k-1)*dt+B*Eak*dt+IV(:,k-1);\nend\n%\n% Plot frequency response\n%\nsubplot(2,1,1)\nh=plot(L,Vf,'k');\nset(h,'LineWidth',2);\ngrid on;\naxis([BF BF+ND -40 30]);\nXT=linspace(BF,BF+ND,7);\nset(gca,'xtick',XT);\nylabel('dBV');title('AC Output Vc3');\nxlabel('Log Freq(Hz)');\n%\n% Plot time response\n%\nsubplot(2,1,2)\nh=plot(t1/ns,IV(1,:),'k',t1/ns,IV(3,:),'r');\nset(h,'LineWidth',2);\naxis auto\ngrid on;ylabel('Volts');title('Transient response, Vc1 & Vc3');\nxlabel('nsec');\nlegend('Vc1','Vc3');\n\nfigure(1) % display plot on screen.\n%\ndisp(' ');disp('Execution time in seconds');\nET=toc\n \n\n\n\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/2435-shortcut-state-space-circuit-analysis/Matlab_Files/xfrmrds2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450964, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5996953857188386}} {"text": "%ADABOOSTC\n%\n% [W,V,ALF] = ADABOOSTC(A,CLASSF,N,RULE,VERBOSE);\n%\n% INPUT\n% A Dataset\n% CLASSF Untrained weak classifier\n% N Number of classifiers to be trained\n% RULE Combining rule (default: weighted voting)\n% VERBOSE Suppress progress report if 0 (default)\n%\n% OUTPUT\n% W Combined trained classifier\n% V Cell array of all classifiers\n% Use VC = stacked(V) for combining\n% ALF Weights\n%\n% DESCRIPTION\n%\n% Computation of a combined classifier according to adaboost.\n%\n% In total N weighted versions of the training set A are generated\n% iteratevely and used for the training of the specified classifier.\n% Weights, to be used for the probabilities of the objects in the training\n% set to be selected, are updated according to the Adaboost rule.\n%\n% The entire set of generated classifiers is given in V.\n% The set of classifier weigths, according to Adaboost is returned in ALF\n%\n% Various aggregating possibilities can be given in \n% the final parameter rule:\n% []: WVOTEC, weighted voting.\n% VOTEC voting\n% MEANC sum rule\n% AVERAGEC averaging of coeffients (for linear combiners)\n% PRODC product rule\n% MAXC maximum rule\n% MINC minimum rule\n% MEDIANC median rule\n%\n% REFERENCE\n% Ji Zhu, Saharon Rosset, Hui Zhou and Trevor Hastie, \n% Multiclass Adaboost. A multiclass generalization of the Adaboost \n% algorithm, based on a generalization of the exponential loss.\n% http://www-stat.stanford.edu/~hastie/Papers/samme.pdf\n%\n% SEE ALSO (PRTools Guide)\n% MAPPINGS, DATASETS\n\n% Copyright: R.P.W. Duin, r.p.w.duin@37steps.com\n% Faculty EWI, Delft University of Technology\n% P.O. Box 5031, 2600 GA Delft, The Netherlands\n% (Multiclass correction by Marcin Budka, Bournemouth Univ., UK)\n\n%function [W,V,alf] = adaboostc(a,clasf,n,rule,verbose)\nfunction [out,V,alf] = adaboostc(varargin)\n\n%% INITIALISATION\nargin = setdefaults(varargin,[],nmc,100,[],0);\nif mapping_task(argin,'definition')\n \n out = define_mapping(argin,'untrained','Adaboost');\n \n%% TRAINING\nelseif mapping_task(argin,'training')\n \n [a,clasf,n,rule,verbose] = deal(argin{:});\n [m,k,c] = getsize(a);\n V = [];\n laba = getlab(a);\n u = ones(m,1)/m;\t\t\t% initialise object weights\n alf = zeros(1,n);\t\t\t% space for classifier weights\n isseparable = 0; % check if we can make 0 error\n if verbose && k == 2\n figure(verbose);\n scatterd(a);\n end\n\n %% generate n classifiers\n for i = 1:n\n b = gendatw(a,u,m); % sample training set\n b = setprior(b,getprior(a));\t% use original priors\n w = b*clasf; % train weak classifier\n ra = a*w; % test weak classifier\n\n if verbose && k == 2\n plotc(w,1); drawnow\n end\n\t\n labc = labeld(ra);\n diff = sum(labc~=laba,2)~=0;\t% objects erroneously classified\n erra = sum((diff).*u); % weighted error on original dataset\n\n if (erra==0)\n isseparable = 1;\n V = w;\n break;\n end\n if (erra < (1-1/c)) % if classifier better then random guessing...\n alf(i) = 0.5*(log((1-erra)/erra) + log(c-1));\n correct = find(diff==0); % find correctly classified objects\n wrong = find(diff==1); % find incorrectly classified objects\n u(correct) = u(correct)*exp(-alf(i));\t% give them the ...\n u(wrong) = u(wrong)*exp(alf(i));\t \t% proper weights\n u = u./sum(u); % normalize weights\n else\n alf(i) = 0;\n end\n\t\n if verbose\n disp([erra alf(i) sum(alf)])\n end\n V = [V w]; % store all classifiers\n\n end\n\n %% combine and return\n if isseparable\n W = V;\n W = setname(W,['Boosted ',getname(V)]);\n else\n if isempty(rule)\n W = wvotec(V,alf); % default is weighted combiner\n else\n W = traincc(a,V,rule); % otherwise, use user supplied combiner\n end\n end\n\n if verbose > 0 && k == 2\n plotc(W,'r',3)\n ee = a*W*testc;\n title(['Error: ', num2str(ee)]);\n end\n \n out = W;\n\nelse\n error('Illegal call')\nend\n\nreturn\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/prtools/adaboostc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5995946891879435}} {"text": "function [U_final, V_final, nIter_final, objhistory_final] = GNMF(X, k, W, options, U, V)\n% Graph regularized Non-negative Matrix Factorization (GNMF)\n%\n% where\n% X\n% Notation:\n% X ... (mFea x nSmp) data matrix \n% mFea ... number of words (vocabulary size)\n% nSmp ... number of documents\n% k ... number of hidden factors\n% W ... weight matrix of the affinity graph \n%\n% options ... Structure holding all settings\n% options.alpha ... the regularization parameter. \n% [default: 100]\n% alpha = 0, GNMF boils down to the ordinary NMF. \n% \n%\n% You only need to provide the above four inputs.\n%\n% X = U*V'\n%\n% References:\n% [1] Deng Cai, Xiaofei He, Xiaoyun Wu, and Jiawei Han. \"Non-negative\n% Matrix Factorization on Manifold\", Proc. 2008 Int. Conf. on Data Mining\n% (ICDM'08), Pisa, Italy, Dec. 2008. \n%\n% [2] Deng Cai, Xiaofei He, Jiawei Han, Thomas Huang. \"Graph Regularized\n% Non-negative Matrix Factorization for Data Representation\", IEEE\n% Transactions on Pattern Analysis and Machine Intelligence, , Vol. 33, No.\n% 8, pp. 1548-1560, 2011. \n%\n%\n% version 2.0 --April/2009 \n% version 1.0 --April/2008 \n%\n% Written by Deng Cai (dengcai AT gmail.com)\n%\n\nif min(min(X)) < 0\n error('Input should be nonnegative!');\nend\n\nif ~isfield(options,'error')\n options.error = 1e-5;\nend\nif ~isfield(options, 'maxIter')\n options.maxIter = [];\nend\n\nif ~isfield(options,'nRepeat')\n options.nRepeat = 10;\nend\n\nif ~isfield(options,'minIter')\n options.minIter = 30;\nend\n\nif ~isfield(options,'meanFitRatio')\n options.meanFitRatio = 0.1;\nend\n\nif ~isfield(options,'alpha')\n options.alpha = 100;\nend\n\nnSmp = size(X,2);\n\nif isfield(options,'alpha_nSmp') && options.alpha_nSmp\n options.alpha = options.alpha*nSmp; \nend\n\nif isfield(options,'weight') && strcmpi(options.weight,'NCW')\n feaSum = full(sum(X,2));\n D_half = X'*feaSum;\n X = X*spdiags(D_half.^-.5,0,nSmp,nSmp);\nend\n\nif ~isfield(options,'Optimization')\n options.Optimization = 'Multiplicative';\nend\n\nif ~exist('U','var')\n U = [];\n V = [];\nend\n\nswitch lower(options.Optimization)\n case {lower('Multiplicative')} \n [U_final, V_final, nIter_final, objhistory_final] = GNMF_Multi(X, k, W, options, U, V);\n otherwise\n error('optimization method does not exist!');\nend\n\n\n \n ", "meta": {"author": "ZJULearning", "repo": "MatlabFunc", "sha": "97504df0f597c1980ab76ddc0c9c5d669043c6c9", "save_path": "github-repos/MATLAB/ZJULearning-MatlabFunc", "path": "github-repos/MATLAB/ZJULearning-MatlabFunc/MatlabFunc-97504df0f597c1980ab76ddc0c9c5d669043c6c9/MatrixFactorization/GNMF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5995753297744444}} {"text": "function [rq,rqSS,diagnostics] = realized_quantile_variance(price,time,timeType,samplingType,samplingInterval,quantiles,blockSize,symmetric,overlap,subsamples)\n% Computes the Quantile Realized Variance of Christensen, Oomen and Podolskij (2008), the MinRV and\n% MedRV estimator of Andersen, Dobrev and Shaumberg and the general symmetrized version suggested by\n% Sheppard in a discussion of COP \n%\n% USAGE:\n% [RQ] = realized_quantile_variance(PRICE,TIME,TIMETYPE,SAMPLINGTYPE,SAMPLINGINTERVAL,QUANTILES,BLOCKSIZE)\n% [RQ,RQSS,DIAGNOSTICS] = realized_quantile_variance(PRICE,TIME,TIMETYPE,SAMPLINGTYPE,SAMPLINGINTERVAL,QUANTILES,BLOCKSIZE,SYMMETRIC,OVERLAP,SUBSAMPLES)\n%\n% INPUTS:\n% PRICE - m by 1 vector of high frequency prices\n% TIME - m by 1 vector of times where TIME(i) corresponds to PRICE(i)\n% TIMETYPE - String describing the way times are measured\n% 'wall' 24-hour clock of the form HHMMSS, e.g. 101543 or 153217\n% 'seconds' Time measured in seconds past midnight on the first day.\n% 'unit' Unit normalized date format, e.g. .1, .234, .9\n% Unit normalized times are more general than the other types and can be\n% applied to data from more than one calendar day\n% SAMPLINGTYPE - String describing the type of sampling to use when\n% filtering PRICE\n% 'CalendarTime' - Sample in calendar time using observations separated by\n% SAMPLINGINTERVAL seconds\n% 'CalendarUniform' - Sample in calendar time using SAMPLINGINTERVAL\n% observations spread uniformly between TIME(1) and TIME(m)\n% 'BusinessTime' - Sample in business (tick) time using observation separated\n% by SAMPLINGINTERVALticks\n% 'BusinessUniform' - Sample in business (tick) time using observations\n% uniformly spaced in business time.\n% 'Fixed' - Sample at specific points in time. When using fixed,\n% SAMPLINGINTERVAL must be a n by 1 vector of times with the same TIMETYPE\n% as TIME (i.e. seconds if TIME is in seconds)\n% SAMPLINGINTERVAL - Scalar integer or n by 1 vector whose meaning depends on the selected SAMPLINGTYPE\n% QUANTILES - k by 1 vector of quantile values to use when computing RQ.\n% When SYMMETRIC = false, 0.510\n error('Seven to ten inputs required.')\nend\nswitch nargin\n case 7\n symmetric = false;\n overlap = true;\n subsamples = 1;\n case 8\n overlap = true;\n subsamples = 1;\n case 9\n subsamples = 1;\nend\n\n\nif size(price,2)>size(price,1)\n price=price';\nend\nif size(price,2)>1\n error('PRICE must be a m by 1 vector.')\nend\nif size(time,2)>size(time,1)\n time=time';\nend\nif any(diff(time)<0)\n error('TIME must be sorted and increasing')\nend\nif size(time,2)>1 || length(time)~=length(price)\n error('TIME must be a m by 1 vector.')\nend\n% Inserted to protect against inputing integer times\ntime = double(time);\n\ntimeType=lower(timeType);\nif ~ismember(timeType,{'wall','seconds','unit'})\n error('TIMETYPE must be one of ''wall'', ''seconds'' or ''unit''.');\nend\nsamplingType=lower(samplingType);\nif ~ismember(samplingType,{'calendartime','calendaruniform','businesstime','businessuniform','fixed'})\n error('SAMPLINGTYPE must be one of ''CalendarTime'', ''CalendarUniform'', ''BusinessTime'', ''BusinessUniform'' or ''Fixed''.');\nend\n\nm=size(price,1);\nt0=time(1);\ntT=time(m);\nif ismember(samplingType,{'calendartime','calendaruniform','businesstime','businessuniform'})\n % Must be a scalar integer\n if ~isscalar(samplingInterval) || floor(samplingInterval)~=samplingInterval || samplingInterval<1\n error('SAMPLINGINTERVAL must be a positive integer for the SAMPLINGTYPE selected.')\n end\nelse\n if size(samplingInterval,2)>size(samplingInterval,1)\n samplingInterval=samplingInterval';\n end\n if ~(any(samplingInterval>=t0) && any(samplingInterval<=tT))\n error('At least one sampling interval must be between min(TIME) and max(TIME) when using ''Fixed'' as SAMPLINGTYPE.')\n end\n if any(diff(samplingInterval)<=0)\n error('When using ''Fixed'' as SAMPLINGTYPE the vector of sampling times in SAMPLINGINTERVAL must be sorted and strictly increasing.')\n end\nend\n\n% SAMPLERPERBIN, positive integer >=2\nif blockSize<1 || floor(blockSize)~=blockSize\n error('SAMPLESPERBIN must be a positive integer greater than or equal to 2 (and usually at least 20)')\nend\n\n% SYMMETRIC\nif isempty(symmetric)\n symmetric = false;\nend\nif ~isscalar(symmetric)\n error('SYMMETRIC must be a scalar logical value.')\nend\nsymmetric = logical(symmetric);\n\n% QUANTILES\nif symmetric\n if any(quantiles<=0) || any(quantiles>1) || length(quantiles)>blockSize || length(unique(quantiles*blockSize)) ~= length(quantiles)\n error('QUANTILES must be unique, greater than 0 and less than or equal to 1, and the number of quantiles must be smaller than SAMPLESPERBIN when SYMMETRIC = true.')\n end\nelse\n if any(quantiles<=0.5) || any(quantiles>1) || length(quantiles)>(blockSize/2) || length(unique(quantiles*blockSize)) ~= length(quantiles)\n error('QUANTILES must be unique, greater than 0.5 and less than or equal to 1, and the number of quantiles must be smaller than 0.5*SAMPLESPERBIN when SYMMETRIC = false.')\n end\nend\n\n% OVERLAP\nif isempty(overlap)\n overlap = true;\nend\nif ~isscalar(overlap)\n error('OVERLAP must be a scalar logical value.')\nend\noverlap = logical(overlap);\n\n% SUBSAMPLES\nif isempty(subsamples)\n subsamples = 1;\nend\nif ~isscalar(subsamples) || subsamples<0 || floor(subsamples)~=subsamples\n error('SUBSAMPLES must be a non-negative integer.')\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% 1. Compute returns\nlogPrice = log(price);\nfilteredLogPrice = realized_price_filter(logPrice,time,timeType,samplingType,samplingInterval);\nreturns = diff(filteredLogPrice);\n% Check that the number of returns is compatible with SAMPLESPERBIN\nn=length(returns);\nif ~overlap\n if floor(n/blockSize)~=(n/blockSize)\n error(['The number of returns computed from the prices returned from realized_price_filter(PRICE,TIME,TIMETYPE,SAMPLINGTYPE,SAMPLINGINTERVAL) must be an integer multiple of SAMPLESPERBIN. The number of return produced is ' num2str(n)]);\n end\nend\n\nif overlap\n binStart = 1:n-blockSize+1;\nelse\n binStart = 1:blockSize:n;\nend\nreturns = returns * sqrt(n);\nif symmetric\n returns = abs(returns);\nend\nq = length(quantiles);\nrqindiv = zeros(length(binStart),q);\n\n\n\n% Compute the indices to use\nif symmetric\n indices = round(quantiles*blockSize);\nelse\n upperIndices = round(quantiles*blockSize);\n lowerIndices = round((1-quantiles)*blockSize+1);\nend\n% Loop over the bins\n\n\n\ncount = 1;\nfor j=binStart\n binreturns = returns(j:j+blockSize-1);\n binreturns = sort(binreturns)';\n if symmetric\n rqindiv(count,:)=binreturns(indices).^2;\n else\n rqindiv(count,:)=binreturns(lowerIndices).^2+binreturns(upperIndices).^2;\n end\n count = count + 1;\nend\nrqindiv = mean(rqindiv);\n\n[rq,rqindiv,rqcov,rqweights] = realized_quantile_variance_core(rqindiv,blockSize,quantiles,symmetric);\n\ndiagnostics.rqindiv = rqindiv;\ndiagnostics.rqcov = rqcov;\ndiagnostics.rqweights = rqweights;\n\n\nsubsampledLogPrice = realized_subsample(logPrice,time,timeType,samplingType,samplingInterval,subsamples);\nrqindiv = nan(subsamples * length(binStart),q);\ncount = 1;\nfor i=1:subsamples\n filteredLogPrice = subsampledLogPrice{i};\n returns = diff(filteredLogPrice);\n n = length(returns);\n returns = returns * sqrt(n);\n if symmetric\n returns = abs(returns);\n end\n binStart = 1:n-blockSize+1;\n for j=binStart\n binreturns = returns(j:j+blockSize-1);\n binreturns = sort(binreturns)';\n if symmetric\n rqindiv(count,:)=binreturns(indices).^2;\n else\n rqindiv(count,:)=binreturns(lowerIndices).^2+binreturns(upperIndices).^2;\n end\n count = count + 1;\n end\nend\nrqindiv = rqindiv(1:count-1,:);\nrqindiv = mean(rqindiv);\n\n[rqSS,rqindivSS] = realized_quantile_variance_core(rqindiv,blockSize,quantiles,symmetric);\ndiagnostics.rqindivSS = rqindivSS;\n\nend\n\n\nfunction [rq,rqindiv,rqcov,rqweights] = realized_quantile_variance_core(rqindiv,blockSize,quantiles,symmetric)\n\nscales = load('realized_quantile_scales');\nif symmetric\n simulationBlockSize = scales.symmetricSimulationSamplerperbin;\n simulationCovariance = scales.symmetricExpectedCovariance;\n simulationExpectedQuantiles = scales.symmetricExpectedQuantiles;\n simulationQuantile = scales.symmetricSimulationQuantile;\nelse\n simulationBlockSize = scales.asymmetricSimulationSamplerperbin;\n simulationCovariance = scales.asymmetricExpectedCovariance;\n simulationExpectedQuantiles = scales.asymmetricExpectedQuantiles;\n simulationQuantile = scales.asymmetricSimulationQuantile;\n \nend\nsimulationBlockSize = cell2mat(simulationBlockSize);\nif ismember(blockSize,simulationBlockSize )\n % If available load and use the pre-computed value\n \n \n [~,pl]=ismember(blockSize,simulationBlockSize);\n thisScale = simulationExpectedQuantiles{pl};\n thisQuantile = simulationQuantile{pl};\n thisCovariance = simulationCovariance{pl};\n q = length(quantiles);\n indicator = zeros(1,q);\n for i = 1:q\n [~,indicator(i)] = min(abs(thisQuantile-quantiles(i)));\n end\n rqExpectedSquaredQuantileValue = thisScale(indicator);\n % Find index\n rqcov = thisCovariance(indicator,indicator);\n rqCovInv = rqcov \\ eye(q);\n rqweights = rqCovInv*ones(q,1)/(ones(1,q)*rqCovInv*ones(q,1));\nelse\n % Need to simulate using 1,000,000 simulations\n if blockSize>100\n warning('oxfordRealized:realizedQuantileVariance','Computing the scales needed. Since SAMPLESPERBIN is very large this may take a long time. \\nConsider pre-computing this value, especially if using this value of SAMPLESPERBIN many times.')\n else\n warning('oxfordRealized:realizedQuantileVariance','Computing the scales needed. \\nConsider pre-computing this value, especially if using this value of SAMPLESPERBIN many times.')\n end\n [rqExpectedSquaredQuantileValue,rqweights,rqcov]=realized_quantile_variance_scale(adjSamplesPerBin,quantiles,1000000);\nend\n\n\nrqindiv = rqindiv ./ rqExpectedSquaredQuantileValue;\nrq = rqweights'*rqindiv';\nend", "meta": {"author": "bashtage", "repo": "mfe-toolbox", "sha": "9622b6c546bc6d649fd9bf0a36a7fcd53872e04a", "save_path": "github-repos/MATLAB/bashtage-mfe-toolbox", "path": "github-repos/MATLAB/bashtage-mfe-toolbox/mfe-toolbox-9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/realized/realized_quantile_variance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.599575320001054}} {"text": "classdef LossSmoothL1 < dagnn.Loss\n%LossSmoothL1 Smooth L1 loss\n% `LossSmoothL1.forward({x, x0, w})` computes the smooth L1 distance \n% between `x` and `x0`, weighting the elements by `w`.\n%\n% Here the smooth L1 loss between two vectors is defined as:\n%\n% Loss = sum_i f(x_i - x0_i) w_i.\n%\n% where f is the function (following the Faster R-CNN definition):\n%\n% { 0.5 * sigma^2 * delta^2, if |delta| < 1 / sigma^2,\n% f(delta) = {\n% { |delta| - 0.5 / sigma^2, otherwise.\n%\n% In practice, `x` and `x0` can pack multiple instances as 1 x 1 x C\n% x N arrays (or simply C x N arrays).\n\n properties\n sigma = 1.\n end\n\n methods\n function outputs = forward(obj, inputs, params)\n sigma2 = obj.sigma^2 ;\n delta = inputs{1} - inputs{2} ;\n absDelta = abs(delta) ;\n\n linearRegion = (absDelta > 1. / sigma2) ;\n absDelta(linearRegion) = absDelta(linearRegion) - 0.5/sigma2 ;\n absDelta(~linearRegion) = 0.5 * sigma2 * absDelta(~linearRegion).^2 ;\n\n % Mutliply by instance weights and sum.\n outputs{1} = inputs{3}(:)' * absDelta(:) ;\n\n % Accumulate loss statistics.\n if obj.ignoreAverage, return; end;\n n = obj.numAveraged ;\n m = n + gather(sum(inputs{3}(:))) + 1e-9 ;\n obj.average = (n * obj.average + gather(outputs{1})) / m ;\n obj.numAveraged = m ;\n end\n\n function [derInputs, derParams] = backward(obj, inputs, params, derOutputs)\n % Function derivative:\n %\n % { sigma^2 * x, if |x| < 1 / sigma^2,\n % f'(x) = {\n % { sign(x), otherwise.\n\n sigma2 = obj.sigma^2 ;\n delta = inputs{1} - inputs{2} ;\n absDelta = abs(delta) ;\n\n linearRegion = (absDelta > 1. / sigma2) ;\n delta(linearRegion) = sign(delta(linearRegion));\n delta(~linearRegion) = sigma2 * delta(~linearRegion) ;\n\n derInputs = {inputs{3} .* delta .* derOutputs{1}, [], []} ;\n derParams = {} ;\n end\n\n function obj = LossSmoothL1(varargin)\n obj.load(varargin) ;\n obj.loss = 'smoothl1';\n end\n end\nend\n", "meta": {"author": "phoenix104104", "repo": "LapSRN", "sha": "95154bba82a3aab9bdaec8e0eedd4187babc5ed2", "save_path": "github-repos/MATLAB/phoenix104104-LapSRN", "path": "github-repos/MATLAB/phoenix104104-LapSRN/LapSRN-95154bba82a3aab9bdaec8e0eedd4187babc5ed2/matconvnet/examples/fast_rcnn/+dagnn/LossSmoothL1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.599572804207929}} {"text": "function [ccg,ic] = chXcorr(hc_L,hc_R,fs,varargin)\n%CHXCORR Calculate cross-correlograms with a wide range of options.\n% \n% CCG = IOSR.AUDITORY.CHXCORR(HC_L,HC_R,FS) cross-correlates the input\n% 2-D matrices HC_L and HC_R over 10ms frame with a maximum lag of 1ms.\n% It is assumed that the number of frequency channels is min(size(HC_L))\n% and hence HC_L and HC_R can be in either orientation. The\n% cross-correlograms consist of cross-correlations for every frame and\n% frequency channel. CCG has dimensions [lag,frequency,frame]. The\n% function calculates running cross-correlations for every sample and\n% integrates these cross-correlations over each frame. The number of\n% frames frame_count is calculated thus:\n% \n% frame_count = ...\n% floor((max(size(hc_L))-maxlag-1)/frame_length);\n% \n% The underlying cross-correlation algorithm is based on that proposed by\n% Faller & Merimaa [1]. In this implmentation, the time constant of the\n% backward infinite exponential window is given by tau (in samples).\n% \n% CCG = IOSR.AUDITORY.CHXCORR(HC_L,HC_R,FS,'PARAMETER',VALUE) allows a\n% number of options to be specified. The options are:\n% \n% ({} indicates the default value)\n% \n% 'frame_length' : {round(0.01*fs)} | scalar\n% The length of frames used to calculate for integrating\n% cross-correlations.\n% 'noverlap' : {1} | scalar\n% The number of frames over which to integrate the\n% cross-correlations. Note that the frame count is reduced\n% accordingly.\n% 'maxlag' : {round(0.001*fs)} | scalar\n% The maximum lag of the cross-correlation.\n% 'tau' : {round(0.01*fs)} | scalar\n% The time constant of the exponential window used to calculate\n% running cross-correlations. It is recommended that if norm_flag = 1\n% then tau >> 1. As can be seen below, as tau -> 1 then \n% [aL(m,i,n?1), aR(m,i,n?1)] -> 0, and hence c(m,i,n) -> 1.\n% 'inhib' : {[]} | array\n% Specificies an array with which to multiply the cross-correlations\n% before they are integrated. The value defaults to an empty array,\n% meaning that no inhibition will be applied.\n% 'ic_t' : {0} | scalar\n% Specifies the interaural coherence (IC) threshold. Only samples for\n% which the IC exceeds this threshold will be used to integrate\n% cross-correlations. The algorithm calculates Interaural Coherence\n% (IC) according to [1]. The value should be in the range [0,1].\n% 'norm_flag' : {0} | scalar\n% Specifies whether the cross-correlograms are calculated using\n% normalised cross-correlations. A non-zero value indicates that\n% normalised cross-correlations are used.\n% 'inhib_mode' : {'subtract'} | 'multiply'\n% Specify how the inhibition is applied. The default 'subtract' will\n% subtract inhib from the running cross-correlations (negative values\n% are set to zero); 'multiply' will multiply inhib with the running\n% cross-correlations.\n% \n% [CCG,IC] = IOSR.AUDITORY.CHXCORR(...) returns the calculated IC to the\n% matrix IC. Although the matrix returned is the same size as hc_L, IC is\n% only calculated for samples 1:frame_count*frame_length, other values\n% will be set to 0.\n% \n% Algorithm\n% \n% The running normalised cross-correlation is calculated as [1]:\n% \n% C(m,i,n) = c(m,i,n) / sqrt( aL(m,i,n) * aR(m,i,n)\n% \n% where\n% \n% c(m,i,n) = (1/tau) * HC_L(i, max(n+m,n)) * HC_R(i, max(n-m,n)) + ...\n% (1-1/tau) * c(m,i,n-1),\n% \n% aL(m,i,n) = (1/tau) * (HC_L(i, max(n+m,n)))^2 + ...\n% (1-1/tau) * aL(m,i,n-1),\n% \n% aR(m,i,n) = (1/tau) * (HC_R(i, max(n+m,n)))^2 + ...\n% (1-1/tau) * aR(m,i,n-1),\n% \n% i is the frequency index, m is the lag index, and n is the sample\n% index. The running (non-normalised) cross-correlation is calculated is\n% simply c(m,i,n).\n% \n% The interaural coherence is\n% \n% IC(i,n) = max(C(m,i,n)) % (i.e. over m)\n% \n% The cross-correlogram is calculated as the sum of cross- correlations\n% in a given frame:\n% \n% CCG(m,i,j) = sum(C(m,i,J),3)\n% \n% where\n% \n% J = (j-1) * frame_length + 1 : j * frame_length\n% \n% References\n% \n% [1] C. Faller and J. Merimaa, \"Source localization in complex listening\n% situations: Selection of binaural cues based on interaural\n% coherence\", The Journal of the Acoustical Society of America, vol.\n% 116, pp.3075-3089, Nov. 2004.\n% \n% Further Reading\n% \n% C. Hummersone, R. Mason, and T. Brookes, \"A comparison of computational\n% precedence models for source separation in reverberant\n% environments\", The Journal of the Audio Engineering Society, vol.\n% 61(7/8), pp.508-520, July 2013.\n\n% Copyright 2016 University of Surrey.\n\n assert(nargin>=3, 'iosr:chXcorr:nargin', 'Number of input arguments must be greater than or equal to three.')\n\n if isparameter(varargin,'inhib_mode') && ~isparameter(varargin,'inhib')\n warning('iosr:instIld:inhibMode','''inhib_mode'' specified, but no inhibition array ''inhib''.');\n end\n\n % Check source file is compiled\n iosr.general.checkMexCompiled('-largeArrayDims',fullfile(fileparts(mfilename('fullpath')),'chXcorr_c.c'))\n\n options = struct(...\n 'frame_length',round(0.01*fs),...\n 'noverlap',1,...\n 'maxlag',round(0.001*fs),...\n 'tau',round(0.01*fs),...\n 'inhib',[],...\n 'ic_t',0,...\n 'norm_flag',0,...\n 'inhib_mode','subtract');\n\n % read parameter/value inputs\n if nargin > 3 % if parameters are specified\n % read the acceptable names\n optionNames = fieldnames(options);\n % count arguments\n nArgs = length(varargin);\n if round(nArgs/2)~=nArgs/2\n error('iosr:chXcorr:nameValuePair','CHXCORR needs propertyName/propertyValue pairs')\n end\n % overwrite defults\n for pair = reshape(varargin,2,[]) % pair is {propName;propValue}\n IX = strcmpi(pair{1},optionNames); % find match parameter names\n if any(IX)\n % do the overwrite\n options.(optionNames{IX}) = pair{2};\n else\n error('iosr:chXcorr:unknownOption','%s is not a recognized parameter name',pair{1})\n end\n end\n end\n\n % assign options to variables\n frame_length = options.frame_length;\n noverlap = options.noverlap;\n maxlag = options.maxlag;\n tau = options.tau;\n inhib_mode = options.inhib_mode;\n norm_flag = options.norm_flag;\n ic_t = options.ic_t;\n inhib = options.inhib;\n\n % check inputs\n assert(all(size(hc_L)==size(hc_R)), 'iosr:chXcorr:invalidInput', '''hc_L'' and ''hc_R'' must be the same size')\n assert(round(frame_length)==frame_length && isscalar(frame_length) && frame_length>0, 'iosr:chXcorr:invalidFrame', ...\n '''frame_length'' must be an integer greater than zero')\n assert(round(noverlap)==noverlap && isscalar(noverlap) && noverlap>0, 'iosr:chXcorr:invalidNoverlap', ...\n '''noverlap'' must be an integer greater than zero')\n assert(round(maxlag)==maxlag && isscalar(maxlag) && maxlag>0, 'iosr:chXcorr:invalidMaxlag', ...\n '''maxlag'' must be an integer greater than zero')\n assert(isscalar(tau) && tau>=1, 'iosr:chXcorr:invalidTau', '''tau'' must be a scalar greater than or equal to one')\n assert(isscalar(norm_flag), 'iosr:chXcorr:invalidNorm', '''norm_flag'' must be a scalar')\n assert(isscalar(ic_t) && ic_t>=0 && ic_t<=1, 'iosr:chXcorr:invalidIct', '''ic_t'' must be a scalar in the range [0,1]')\n assert(ischar(inhib_mode), 'iosr:chXcorr:invalidInhibMode', '''inhib_mode'' must be a char array (string)')\n\n % Calculate frame count\n frame_count = floor(max(size(hc_L))/(frame_length));\n frame_count = frame_count-noverlap+1;\n\n % Calculate number of frequency channels\n numchans = min(size(hc_L));\n numsamples = max(size(hc_L));\n\n % Check orientation of HC and inhib data (i.e. that frequency runs across the rows)\n dims = size(hc_L);\n hc_L = check_input(hc_L,2,numchans);\n hc_R = check_input(hc_R,2,numchans);\n\n % set a flag if data has been transposed in this way\n if dims(1)~=size(hc_L,1)\n rot = true;\n else\n rot = false;\n end\n\n % set inhibition mode ID\n switch inhib_mode\n case 'multiply'\n inhib_mode_ID = 1;\n if isempty(inhib)\n inhib = ones(size(hc_L));\n end\n case 'subtract'\n inhib_mode_ID = 2;\n if isempty(inhib)\n inhib = zeros(size(hc_L));\n end\n otherwise\n error('iosr:chXcorr:unknownInhibMode','''inhib_mode'' must be set to ''multiply'' or ''subtract''')\n end\n\n inhib = check_input(inhib,2,numchans);\n\n % Append HC and inhibition data with zeros for cross-correlation\n hc_L = [hc_L; zeros(maxlag+1,numchans)];\n hc_R = [hc_R; zeros(maxlag+1,numchans)];\n inhib = [inhib; zeros(maxlag+1,numchans)];\n\n assert(all(size(inhib)==size(hc_L)), 'iosr:chXcorr:invalidInhib', '''inhib'' must be a matrix the same size as ''hc_L'' or ''hc_R''')\n\n % Calculate cross-correlograms\n [ccg,ic] = iosr.auditory.chXcorr_c(hc_L,hc_R,frame_count,frame_length,noverlap,maxlag,tau,inhib,ic_t,norm_flag,inhib_mode_ID);\n\n % Correct orientation of IC data, if data was transposed, and crop to remove appended zeros\n ic = ic(1:numsamples,:);\n if rot\n ic = ic';\n end\n\nend\n\nfunction output = check_input(input,dim,target)\n%CHECK_INPUT check input is correct orientation\n\n if size(input,dim)~=target\n output = input';\n assert(size(output,dim)==target, 'iosr:chXcorr:invalidInputs', 'Input invalid')\n else\n output = input;\n end\n\nend\n\nfunction set = isparameter(input,parameter)\n%ISPARAMETER check for input parameter\n\n set = any(strcmpi(input(cellfun(@ischar,input)),parameter));\n\nend\n", "meta": {"author": "IoSR-Surrey", "repo": "MatlabToolbox", "sha": "4bff1bb2da7c95de0ce2713e7c710a0afa70c705", "save_path": "github-repos/MATLAB/IoSR-Surrey-MatlabToolbox", "path": "github-repos/MATLAB/IoSR-Surrey-MatlabToolbox/MatlabToolbox-4bff1bb2da7c95de0ce2713e7c710a0afa70c705/+iosr/+auditory/chXcorr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.599572798596266}} {"text": "function c = nancov(x,varargin)\n%NANCOV Covariance matrix, ignoring NaNs.\n% C = NANCOV(X), if X is a vector, returns the sample variance of the\n% values in X, treating NaNs as missing values. For matrices, where\n% each row is an observation and each column a variable, NANCOV(X) is\n% the covariance matrix computing using rows of X that do not contain\n% any NaN values. NANCOV(X,Y), where X and Y are matrices with\n% the same number of elements, is equivalent to NANCOV([X(:) Y(:)]). \n% \n% NANCOV(X) or NANCOV(X,Y) normalizes by (N-1) if N>1, where N is the\n% number of observations after removing missing values. This makes\n% NANCOV(X) the best unbiased estimate of the covariance matrix if the\n% observations are from a normal distribution. For N=1, COV normalizes\n% by N.\n%\n% NANCOV(X,1) or NANCOV(X,Y,1) normalizes by N and produces the second\n% moment matrix of the observations about their mean. NANCOV(X,Y,0) is\n% the same as NANCOV(X,Y), and NANCOV(X,0) is the same as NANCOV(X).\n%\n% C = NANCOV(...,'pairwise') computes C(I,J) using rows with no NaN\n% values in columns I or J. The result may not be a positive definite\n% matrix. C = NANCOV(...,'complete') is the default, and it omits rows\n% with any NaN values, even if they are not in column I or J.\n%\n% The mean is removed from each column before calculating the\n% result.\n%\n% Example: Generate random data having non-zero covariance between\n% column 4 and the other columns.\n% x = randn(30,4); % uncorrelated data\n% x(:,4) = sum(x,2); % introduce correlation\n% x(2,3) = NaN; % introduce one missing value\n% c = nancov(x) % compute sample covariance\n%\n% Class support for inputs X,Y:\n% float: double, single\n%\n% See also COV, VAR, NANVAR.\n\n% Copyright 1984-2011 The MathWorks, Inc.\n% $Revision: 1.1.8.3 $ $Date: 2011/02/09 19:35:29 $\n\nif nargin<1\n error(message('stats:nancov:NotEnoughInputs'));\nend\n\n% Should we ignore NaNs by complete rows or pairwise?\ndopairwise = false;\nif numel(varargin)>0\n temp = varargin{end};\n if ischar(temp)\n j = find(strncmpi(temp, {'pairwise' 'complete'},length(temp)));\n if isempty(j)\n error(message('stats:nancov:InvalidArg', temp));\n end\n dopairwise = (j==1);\n varargin(end) = [];\n end\nend\n\n% Should we use the mle (divide by N) or unbiased estimate (N-1)?\ndomle = false;\nif numel(varargin)>0\n temp = varargin{end};\n if isequal(temp,0) || isequal(temp,1)\n domle = (temp==1);\n varargin(end) = [];\n end\nend\n\nif numel(varargin)>1\n error(message('stats:nancov:TooManyArgs'));\nend\n\nscalarxy = false; % nancov(scalar,scalar) is an ambiguous case\nif numel(varargin)>0\n y = varargin{1};\n\n % Two inputs, convert to equivalent single input\n x = x(:);\n y = y(:);\n if length(x)~=length(y)\n error(message('stats:nancov:XYmismatch'));\n end\n scalarxy = isscalar(x) && isscalar(y);\n x = [x y];\nelseif ndims(x)>2\n error(message('stats:nancov:InputDim'));\nend\n\nif isvector(x) && ~scalarxy\n x = x(:);\nend\n\nxnan = isnan(x);\n[m,n] = size(x);\n\nif isempty(x);\n if (m==0 && n==0)\n c = NaN(class(x));\n else\n c = NaN(n,class(x));\n end\n return;\nend\n\nif ~dopairwise || ~any(any(xnan)) % no need to do pairwise\n nanrows = any(xnan,2);\n if any(nanrows)\n x = x(~nanrows,:);\n end\n c = localcov(x,domle);\nelse % pairwise with some NaNs\n % Compute variance using complete data separately by column\n c = zeros(n,class(x));\n x(xnan) = 0;\n colsize = sum(~xnan,1);\n xmean = sum(x,1) ./ max(1,colsize);\n xmean(colsize==0) = NaN;\n xc = x - repmat(xmean,m,1);\n xc(xnan) = 0;\n xvar = sum(xc.^2,1);\n if domle\n denom = colsize;\n else\n denom = max(0,colsize-1);\n end\n xvar(denom>1) = xvar(denom>1) ./ denom(denom>1);\n xvar(denom==0) = NaN;\n c(1:n+1:end) = xvar;\n\n % Now compute off-diagonal entries\n jk = 1:2;\n for j = 2:n\n jk(1) = j;\n for k=1:j-1\n jk(2) = k;\n rowsjk = ~any(xnan(:,jk),2);\n njk = sum(rowsjk);\n if njk<=1\n cjk = NaN;\n else\n cjk = localcov(x(rowsjk,jk),domle);\n cjk = cjk(1,2);\n end\n c(j,k) = cjk;\n end\n end\n c = c + tril(c,-1)';\nend\n\n% ------------------------------------------------\nfunction [c,n] = localcov(x,domle)\n%LOCALCOV Compute cov with no error checking and assuming NaNs are removed\n\n[m,n] = size(x);\nif domle\n denom = m;\nelse\n denom = max(0,m-1);\nend\n\nif m==1 % and doing mle, be sure to get exact 0\n c = zeros(n,class(x));\nelseif denom==0\n c = NaN(n,class(x));\nelse\n xc = x - repmat(mean(x),m,1);\n c = xc' * xc / denom;\nend\n\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/wavedet/nancov.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.5995703508876661}} {"text": "function varargout = calcTensor(odf,T,varargin)\n% compute the average tensor for an ODF\n%\n% Syntax\n% [TVoigt, TReuss, THill] = calcTensor(odf,T)\n% THill = calcTensor(odf,T,'Hill')\n% TGeo = calcTensor(odf,T,'geometric')\n%\n% Input\n% odf - @SO3Fun\n% T - @tensor\n%\n% Output\n% T - @tensor\n%\n% Options\n% Voigt - Boigt mean\n% Reuss - Reuss mean\n% Hill - Hill mean\n% geometric - geometric mean\n%\n% See also\n% tensor/mean EBSD/calcTensor\n\n% decide between the quadrature based method and the harmonic method\nif ~check_option(varargin,'quadrature')\n\n % the harmonic route is directly implemented into tensor/mean\n [varargout{1:nargout}] = mean(T,odf,varargin{:});\n\nelse % quadrature based method\n\n % define a grid\n res = get_option(varargin,'resolution',2.5*degree);\n S3G = equispacedSO3Grid(odf.CS,odf.SS,'resolution',res);\n\n % evaluate the ODF\n f = eval(odf,S3G,varargin{:});\n f = f ./ sum(f(:));\n\n % compute the means\n [varargout{1:nargout}] = mean(S3G*T,'weights',f(:),varargin{:});\n\nend\n\nend\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/SO3Fun/@SO3Fun/calcTensor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5995414640888567}} {"text": "function [nrm] = normals(pnt, tri, opt)\n\n% NORMALS compute the surface normals of a triangular mesh\n% for each triangle or for each vertex\n%\n% Use as\n% [nrm] = normals(pnt, tri, opt)\n% where opt is either 'vertex' (default) or 'triangle'.\n%\n% See also PCNORMALS, PROJECTTRI\n\n% Copyright (C) 2002-2007, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\nif nargin<3\n opt='vertex';\nelseif (opt(1)=='v' || opt(1)=='V')\n opt='vertex';\nelseif (opt(1)=='t' || opt(1)=='T')\n opt='triangle';\nelse\n ft_error('invalid optional argument');\nend\n\nnpnt = size(pnt,1);\nntri = size(tri,1);\n\n% shift to center\npnt(:,1) = pnt(:,1)-mean(pnt(:,1),1);\npnt(:,2) = pnt(:,2)-mean(pnt(:,2),1);\npnt(:,3) = pnt(:,3)-mean(pnt(:,3),1);\n\n% compute triangle normals\n% nrm_tri = zeros(ntri, 3);\n% for i=1:ntri\n% v2 = pnt(tri(i,2),:) - pnt(tri(i,1),:);\n% v3 = pnt(tri(i,3),:) - pnt(tri(i,1),:);\n% nrm_tri(i,:) = cross(v2, v3);\n% end\n\n% vectorized version of the previous part\nv2 = pnt(tri(:,2),:) - pnt(tri(:,1),:);\nv3 = pnt(tri(:,3),:) - pnt(tri(:,1),:);\nnrm_tri = cross(v2, v3);\n\n\nif strcmp(opt, 'vertex')\n % compute vertex normals\n nrm_pnt = zeros(npnt, 3);\n for i=1:ntri\n nrm_pnt(tri(i,1),:) = nrm_pnt(tri(i,1),:) + nrm_tri(i,:);\n nrm_pnt(tri(i,2),:) = nrm_pnt(tri(i,2),:) + nrm_tri(i,:);\n nrm_pnt(tri(i,3),:) = nrm_pnt(tri(i,3),:) + nrm_tri(i,:);\n end\n % normalise the direction vectors to have length one\n nrm = nrm_pnt ./ (sqrt(sum(nrm_pnt.^2, 2)) * ones(1,3));\nelse\n % normalise the direction vectors to have length one\n nrm = nrm_tri ./ (sqrt(sum(nrm_tri.^2, 2)) * ones(1,3));\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% fast cross product to replace the MATLAB standard version\nfunction [c] = cross(a,b)\nc = [a(:,2).*b(:,3)-a(:,3).*b(:,2) a(:,3).*b(:,1)-a(:,1).*b(:,3) a(:,1).*b(:,2)-a(:,2).*b(:,1)];\n\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/external/fieldtrip/forward/private/normals.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.599541462073459}} {"text": "function fk_space = autoGen_fk_space(q1,q2,q3)\n%AUTOGEN_FK_SPACE\n% FK_SPACE = AUTOGEN_FK_SPACE(Q1,Q2,Q3)\n\n% This function was generated by the Symbolic Math Toolbox version 8.4.\n% 01-Jun-2020 11:59:03\n\nt2 = cos(q1);\nt3 = cos(q2);\nt4 = sin(q1);\nt5 = q2+q3;\nt6 = cos(t5);\nt7 = sin(t5);\nt8 = t3.*(4.0./2.5e+1);\nt9 = t6.*(5.7e+1./2.0e+2);\nt10 = t8+t9;\nfk_space = reshape([t2.*t6,t4.*t6,-t7,0.0,-t4,t2,0.0,0.0,t2.*t7,t4.*t7,t6,0.0,t2.*t10,t4.*t10,t7.*(-5.7e+1./2.0e+2)-sin(q2).*(4.0./2.5e+1),1.0],[4,4]);\n", "meta": {"author": "ShuoYangRobotics", "repo": "QuadrupedSim", "sha": "8427715395b63bddb77329e66f7484e529998445", "save_path": "github-repos/MATLAB/ShuoYangRobotics-QuadrupedSim", "path": "github-repos/MATLAB/ShuoYangRobotics-QuadrupedSim/QuadrupedSim-8427715395b63bddb77329e66f7484e529998445/autoGen_fk_space.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5995414580426636}} {"text": "function [varargout, peval] = separcomp(dpix, peval, winit_pix, hinit)\n% separcomp(dpix, p_script, savethis, winit, hinit)\n% separate components\n% V ~ WH\n% V -> N_pix x N_t\n% W -> N_pix x N_comp - xth pixel of the ith components\n% H -> N_copm x N_t - contribution of the i-th component in the time t\n\n[peval.nx, peval.ny, peval.nt] = size(dpix);\npeval.numpix = peval.nx*peval.ny;\npeval.meandata = mean(dpix(:));\n\ndvec = reshape(dpix,peval.numpix, peval.nt);\ndpix_dip = dip_image(dpix);\n\n% background subtraction with empirical values:\npeval.bg_clip = 'no'; \npeval.bg_fs_var = 5; \npeval.bg_perc = 20; \npeval.bg_ob_dist = 8;\nif ~isfield(peval, 'bg')\n [out_nobg, peval.bg, bg_im]=backgroundoffset(dpix_dip, peval.bg_clip, peval.bg_fs_var, peval.bg_perc, peval.bg_ob_dist);\nend\n\nif ~isfield(peval, 'ncomp')\n peval.ncomp=estimate_ncpomp(dvec);\nend\n\n[winit, hinit] = initwh(winit_pix, hinit, peval); %initialization of w and h\n\n\n\nif ~isfield(peval, 'w_fixvec') peval.w_fixvec=[]; end\nif ~isfield(peval, 'h_fixvec') peval.h_fixvec=[]; end\n\nif isempty(peval.w_fixvec)\n peval.w_fixvec = peval.ncomp + 1; %fixing background component\nelseif ~(peval.w_fixvec(end) == peval.ncomp + 1)\n peval.w_fixvec = [peval.w_fixvec, peval.ncomp + 1];\nend\n\nif isempty(peval.h_fixvec)\n peval.h_fixvec = peval.ncomp + 1; %fixing background component\nelseif ~(peval.h_fixvec(end) == peval.ncomp + 1)\n peval.h_fixvec = [peval.h_fixvec, peval.ncomp + 1];\nend\n\nverbose = 1;\n% if strcmp (peval.method, 'nmf_classic') %classical nmf updates \n% [w,h,peval, dtrace, htrace]=nmf_classic(dvec,winit,hinit,peval,verbose);\n% elseif strcmp (peval.method, 'nmf_conjgrad_penalty') %classical nmf updates\n% [w,h,peval, dtrace, htrace]=nmf_conjgrad_penalty(dvec,winit,hinit,peval,verbose);\n% end\neval (['[w,h,peval, dtrace, htrace]=' peval.method '(dvec,winit,hinit,peval,verbose);']);\n\nvarargout = struct('w',w,'h',h, 'dtrace', dtrace, 'htrace', htrace);", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/separ/separcomp_penalty.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995027, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5995414545175545}} {"text": "%% INS惯导解算\nclear;\nclc;\nclose all;\n\n%% \nFs = 100; %采样频率\nN = 1000; %采样次数\n\ndt = 1 / Fs;\ngyr = [0.01, 0.02, 0.03]; %单位rad\nacc = [0, 0, 9.8]; % 单位m/s^(2)\n\n% 捷联惯导解算\np = zeros(3, 1);\nv = zeros(3, 1);\nq= [1 0 0 0]';\n\nfor i=1:N\n [p ,v, q] = ch_nav_equ_local_tan(p, v, q, acc', gyr' , dt, [0, 0, -9.8]');\n h_pos(i,:) = p;\n h_vel(i,:) = v;\n h_eul(i,:) = ch_q2eul(q);\nend\n\nfigure;\nsubplot(2,2,1);\nch_plot_pos3d(h_pos);\nsubplot(2,2,2);\nch_plot_pos2d(h_pos);\nsubplot(2,2,3);\nch_plot_att(h_eul);\n\nfprintf('纯积分测试: 陀螺(rad/s):%.3f %.3f %.3f\\n', gyr(1), gyr(2), gyr(3));\nfprintf('纯积分测试: 加计(m/s^(2)):%.3f %.3f %.3f\\n', acc(1), acc(2), acc(3));\n\nfprintf('解算:%d次 总时间:%.3fs\\n', N, N /Fs);\nfprintf('最终误差(m): %.3f %.3f %.3f\\n', h_pos(end, 1), h_pos(end, 2), h_pos(end, 3));\n\n\n", "meta": {"author": "yandld", "repo": "nav_matlab", "sha": "da70cb2083de407409ebe1ec1096a308611cf063", "save_path": "github-repos/MATLAB/yandld-nav_matlab", "path": "github-repos/MATLAB/yandld-nav_matlab/nav_matlab-da70cb2083de407409ebe1ec1096a308611cf063/example/ins_test/example_ins1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875225, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5995414444405663}} {"text": " function proj = ellipsoid_proj(cg, params, varargin)\n%|function proj = ellipsoid_proj(cg, params, varargin)\n%|\n%| Compute set of 2d line-integral projection views of ellipsoid(s).\n%| Works for both parallel-beam and cone-beam geometry.\n%|\n%| in\n%|\tcg\t\t\tct_geom()\n%|\tparams [ne 9]\t\tellipsoid parameters:\n%|\t\t\t[x_center y_center z_center x_radius y_radius z_radius\n%|\t\t\t\txy_angle_degrees z_angle_degrees amplitude]\n%| options\n%|\toversample\t\tover-sampling factor for emulating \"strips\"\n%|\t\t\t\t(to account for finite detector size)\n%|\n%| out\n%|\tproj\t[ns nt na]\tprojection views\n%|\n%| Copyright 2003-10-22, Patty Laskowsky, Nicole Caparanis, Taka Masuda,\n%| and Jeff Fessler, University of Michigan\n\nif nargin == 1 && streq(cg, 'test'), ellipsoid_proj_test, return, end\nif nargin < 2, ir_usage, end\n\narg.oversample = 1;\narg = vararg_pair(arg, varargin);\n\nproj = ellipsoid_proj_do(params, cg.s, cg.t, cg.ar, cg.source_zs, ...\n\t\tcg.dso, cg.dod, cg.dfs, arg.oversample);\n\nend % ellipsoid_proj()\n\n\n% ellipsoid_proj_do()\nfunction proj = ellipsoid_proj_do(params, ss, tt, ...\n\t\tbeta, ... % [radians]\n\t\tsource_zs, dso, dod, dfs, oversample)\n\nif size(params, 2) ~= 9, error '9 parameters per ellipsoid', end\n\nif oversample > 1\n\tds = ss(2) - ss(1);\n\tdt = tt(2) - tt(1);\n\tif any(abs(diff(ss) / ds - 1) > 1e-6) ...\n\t|| any(abs(diff(tt) / dt - 1) > 1e-6)\n\t\terror 'uniform spacing required for oversampling'\n\tend\n\tNo = oversample;\n\t% determine new finer sampling positions\n\tss = outer_sum([-(No-1):2:(No-1)]'/(2*No)*ds, ss(:)'); % [No ns]\n\ttt = outer_sum([-(No-1):2:(No-1)]'/(2*No)*dt, tt(:)'); % [No nt]\n\tproj = ellipsoid_proj_do(params, ss(:), tt(:), beta, source_zs, dso, dod, dfs, 1);\n\tproj = downsample3(proj, [No No 1]);\nreturn\nend\n\n\n% determine equivalent parallel-beam projection coordinates, at beta=0\nns = length(ss);\nnt = length(tt);\n[sss ttt] = ndgrid(ss, tt);\n\nif isinf(dso) % parallel beam\n\tuu = sss;\n\tvv = ttt;\n\tazim0 = 0;\n\tpolar = 0;\n\nelseif isinf(dfs) % cone-beam with flat detector\n\t[uu vv azim0 polar] = ir_coord_cb_flat_to_par(sss, ttt, dso, dod);\n\nelseif dfs == 0 % cone-beam with arc detector\n\t[uu vv azim0 polar] = ir_coord_cb_arc_to_par(sss, ttt, dso, dod);\n\nelse\n\tfail 'not done'\nend\n\nclear sss ttt\n\ncpolar = cos(polar);\nspolar = sin(polar);\nproj = zeros(ns, nt, numel(beta));\n\n% loop over ellipsoids\nfor ip = 1:size(params,1)\n\tpar = params(ip,:);\n\n\tcx = par(1);\trx = par(4);\n\tcy = par(2);\try = par(5);\n\tcz = par(3);\trz = par(6);\n\txang = deg2rad(par(7)); % xy-plane rotation\n\tzang = deg2rad(par(8)); % z-plane rotation\n\tif zang, error 'z rotation not done', end\n\tval = par(9);\n\n\tfor ib = 1:length(beta)\n%\t\taz = beta(ib) + azim0 - xang; % assume source rotate in xy plane\n\t\taz = beta(ib) + azim0; % correction due to Lei Zhu of Stanford\n\n\t\t% shift property of 3D transform:\n\t\tcz_eff = cz - source_zs(ib); % center relative to source\n\t\tushift = cx * cos(az) + cy * sin(az);\n\t\tvshift = (cx * sin(az) - cy * cos(az)) .* spolar + cz_eff * cpolar;\n\n\t\taz = az - xang; % correction due to Lei Zhu of Stanford\n\t\tp1 = (uu-ushift) .* cos(az) + (vv-vshift) .* sin(az) .* spolar;\n\t\tp2 = (uu-ushift) .* sin(az) - (vv-vshift) .* cos(az) .* spolar;\n\t\tp3 = (vv-vshift) .* cpolar;\n\n\t\te1 = -sin(az) .* cpolar;\n\t\te2 = cos(az) .* cpolar;\n\t\te3 = spolar;\n\n\t\tA = e1.^2 / rx^2 + e2.^2 / ry^2 + e3.^2 / rz^2;\n\t\tB = p1 .* e1 / rx^2 + p2 .* e2 / ry^2 + p3 .* e3 / rz^2;\n\t\tC = p1.^2 / rx^2 + p2.^2 / ry^2 + p3.^2 / rz^2 - 1;\n\n\t\tproj(:,:,ib) = proj(:,:,ib) + 2 * val * sqrt(B.^2 - A.*C) ./ A;\n\tend\nend\n\n% trick: anywhere proj of a single ellipsoid is imaginary, the real part is 0.\nproj = real(proj);\nend % ellipsoid_proj_do()\n\n\n% ellipsoid_proj_test()\nfunction ellipsoid_proj_test\n\nell = [20 0*50 -40 200 100 50 90 0 10;\n 0 50 100 80 80 20 0 0 10];\n\nfun_proj = @(cg) ellipsoid_proj(cg, ell, 'oversample', 2); % analytical\nfun_im = @(ig) ellipsoid_im(ig, ell, 'oversample', 2, 'checkfov', true);\n\nir_proj3_compare1(fun_proj, fun_im, 'chat', 1);\n\nend % ellipsoid_proj_test()\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/fbp/ellipsoid_proj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.5993900615853215}} {"text": "function [w, infos] = cd_lasso_elasticnet(problem, options)\n% Coordinate descent algorithm for LASSO problem.\n%\n% Inputs:\n% problem function (cost/grad/hess)\n% options options\n% Output:\n% w solution of w\n% infos information\n%\n% This file is part of GDLibrary and SGDLibrary.\n%\n% Created by H.Kasai on Apr. 18, 2017\n\n\n % set dimensions and samples\n d = problem.dim();\n n = problem.samples(); \n A = problem.A();\n\n % extract options\n if ~isfield(options, 'tol_optgap')\n tol_optgap = 1.0e-12;\n else\n tol_optgap = options.tol_optgap;\n end \n \n if ~isfield(options, 'tol_gnorm')\n tol_gnorm = 1.0e-12;\n else\n tol_gnorm = options.tol_gnorm;\n end \n \n if ~isfield(options, 'max_iter')\n max_iter = 100;\n else\n max_iter = options.max_iter;\n end \n \n if ~isfield(options, 'verbose')\n verbose = false;\n else\n verbose = options.verbose;\n end \n \n if ~isfield(options, 'w_init')\n w = randn(d,1);\n else\n w = options.w_init;\n end \n \n if ~isfield(options, 'f_opt')\n f_opt = -Inf;\n else\n f_opt = options.f_opt;\n end \n \n if ~isfield(options, 'store_w')\n store_w = false;\n else\n store_w = options.store_w;\n end \n \n if ~isfield(options, 'sub_mode')\n sub_mode = 'lasso';\n else\n sub_mode = options.sub_mode;\n end \n \n % initialise\n iter = 0;\n if strcmp(sub_mode, 'lasso')\n AtA = problem.AtA();\n squred_norm_col = diag(AtA);\n else\n AtA_l2 = problem.AtA_l2();\n squred_norm_col = diag(AtA_l2);\n end\n prox_th = ones(d, 1)./squred_norm_col;\n \n % store first infos\n clear infos;\n infos.iter = iter;\n infos.time = 0; \n infos.grad_calc_count = 0; \n f_val = problem.cost(w);\n infos.cost = f_val; \n optgap = f_val - f_opt;\n infos.optgap = optgap;\n grad = problem.full_grad(w);\n gnorm = norm(grad);\n infos.gnorm = gnorm;\n if ismethod(problem, 'reg')\n infos.reg = problem.reg(w); \n end \n if store_w\n infos.w = w; \n end\n \n % set start time\n start_time = tic(); \n \n % print info\n if verbose\n fprintf('CD (%s): Iter = %03d, cost = %.24e, gnorm = %.4e, optgap = %.4e\\n', sub_mode, iter, f_val, gnorm, optgap);\n end \n\n % main loop\n while (optgap > tol_optgap) && (gnorm > tol_gnorm) && (iter < max_iter) \n\n % update i-th coordinate\n if strcmp(sub_mode, 'lasso')\n for i = 1:d \n w_except_i = w;\n w_except_i(i) = 0;\n residual = problem.residual(w_except_i);\n\n snc = squred_norm_col(i);\n w(i) = problem.prox(A(:, i)'*residual/snc, prox_th(i));\n end\n else\n for i = 1:d \n w_except_i = w;\n w_except_i(i) = 0;\n residual = problem.residual(w_except_i, i);\n\n snc = squred_norm_col(i);\n w(i) = problem.prox(residual/snc, prox_th(i));\n end \n \n end\n \n % calculate gradient\n grad = problem.full_grad(w);\n\n % update iter \n iter = iter + 1;\n % calculate error\n f_val = problem.cost(w);\n optgap = f_val - f_opt; \n % calculate norm of gradient\n gnorm = norm(grad);\n \n % measure elapsed time\n elapsed_time = toc(start_time); \n\n % store infoa\n infos.iter = [infos.iter iter];\n infos.time = [infos.time elapsed_time]; \n infos.grad_calc_count = [infos.grad_calc_count iter*n]; \n infos.optgap = [infos.optgap optgap]; \n infos.cost = [infos.cost f_val];\n infos.gnorm = [infos.gnorm gnorm]; \n if ismethod(problem, 'reg')\n reg = problem.reg(w);\n infos.reg = [infos.reg reg];\n end \n if store_w\n infos.w = [infos.w w]; \n end \n \n % print info\n if verbose\n fprintf('CD (%s): Iter = %03d, cost = %.24e, gnorm = %.4e, optgap = %.4e\\n', sub_mode, iter, f_val, gnorm, optgap);\n end \n end\n \n if gnorm < tol_gnorm\n fprintf('Gradient norm tolerance reached: tol_gnorm = %g\\n', tol_gnorm);\n elseif optgap < tol_optgap\n fprintf('Optimality gap tolerance reached: tol_optgap = %g\\n', tol_optgap); \n elseif iter == max_iter\n fprintf('Max iter reached: max_iter = %g\\n', max_iter);\n end \n \nend\n", "meta": {"author": "hiroyuki-kasai", "repo": "SGDLibrary", "sha": "d19a12559c79c3726683243885b15f982f4bec3d", "save_path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary/SGDLibrary-d19a12559c79c3726683243885b15f982f4bec3d/gd_solver/cd_lasso_elasticnet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.5993900343037084}} {"text": "function [csubl, csubd] = aerodyn(alpha)\n\n% aerodynamic properties\n\n% input\n\n% alpha = angle-of-attack (radians)\n\n% output\n\n% csubl = lift coefficient (non-dimensional)\n% csubd = drag coefficient (non-dimensional)\n\n% STS aero - J. Betts model\n\n% Orbital Mechanics with Matlab\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nrtd = 180.0 / pi;\n\ncl0 = -0.20704d0;\n\ncl1 = 0.029244d0;\n\ncd0 = 0.07854d0;\n\ncd1 = -6.1592d-3;\n\ncd2 = 6.21408d-4;\n\nalphad = rtd * alpha;\n\ncsubl = cl0 + cl1 * alphad;\n\ncsubd = cd0 + (cd1 + cd2 * alphad) * alphad;\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/39095-trajectory-modeling-in-the-flight-path-system/aerodyn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5993262203849536}} {"text": "function [F] = mci_ramsay_fx (x,U,P,M)\n% State equation for Ramsay model\n% FORMAT [F] = mci_ramsay_fx (x,U,P,M)\n%\n% x State vector\n% x(1) Voltage variable\n% x(2) Recovery variable\n% U inputs\n% P vector of model parameters - 2 params only\n% M model\n%\n% F dx/dt\n%\n% J Ramsay et al (2007) Parameter estimation for differential equations:\n% a generalised smoothing approach. J Roy Stat Soc B, 69(5):741-796.\n%\n% See also section 10 (page 26) and contribution by W.Penny on page 75 of: \n%\n% Girolami and Calderhead (2011) Riemann manifold Langevin and Hamiltonian\n% Monte Carlo methods. J Roy Stat Soc B,73(2):123-214.\n%__________________________________________________________________________\n% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny \n% $Id: mci_ramsay_fx.m 6548 2015-09-11 12:39:47Z will $\n\nc=3;\n\nP(1)=exp(P(1));\nP(2)=exp(P(2));\n\nF=zeros(2,1);\nF(1)=c*(x(1)-(1/3)*x(1)^3+x(2));\nF(2)=-(1/c)*(x(1)-P(1)+P(2)*x(2));\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/mci/models/ramsay/mci_ramsay_fx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5993262104546787}} {"text": "function [mxc,mlat,OUT] = xc_stats(xc,xl,varargin)\n% [mxc,mlat,OUT] = xc_stats(xc,xl,varargin)\n% calculate t-statistic values for a k x k x n 3-D matrix of \n% correlation (xc) and latency (xl) values across n subjects.\n%\n% tor wager\n\n\nnames = [];\nif length(varargin) > 0, names = varargin{1};,end\n\n if isempty(xl), mlat = [];, end\n\n% ------------------------------------------------------------\n% stats on correlation values\n% ------------------------------------------------------------\n\nwarning off, clear stelatency, clear tlat, clear stecorr, clear tcorr\n% standard errors and t-values, element by element\n\n% only do this on the upper triangle, to be faster\n\nfor j = 1:size(xc,2)-1\n for k = j + 1 : size(xc,2)\n \n if ~isempty(xl)\n tmp = squeeze(xl(j,k,:));\n z = tmp; \n [stelatency(j,k),tlat(j,k)] = ste(z); % t-test on latencies; maybe should be poisson dist?\n end\n \n tmp = squeeze(xc(j,k,:));\n z = .5 * log( (1+tmp) ./ (1-tmp) ); % Fisher's r-to-z transform\n [stecorr(j,k),tcorr(j,k)] = ste(z); % correl in rand fx analysis across ss\n end\nend\nwarning on\n\n\n% makes symmetric matrices from upper tri\n\nif ~isempty(xl), stelatency(end+1,:) = 0; ,end\nstecorr(end+1,:) = 0;\ntcorr(end+1,:) = 0; \nif ~isempty(xl), \n tlat(end+1,:) = 0; \n stelatency = stelatency + stelatency';\nend\n\nstecorr = stecorr + stecorr' + Inf * eye(size(stecorr,1));\ntcorr = tcorr + tcorr'; % t-scores for significance/reliability of cross-correlations across subjects\n\nif ~isempty(xl)\n tlat = tlat + tlat'; % same for time lags across subjects\nend\n\n% group means\n\nif ~isempty(xl)\n mlat = mean(xl,3); % mean of latency data (cross-lag, group average)\nend\nmxc = mean(xc,3); % mean cross-correlations among k regions, group average\n\n\n% ------------------------------------------------------------\n% print and save output\n% ------------------------------------------------------------\n\n\nOUT.desc1 = 'xl is latency mtx for each subject, xc is individual correlation mtx';\nif ~isempty(xl), OUT.xl = xl;, end\nOUT.xc = xc;\nOUT.desc2 = 'mlat and mxc: matrices of means across subjects for latency and correl'\nOUT.desc3 = 'tlat/tcorr are t-values across z-transformed correlations';\nOUT.mxc = mxc;\n\nif ~isempty(xl)\n OUT.mlat = mlat;\n OUT.tlat = tlat;\n OUT.tcorr = tcorr;\nend\n\n% Output\nif ~isempty(xl)\n fprintf(1,'Latency\\n');\n str = correlation_to_text(mlat,Inf,names);\nend\n\nfprintf(1,'correlation T-values, p<.05 corrected, assuming normal distribution of latency diffs\\n');\n% Alpha correction - bonferroni.\nnumobs=(size(mxc,1)*(size(mxc,1)-1))/2;\ncorrp=1-(0.05/ (2 * ( numobs ))); % 2-tailed corr p\ncrit_t = tinv_t(corrp,size(xc,1)-3); % critical t-value for corrected significance\ncrit_tu = tinv_t(1-(.05/2),size(xc,1)-3); % critical t-value for uncorrected significance\n\nif ~isempty(xl)\n str = correlation_to_text(tlat,crit_t,names);\nend\n\nOUT.crit_t = crit_t;\nOUT.crit_tu = crit_tu;\nOUT.crit_tdesc = 'crit_t crit t value corrected, _tu uncorrected';\nOUT.corrp = corrp;\nOUT.corrpdesc = 'critical corrected p-value (bonferroni)';\n\n\nfprintf(1,'Average correlation across subjects\\n');\n[str, sigu] = correlation_to_text(mxc,Inf,names);\n\nfprintf(1,'Corr T-values, p<.05 uncorrected, 2-tailed, assuming independent samples over time\\n');\n[str, sigu] = correlation_to_text(tcorr,crit_tu,names);\nOUT.sigmat_uncorrected = sigu;\n\nfprintf(1,'Corr T-values, p<.05 corrected, 2-tailed, assuming independent samples over time\\n');\n[str, sigmat] = correlation_to_text(tcorr,crit_t,names);\n\nOUT.sigmat = sigmat;\n\n\n\n\nreturn", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Statistics_tools/Support_functions/xc_stats.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278633625322, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5993262083546861}} {"text": "function grad = compute_NN_grad(W, X, resp, hout, nonlinearity, nonzero_grad)\n\n% nonlinearity = 1 -- hyperbolic tangent\n% nonlinearity = 2 -- logistic sigmoid (subtract 0.5 from last layer's outputs)\n% nonlinearity = 3 -- logistic sigmoid + hyperbolic tangent (last layer)\n\nncases = size(resp{1},2);\nif isa(X, 'gsingle')\n gputype = 'gsingle';\n onesncases = gones(ncases,1,gputype);\nelseif isa(X, 'gdouble')\n gputype = 'gsingle';\n onesncases = gones(ncases,1,gputype);\nelse\n onesncases = ones(ncases,1);\nend\n\nnlayer = numel(W);\n\nif (nonlinearity == 1)\n \n if (exist('nonzero_grad', 'var'))\n snonzero_grad = sum(nonzero_grad);\n if (snonzero_grad == 0)\n for i=nlayer:-1:1\n\tgrad{i} = zeros(size(W{i}));\n end\n return;\n end\n \n for i=nlayer:-1:1\n if (i == nlayer)\n\ttmp = hout(:, nonzero_grad);\n else\n\ttmp = (W{i+1}' * backward{i+1});\n end\n \n if (size(tmp, 1) ~= size(resp{i}, 1))\n\ttmp = tmp(1:end-1, :);\n end\n \n backward{i} = tmp .* (1 - resp{i}(:,nonzero_grad).^2);\n \n if (i-1) >= 1\n\tif (size(W{i}, 2) == size(resp{i-1}, 1) + 1)\n\t grad{i} = backward{i} * [resp{i-1}(:,nonzero_grad)' ones(snonzero_grad, 1)];\n\telse\n\t grad{i} = backward{i} * resp{i-1}(:,nonzero_grad)';\n\tend \n else\n\tgrad{i} = backward{i} * X(:, nonzero_grad)';\n end\n end\n else\n for i=nlayer:-1:1\n if (i == nlayer)\n\ttmp = hout;\n else\n\ttmp = (W{i+1}' * backward{i+1});\n end\n \n if (size(tmp, 1) ~= size(resp{i}, 1))\n\ttmp = tmp(1:end-1, :);\n end\n \n backward{i} = tmp .* (1 - resp{i}.^2);\n \n if (i-1) >= 1\n\tif (size(W{i}, 2) == size(resp{i-1}, 1) + 1)\n\t grad{i} = backward{i} * [resp{i-1}' onesncases];\n\telse\n\t grad{i} = backward{i} * resp{i-1}';\n\tend\n else\n\tgrad{i} = backward{i} * X';\n end\n end\n end\n \nelseif (nonlinearity == 2)\n\n if (exist('nonzero_grad', 'var'))\n snonzero_grad = sum(nonzero_grad);\n if (snonzero_grad == 0)\n for i=nlayer:-1:1\n\tgrad{i} = zeros(size(W{i}));\n end\n return;\n end\n \n for i=nlayer:-1:1\n if (i == nlayer)\n\ttmp = hout(:, nonzero_grad);\n else\n\ttmp = (W{i+1}' * backward{i+1});\n end\n \n if (size(tmp, 1) ~= size(resp{i}, 1))\n\ttmp = tmp(1:end-1, :);\n end\n \n backward{i} = tmp .* (1 - resp{i}(:,nonzero_grad)) .* resp{i}(:,nonzero_grad);\n \n if (i-1) >= 1\n\tif (size(W{i}, 2) == size(resp{i-1}, 1) + 1)\n\t grad{i} = backward{i} * [resp{i-1}(:,nonzero_grad)' gones(snonzero_grad,1,gputype)];\n\telse\n\t grad{i} = backward{i} * resp{i-1}(:,nonzero_grad)';\n\tend\n else\n\tgrad{i} = backward{i} * X(:, nonzero_grad)';\n end\n end\n else\n for i=nlayer:-1:1\n if (i == nlayer)\n\ttmp = hout;\n else\n\ttmp = (W{i+1}' * backward{i+1});\n end\n \n if (size(tmp, 1) ~= size(resp{i}, 1))\n\ttmp = tmp(1:end-1, :);\n end\n \n backward{i} = tmp .* (1 - resp{i}) .* resp{i};\n \n if (i-1) >= 1\n\tif (size(W{i}, 2) == size(resp{i-1}, 1) + 1)\n\t grad{i} = backward{i} * [resp{i-1}' onesncases];\n\telse\n\t grad{i} = backward{i} * resp{i-1}';\n\tend\n else\n\tgrad{i} = backward{i} * X';\n end\n end\n end\n \nelseif (nonlinearity == 3)\n \n if (exist('nonzero_grad', 'var'))\n snonzero_grad = sum(nonzero_grad);\n if (snonzero_grad == 0)\n for i=nlayer:-1:1\n\tgrad{i} = zeros(size(W{i}));\n end\n return;\n end\n \n for i=nlayer:-1:1\n if (i == nlayer)\n\ttmp = hout(:, nonzero_grad);\n else\n\ttmp = (W{i+1}' * backward{i+1});\n end\n \n if (size(tmp, 1) ~= size(resp{i}, 1))\n\ttmp = tmp(1:end-1, :);\n end\n \n if (i == nlayer)\n\tbackward{i} = tmp .* (1 - resp{i}(:,nonzero_grad)^2);\n else\n\tbackward{i} = tmp .* (1 - resp{i}(:,nonzero_grad)) .* resp{i}(:,nonzero_grad);\n end\n \n if (i-1) >= 1\n\tif (size(W{i}, 2) == size(resp{i-1}, 1) + 1)\n\t grad{i} = backward{i} * [resp{i-1}(:,nonzero_grad)' gones(snonzero_grad,1,gputype)];\n\telse\n\t grad{i} = backward{i} * resp{i-1}(:,nonzero_grad)';\n\tend\n else\n\tgrad{i} = backward{i} * X(:, nonzero_grad)';\n end\n end\n else\n for i=nlayer:-1:1\n if (i == nlayer)\n\ttmp = hout;\n else\n\ttmp = (W{i+1}' * backward{i+1});\n end\n \n if (size(tmp, 1) ~= size(resp{i}, 1))\n\ttmp = tmp(1:end-1, :);\n end\n \n if (i == nlayer)\n\tbackward{i} = tmp .* (1 - resp{i}.^2);\n else\n\tbackward{i} = tmp .* (1 - resp{i}) .* resp{i};\n end\n\n if (i-1) >= 1\n\tif (size(W{i}, 2) == size(resp{i-1}, 1) + 1)\n\t grad{i} = backward{i} * [resp{i-1}' onesncases];\n\telse\n\t grad{i} = backward{i} * resp{i-1}';\n\tend\n else\n\tgrad{i} = backward{i} * X';\n end\n end\n end\n\nend\n", "meta": {"author": "norouzi", "repo": "hdml", "sha": "78e01180fc2494db31f04a9f4653456a8bfb8ba0", "save_path": "github-repos/MATLAB/norouzi-hdml", "path": "github-repos/MATLAB/norouzi-hdml/hdml-78e01180fc2494db31f04a9f4653456a8bfb8ba0/compute_NN_grad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5992905195978329}} {"text": "% GP_COV_SUM - Covariance function as a sum of two covariance functions.\n%\n% Usage:\n%\n% COVFUNC = GP_COV_SUM(COVFUNC1, COVFUNC2)\n%\n% The returned covariance function is called as\n%\n% K = COVFUNC(THETA)\n% [K, DK] = COVFUNC(THETA)\n%\n% where THETA is a vector of parameters. The parameters of COVFUNC1 and\n% COVFUNC2 are concatenated into a single parameter vector.\n%\n% If no arguments are given, dimensionality information is returned:\n%\n% [N_THETA, N1, N2] = COVFUNC()\n%\n% N_THETA : Number of non-fixed parameters\n% N1 : Number of rows in the covariance matrix\n% N2 : Number of columns in the covariance matrix\n%\n% See also GP_COV, GP_COV_PRODUCT.\n\n% Last modified 2010-01-25\n% Copyright (c) Jaakko Luttinen (jaakko.luttinen@tkk.fi)\n\nfunction func = gp_cov_sum(varargin)\n\nfunc = @get_covariance;\n\nif nargin < 2\n error('Must give at least two covariance functions')\nend\n\ncovfuncs = varargin ;\n\n% Number of covariance functions\nn_funcs = nargin ;\n\n% Number of parameters for each covariance function\nn_theta = zeros(n_funcs,1) ;\n% Dimensionalities of each covariance function\nM = zeros(n_funcs,1) ;\nN = zeros(n_funcs,1) ;\n% Extract the values from the covariance functions\nfor i = 1:n_funcs\n [n_theta(i), M(i), N(i)] = varargin{i}();\nend\n\n% Indices of the hyperparameters for each covariance function\nind_theta = cell(n_funcs,1);\nfor i = 1:n_funcs\n ind_theta{i} = (1+sum(n_theta(1:(i-1)))):(sum(n_theta(1:i))) ;\nend\n\n%[n_theta1, M1, N1] = covfunc1();\n%[n_theta2, M2, N2] = covfunc2();\n\nif ~all(M == M(1)) || ~all(N == N(1))\n error('Can''t sum covariance matrices with different dimensionalities');\nend\nM = M(1) ;\nN = N(1) ;\n\n function varargout = get_covariance(theta)\n \n if nargout == 0\n nout = 1 ;\n else\n nout = nargout ;\n end\n \n varargout = cell(nout,1);\n\n out = cell(nout,1);\n varargout = cell(nout,1);\n \n % Return only dimension information if requested\n if nargin == 0\n if nout >= 1\n varargout{1} = sum(n_theta); % number of parameters\n if nout >= 2\n varargout{2} = M; % dimensionalities\n if nout >= 3\n varargout{3} = N; % dimensionalities\n end\n end\n end\n return\n end\n\n varargout{1} = 0 ;\n varargout{2} = cell(sum(n_theta),1) ;\n \n for i = 1:n_funcs\n % Compute the covariance matrix\n [out{:}] = covfuncs{i}(theta(ind_theta{i}));\n varargout{1} = varargout{1} + out{1};\n \n % Compute the derivative\n if nout >= 2\n varargout{2}(ind_theta{i}) = out{2}(:);\n end\n end\n \n end\n\nend", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/gp/gp_cov_sum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095992, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.5992588175898862}} {"text": "function [beta, t, pvals, convals, con_t, con_pvals, sigma, Phi, df, stebeta, conste, F] = fit_gls(y, X, c, p, varargin)\n% Fit a linear model using generalized least squares and an AR(p) model\n%\n% :Usage:\n% ::\n%\n% [beta, t, pvals, convals, con_t, con_pvals, sigma, Phi, df, stebeta, conste, F] = fit_gls(y,X,c,p,[PX, equal to pinv(X), for speed], [Weights])\n%\n% This program uses the Cochrane-Orcutt algorithm to iteratively find the\n% GLS solution and estimate the noise parameters.\n%\n% Step 1: Find the OLS solution.\n%\n% Step 2: Use residuals from the previous fit to estimate the parameters in\n% the AR(p) noise model.\n%\n% Step 3: Find the GLS solution using the covariance matrix corresponding\n% to an AR(p) model with parameters estimated in Step 2 inserted.\n%\n% Step 4: Repeat steps 2-3 until convergence.\n%\n% :Inputs:\n%\n% **y:**\n% fMRI time course (T x 1 vector)\n%\n% **X:**\n% Design matrix (T x param matrix)\n%\n% **c:**\n% contrast vector(s) (param x # contrasts matrix)\n%\n% **p:**\n% order of AR model.\n%\n% **PX:**\n% pinv(X), for speeded, repeated calculations with different y vectors\n%\n% Note: if using weights, px = inv(X' * W * X) * X' * W; \n% where W = diag(Weights);\n%\n% **Weights:**\n% Optional, vector of weights for each observation\n%\n% Empty or missing: Unweighted analysis.\n%\n% Note that setting p=0 implies a white noise model.\n%\n% :Output:\n%\n% **t:**\n% t-value for the contrast c'beta\n%\n% **df:**\n% degrees of freedom using Satterthwaite approximation\n%\n% **beta:**\n% beta vector\n%\n% **Phi:**\n% vector of coefficients in AR(p) model\n%\n% **sigma:**\n% standard deviation\n%\n% **stebeta:**\n% standard error of betas\n%\n% ..\n% by Martin Lindquist\n%\n% Last updated: 3/29/08, Tor Wager, added weighted least squares\n% verified that beta and t-values are identical to\n% glmfit.m in matlab7.5 with ar p = 0\n% ***AR(p) with weighted least squares needs to be\n% checked. behaving reasonably.\n% 4/1/08, Tor : output stats for boht betas and contrasts\n% Reorganized order of outputs\n% 5/15/08 Tor : Weird things happening with single inputs; particulaly with aryule; force\n% double\n% ..\n\ny = double(y);\nX = double(X);\n\nT = length(y); % Length of time course\n\nk = size(X, 2); % predictors\n\n\nif length(varargin) > 1\n w = double(varargin{2}); % weights for weighted least squares\nelse\n w = ones(T, 1);\nend\nW = diag(w);\nsqrtW = sqrt(W); % for weighted residuals\n\nif ~isempty(varargin) && ~isempty(varargin{1})\n px = double(varargin{1});\nelse\n invxvx = inv(X' * W * X); % we can re-use this later if p == 0\n px = invxvx * X' * W; \nend\n\n\n% Step 1: Find the OLS solution \nbeta = px*y; % Beta values; weighted, if weights are used\nresid = sqrtW * y - sqrtW * X * beta; % Residuals (Weighted, if weights are used)\nsigma = sqrt((1 / (T - k)) * resid' * resid); %sum(resid.^2))); % Estimate of Sigma\n\n% Weighted residuals: Three equivalent ways\n% We pick one that is compatible with AR estimation\n% 1)\n% beta = px*y; % Beta values\n% resid = y - X*beta; % Residuals\n% sigma = sqrt((1 / (T - k)) * resid' * W * resid); %sum(resid.^2))); % Estimate of Sigma\n\n% 2) \n%r2 = sqrt(W) * resid; sigma2 = sqrt((1 / (T - k)) * r2' * r2)\n\n% 3)\n% r2 = sqrt(W) * y - sqrt(W) * X * beta;\n% sigma2 = sqrt((1 / (T - k)) * r2' * r2)\n\n% Stuff needed for future iterations\niV = W; % for ar p = 0 case\nA = W; % for ar p = 0 case\nPhi = 0;\nbetaold = 0;\n\n% Steps 2-4: Find the GLS solution by iteration \n% If p=0, skip this step. Appropriate solution already calculated above.\n% Continue iteration until convergence or for at most 10 loops.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Note to Jack and Tor: Keith Worsley uses a similar algorithm when fitting\n% a GLM with an AR(p) noise model. However, he skips the iterative step\n% and only goes through the loop one time. He claims that this is enough. I\n% am not entirely convinced, therefore it is probably better to go through\n% a few times if needed.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\ni=1; % Set counter\n\nwhile i < 10 && p > 0 && (i == 1 || sum((beta - betaold).^2) > 0.001)\n % Do up to 10 iterations, if arp > 0 and either first iteration or\n % there's a difference from last iteration\n \n % resid = y - X*beta; % Calculate residuals of current model fit\n\n resid = sqrtW * y - sqrtW * X * beta; % Residuals (Weighted, if weights are used)\n\n % Estimate AR parameters using residuals\n [a,e] = aryule(resid, p);\n Phi =zeros(length(a)-1,1);\n Phi(1:p) = -a(2:(p+1));\n\n %sigma = sqrt(e); % swrtW*e?? % Moved later, because never used until\n %after iteration loop\n\n % Find the inverse of the covariance matrix\n A = sqrtW; % ***should be sqrt(W)?\n\n for j=1:p\n %A = A + diag(-Phi(j)*ones((T-j),1),-j);\n\n A = A + sqrtW * diag(-Phi(j)*ones((T-j),1),-j);\n end;\n\n %create_figure('A'); imagesc(A, [-.2 .2]); colorbar, drawnow, input(' ')\n\n iV = A*A'; % New weights, with AR estimates, The inverse of the covariance matrix\n\n\n betaold = beta; % Set old solution to be betaold\n beta = inv(X'*iV*X)*X'*iV*y; % Calculate new solution\n\n i = i+1; % Add one to counter\n\n %create_figure('COV'); imagesc(iV, [-.02 .02]); colorbar, drawnow, input(' ')\nend\n\nif p > 0 \n % re-calc sigma\n sigma = sqrt(e);\n\n invxvx = inv(X'*iV*X);\n \n % Should we use the kind of thing below? Seems like sqrt(e) is unweighted,\n % though it seems reasonable...\n % sqrtiv = sqrt(iV);\n % resid = sqrtiv * y - sqrtiv * X * beta; % Residuals (Weighted, if weights are used)\n % sigma = sqrt((1 / (T - k)) * resid' * resid)\nend\n\n\n\nR = (eye(T) - X * invxvx * X' * iV); % Residual inducing matrix\n\nWd = R * A * inv(iV) * A'; % inv(iV) = Covariance matrix\ndf = (trace(Wd).^2)./trace(Wd*Wd); % Satterthwaite approximation for degrees of freedom\n\n\n% Should check on below: this creates difference in t-values from\n% glmfit...but why wouldn't we need to re-calculate a (larger) sigma if we have reduced df?\n% if df ~= (T - k) % Tor added 3/29, have to re-calculate sigma\n% sigma = sqrt((1 / df) * resid' * iV * resid); %sum(resid.^2))); % Estimate of Sigma\n% end\n\nvarbeta = sigma^2.* invxvx; % Var(beta)\nstebeta = diag(varbeta).^.5;\nt = beta ./ stebeta;\n\nconvals = [];\nconste = [];\ncon_t = [];\ncon_pvals = [];\nF = [];\nif ~isempty(c)\n % Contrast(s)\n convals = (c' * beta);\n conste = diag(c' * varbeta * c).^.5; % tor added as output\n con_t = convals ./ conste; %sqrt(c'*varbeta*c); % t-value\nend\n\n% get rid of nuisance regressors that aren't in any contrast\n% wh = stebeta > 0;\n% c = c(wh,wh); \n% beta = beta(wh);\n% stebeta = stebeta(wh);\n% \n% if ~isempty(c)\n% beta = (c' * beta);\n% %beta = beta(wh);\n% t = beta ./ stebeta; %sqrt(c'*varbeta*c); % t-value\n% else\n% t = beta(wh) ./ stebeta;\n% end\n\n%%%%%% Test H0: beta_1 = beta_2 = .... = beta_param = 0\nif nargout > 6\n SSE = y'*y - beta'*X'*y; % Error sum of squares\n mSSE = SSE/df;\n J = ones(T);\n SST=y'*y - (1/T).*y'*J*y; % Total sum of squares\n SSM=SST-SSE; % Model sum of squares\n\n dfSSM=length(c) - 1; % degrees of freedom for model (param - 1)\n mSSM=SSM/dfSSM;\n\n F=mSSM/mSSE; % F-statistic - compare with F-distruibution with (param-1, df) degrees of freedom\nend\n\n% % get contrast values if we need those\n% if ~isempty(c)\n% beta = (beta' * c)';\n% end\n\nif nargout > 2\n pvals = 2 .* (1 - tcdf(abs(t), df)); % two-tailed\n \n \n % make sure p-values for valid results are not zero...\n pvals(pvals == 0 & beta ~= 0 & ~isnan(beta)) = 1000*eps;\n \n if ~isempty(c) && nargout > 5\n con_pvals = 2 .* (1 - tcdf(abs(con_t), df)); % two-tailed\n \n con_pvals(con_pvals == 0 & convals ~= 0 & ~isnan(convals)) = 1000*eps;\n end\n \nend\n\nreturn\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Statistics_tools/fit_gls.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.599258816313898}} {"text": "function [ quasi, seed_new ] = sobol ( dim_num, seed )\n\n%% SOBOL generates a new quasirandom Sobol vector with each call.\n%\n% Discussion:\n%\n% The routine adapts the ideas of Antonov and Saleev.\n%\n% Modified:\n%\n% 30 March 2003\n%\n% Reference:\n%\n% Antonov and Saleev,\n% USSR Computational Mathematics and Mathematical Physics,\n% Volume 19, 1980, pages 252 - 256.\n%\n% Paul Bratley and Bennett Fox,\n% Algorithm 659:\n% Implementing Sobol's Quasirandom Sequence Generator,\n% ACM Transactions on Mathematical Software,\n% Volume 14, Number 1, pages 88-100, 1988.\n%\n% Bennett Fox,\n% Algorithm 647:\n% Implementation and Relative Efficiency of Quasirandom \n% Sequence Generators,\n% ACM Transactions on Mathematical Software,\n% Volume 12, Number 4, pages 362-376, 1986.\n%\n% I Sobol,\n% USSR Computational Mathematics and Mathematical Physics,\n% Volume 16, pages 236-242, 1977.\n%\n% I Sobol and Levitan, \n% The Production of Points Uniformly Distributed in a Multidimensional \n% Cube (in Russian),\n% Preprint IPM Akad. Nauk SSSR, \n% Number 40, Moscow 1976.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the number of spatial dimensions.\n% DIM_NUM must satisfy 2 <= DIM_NUM <= 40.\n%\n% Input/output, integer SEED, the \"seed\" for the sequence.\n% This is essentially the index in the sequence of the quasirandom\n% value to be generated. On output, SEED has been set to the\n% appropriate next value, usually simply SEED+1.\n% If SEED is less than 0 on input, it is treated as though it were 0.\n% An input value of 0 requests the first (0-th) element of the sequence.\n%\n% Output, real QUASI(DIM_NUM), the next quasirandom vector.\n%\n global SOBOL_lastq;\n global SOBOL_seed;\n\n dim_max = 40;\n%\n% Initialize (part of) V.\n%\n v(1:40,1:30) = zeros(40,30);\n\n v(1:40,1) = [ ...\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]';\n\n v(3:40,2) = [ ...\n 1, 3, 1, 3, 1, 3, 3, 1, ...\n 3, 1, 3, 1, 3, 1, 1, 3, 1, 3, ...\n 1, 3, 1, 3, 3, 1, 3, 1, 3, 1, ...\n 3, 1, 1, 3, 1, 3, 1, 3, 1, 3 ]';\n\n v(4:40,3) = [ ...\n 7, 5, 1, 3, 3, 7, 5, ...\n 5, 7, 7, 1, 3, 3, 7, 5, 1, 1, ...\n 5, 3, 3, 1, 7, 5, 1, 3, 3, 7, ...\n 5, 1, 1, 5, 7, 7, 5, 1, 3, 3 ]';\n\n v(6:40,4) = [ ...\n 1, 7, 9,13,11, ...\n 1, 3, 7, 9, 5,13,13,11, 3,15, ...\n 5, 3,15, 7, 9,13, 9, 1,11, 7, ...\n 5,15, 1,15,11, 5, 3, 1, 7, 9 ]';\n \n v(8:40,5) = [ ...\n 9, 3,27, ...\n 15,29,21,23,19,11,25, 7,13,17, ...\n 1,25,29, 3,31,11, 5,23,27,19, ...\n 21, 5, 1,17,13, 7,15, 9,31, 9 ]';\n\n v(14:40,6) = [ ...\n 37,33, 7, 5,11,39,63, ...\n 27,17,15,23,29, 3,21,13,31,25, ...\n 9,49,33,19,29,11,19,27,15,25 ]';\n\n v(20:40,7) = [ ...\n 13, ...\n 33,115, 41, 79, 17, 29,119, 75, 73,105, ...\n 7, 59, 65, 21, 3,113, 61, 89, 45,107 ]';\n\n v(38:40,8) = [ ...\n 7, 23, 39 ]';\n%\n% Set POLY.\n%\n poly(1:40)= [ ...\n 1, 3, 7, 11, 13, 19, 25, 37, 59, 47, ...\n 61, 55, 41, 67, 97, 91, 109, 103, 115, 131, ...\n 193, 137, 145, 143, 241, 157, 185, 167, 229, 171, ...\n 213, 191, 253, 203, 211, 239, 247, 285, 369, 299 ];\n%\n% Check parameters.\n%\n if ( dim_num < 2 | dim_max < dim_num )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SOBOL - Fatal error!\\n' );\n fprintf ( 1, ' The spatial dimension DIM_NUM should satisfy:\\n' );\n fprintf ( 1, ' 2 <= DIM_NUM <= %d\\n', dim_max );\n fprintf ( 1, ' But this input value is DIM_NUM = %d\\n', dim_num );\n return\n end\n\n atmost = 2^30 - 1;\n%\n% Find the number of bits in ATMOST.\n%\n maxcol = bit_hi1_base_2 ( atmost );\n%\n% Initialize row 1 of V.\n%\n v(1,1:maxcol) = 1;\n%\n% Initialize the remaining rows of V.\n%\n for ( i = 2 : dim_num )\n%\n% The bit pattern of the integer POLY(I) gives the form\n% of polynomial I.\n%\n% Find the degree of polynomial I from binary encoding.\n%\n j = poly(i);\n m = 0;\n\n while ( 1 )\n\n j = floor ( j / 2 );\n\n if ( j <= 0 )\n break;\n end\n\n m = m + 1;\n\n end\n%\n% We expand this bit pattern to separate components of the logical array INCLUD.\n%\n j = poly(i);\n for ( k = m : -1 : 1 )\n j2 = floor ( j / 2 );\n includ(k) = ( j ~= 2 * j2 );\n j = j2;\n end\n%\n% Calculate the remaining elements of row I as explained\n% in Bratley and Fox, section 2.\n%\n for ( j = m + 1 : maxcol )\n\n newv = v(i,j-m);\n l = 1;\n\n for ( k = 1 : m )\n\n l = 2 * l;\n\n if ( includ(k) )\n newv = exor ( newv, l * v(i,j-k) );\n end\n\n end\n\n v(i,j) = newv;\n\n end\n\n end\n%\n% Multiply columns of V by appropriate power of 2.\n%\n l = 1;\n for ( j = maxcol-1 : -1 : 1 )\n l = 2 * l;\n v(1:dim_num,j) = v(1:dim_num,j) * l;\n end\n%\n% RECIPD is 1/(common denominator of the elements in V).\n%\n recipd = 1.0E+00 / ( 2 * l );\n\n seed = floor ( seed );\n\n if ( seed < 0 )\n seed = 0;\n end\n\n if ( seed == 0 )\n\n l = 1;\n SOBOL_lastq(1:dim_num) = 0;\n\n elseif ( seed == SOBOL_seed + 1 )\n%\n% Find the position of the right-hand zero in SEED.\n%\n l = bit_lo0_base_2 ( seed );\n\n elseif ( seed <= SOBOL_seed )\n\n SOBOL_seed = 0;\n l = 1;\n SOBOL_lastq(1:dim_num) = 0;\n\n for ( seed_temp = SOBOL_seed : seed-1 )\n\n l = bit_lo0_base_2 ( seed_temp );\n\n for ( i = 1 : dim_num )\n SOBOL_lastq(i) = exor ( SOBOL_lastq(i), v(i,l) );\n end\n\n end\n\n l = bit_lo0_base_2 ( seed );\n\n elseif ( SOBOL_seed+1 < seed )\n\n for ( seed_temp = SOBOL_seed+1 : seed-1 )\n\n l = bit_lo0_base_2 ( seed_temp );\n\n for ( i = 1 : dim_num )\n SOBOL_lastq(i) = exor ( SOBOL_lastq(i), v(i,l) );\n end\n\n end\n\n l = bit_lo0_base_2 ( seed );\n\n end\n%\n% Check that the user is not calling too many times!\n%\n if ( maxcol < l )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SOBOL - Fatal error!\\n' );\n fprintf ( 1, ' Too many calls!\\n' );\n fprintf ( 1, ' MAXCOL = %d\\n', maxcol );\n fprintf ( 1, ' L = %d\\n', l );\n return\n end\n%\n% Calculate the new components of QUASI.\n%\n for ( i = 1 : dim_num )\n\n quasi(i) = SOBOL_lastq(i) * recipd;\n\n SOBOL_lastq(i) = exor ( SOBOL_lastq(i), v(i,l) );\n\n end\n\n SOBOL_seed = seed;\n seed_new = seed + 1;\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/OptimizeDesign11/GA3/Sobol/sobol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095992, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5992588126762608}} {"text": "function w = dwt3D(x, J, af)\n\n% 3-D Discrete Wavelet Transform\n%\n% USAGE:\n% w = dwt3D(x, stages, af)\n% INPUT:\n% x - N1 by N2 by N3 matrix\n% 1) Ni all even\n% 2) min(Ni) >= 2^(J-1)*length(af)\n% J - number of stages\n% af - analysis filters\n% OUTPUT:\n% w - cell array of wavelet coefficients\n% EXAMPLE:\n% [af, sf] = farras;\n% x = rand(128,64,64);\n% w = dwt3D(x,3,af);\n% y = idwt3D(w,3,sf);\n% err = x-y; \n% max(max(max(abs(err))))\n%\n% WAVELET SOFTWARE AT POLYTECHNIC UNIVERSITY, BROOKLYN, NY\n% http://taco.poly.edu/WaveletSoftware/\n\nfor k = 1:J\n [x w{k}] = afb3D(x, af, af, af);\nend\nw{J+1} = x;\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/utils/utils_TRAFO/DTCWT/dwt3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5992588064866473}} {"text": "function [nuisance_ratio, rsquare_design, rsquare_nuis] = scn_component_rsquare(V, nuisanceX, designX)\n% Print a table of r-square values (variance explained) for each of V data\n% vectors by nuisance (mvmt, physio) and task-related predictors\n%\n% Designed to work with components\n%\n% :Examples:\n% ::\n%\n% % Typical operation\n% scn_component_rsquare(compscore, movement_params(1:157, :), X(1:157, :));\n%\n% % No design\n% scn_component_rsquare(compscore, movement_params(1:157, :));\n%\n% % Neither design nor nuisance, uses linear drift\n% scn_component_rsquare(compscore, []);\n%\n% ..\n% Tor Wager, Feb 2008\n% ..\n\n[t, m] = size(V);\n\nif nargin < 3, designX = []; end\n\nif isempty(nuisanceX) \n disp('Looking for nuisance covariates, but none found. Using linear drift.');\n nuisanceX = (1:t)'; \nend\n \ndisp('Variance in each component explained:')\n\n% Nuisance\nrsquare_nuis = get_rsquare(V, nuisanceX)';\n\nif ~isempty(designX)\nrsquare_design = get_rsquare(V, designX)';\nelse\n rsquare_design = .01 * ones(m, 1);\nend\n\nnuisance_ratio = rsquare_nuis ./ rsquare_design;\n\nnuis_related = find(nuisance_ratio > 2);\ntask_related = find(nuisance_ratio < 1);\n\n%rank_badness = sort(nuisance_ratio, 1, 'descend');\ndisp('All components');\nprint_matrix([(1:m)' rsquare_design rsquare_nuis nuisance_ratio], {'Comp.' 'R^2 Task' 'R^2 Nuisance' 'Ratio'});\nfprintf('\\n');\n\ndisp('Most task-related');\nif isempty(designX)\n disp('NO DESIGN INFORMATION.');\nelse\nprint_matrix([task_related rsquare_design(task_related) rsquare_nuis(task_related) nuisance_ratio(task_related)], {'Comp.' 'R^2 Task' 'R^2 Nuisance' 'Ratio'});\nend\nfprintf('\\n');\n\ndisp('Most nuisance-related');\nprint_matrix([nuis_related rsquare_design(nuis_related) rsquare_nuis(nuis_related) nuisance_ratio(nuis_related)], {'Comp.' 'R^2 Task' 'R^2 Nuisance' 'Ratio'});\nfprintf('\\n');\n\n\n%fprintf('\\tComp %3.0f : %3.0f%%\\n', j, rsquare(j)*100);\nend\n\nfunction rsquare = get_rsquare(V, X)\n\n [t, m] = size(V);\n \n for j = 1:m\n % Center component to avoid counting intercept in r-square?\n % Don't have to, doesn't matter because var operator is 2nd moment\n y = V(:, j); \n b = X \\ y;\n\n fits = X * b;\n\n rsquare(j) = var(fits) / var(y);\n \n end\n\n \nend\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/diagnostics/scn_component_rsquare.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.5992587966593964}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Q = INVERSEKINEMATIC_SCARA(robot, T)\t\n% Solves the inverse kinematic problem for the SCARA example 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_SCARA returns 2 possible solutions, thus,\n% Q is a 4x4 matrix where each column stores 4 feasible joint values.\n%\n% \n% Example code:\n%\n% robot=load_robot('example', 'scara');\n% q = [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:2,\n% Ti = directkinematic(robot, qinv(:,i))\n% end\n%\n%\tSee also DIRECTKINEMATIC.\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_scara(robot, T)\n\nfprintf('\\nComputing inverse kinematics for the %s robot', robot.name);\n\n\n%initialize q\nq=zeros(4,2);\n\n%Evaluate the DH table to obtain geometric parameters\nd = eval(robot.DH.d);\na = eval(robot.DH.a);\n\n%Store geometric parameters\nL1=abs(d(1));\nL2=abs(a(1));\nL3=abs(a(2));\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\n%Distance of the point to the origin of S0\nR = sqrt(Px^2+Py^2);\n\n%Compute angles\ngamma = real(acos((L2^2+R^2-L3^2)/(2*R*L2)));\nbeta = atan2(Py,Px); \ndelta = real(acos((L2^2+L3^2-R^2)/(2*L2*L3)));\n\n%find the last rotation for the two possible configurations\nq4_1= find_last_rotation(robot,[beta+gamma delta-pi L1-Pz 0], T);\nq4_2= find_last_rotation(robot,[beta-gamma pi-delta L1-Pz 0], T);\n\n%Arrange all possible solutions\nq=[beta+gamma beta-gamma;\n delta-pi pi-delta;\n L1-Pz L1-Pz;\n q4_1 q4_2];\n\n\n% Compute the last rotation\nfunction q4 = find_last_rotation(robot, q, T)\n\nU = T(1:3,1);\n\n%Recompute the DH table according to q1, q2 and q3\ntheta = eval(robot.DH.theta);\nd = eval(robot.DH.d);\na = eval(robot.DH.a);\nalpha = eval(robot.DH.alpha);\n\n%now compute the position/orientation of the system S3\nH=eye(4);\nfor i=1:3,\n H=H*dh(theta(i), d(i), a(i), alpha(i));\nend\n\nX3=H(1:3,1);\nY3=H(1:3,2);\n\ncoseno=X3'*U;\nseno=U'*Y3;\n%compute the last rotation\nq4=atan2(seno,coseno);\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/example/scara/inversekinematic_scara.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5992534276334974}} {"text": "function Gamma = simgamma_ltd(T,P,Pi,rate,L,refractory_period,grouping)\n%\n% Simulate state time courses with longer-than-order-1-markov time dependencies\n%\n% INPUTS:\n%\n% T Number of time points for each time series\n% P Transition probability matrix (K by K)\n% Pi Initial probabilities (K by 1)\n% rate The weights that model the contribution of the\n% latest L points are modelled by a Gamma\n% distribution, whose shape is 1 - and rate is\n% specified here\n% L The length of the history (in number of time points)\n% that influences the state at time t\n% refractory_period to prevent bursts of quick changes, refractory_period\n% can be set so that, after a change, you cannot change again \n% after 'refractory_period' number of iterations\n%\n% OUTPUTS\n%\n% Gamma simulated p(state | data)\n%\n% Author: Diego Vidaurre, OHBA, University of Oxford\n\nN = length(T); K = length(Pi);\n\nif nargin<4, rate = 2; end\nif nargin<5, L = 10; end \nif nargin<6, refractory_period = 2; end \nif nargin<7, grouping = []; end\n\nGamma = zeros(sum(T),K);\nweights = gampdf(0:L-1,1,rate)'; \nweights = weights / sum(weights);\nweights = weights(end:-1:1);\n\nfor n = 1:N\n if ~isempty(grouping)\n i = grouping(n);\n Pn = P(:,:,i); Pin = Pi(:,i)';\n else\n Pn = P; Pin = Pi;\n end \n Gammai = zeros(T(n),K);\n if any(Pin==1)\n Gammai(1,Pin==1) = 1;\n else\n Gammai(1,:) = mnrnd(1,Pin);\n end\n last_ch = Inf; \n for t = 2:L \n if last_ch < refractory_period\n Gammai(t,:) = Gammai(t-1,:); \n last_ch = last_ch + 1;\n else\n if t==2\n g = repmat(weights(end-t+2:end,1),1,K) .* Gammai(1:t-1,:);\n else\n g = sum(repmat(weights(end-t+2:end,1),1,K) .* Gammai(1:t-1,:));\n end\n g = g / sum(g);\n Gammai(t,:) = mnrnd(1,g*Pn);\n if any(Gammai(t,:)~=Gammai(t-1,:)), last_ch = 1; end\n Gammai(t,:) = Gammai(t,:) / sum(Gammai(t,:)); \n end\n end\n for t=L+1:T(n)\n if last_ch < refractory_period\n Gammai(t,:) = Gammai(t-1,:);\n last_ch = last_ch + 1;\n else\n g = sum(repmat(weights,1,K) .* Gammai(t-L:t-1,:));\n Gammai(t,:) = mnrnd(1,g*Pn);\n if any(Gammai(t,:)~=Gammai(t-1,:)), last_ch = 1; end\n end\n end\n t = (1:T(n)) + sum(T(1:n-1));\n Gamma(t,:) = Gammai;\nend\n\nend\n\n", "meta": {"author": "OHBA-analysis", "repo": "HMM-MAR", "sha": "bb0433b75482e473980791a2b30afe2012cf6578", "save_path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR", "path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR/HMM-MAR-bb0433b75482e473980791a2b30afe2012cf6578/simulate/simgamma_ltd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5992534261981918}} {"text": "function rchy = realized_hayashi_yoshida(priceA,timeA,priceB,timeB,timeType,samplingType,samplingInterval,overlap)\n% Computed the Hayashi-Yoshida estimator of quadratic covariation, and allows for\n% the empirical-performance motivated K-lead-and-lag version similar to Drost and Nijman (1997).\n%\n% USAGE:\n% [RCHY] = realized_hayashi_yoshida_(PRICEA,TIMEA,PRICEB,TIMEB,TIMETYPE,SAMPLINGTYPE,SAMPLINGINTERVAL,OVERLAP)\n%\n% INPUTS:\n% PRICEA - mA by 1 vector of high frequency prices\n% TIMEA - mA by 1 vector of times where TIMEB(i) corresponds to PRICEA(i)\n% PRICEA - mB by 1 vector of high frequency prices\n% TIMEA - mB by 1 vector of times where TIMEB(i) corresponds to PRICEB(i)\n% TIMETYPE - String describing the way times are measured\n% 'wall' 24-hour clock of the form HHMMSS, e.g. 101543 or 153217\n% 'seconds' Time measures in seconds past midnight.\n% TIME must satisfy 0<=TIME<86400\n% 'unit' Unit normalized date format, e.g. .1, .234, .9\n% Unit normalized times are more general than the\n% other types and can be applied to data from more\n% than one calendar day\n% SAMPLINGTYPE - String describing the type of sampling to use when\n% filtering PRICE\n% 'CalendarTime' - Sample in calendar time using\n% observations separated by SAMPLINGINTERVAL\n% seconds. If TIMETYPE is 'unit',\n% SAMPLINGINTERVAL must be between 0 and 1 and\n% represents the fraction of the sample to skip\n% when sampling.\n% 'CalendarUniform' - Sample in calendar time using\n% SAMPLINGINTERVAL observations spread uniformly\n% between TIME(1) and TIME(m)\n% 'BusinessTime' - Sample in business (tick) time\n% using observation separated by SAMPLINGINTERVAL\n% ticks\n% 'BusinessUniform' - Sample in business (tick)\n% time using observations uniformly spaced in\n% business time.\n% 'Fixed' - Sample at specific points in time. When\n% using fixed, SAMPLINGINTERVAL must be a n by 1 vector\n% of times with the same TIMETYPE as TIME (i.e.\n% seconds if TIME is in seconds)\n% SAMPLINGINTERVAL - Scalar integer or n by 1 vector whose meaning depends on the\n% selected SAMPLINGTYPE\n% OVERLAP - Number of ticks to overlap when computing the HY estimator. The original HY\n% estimator uses 0, which corresponds to the maximum likelihood estimator for\n% price processes whose observation times are driven by independent Poisson\n% processes. Empirically this estimator performs poorly because prices are\n% not a vector semi-martingale and using a larger number of lags can alleviate\n% this problem.\n%\n% OUTPUTS:\n% RCHY - The K-lead-and-lag Hayashi-Yoshida covariance estimator\n%\n% COMMENTS:\n% Filtering the price in calendar time allow the creation of a Hayashi-Yoshida corrected\n% calendar-time sampled realized covariance. The value in SAMPLINGTYPE is applied to price A and\n% then the realized HY estimator is computed using the filtered price of A and the filtered times\n% of A, and all observations of B. Price filtering is done using realized_price_filter\n%\n% EXAMPLES:\n% % Standard use with all prices with wall time prices\n% RCHY = realized_hayashi_yoshida(PRICEA,TIMEA,PRICEB,TIMEB,'wall','BusinessTime',1,0)\n%\n% % 10 lead and lag RCHY with all prices with wall time prices\n% RCHY = realized_hayashi_yoshida(PRICEA,TIMEA,PRICEB,TIMEB,'wall','BusinessTime',1,10)\n%\n% % 1-minute realized covariance with a HY correction\n% RCHY = realized_hayashi_yoshida(PRICEA,TIMEA,PRICEB,TIMEB,'wall','CalendarTime',60,0)\n%\n% See also REALIZED_MULTIVARIATE_KERNEL, REALIZED_COVARIANCE, REALIZED_KERNEL, REALIZED_VARIANCE,\n% REALIZED_RANGE, REALIZED_QUANTILE_VARIANCE\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 1 Date: 5/1/2008\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif nargin<7 || nargin>8\n error('Seven or eight inputs required.')\nend\nif size(priceA,2)>size(priceA,1)\n priceA=priceA';\nend\nif size(priceA,2)>1\n error('PRICEA must be a m by 1 vector.')\nend\nif size(timeA,2)>size(timeA,1)\n timeA=timeA';\nend\nif any(diff(timeA)<0)\n error('TIMEA must be sorted and increasing')\nelseif any(diff(timeA)==0)\n warning('oxfordRealized:realizedPriceFilter','TIMEA contains multiple entries with the same value. This creates an ambiguity and FILTEREDPRICE will contain the last price if TIMEA does not only unique elements.')\nend\nif size(timeA,2)>1 || length(timeA)~=length(priceA)\n error('TIMEA must be a m by 1 vector.')\nend\n% Inserted to protect against inputing integer times\ntimeA = double(timeA);\nif size(priceB,2)>size(priceB,1)\n priceB=priceB';\nend\nif size(priceB,2)>1\n error('PRICEB must be a m by 1 vector.')\nend\nif size(timeB,2)>size(timeB,1)\n timeB=timeB';\nend\nif any(diff(timeB)<0)\n error('TIMEB must be sorted and increasing')\nelseif any(diff(timeB)==0)\n warning('oxfordRealized:realizedPriceFilter','TIMEB contains multiple entries with the same value. This creates an ambiguity and FILTEREDPRICE will contain the last price if TIMEB does not only unique elements.')\nend\nif size(timeB,2)>1 || length(timeB)~=length(priceB)\n error('TIMEB must be a m by 1 vector.')\nend\n% Inserted to protect against inputing integer times\ntimeB = double(timeB);\n\n% make sure the intersection is non-empty\nif ~(min(timeB)size(samplingInterval,1)\n samplingInterval=samplingInterval';\n end\n if ~(any(samplingInterval>=t0Original) && any(samplingInterval<=tTOriginal))\n error('At least one sampling interval must be between min(TIME) and max(TIME) when using ''Fixed'' as SAMPLINGTYPE.')\n end\n if any(diff(samplingInterval)<=0)\n error('When using ''Fixed'' as SAMPLINGTYPE the vector of sampling times in SAMPLINGINTERVAL must be sorted and strictly increasing.')\n end\nend\n\nif strcmp(timeType,'unit') && strcmp(samplingType,'calendartime')\n % samplingInterval must be between 0 and 1\n if samplingInterval>1\n error('When TIMETYPE is ''unit'' and SAMPLINGTYPE is ''CalendarTime'', SAMPLINGINTERVAL must also be in ''unit'' terms, and so must be between 0 and 1')\n end\nend\n\nif nargin==7\n overlap = 0;\nelseif overlap<0 || floor(overlap)~=overlap || max(size(overlap))>1\n error('OVERLAP must be a non-negative integer.')\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n% Price A is the base price, price B is the other price. First sample priceA according to\n% samplingType and samplingInterval, then use the actual times of these to estimate the HY\n% respecting the value in overlap\n\nif ~intersectionIsEmpty\n % First filter the price\n [filteredPriceA,filteredTimeA,actualTimeA] = realized_price_filter(priceA,timeA,timeType,samplingType,samplingInterval);\n\n % Then call the core routine\n rchy = realized_hayashi_yoshida_core(filteredPriceA,actualTimeA,priceB,timeB,overlap);\nelse\n rchy = 0;\nend\n\n\n\n\n\nfunction [rchy,times] = realized_hayashi_yoshida_core(priceA,timeA,priceB,timeB,overlap)\n% Core routine for computing the Hayashi-Yoshida estimator of quadratic covariation, and allows for\n% the empirical-performance motivated K-lead-and-lag version similar to Drost and Nijman (1997).\n%\n% USAGE:\n% [RCHY,TIMES] = realized_hayashi_yoshida_core(PRICEA,TIMEA,PRICEB,TIMEB,OVERLAP)\n%\n% INPUTS:\n% PRICEA - mA by 1 vector of high frequency prices\n% TIMEA - mA by 1 vector of times where TIMEB(i) corresponds to PRICEA(i)\n% PRICEA - mB by 1 vector of high frequency prices\n% TIMEA - mB by 1 vector of times where TIMEB(i) corresponds to PRICEB(i)\n% OVERLAP - [OPTIONA] Number of ticks to overlap when computing the HY estimator. The\n% original HY estimator uses 0, which corresponds to the maximum likelihood\n% estimator for price processes whose observation times are driven by\n% independent Poisson processes. Empirically this estimator performs poorly\n% because prices are not a vector semi-martingale and using a larger number\n% of lags can alleviate this problem. If omitted OVERLAP = 0.\n%\n% OUTPUTS:\n% RCHY - The K-lead-and-lag Hayashi-Yoshida covariance estimator\n% TIMES - A mA by 1 matrix of time stamps contains the times where the prices were\n% sampled for computing the returns in the HY estimator. This is mostly for\n% diagnostic purposes.\n%\n% COMMENTS:\n% This is a helper function of realized_hayashi_yoshida and does no input checking. In general\n% it should not be directly called.\n%\n% See also REALIZED_MULTIVARIATE_KERNEL, REALIZED_COVARIANCE, REALIZED_KERNEL, REALIZED_VARIANCE,\n% REALIZED_RANGE, REALIZED_QUANTILE_VARIANCE\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 1 Date: 5/1/2008\n\npriceA = log(priceA);\npriceB = log(priceB);\ntimeA = double(timeA);\ntimeB = double(timeB);\n% Price A is the base price, price B is the one which will move\n\n% First find the first time that B is available before timeA(1). If it is empty then find the first\n% timeA(1) which is weakly after the timeB(1)\nnA = size(priceA,1);\nnB = size(priceB,1);\n\nif timeA(1)timeB(nB)\n % A ends after B, so the easy solution is to project forward the last price B to the\n % time of the last A. This will generate a 0 return but makes the algorithm easier.\n timeB=[timeB;timeA(nA)];\n priceB=[priceB;priceB(nB)];\n nB = size(priceB,1);\nend\n\n\n\n\n% Initialize the indices for A and B\nindexA = 1;\nindexB = find(timeB<=timeA(1), 1,'last');\nif overlap>0\n indexB = max(indexB-overlap,1); % Make sure that indexB is >= 1\nend\n\n% Initialize rchy and the times\nrchy = 0;\ntimes = zeros(nA-1,4);\nwhile indexAtimeA(indexA)\n indexB = indexB - 1;\n end\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/realized/realized_hayashi_yoshida.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.5992534044337503}} {"text": "function [ S, f, Serr ]= mtspectrumc_unequal_length_trials( data, movingwin, params, sMarkers )\n\n% This routine computes the multi-taper spectrum for a given set of unequal length segments. It is\n% based on modifications to the Chronux routines. The segments are continuously structured in the \n% data matrix, with the segment boundaries given by markers. Below,\n% movingwin is used in a non-overlaping way to partition each segment into\n% various windows. Th spectrum is evaluated for each window, and then the\n% window spectrum estimates averaged. Further averaging is conducted by\n% repeating the process for each segment. \n%\n% Inputs: \n%\n% data = data( samples, channels )- here segments must be stacked\n% as explained in the email \n% movingwin = [window winstep] i.e length of moving\n% window and step size. Note that units here have\n% to be consistent with units of Fs. If Fs=1 (ie normalized)\n% then [window winstep]should be in samples, or else if Fs is\n% unnormalized then they should be in time (secs). \n% sMarkers = N x 2 array of segment start & stop marks. sMarkers(n, 1) = start\n% sample index; sMarkers(n,2) = stop sample index for the nth segment\n% params = see Chronux help on mtspecgramc\n%\n% Output:\n%\n% S frequency x channels\n% f frequencies x 1\n% Serr (error bars) only for err(1)>=1\n%\n%\n\niwAvg = 1; % 0=no weighted average, 1=weighted average\ndebug = 0; % will display intermediate calcs. \n\nif nargin < 2; error('Unequal length trials:: Need data and window parameters'); end;\nif nargin < 3; params=[]; end;\nif isempty( sMarkers ), error( 'Unequal length trials:: Need Markers...' ); end\n[ tapers, pad, Fs, fpass, err, trialave, params ] = getparams( params );\nif nargout > 2 && err(1)==0; \n% Cannot compute error bars with err(1)=0. change params and run again.\n error('Unequal length trials:: When Serr is desired, err(1) has to be non-zero.');\nend;\n\n% Set moving window parameters to no-overlapping\nif abs(movingwin(2) - movingwin(1)) >= 1e-6, disp( 'avgSpectrum:: Warming: Window parameters for averaging should be non-overlapping. Set movingwin(2) = movingwin(1).' ); end\n\nwLength = round( Fs * movingwin(1) ); % number of samples in window\nwStep = round( movingwin(2) * Fs ); % number of samples to step through\n\n% Check whether window lengths satify segment length > NW/2\nif ( wLength < 2*tapers(1) ), error( 'avgSpectrum:: movingwin(1) > 2*tapers(1)' ); end\n\n% Left align segment markers for easier coding\nsM = ones( size( sMarkers, 1 ), 2 ); \nsM( :, 2 ) = sMarkers( :, 2 ) - sMarkers( :, 1 ) + 1;\n\n% min-max segments \nNmax = max( sM(:,2) ); Nmin = min( sM(:,2) );\nif ( Nmin < 2*tapers(1) ), error( 'avgSpectrum:: Smallest segment length > 2*tapers(1). Change taper settings' ); end\n\n% max time-sample length will be the window length. \nnfft = 2^( nextpow2( wLength ) + pad );\n[ f, findx ] = getfgrid( Fs, nfft, fpass); \n\n% Precompute all the tapers\nsTapers = tapers;\nsTapers = dpsschk( sTapers, wLength, Fs ); % compute tapers for window length\n\nnChannels = size( data, 2 ); \nnSegments = size( sMarkers, 1 );\n\nif debug\n disp( ['Window Length = ' num2str(wLength)] );\n disp( ['Window Step = ' num2str(wStep)] );\n disp( ' ' );\nend\n\ns = zeros( length(f), nChannels );\nserr = zeros( 2, length(f), nChannels );\nS = zeros( length(f), nChannels );\nSerr = zeros( 2, length(f), nChannels );\nnWins = 0;\nfor sg = 1 : nSegments\n % Window lengths & steps fixed above\n % For the given segment, compute the positions & number of windows\n N = sM(sg,2); \n wStartPos = 1 : wStep : ( N - wLength + 1 );\n nWindows = length( wStartPos );\n if nWindows\n nWins = nWins + nWindows; % for averaging purposes\n\n w=zeros(nWindows,2);\n for n = 1 : nWindows\n w(n,:) = [ wStartPos(n), (wStartPos(n) + wLength - 1) ]; % nWindows x 2. just like segment end points\n end\n\n % Shift window limits back to original sample-stamps\n w(:, 1) = w(:,1) + (sMarkers( sg, 1 ) - 1);\n w(:, 2) = w(:,2) + (sMarkers( sg, 1 ) - 1);\n\n if debug\n disp( ['Segment Start/Stop = ' num2str( w(1,1) ) ' ' num2str( w(end,2) ) ] );\n disp( ['Min / Max Window Positions = ' num2str( min(w(:,1)) ) ' ' num2str( max(w(:,1)) ) ] );\n disp( ['Total Number of Windows = ' num2str(nWindows) ]);\n disp( ' ' );\n end\n\n % Pile up window segments similar to segment pileup\n wData = zeros( wLength, nChannels, nWindows ); %initialize to avoid fragmentation\n for n = 1:nWindows\n %wData( :, :, n ) = detrend( data( w(n,1):w(n,2), : ), 'constant' );\n wData( :, :, n ) = detrend( data( w(n,1):w(n,2), : ) );\n end\n\n % J1 = frequency x taper x nWindows\n % J2 = frequency x taper x nWindows x nChannels\n J2 = zeros( length(f), tapers(2), nWindows, nChannels ); J2 = complex( J2, J2 );\n for c = 1 : nChannels\n J1 = mtfftc( squeeze(wData( :, c, : )), sTapers, nfft, Fs ); % FFT for the tapered data\n J2( :, :, :, c ) = J1(findx,:,:);\n end\n % J2 = frequency x taper x nWindows x nChannels\n % Inner mean = Average over tapers => frequency x nWindows x nChannels\n % Outer mean = Average over windows => frequency x nChannels\n dim1 = [length(f), nWindows, nChannels];\n dim2 = [length(f), nChannels];\n % s = frequency x nChannels\n s = reshape( squeeze( mean( reshape( squeeze( mean( conj(J2).*J2, 2 ) ), dim1), 2 ) ), dim2 );\n\n % Now treat the various \"windowed data\" as \"trials\"\n % serr = 2 x frequency x channels. Output from specerr = 2 x frequency x 1\n for c = 1 : nChannels\n serr( :, :, c ) = specerr( squeeze( s(:, c ) ), squeeze( J2(:,:,:, c ) ), err, 1 );\n end\n \n if iwAvg\n % Segment Weighted error estimates.\n S = S + nWindows*s;\n Serr = Serr + nWindows*serr;\n else\n S = S + s;\n Serr = Serr + serr;\n end\n\n else\n if debug, disp(['avgSpectrum:: Zero windows for segment: ' num2str(sg) ]); end\n end\nend\n\n% Segment Weighted error estimates.\n% Only over those that had non-zero windows\nif nWins && iwAvg\n S=S/nWins; Serr=Serr/nWins;\nend\nif ~nWins\n if debug, disp(['avgCoherence:: No segment long enough with movingwin parameters found. Reduce movingwin.' ]); end\nend\n\n\n\n\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/chronux_2_12/spectral_analysis/continuous/mtspectrumc_unequal_length_trials.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673223709251, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5992117865136527}} {"text": "function segment_length = p07_boundary_segment_length ( segment_index, h )\n\n%*****************************************************************************80\n%\n%% P07_BOUNDARY_SEGMENT_LENGTH returns boundary segment lengths in problem 07.\n%\n% Discussion:\n%\n% No attempt has been made here to accurately compute a value of N\n% which would guarantee that the boundary would be divided into pieces\n% of length no more than H. The curve is a little too complicated\n% to make this easy to do.\n%\n% Moreover, the points that will be generated will only be equally\n% spaced in their X argument, not in their arc length.\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% Reference:\n%\n% Per-Olof Persson and Gilbert Strang,\n% A Simple Mesh Generator in MATLAB,\n% SIAM Review,\n% Volume 46, Number 2, June 2004, pages 329-345.\n%\n% Parameters:\n%\n% Input, integer SEGMENT_INDEX, the index of one of the boundary segments.\n%\n% Input, real H, the suggested spacing between points.\n%\n% Output, integer SEGMENT_LENGTH, the number of points in the segment.\n%\n if ( h <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'P07_BOUNDARY_SEGMENT_LENGTH - Fatal error!' );\n fprintf ( 1, ' Nonpositive H = %f\\n', h );\n error ( 'P07_BOUNDARY_SEGMENT_LENGTH - Fatal error!' );\n end\n\n if ( segment_index == 1 )\n\n n = round ( 10.0 * pi / h );\n n = max ( n, 13 );\n segment_length = n;\n\n else\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'P07_BOUNDARY_SEGMENT_LENGTH - Fatal error!' );\n fprintf ( 1, ' Illegal SEGMENT_INDEX = %d\\n', segment_index );\n error ( 'P07_BOUNDARY_SEGMENT_LENGTH - Fatal error!' );\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/test_triangulation/p07_boundary_segment_length.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.5992117651108622}} {"text": "%% Author: epokh\n%% Website: www.epokh.org/drupy\n%% This software is under GPL\n\nclf\nclear\n%%Cartesian manipulator with an RPY wrist\npx=2.3;\npy=1.7;\npz=7.4;\n\nfia=32;\nfio=178;\nfin=4;\nTcartesian=Tras(px,py,pz);\nTorient=RPY(fia,fio,fin);\n\n%%The trasformation matrix is:\nTend=Tcartesian*Torient;\nfigure(1);\nplot3(0,0,0,'r');\nplotT(Tend);\ntitle('Cartesian manipulator example');\n%%Cylindrical manipulator with an Euler wrist\nTcyl=Tcyl(62,8.2,5.2)*Euler(32,15,17);\nfigure(2);\nplot3(0,0,0,'r');\nplotT(Tcyl);\ntitle('Cylindrical manipulator example');\n%%Spherical maninupaltor with an Euler an RPY wrist\nTsfer=Tsfer(40,50,10)*RPY(10,0,10);\nfigure(3);\nplot3(0,0,0,'r');\nplotT(Tsfer);\ntitle('Spherical manipulator example');\n\n%%Invert the Euler transformation\neuwrist=Euler(32,15,17);\n[fi1,fio,fi2]=invEuler(euwrist);\nfprintf('Invers euler angles %d %d %d \\n',fi1,fio,fi2);\nrpywrist=RPY(5,10,15);\n[fia,fio,fin]=invRPY(rpywrist);\nfprintf('Invers rpy angles %d %d %d \\n',fia,fio,fin);", "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/14886-robotic-toolbox/somExamples.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5989426089835809}} {"text": "% The original source code is from https://github.com/zhengliu6699/imageFusionMetrics/blob/master/metricChenBlum.m\n% The interface is modified by the authors of VIFB to integrate it into VIFB. \n\nfunction res=metricsQcb(img1,img2,fused)\n\n fused = double(fused); \n img1 = double(img1);\n img2 = double(img2);\n % Get the size of img \n [m,n,b] = size(fused); \n [m1,n1,b1] = size(img2);\n \n if b == 1\n g = Qcb(img1,img2,fused);\n res = g;\n elseif b1 == 1\n for k = 1 : b \n g(k) = Qcb(img1(:,:,k),img2,fused(:,:,k)); \n end \n res = mean(g); \n else \n for k = 1 : b \n g(k) = Qcb(img1(:,:,k),img2(:,:,k),fused(:,:,k)); \n end \n res = mean(g); \n end\n\n\nend\n\nfunction output = Qcb(im1, im2, fused)\n\n % function res=metricChenBlum(im1,im2,fused)\n %\n % This function implements Yin Chen's algorithm for fusion metric.\n % im1, im2 -- input images;\n % fused -- fused image;\n %\n % IMPORTANT: The size of the images need to be 2X. \n % See also: evalu_fusion.m\n %\n % Z. Liu [July 2009] %\n\n % Ref: A new automated quality assessment algorithm for image fusion, Image and Vision Computing, 27 (2009) 1421-1432 \n % By Yin Chen et al.\n % \n\n im1 = im2double(im1);\n im2 = im2double(im2);\n fused = im2double(fused);\n\n im1=normalize1(im1);\n im2=normalize1(im2);\n fused=normalize1(fused);\n\n %% set up some constant values for experiment\n\n f0=15.3870;\n f1=1.3456;\n a=0.7622;\n\n % parameters for local constrast computation\n k=1;\n h=1;\n p=3; %2.4;\n %p=2.4;\n q=2;\n Z=0.0001;\n sigma=2;\n %% caculate the quality Q\n\n [hang,lie]=size(im1);\n\n %DoG filter\n %DoG1\n %HH=hang/2; LL=lie/2;\n HH=hang/30; LL=lie/30;\n\n %DoG2\n %HH=hang/4; LL=lie/4;\n\n %DoG3\n %HH=hang/8; LL=lie/8;\n\n [u,v]=freqspace([hang,lie],'meshgrid');\n u=LL*u; v=HH*v;\n r=sqrt(u.^2+v.^2);\n\n Sd=exp(-(r/f0).^2)-a*exp(-(r/f1).^2);\n\n % constrast sensitivity filtering\n fused1=ifft2(ifftshift(fftshift(fft2(im1)).*Sd));\n fused2=ifft2(ifftshift(fftshift(fft2(im2)).*Sd));\n ffused=ifft2(ifftshift(fftshift(fft2(fused)).*Sd));\n\n %--------------------\n %fused1=normalize1(fused1);\n %fused2=normalize1(fused2);\n %ffused=normalize1(ffused);\n\n % local contrast computation\n % one level of contrast\n G1=gaussian2d(hang,lie,2);\n G2=gaussian2d(hang,lie,4);\n\n\n % filtering in frequency domain\n C1=contrast(G1,G2,fused1);\n C1=abs(C1); % I add this. (see your notes)\n C1P=(k*(C1.^p))./(h*(C1.^q)+Z);\n\n C2=contrast(G1,G2,fused2);\n C2=abs(C2); % I add this.\n C2P=(k*(C2.^p))./(h*(C2.^q)+Z);\n\n Cf=contrast(G1,G2,ffused);\n Cf=abs(Cf); % I add this.\n CfP=(k*(Cf.^p))./(h*(Cf.^q)+Z);\n\n % contrast preservation calculation\n mask=(C1P y; lie (L) -> x\n\nH=floor((n1-1)/2);\nL=floor((n2-1)/2);\n\n\n[x,y]=meshgrid(-15:15,-15:15);\nG=exp(-(x.*x+y.*y)/(2*sigma*sigma))/(2*pi*sigma*sigma);\n\n%This is to normalize\n%G=G/sum(G(:));\nres=G;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction res=contrast(G1,G2,im)\n\n%[hang,lie]=size(im);\n\n%FG1=fft2(G1,hang,lie);\n%FG2=fft2(G2,hang,lie);\n%fused=fft2(im);\n\n%buff=real(ifft2(FG1.*fused));\n%buff1=real(ifft2(FG2.*fused));\n\nbuff=filter2(G1,im,'same');\nbuff1=filter2(G2,im,'same');\n\nres=buff./buff1-1;\nend\n\nfunction RES=normalize1(data)\n\n % function RES=normalize1(data)\n %\n % This function is to NORMALIZE the data. \n % The data will be in the interval 0-255 (gray level) and pixel value has\n % been rounded to an integer.\n % \n % See also: normalize.m \n %\n % Z. Liu @NRCC (Aug 24, 2009)\n\n data=double(data);\n da=max(data(:));\n xiao=min(data(:));\n if (da==0 & xiao==0)\n RES=data;\n else\n newdata=(data-xiao)/(da-xiao);\n RES=round(newdata*255);\n end\nend", "meta": {"author": "xingchenzhang", "repo": "VIFB", "sha": "7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa", "save_path": "github-repos/MATLAB/xingchenzhang-VIFB", "path": "github-repos/MATLAB/xingchenzhang-VIFB/VIFB-7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa/metrics/metricsQcb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767906859264, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5989426042126131}} {"text": "function [lat, lon, gam, k] = utm_inv(zone, northp, x, y)\n%UTM_INV Forward transverse Mercator projection\n%\n% [LAT, LON] = UTM_INV(ZONE, NORTHP, X, Y)\n% [LAT, LON, GAM, K] = UTM_INV(ZONE, NORTHP, X, Y)\n%\n% performs the inverse universal transverse Mercator projection of points\n% (X,Y) to (LAT,LON) using ZONE and NORTHP. X and Y can be scalars or\n% arrays of equal size. ZONE should be an integer in [1,60] and NORTHP\n% is a logical indicating whether the transformation should use the false\n% northing for the northern (NORTHP = true) or southern (NORTHP = false)\n% hemisphere. The forward projection is given by UTM_FWD.\n%\n% GAM and K give metric properties of the projection at (LAT,LON); GAM is\n% the meridian convergence at the point and K is the scale.\n%\n% LAT, LON, GAM are in degrees. The projected coordinates X, Y are in\n% meters. K is dimensionless.\n%\n% This implementation for the UTM projection is based on the series\n% method described in\n%\n% C. F. F. Karney, Transverse Mercator with an accuracy of a few\n% nanometers, J. Geodesy 85(8), 475-485 (Aug. 2011);\n% Addenda: http://geographiclib.sf.net/tm-addenda.html\n%\n% This extends the series given by Krueger (1912) to sixth order in the\n% flattening. This is a substantially better series than that used by\n% the MATLAB mapping toolbox. In particular the errors in the projection\n% are less than 5 nanometers withing 3900 km of the central meridian (and\n% less than 1 mm within 7600 km of the central meridian). The mapping\n% can be continued accurately over the poles to the opposite meridian.\n%\n% This routine depends on the MATLAB File Exchange package \"Geodesics on\n% an ellipsoid of revolution\":\n%\n% http://www.mathworks.com/matlabcentral/fileexchange/39108\n%\n% See also GEODPROJ, UTM_FWD, TRANMERC_INV.\n\n% Copyright (c) Charles Karney (2012) .\n%\n% This file was distributed with GeographicLib 1.29.\n\n if nargin < 4, error('Too few input arguments'), end\n lon0 = -183 + 6 * zone; lat0 = 0;\n fe = 500e3; fn = cvmgt(0, 10000e3, logical(northp)); k0 = 0.9996;\n x = (x - fe) / k0; y = (y - fn) / k0;\n [lat, lon, gam, k] = tranmerc_inv(lat0, lon0, x, y);\n k = k * k0;\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/39366-geodesic-projections-for-an-ellipsoid/geographiclib-matlab/utm_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5988871768745724}} {"text": "function D = driving_function_mono_nfchoa_ps(x0,xs,f,N,conf)\n%DRIVING_FUNCTION_MONO_NFCHOA_PS driving signal for a point source in NFC-HOA\n%\n% Usage: D = driving_function_mono_nfchoa_ps(x0,xs,f,N,conf)\n%\n% Input parameters:\n% x0 - position of the secondary sources / m [nx3]\n% xs - position of virtual point source / m [nx3]\n% f - frequency of the monochromatic source / Hz\n% N - maximum order of spherical harmonics\n% conf - configuration struct (see SFS_config)\n%\n% Output parameters:\n% D - driving function signal [nx1]\n%\n% See also: driving_function_mono_nfchoa, driving_function_imp_nfchoa_ps\n\n%*****************************************************************************\n% The MIT License (MIT) *\n% *\n% Copyright (c) 2010-2019 SFS Toolbox Developers *\n% *\n% Permission is hereby granted, free of charge, to any person obtaining a *\n% copy of this software and associated documentation files (the \"Software\"), *\n% to deal in the Software without restriction, including without limitation *\n% the rights to use, copy, modify, merge, publish, distribute, sublicense, *\n% and/or sell copies of the Software, and to permit persons to whom the *\n% Software is furnished to do so, subject to the following conditions: *\n% *\n% The above copyright notice and this permission notice shall be included in *\n% all copies or substantial portions of the Software. *\n% *\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *\n% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *\n% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *\n% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *\n% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *\n% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *\n% DEALINGS IN THE SOFTWARE. *\n% *\n% The SFS Toolbox allows to simulate and investigate sound field synthesis *\n% methods like wave field synthesis or higher order ambisonics. *\n% *\n% https://sfs.readthedocs.io sfstoolbox@gmail.com *\n%*****************************************************************************\n\n\n%% ===== Checking of input parameters ==================================\nnargmin = 5;\nnargmax = 5;\nnarginchk(nargmin,nargmax);\nisargmatrix(x0,xs);\nisargpositivescalar(f,N);\nisargstruct(conf);\n\n\n%% ===== Configuration ==================================================\nxref = conf.xref;\nc = conf.c;\ndimension = conf.dimension;\ndriving_functions = conf.driving_functions;\nX0 = conf.secondary_sources.center;\n\n\n%% ===== Computation ====================================================\n\n% Secondary source positions\nx00 = bsxfun(@minus,x0,X0);\n[phi0,theta0,r0] = cart2sph(x00(:,1),x00(:,2),x00(:,3));\n\n% Point source\nxs0 = bsxfun(@minus,xs,X0);\n[phi,theta,r] = cart2sph(xs0(:,1),xs0(:,2),xs0(:,3));\n\n% Wavenumber\nomega = 2*pi*f;\n\n% modal window\nwin = modal_weighting(N,conf);\n\n% Initialize empty driving signal\nD = zeros(size(x0,1),1);\n\nif strcmp('2D',dimension)\n\n % === 2-Dimensional ==================================================\n\n switch driving_functions\n case 'default'\n % --- SFS Toolbox ------------------------------------------------\n to_be_implemented;\n otherwise\n error(['%s: %s, this type of driving function is not implemented ', ...\n 'for a 2D point source.'],upper(mfilename),driving_functions);\n end\n\n\nelseif strcmp('2.5D',dimension)\n\n % === 2.5-Dimensional ================================================\n\n % Reference point\n xref = repmat(xref,[size(x0,1) 1]);\n\n switch driving_functions\n case 'default'\n % --- SFS Toolbox ------------------------------------------------\n % 2.5D point source\n %\n % _N_ (2)\n % 1 \\ h|m|(w/c r)\n % D(phi0,w) = ------ /__ ------------- e^(i m (phi0-phi))\n % 2pi r0 m=-N (2)\n % h|m|(w/c r0)\n %\n % https://sfs.rtfd.io/en/3.2/d_nfchoa/#equation-fd-nfchoa-point-25d\n for m=-N:N\n D = D + 1 ./ (2.*pi.*r0) ...\n .* win(abs(m)+1) ...\n .* sphbesselh(abs(m),2,omega./c.*r) ...\n ./ sphbesselh(abs(m),2,omega./c.*r0) ...\n .* exp(1i.*m.*(phi0-phi));\n end\n otherwise\n error(['%s: %s, this type of driving function is not implemented ', ...\n 'for a 2.5D point source.'],upper(mfilename),driving_functions);\n end\n\n\nelseif strcmp('3D',dimension)\n\n % === 3-Dimensional ==================================================\n\n switch driving_functions\n case 'default'\n % --- SFS Toolbox ------------------------------------------------\n % 3D point source\n %\n % _N_ _n_ (2)\n % 1 \\ \\ hn(w/c r) -m\n % D(theta0,phi0,w) = ------- /__ /__ ----------- Yn(theta,phi) ...\n % 2pi r0^2 n=0 m=-n (2)\n % hn(w/c r0)\n % m\n % x Yn(theta0,phi0)\n %\n % https://sfs.rtfd.io/en/3.2/d_nfchoa/#equation-fd-nfchoa-point-3d\n %\n for n=0:N\n for m=-n:n\n D = D + 1 ./ (2.*pi.*r0.^2) ...\n .* win(n+1) ...\n .* sphbesselh(n,2,omega./c.*r) ...\n ./ sphbesselh(n,2,omega./c.*r0) ...\n .* sphharmonics(n,-m,theta,phi) ...\n .* sphharmonics(n,m,theta0,phi0);\n end\n end\n otherwise\n error(['%s: %s, this type of driving function is not implemented ', ...\n 'for a 3D point source.'],upper(mfilename),driving_functions);\n end\n\nelse\n error('%s: the dimension %s is unknown.',upper(mfilename),dimension);\nend\n", "meta": {"author": "sfstoolbox", "repo": "sfs-matlab", "sha": "02194f0243d1ead26572f760032c40527718919d", "save_path": "github-repos/MATLAB/sfstoolbox-sfs-matlab", "path": "github-repos/MATLAB/sfstoolbox-sfs-matlab/sfs-matlab-02194f0243d1ead26572f760032c40527718919d/SFS_monochromatic/driving_functions_mono/driving_function_mono_nfchoa_ps.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267660487572, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5988871753962872}} {"text": "function [ev,ee,ebound,xyp] = q1p0grid(x,y,xy,mv,bound,mbound);\n%q1p0grid Q1-P0 element grid generator\n% [ev,ee,ebound,xyp] = q1p0grid(x,y,xy,mv,bound,mbound);\n% input\n% x x coordinate vector\n% y y coordinate vector \n% xy nodal coordinate vector \n% mv Q2 macroelement mapping matrix\n% bound boundary vertex vector\n% mbound macroelement boundary vertex vector\n% output \n% ev element vertex matrix\n% ee element edge connection matrix\n% ebound element boundary edge matrix \n% xyp vertex coordinate vector\n%\n% IFISS function: DJS; 28 February 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \nxx=xy(:,1); yy=xy(:,2); nvtx=length(xx);\nadj=sparse(nvtx,nvtx);\nmel=length(mv(:,1)); nel=4*mel;\nev=zeros(nel,4);\n%\n%% loop over macroelements\nk=1:mel;\n% first element\nke=4*k-3;\nev(ke,1)=mv(k,1);\nev(ke,2)=mv(k,5);\nev(ke,3)=mv(k,9);\nev(ke,4)=mv(k,8);\n% second element\nke=4*k-2;\nev(ke,1)=mv(k,5);\nev(ke,2)=mv(k,2);\nev(ke,3)=mv(k,6);\nev(ke,4)=mv(k,9);\n% third element\nke=4*k-1;\nev(ke,1)=mv(k,9);\nev(ke,2)=mv(k,6);\nev(ke,3)=mv(k,3);\nev(ke,4)=mv(k,7);\n% fourth element\nke=4*k;\nev(ke,1)=mv(k,8);\nev(ke,2)=mv(k,9);\nev(ke,3)=mv(k,7);\nev(ke,4)=mv(k,4);\n%\n%% define element edges\nect=1;\n% bottom boundary edges\nk1=find(mbound(:,2)==1)';\nfor k=mbound(k1)\n ebound(ect,1)=4*k-3; ebound(ect+1,1)=4*k-2; \n ebound(ect,2)=1 ; ebound(ect+1,2)=1;\n ect=ect+2;\nend\n% right boundary edges\nk2=find(mbound(:,2)==2)';\nfor k=mbound(k2)\n ebound(ect,1)=4*k-2; ebound(ect+1,1)=4*k-1; \n ebound(ect,2)=2 ; ebound(ect+1,2)=2;\n ect=ect+2;\nend\n% top boundary edges\nk3=find(mbound(:,2)==3)';\nfor k=mbound(k3)\n ebound(ect,1)=4*k-1; ebound(ect+1,1)=4*k; \n ebound(ect,2)=3 ; ebound(ect+1,2)=3;\n ect=ect+2;\nend\n% left boundary edges\nk4=find(mbound(:,2)==4)';\nfor k=mbound(k4)\n ebound(ect,1)=4*k; ebound(ect+1,1)=4*k-3; \n ebound(ect,2)=4 ; ebound(ect+1,2)=4;\n ect=ect+2;\nend\n%%\n% centroid coordinates\nfor ielem=1:nel\nxc(ielem)=mean(xx(ev(ielem,:))); yc(ielem)=mean(yy(ev(ielem,:)));\nend\nxyp=[xc',yc'];\n%\n%% compute edge to edge connection array ee \n np=nel;\n% initialise global matrices\n adj = sparse(nvtx,nvtx); \n ee = zeros(nel,4);\n%\n% evaluate element number on each edge in turn\n% and assemble into adjacency matrix \n%% nx= 0, ny=-1 \n\t\t adj=adj + sparse(ev(:,1),ev(:,2),1:np,nvtx,nvtx); \n%% nx= 1, ny= 0\n\t\t adj=adj + sparse(ev(:,2),ev(:,3),1:np,nvtx,nvtx); \n%% nx= 0, ny= 1 \n\t\t adj=adj + sparse(ev(:,3),ev(:,4),1:np,nvtx,nvtx); \n%% nx=-1, ny= 0\n\t\t adj=adj + sparse(ev(:,4),ev(:,1),1:np,nvtx,nvtx); \n%\n for el=1:nel\n\t\t [ii,jj]=find(adj==el);\n ee(el,:)=diag(adj(jj,ii))';\n\t\t end\n ee=ee(:,[2,4,3,1]);\n%\n% plotting of the grid \n%\n%if mel <=64,\n\tadj=sparse(nvtx,nvtx);\n for i=1:nel\n\tadj(ev(i,1),ev(i,2)) =1;\n\tadj(ev(i,2),ev(i,3)) =1;\n\tadj(ev(i,3),ev(i,4)) =1;\n\tadj(ev(i,4),ev(i,1)) =1;\n end\n figure(30)\n gplot(adj,xy,'b')\n axis('square')\n hold on\n adj=sparse(nvtx,nvtx);\n k1=find(ebound(:,2)==1);\n for k=1:length(k1)\n kk=ebound(k1(k));\n adj(ev(kk,1),ev(kk,2))=1;\n end\n k2=find(ebound(:,2)==2);\n for k=1:length(k2)\n kk=ebound(k2(k));\n adj(ev(kk,2),ev(kk,3))=1;\n end\n k3=find(ebound(:,2)==3);\n for k=1:length(k3)\n kk=ebound(k3(k));\n adj(ev(kk,3),ev(kk,4))=1;\n end\n k4=find(ebound(:,2)==4);\n for k=1:length(k4)\n kk=ebound(k4(k));\n adj(ev(kk,4),ev(kk,1))=1;\n end\n% gplot(adj,xy,'r')\n% axis('off')\nplot(xy(:,1),xy(:,2),'ro')\nxybd=xy(bound,:);\nplot(xybd(:,1),xybd(:,2),'ko')\nplot(xyp(:,1),xyp(:,2),'k*')\nhold off\ndrawnow\ntitle('Q1-P0 finite element subdivision')\n%end\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/grids/q1p0grid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5988223644623938}} {"text": "function [label, model, L] = vbgm(X, init, prior)\n% Perform variational Bayesian inference for Gaussian mixture.\n% X: d x n data matrix\n% init: k (1 x 1) or label (1 x n, 1<=label(i)<=k) or center (d x k)\n% Reference: Pattern Recognition and Machine Learning by Christopher M. Bishop (P.474)\n% Written by Michael Chen (sth4nth@gmail.com).\n\nfprintf('Variational Bayesian Gaussian mixture: running ... \\n');\n[d,n] = size(X);\nif nargin < 3\n prior.alpha = 1;\n prior.kappa = 1;\n prior.m = mean(X,2);\n prior.v = d+1;\n prior.M = eye(d); % M = inv(W)\nend\ntol = 1e-20;\nmaxiter = 2000;\nL = -inf(1,maxiter);\nconverged = false;\nt = 1;\n\nmodel.R = initialization(X,init);\nwhile ~converged && t < maxiter\n t = t+1;\n model = vmax(X, model, prior);\n model = vexp(X, model);\n L(t) = vbound(X,model,prior)/n;\n converged = abs(L(t)-L(t-1)) < tol*abs(L(t));\nend\nL = L(2:t);\nlabel = zeros(1,n);\n[~,label(:)] = max(model.R,[],2);\n[~,~,label] = unique(label);\nif converged\n fprintf('Converged in %d steps.\\n',t-1);\nelse\n fprintf('Not converged in %d steps.\\n',maxiter);\nend\n\nfunction R = initialization(X, init)\n[d,n] = size(X);\nif length(init) == 1 % random initialization\n k = init;\n idx = randsample(n,k);\n m = X(:,idx);\n [~,label] = max(bsxfun(@minus,m'*X,dot(m,m,1)'/2),[],1);\n [u,~,label] = unique(label);\n while k ~= length(u)\n idx = randsample(n,k);\n m = X(:,idx);\n [~,label] = max(bsxfun(@minus,m'*X,dot(m,m,1)'/2),[],1);\n [u,~,label] = unique(label);\n end\n R = full(sparse(1:n,label,1,n,k,n));\nelseif size(init,1) == 1 && size(init,2) == n % initialize with labels\n label = init;\n k = max(label);\n R = full(sparse(1:n,label,1,n,k,n));\nelseif size(init,1) == d %initialize with only centers\n k = size(init,2);\n m = init;\n [~,label] = max(bsxfun(@minus,m'*X,dot(m,m,1)'/2),[],1);\n R = full(sparse(1:n,label,1,n,k,n));\nelse\n error('ERROR: init is not valid.');\nend\n% Done\nfunction model = vmax(X, model, prior)\nalpha0 = prior.alpha;\nkappa0 = prior.kappa;\nm0 = prior.m;\nv0 = prior.v;\nM0 = prior.M;\nR = model.R;\n\nnk = sum(R,1); % 10.51\nalpha = alpha0+nk; % 10.58\nnxbar = X*R;\nkappa = kappa0+nk; % 10.60\nm = bsxfun(@times,bsxfun(@plus,kappa0*m0,nxbar),1./kappa); % 10.61\nv = v0+nk; % 10.63\n\n[d,k] = size(m);\nM = zeros(d,d,k); \nsqrtR = sqrt(R);\n\nxbar = bsxfun(@times,nxbar,1./nk); % 10.52\nxbarm0 = bsxfun(@minus,xbar,m0);\nw = (kappa0*nk./(kappa0+nk));\nfor i = 1:k\n Xs = bsxfun(@times,bsxfun(@minus,X,xbar(:,i)),sqrtR(:,i)');\n xbarm0i = xbarm0(:,i);\n M(:,:,i) = M0+Xs*Xs'+w(i)*(xbarm0i*xbarm0i'); % 10.62\nend\n\nmodel.alpha = alpha;\nmodel.kappa = kappa;\nmodel.m = m;\nmodel.v = v;\nmodel.M = M; % Whishart: M = inv(W)\n% Done\nfunction model = vexp(X, model)\nalpha = model.alpha; % Dirichlet\nkappa = model.kappa; % Gaussian\nm = model.m; % Gasusian\nv = model.v; % Whishart\nM = model.M; % Whishart: inv(W) = V'*V\n\nn = size(X,2);\n[d,k] = size(m);\n\nlogW = zeros(1,k);\nEQ = zeros(n,k);\nfor i = 1:k\n U = chol(M(:,:,i));\n logW(i) = -2*sum(log(diag(U))); \n Q = (U'\\bsxfun(@minus,X,m(:,i)));\n EQ(:,i) = d/kappa(i)+v(i)*dot(Q,Q,1); % 10.64\nend\n\nElogLambda = sum(psi(0,bsxfun(@minus,v+1,(1:d)')/2),1)+d*log(2)+logW; % 10.65\nElogpi = psi(0,alpha)-psi(0,sum(alpha)); % 10.66\n\nlogRho = (bsxfun(@minus,EQ,2*Elogpi+ElogLambda-d*log(2*pi)))/(-2); % 10.46\nlogR = bsxfun(@minus,logRho,logsumexp(logRho,2)); % 10.49\nR = exp(logR);\n\nmodel.logR = logR;\nmodel.R = R;\n% Done\nfunction L = vbound(X, model, prior)\nalpha0 = prior.alpha;\nkappa0 = prior.kappa;\nm0 = prior.m;\nv0 = prior.v;\nM0 = prior.M;\n\nalpha = model.alpha; % Dirichlet\nkappa = model.kappa; % Gaussian\nm = model.m; % Gasusian\nv = model.v; % Whishart\nM = model.M; % Whishart: inv(W) = V'*V\nR = model.R;\nlogR = model.logR;\n\n\n[d,k] = size(m);\nnk = sum(R,1); % 10.51\n\nElogpi = psi(0,alpha)-psi(0,sum(alpha));\n\nEpz = dot(nk,Elogpi);\nEqz = dot(R(:),logR(:));\nlogCalpha0 = gammaln(k*alpha0)-k*gammaln(alpha0);\nEppi = logCalpha0+(alpha0-1)*sum(Elogpi);\nlogCalpha = gammaln(sum(alpha))-sum(gammaln(alpha));\nEqpi = dot(alpha-1,Elogpi)+logCalpha;\nL = Epz-Eqz+Eppi-Eqpi;\n\n\nU0 = chol(M0);\nsqrtR = sqrt(R);\nxbar = bsxfun(@times,X*R,1./nk); % 10.52\n\nlogW = zeros(1,k);\ntrSW = zeros(1,k);\ntrM0W = zeros(1,k);\nxbarmWxbarm = zeros(1,k);\nmm0Wmm0 = zeros(1,k);\nfor i = 1:k\n U = chol(M(:,:,i));\n logW(i) = -2*sum(log(diag(U))); \n \n Xs = bsxfun(@times,bsxfun(@minus,X,xbar(:,i)),sqrtR(:,i)');\n V = chol(Xs*Xs'/nk(i));\n Q = V/U;\n trSW(i) = dot(Q(:),Q(:)); % equivalent to tr(SW)=trace(S/M)\n Q = U0/U;\n trM0W(i) = dot(Q(:),Q(:));\n\n q = U'\\(xbar(:,i)-m(:,i));\n xbarmWxbarm(i) = dot(q,q);\n q = U'\\(m(:,i)-m0);\n mm0Wmm0(i) = dot(q,q);\nend\n\nElogLambda = sum(psi(0,bsxfun(@minus,v+1,(1:d)')/2),1)+d*log(2)+logW; % 10.65\nEpmu = sum(d*log(kappa0/(2*pi))+ElogLambda-d*kappa0./kappa-kappa0*(v.*mm0Wmm0))/2;\nlogB0 = v0*sum(log(diag(U0)))-0.5*v0*d*log(2)-logmvgamma(0.5*v0,d);\nEpLambda = k*logB0+0.5*(v0-d-1)*sum(ElogLambda)-0.5*dot(v,trM0W);\n\nEqmu = 0.5*sum(ElogLambda+d*log(kappa/(2*pi)))-0.5*d*k;\nlogB = -v.*(logW+d*log(2))/2-logmvgamma(0.5*v,d);\nEqLambda = 0.5*sum((v-d-1).*ElogLambda-v*d)+sum(logB);\n\nEpX = 0.5*dot(nk,ElogLambda-d./kappa-v.*trSW-v.*xbarmWxbarm-d*log(2*pi));\n\nL = L+Epmu-Eqmu+EpLambda-EqLambda+EpX;", "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/35362-variational-bayesian-inference-for-gaussian-mixture-model/vbgm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.5987275774691266}} {"text": "function [f,g] = hs71F(x)\n\nf = x(1)*x(4)*sum(x(1:3)) + x(3);\n\nif(nargout > 1)\n g = [ x(1)*x(4) + x(4)*sum(x(1:3))\n x(1)*x(4)\n x(1)*x(4) + 1\n x(1)*sum(x(1:3)) ];\nend", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/OptiToolbox/Test Problems/Development/hs71F.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.598522466733965}} {"text": " function [kb, alpha, kb_m] = kaiser_bessel(x, J, alpha, kb_m, K_N)\n%function [kb, alpha, kb_m] = kaiser_bessel(x, J, alpha, kb_m)\n%function [kb, alpha, kb_m] = kaiser_bessel(x, J, 'best', 0, K_N)\n%\n% generalized Kaiser-Bessel function for x in support [-J/2,J/2]\n% shape parameter \"alpha\" (default 2.34 J)\n% order parameter \"kb_m\" (default 0)\n% see (A1) in lewitt:90:mdi, JOSA-A, Oct. 1990\n% in\n%\tx\t[M,1]\targuments\n% out\n%\tkb\t[M,1]\tKB function values, if x is numbers\n%\t\t\tor string for kernel(k,J), if x is 'string'\n%\t\t\tor inline function, if x is 'inline'\n%\talpha\n%\tkb_m\n%\n% Copyright 2001-3-30, Jeff Fessler, The University of Michigan\n\n% Modification 2002-10-29 by Samuel Matej\n% - for Negative & NonInteger kb_m the besseli() function has\n%\tsingular behavior at the boundaries - KB values shooting-up/down\n%\t(worse for small alpha) leading to unacceptable interpolators\n% - for real arguments and higher/reasonable values of alpha the\n%\tbesseli() gives similar values for positive and negative kb_m\n%\texcept close to boundaries - tested for kb_m=-2.35:0.05:2.35\n%\t(besseli() gives exactly same values for integer +- kb_m)\n%\t=> besseli(kb_m,...) approximated by besseli(abs(kb_m),...), which\n%\tbehaves well at the boundaries\n% WARNING: it is not clear how correct the FT formula (JOSA) is\n%\tfor this approximation (for NonInteger Negative kb_m)\n% NOTE: Even for the original KB formula, the JOSA FT formula\n%\tis derived only for m > -1 !\n\n% if no arguments, make example plots\nif nargin < 2\n\thelp(mfilename)\n\tJ = 8; alpha = 2.34 * J;\n\tx = linspace(-(J+1)/2, (J+1)/2, 1001)';\n%\tx = linspace(J/2-1/4, J/2+1/4, 1001)';\n\n\tmlist = [-4 0 2 7];\n\tleg = {};\n\tfor ii=1:length(mlist)\n\t\tkb_m = mlist(ii);\n\t\tyy(:,ii) = kaiser_bessel(x, J, alpha, kb_m);\n\t\tfunc = kaiser_bessel('inline', 0, alpha, kb_m);\n\t\tyf = func(x, J);\n\t\tif any(yf ~= yy(:,ii)),\n\t\t[yf yy(:,ii)]\n\t\terror 'bug', end\n\t\tleg{ii} = sprintf('m=%d', kb_m);\n\tend\n\tyb = kaiser_bessel(x, J, 'best', [], 2);\n\tplot(\tx, yy(:,1), 'c-', x, yy(:,2), 'y-', ...\n\t\tx, yy(:,3), 'm-', x, yy(:,4), 'g-', x, yb, 'r--')\n\tleg{end+1} = 'best';\n\taxis tight, legend(leg)\n%\taxisy(0, 0.01)\t% to see endpoints\n\txlabel \\kappa, ylabel F(\\kappa)\n\ttitle(sprintf('KB functions, J=%g \\\\alpha=%g', J, alpha) )\nreturn\nend\n\nif ~isvar('J'), J = 6; end\nif ~isvar('alpha') | isempty('alpha'), alpha = 2.34 * J; end\nif ~isvar('kb_m') | isempty('kb_m'), kb_m = 0; end\n\nif ischar(alpha)\n\t[alpha kb_m] = kaiser_bessel_params(alpha, J, K_N);\nend\n\nif ischar(x)\n\tif ischar(alpha)\n\t\tif ~isvar('K_N'), error 'K_N required', end\n\t\tkb = 'kaiser_bessel(k, J, ''%s'', [], %g)';\n\t\tkb = sprintf(kb, alpha, K_N);\n\telse\n\t\tkernel_string = 'kaiser_bessel(k, J, %g, %g)';\n\t\tkb = sprintf(kernel_string, alpha, kb_m);\n\tend\n\tif streq(x, 'inline')\n\t\tkb = inline(kb, 'k', 'J');\n\telseif ~streq(x, 'string')\n\t\terror '1st argument must be \"inline\" or \"string\"'\n\tend\nreturn\nend\n\n%\n% Warn about use of modified formula for negative kb_m\n%\nif (kb_m < 0) & ((abs(round(kb_m)-kb_m)) > eps)\n\tpersistent warned\n\tif isempty(warned)\t% only print this reminder the first time\n\t\tprintf('\\nWarning: Negative NonInt kb_m=%g in kaiser_bessel()', kb_m)\n\t\tprintf('\t- using modified definition of KB function\\n')\n\t\twarned = 1;\n\tend\nend\n\nkb_m_bi = abs(kb_m);\t\t% modified \"kb_m\" as described above\nii = abs(x) < J/2;\nf = sqrt(1 - (x(ii)/(J/2)).^2);\ndenom = besseli(kb_m_bi,alpha);\nif ~denom\n\tprintf('m=%g alpha=%g', kb_m, alpha)\nend\nkb = zeros(size(x));\nkb(ii) = f.^kb_m .* besseli(kb_m_bi, alpha*f) / denom;\nkb = reale(kb);\n\n\n%\n% optimized shape and order parameters\n%\nfunction [alpha, kb_m] = kaiser_bessel_params(alpha, J, K_N)\nif streq(alpha, 'best')\n\tif K_N ~= 2\n\t\twarning 'kaiser_bessel optimized only for K/N=2'\n\t\tprintf('using good defaults: m=0 and alpha = 2.34*J')\n\t\tkb_m = 0;\n\t\talpha = 2.34 * J;\n\telse\n\t\tkb_m = 0;\t% hardwired, because it was nearly the best!\n\t\ttry\n\t\t\ts = 'private/kaiser,m=0';\n\t\t\ts = load(s);\n\t\t\tii = find(J == s.Jlist);\n\t\t\tif isempty(ii)\n\t\t\t\tii = imin(abs(J - s.Jlist));\n\t\t\t\twarning(sprintf('J=%d not found, using %d', ...\n\t\t\t\t\tJ, s.Jlist(ii)))\n\t\t\tend\n\t\t\talpha = J * s.abest.zn(ii);\n\t\tcatch\n\t\t\twarning(['could not open file \"' s '\" so using default alpha = 2.34 J which should be fine.'])\n\t\t\talpha = 2.34 * J;\n\t\tend\n\tend\nelse\n\terror 'unknown alpha mode'\nend\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/kaiser_bessel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272544, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5985224588116524}} {"text": "function [x, mx, sx] = standardise(x, dim, lim)\n\n% STANDARDISE computes the zscore of a matrix along dimension dim\n% has similar functionality as the stats-toolbox's zscore function\n%\n% Use as\n% x = standardise(x, dim)\n%\n% See also ZSCORE\n\n% Copyright (C) 2009, Jan-Mathijs Schoffelen\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\nif nargin == 1,\n dim = find(size(x)>1,1,'first');\nend\n\nif nargin == 3,\n ft_error('third input argument is not used');\nend\n\nswitch dim\ncase 1\n n = size(x,dim);\n mx = mean(x,dim);\n x = x-mx(ones(1,n),:,:,:,:,:,:,:);\n sx = sqrt(sum(abs(x).^2,dim)./n);\n x = x./sx(ones(1,n),:,:,:,:,:,:,:);\ncase 2\n n = size(x,dim);\n mx = mean(x,dim);\n x = x-mx(:,ones(1,n),:,:,:,:,:,:);\n sx = sqrt(sum(abs(x).^2,dim)./n);\n x = x./sx(:,ones(1,n),:,:,:,:,:,:);\ncase 3\n n = size(x,dim);\n mx = mean(x,dim);\n x = x-mx(:,:,ones(1,n),:,:,:,:,:);\n sx = sqrt(sum(abs(x).^2,dim)./n);\n x = x./sx(:,:,ones(1,n),:,:,:,:,:);\ncase 4\n n = size(x,dim);\n mx = mean(x,dim);\n x = x-mx(:,:,:,ones(1,n),:,:,:,:);\n sx = sqrt(sum(abs(x).^2,dim)./n);\n x = x./sx(:,:,:,ones(1,n),:,:,:,:);\ncase 5\n n = size(x,dim);\n mx = mean(x,dim);\n x = x-mx(:,:,:,:,ones(1,n),:,:,:);\n sx = sqrt(sum(abs(x).^2,dim)./n);\n x = x./sx(:,:,:,:,ones(1,n),:,:,:);\ncase 6\n n = size(x,dim);\n mx = mean(x,dim);\n x = x-mx(:,:,:,:,:,ones(1,n),:,:);\n sx = sqrt(sum(abs(x).^2,dim)./n);\n x = x./sx(:,:,:,:,:,ones(1,n),:,:);\ncase 7\n n = size(x,dim);\n mx = mean(x,dim);\n x = x-mx(:,:,:,:,:,:,ones(1,n),:);\n sx = sqrt(sum(abs(x).^2,dim)./n);\n x = x./sx(:,:,:,:,:,:,ones(1,n),:);\ncase 8\n n = size(x,dim);\n mx = mean(x,dim);\n x = x-mx(:,:,:,:,:,:,:,ones(1,n));\n sx = sqrt(sum(abs(x).^2,dim)./n);\n x = x./sx(:,:,:,:,:,:,:,ones(1,n));\notherwise\n ft_error('dim too large, standardise currently supports dimensionality up to 8');\nend\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/external/fieldtrip/connectivity/private/standardise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5985070070343845}} {"text": " function [err, sn, T1] = nufft1_err_mm(om, N1, J1, K1, type, alpha, beta)\n%function [err, sn, T1] = nufft1_err_mm(om, N1, J1, K1, type, alpha, beta)\n% Compute worst-case error for each input frequency for min-max 1D NUFFT.\n% in:\n%\tom\t[M,1]\tdigital frequency omega in radians\n%\tN1\t\tsignal length\n%\tJ1\t\t# of neighbors used per frequency location\n%\tK1\t\tFFT size (should be > N1)\n%\ttype\t\t'sinc' 'diric' 'qr'\n%\talpha\t[L,1]\tFourier series coefficients of scaling factors\n%\t\t\ttrick: or, \"sn\" if length N1\n%\tbeta\t\tscale gamma=2pi/K by this in Fourier series\n%\t\t\ttypically is K/N (me) or 0.5 (Liu)\n% out:\n%\terr\t[M,1]\tworst-case error over unit-norm signals\n%\tsn\t[N,1]\tscaling factors corresponding to alpha,beta\n%\tT1\t[J,J]\tT matrix\n%\n% Copyright 2001-12-7, Jeff Fessler, The University of Michigan\n\n% if no arguments, give an example\nif nargin < 4\n\thelp(mfilename)\n\tN = 100; K = 2*N; gam = 2*pi/K;\n\tJ = 14;\n\tom = gam * linspace(0,1,101);\n\t[alpha, beta, ok] = nufft_best_alpha(J, 2, K/N);\n\tif ~ok, alpha = []; beta = 0.5; end\n\terrd = nufft1_err_mm(om, N, J, K, 'diric');\n\terrs = nufft1_err_mm(om, N, J, K, 'sinc');\n\terrq = nufft1_err_mm(om, N, J, K, 'qr');\n\tsemilogy(om/gam, errs, 'g-x', om/gam, errd, 'y-+', om/gam, errq, 'c-o')\n\txlabel '\\omega / \\gamma', ylabel 'E_{max}(\\omega)'\n\tlegend('Tr sinc', 'Tr diric', 'QR approach')\nreturn\nend\n\nif ~isvar('type') | isempty(type),\ttype = 'sinc'; end\nif ~isvar('alpha') | isempty(alpha)\n\talpha = [1];\t% default Fourier series coefficients of scaling factors\nend\nif ~isvar('beta') | isempty(beta)\n\tbeta = 0.5;\t% default is Liu version for now\nend\n\nuse_qr = logical(0);\nif streq(type, 'sinc')\n\tuse_true_diric = logical(0);\nelseif streq(type, 'diric')\n\tuse_true_diric = logical(1);\nelseif streq(type, 'qr')\n\tuse_qr = logical(1);\nelse\n\terror 'unknown type'\nend\n\n\n%\n% see if 'best' alpha is desired\n%\nif ischar(alpha)\n\tif streq(alpha, 'uniform')\n\t\talpha = [1];\n\t\tbeta = 0.5;\n\telse\n\t\tif streq(alpha, 'best')\n\t\t\tL = 0;\n\t\telseif streq(alpha, 'best,L=1')\n\t\t\tL = 1;\n\t\telseif streq(alpha, 'best,L=2')\n\t\t\tL = 2;\n\t\telse\n\t\t\terror 'unknown alpha argument'\n\t\tend\n\t\t[alpha, beta, ok] = nufft_best_alpha(J1, L, K1/N1);\n\t\tif ~ok\n\t\t\ttmp = 'optimal alpha unknown for J=%d, K/N=%g, L=%d';\n\t\t\twarning(sprintf(tmp, J1, K1/N1, L))\n\t\t\tsn = ones(N1,1);\n\t\t\terr = nan;\n\t\t\treturn\n\t\tend\n\tend\nend\n\n%\n% if requested, return corresponding scaling factors too\n%\nif length(alpha) == N1\t% trick: special way to give explicit sn's\n\tsn = alpha;\n\tif ~use_qr, error 'give sn only allowed for QR version', end\nelseif nargout > 1 | use_qr\n\tsn = nufft_scale(N1, K1, alpha, beta);\nend\n\n%\n% QR approach to error\n%\nif use_qr\n\tn = [0:N1-1]' - (N1-1)/2;\n\t[nn, jj] = ndgrid(n, 1:J1);\n\tgam1 = 2*pi/K1;\n\tC = exp(i * gam1 * nn .* jj) / sqrt(N1);\n\tS = spdiag(sn);\n\tA = S' * C;\n\t[Q,R] = qr(S' * C, 0);\t% [N,J] compact QR decomposition\n\n\tdo = col(om - gam1*nufft_offset(om, J1, K1));\n\tDb = exp(i * n * do') / sqrt(N1);\t% [N,M]\n\terr = Db - Q * (Q' * Db);\n\terr = sqrt(sum(abs(err).^2,1))';\t% [M]\nreturn\nend\n\ntol = 0;\nT1 = nufft_T(N1, J1, K1, tol, alpha, beta, use_true_diric);\t% [J,J]\nr1 = nufft_r(om, N1, J1, K1, alpha, beta, use_true_diric);\t% [J,M]\n\n%\n% worst-case error at each frequency\n%\nTr1 = T1 * r1;\t\t\t% [J,M]\nerr = sum(conj(r1) .* Tr1).';\t% [M,1]\nerr = min(real(err), 1);\nerr = sqrt(1 - err);\t\t% caution: this \"1 -\" may cause numerical error\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/nufft1_err_mm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5985070032811254}} {"text": "function [out,Wc,Wo] = hankelsv(SYS)\n%HANKELSV Compute Hankel singular values and grammians.\n%\n% [OUT,Wc,Wo] = HANKELSV(SYS) computes controllability and observability\n% grammians Wc, Wo, and the Hankel singular values OUT of an LTI \n% model SYS (created with either TF, ZPK, SS, or FRD). The model\n% SYS can be either continuous-time or discrete-time. However, only\n% in continuous-time case that SYS is allowed to be unstable. \n% The computed Hankel singular values are sorted in ascending order. \n%\n% For unstable continuous-time system, state-space stable/anti-stable \n% decomposition is used instead, and OUT=[OUT_stable;OUT_anti-stable].\n% In addition, Wc={Wc_stable,Wc_anti-stable} and Wo is either. \n\n% The former version of HKSV employs an obsolete fashion in using the \n% Matlab function GRAM, i.e., instead of using GRAM(SYS,'c') and \n% GRAM(SYS,'o'), it uses GRAM(A,B) and GRAM(A',C'), respectively. \n% This restricts the computation of gramians to continuous-time case,\n% only, since GRAM(A,B) and GRAM(A',C') solve LYAP, not DLYAP. \n% \n% This improved version also correct some other bugs in the former \n% version, for example, HKSV does not return gramians when SYS is \n% unstable, but not anti-stable. \n\n% Developer: Wathanyoo Khaisongkram\n% Date Developed: Oct 20, 2004\n% Email: sunboom15@yahoo.com \n% Improved version of HKSV by R. Y. Chiang & M. G. Safonov March, 1986\n% -----------------------------------------------------------------------\n\nSYS=ss(SYS); % convert to state-space model\n\n% Discrete-time LTI model\nif get(SYS,'Ts')~=0 % discrete-time LTI model\n if max(abs(pole(SYS))) > 1 % unstable discrete system\n error('For discrete LTI model, system must be stable')\n end\n Wc = gram(SYS,'c'); % controllability matrix\n Wo = gram(SYS,'o'); % observability matrix\n out = sqrt(eig(Wc*Wo)); % Hankel singular values\n [no_use,index] = sort(out); % index for sorting \n out = out(index); % sorted singular values\n return % end function\nend \n\n% Continuous-time LTI model \n[A,B,C,D]=ssdata(SYS); % extract the system matrices\n mode = eig(A); % the eigen values of 'a'\n nrow = size(A,1); % the number of rows in 'a'\n nsta = length(find(real(mode) < 0)); % the number of unstable modes\nif isequal(nsta,nrow), % completely stable\n Wc = gram(SYS,'c'); % controllability matrix\n Wo = gram(SYS,'o'); % observability matrix\n out = sqrt(eig(Wc*Wo)); % Hankel singular values\n [no_use,index] = sort(out); % index for sorting \n out = out(index); % sorted singular values\nelseif isequal(nsta,0), % completely unstable\n SYS=ss(-A,-B,C,D,SYS); % change the dynamic and the input matrices to '-a' and '-b', \n % respectively with all LTI properties inherited from \n % original SYS, e.g., discrete or continuous domain. \n Wc = gram(SYS,'c'); % controllability matrix\n Wo = gram(SYS,'o'); % observability matrix\n out = sqrt(eig(Wc*Wo)); % Hankel singular values\n [no_use,index] = sort(out); % index for sorting \n out = out(index); % sorted singular values\nelse, % 0 < nsta < nrow\n [SYSs,SYSu] = stabproj(SYS); % decompose stable/anti-stable parts\n % Stable part \n Wcs = gram(SYSs,'c'); % controllability matrix\n Wos = gram(SYSs,'o'); % observability matrix\n outl = sqrt(eig(Wcs*Wos)); % Hankel singular values1\n [no_use,index] = sort(outl); % index for sorting \n outl = outl(index); % sorted singular values\n % Anti-stable part \n [Au,Bu,Cu,Du]=ssdata(SYSu); % obtain the system matrices of SYSu\n SYSu=ss(-Au,-Bu,Cu,Du,SYSu); % change the dynamic and the input matrices to '-ar' and '-br'. \n Wcu = gram(SYSu,'c'); % controllability matrix\n Wou = gram(SYSu,'o'); % observability matrix\n outr = sqrt(eig(Wcu*Wou)); % Hankel singular values\n [no_use,index] = sort(outr); % index for sorting \n outr = outr(index); % sorted singular values\n out = [outl;outr]; % gather two cases\n Wc={Wcs,Wcu}; % controllability gramian\n Wo={Wos,Wou}; % observability gramian\nend\n\n% end of HKSV_MOD", "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/6082-hankelsv/hankelsv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5984829587982801}} {"text": "classdef ZXH_CF14 < PROBLEM\n% \n% Constrained benchmark MOP proposed by Zhou, Xiang, and He\n\n%------------------------------- Reference --------------------------------\n% Y. Zhou, Y. Xiang, and X. He, Constrained multiobjective optimization:\n% Test problem construction and performance evaluations, IEEE Transactions\n% on Evolutionary Computation, 2021, 25(1): 172-186.\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 properties\n k; % Number of constrained variables\n end\n methods\n %% Default settings of the problem\n function Setting(obj)\n if isempty(obj.M); obj.M = 2; end\n if isempty(obj.D); obj.D = obj.M+10; end\n obj.lower = zeros(1,obj.D) + 1e-10;\n obj.upper = ones(1,obj.D) - 1e-10;\n obj.encoding = ones(1,obj.D);\n if obj.M <= 3\n obj.k = obj.M - 1;\n elseif obj.M > 3 && obj.M <= 8 \n obj.k = floor(obj.M/2); \n else\n obj.k = 3; \n end\n end\n %% Evaluate multiple solutions\n function Population = Evaluation(obj,varargin)\n PopDec = varargin{1};\n OptX = 0.2;\n [N,D] = size(PopDec);\n M = obj.M;\n % Step 1: Compute cumsum \n Sx = cumsum(PopDec(:,1:M).^2,2,'reverse'); \n % Step 2: Compute theta\n THETA = 2/pi*atan(sqrt(Sx(:,2:end))./PopDec(:,1:M-1));\n % Step 3: Calculate Ackley function\n h = 20 - 20 * exp(-0.2 * sqrt(sum((PopDec(:,M+1:end)-OptX).^2,2)/(D-M))) + exp (1) - exp(sum(cos(2 * pi .*(PopDec(:,M+1:end)-OptX)),2)/(D-M));\n % Step 4: Compute T_\n T = (1 - Sx(:,1)).^2 + h;\n % Step 5: Objectives (linear)\n G = [ones(N,1) cumprod(THETA,2)] .* [1-THETA ones(N,1)];\n PopObj = G .* repmat((1+T),1,M);\n % Step 6: Constraints\n PopCon(:,1) = Sx(:,1) + h - 1; \n PopCon(:,2) = -(Sx(:,1) + h - 1/4); \n for i = 1 : obj.k\n PopCon(:,i+2) = min(min(THETA(:,i)-1/10,4/5-THETA(:,i)),max(2/5-THETA(:,i),THETA(:,i)-7/10));\n end\n Population = SOLUTION(varargin{1},PopObj,PopCon,varargin{2:end});\n obj.FE = obj.FE + length(Population);\n end\n %% Generate points on the Pareto front\n function R = GetOptimum(obj,N)\n R = UniformPoint(N,obj.M);\n T = zeros(size(R));\n for i = obj.M-1 : -1 : 1\n T(:,i) = R(:,i+1)./R(:,i)./(1-T(:,i+1)+R(:,i+1)./R(:,i));\n end\n THETA = T(:,1:obj.k);\n Valid = all(THETA<=1/10|THETA>=2/5&THETA<=7/10|THETA>=4/5,2);\n R = R(Valid,:);\n end\n %% Generate the image of Pareto front\n function R = GetPF(obj)\n if obj.M == 2\n R = obj.GetOptimum(100);\n elseif obj.M == 3\n a = linspace(0,1,30)';\n R = {a*a',a*(1-a'),(1-a)*ones(size(a'))};\n T2 = R{3}./R{2}./(1+R{3}./R{2});\n T1 = R{2}./(1-T2);\n THETA = cat(3,T1,T2);\n Valid = all(THETA<=1/10|THETA>=2/5&THETA<=7/10|THETA>=4/5,3);\n R{1}(~Valid) = nan;\n else\n R = [];\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/Problems/Multi-objective optimization/ZXH_CF/ZXH_CF14.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.59848294270391}} {"text": "function [ quasi, seed ] = i4_sobol ( dim_num, seed )\n\n%*****************************************************************************80\n%\n%% I4_SOBOL generates a new quasirandom Sobol vector with each call.\n%\n% Discussion:\n%\n% The routine adapts the ideas of Antonov and Saleev.\n%\n% Thanks to Francis Dalaudier for pointing out that the range of allowed\n% values of DIM_NUM should start at 1, not 2! 17 February 2009.\n%\n% This function was modified to use PERSISTENT variables rather than\n% GLOBAL variables, 13 December 2009.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 March 2012\n%\n% Author:\n%\n% Original FORTRAN77 version by Bennett Fox.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Antonov, Saleev,\n% USSR Computational Mathematics and Mathematical Physics,\n% Volume 19, 1980, pages 252 - 256.\n%\n% Paul Bratley, Bennett Fox,\n% Algorithm 659:\n% Implementing Sobol's Quasirandom Sequence Generator,\n% ACM Transactions on Mathematical Software,\n% Volume 14, Number 1, pages 88-100, 1988.\n%\n% Bennett Fox,\n% Algorithm 647:\n% Implementation and Relative Efficiency of Quasirandom \n% Sequence Generators,\n% ACM Transactions on Mathematical Software,\n% Volume 12, Number 4, pages 362-376, 1986.\n%\n% Ilya Sobol,\n% USSR Computational Mathematics and Mathematical Physics,\n% Volume 16, pages 236-242, 1977.\n%\n% Ilya Sobol, Levitan, \n% The Production of Points Uniformly Distributed in a Multidimensional \n% Cube (in Russian),\n% Preprint IPM Akad. Nauk SSSR, \n% Number 40, Moscow 1976.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the number of spatial dimensions.\n% DIM_NUM must satisfy 1 <= DIM_NUM <= 40.\n%\n% Input/output, integer SEED, the \"seed\" for the sequence.\n% This is essentially the index in the sequence of the quasirandom\n% value to be generated. On output, SEED has been set to the\n% appropriate next value, usually simply SEED+1.\n% If SEED is less than 0 on input, it is treated as though it were 0.\n% An input value of 0 requests the first (0-th) element of the sequence.\n%\n% Output, real QUASI(DIM_NUM), the next quasirandom vector.\n%\n persistent atmost;\n persistent dim_max;\n persistent dim_num_save;\n persistent initialized;\n persistent lastq;\n persistent log_max;\n persistent maxcol;\n persistent poly;\n persistent recipd;\n persistent seed_save;\n persistent v;\n\n if ( isempty ( initialized ) )\n initialized = 0;\n dim_num_save = -1;\n end\n\n if ( ~initialized | dim_num ~= dim_num_save )\n\n initialized = 1;\n\n dim_max = 40;\n dim_num_save = -1;\n log_max = 30;\n seed_save = -1;\n%\n% Initialize (part of) V.\n%\n v(1:dim_max,1:log_max) = zeros(dim_max,log_max);\n\n v(1:40,1) = [ ...\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]';\n\n v(3:40,2) = [ ...\n 1, 3, 1, 3, 1, 3, 3, 1, ...\n 3, 1, 3, 1, 3, 1, 1, 3, 1, 3, ...\n 1, 3, 1, 3, 3, 1, 3, 1, 3, 1, ...\n 3, 1, 1, 3, 1, 3, 1, 3, 1, 3 ]';\n\n v(4:40,3) = [ ...\n 7, 5, 1, 3, 3, 7, 5, ...\n 5, 7, 7, 1, 3, 3, 7, 5, 1, 1, ...\n 5, 3, 3, 1, 7, 5, 1, 3, 3, 7, ...\n 5, 1, 1, 5, 7, 7, 5, 1, 3, 3 ]';\n\n v(6:40,4) = [ ...\n 1, 7, 9,13,11, ...\n 1, 3, 7, 9, 5,13,13,11, 3,15, ...\n 5, 3,15, 7, 9,13, 9, 1,11, 7, ...\n 5,15, 1,15,11, 5, 3, 1, 7, 9 ]';\n \n v(8:40,5) = [ ...\n 9, 3,27, ...\n 15,29,21,23,19,11,25, 7,13,17, ...\n 1,25,29, 3,31,11, 5,23,27,19, ...\n 21, 5, 1,17,13, 7,15, 9,31, 9 ]';\n\n v(14:40,6) = [ ...\n 37,33, 7, 5,11,39,63, ...\n 27,17,15,23,29, 3,21,13,31,25, ...\n 9,49,33,19,29,11,19,27,15,25 ]';\n\n v(20:40,7) = [ ...\n 13, ...\n 33,115, 41, 79, 17, 29,119, 75, 73,105, ...\n 7, 59, 65, 21, 3,113, 61, 89, 45,107 ]';\n\n v(38:40,8) = [ ...\n 7, 23, 39 ]';\n%\n% Set POLY.\n%\n poly(1:40)= [ ...\n 1, 3, 7, 11, 13, 19, 25, 37, 59, 47, ...\n 61, 55, 41, 67, 97, 91, 109, 103, 115, 131, ...\n 193, 137, 145, 143, 241, 157, 185, 167, 229, 171, ...\n 213, 191, 253, 203, 211, 239, 247, 285, 369, 299 ];\n\n atmost = 2^log_max - 1;\n%\n% Find the number of bits in ATMOST.\n%\n maxcol = i4_bit_hi1 ( atmost );\n%\n% Initialize row 1 of V.\n%\n v(1,1:maxcol) = 1;\n\n end\n%\n% Things to do only if the dimension changed.\n%\n if ( dim_num ~= dim_num_save )\n%\n% Check parameters.\n%\n if ( dim_num < 1 | dim_max < dim_num )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4_SOBOL - Fatal error!\\n' );\n fprintf ( 1, ' The spatial dimension DIM_NUM should satisfy:\\n' );\n fprintf ( 1, ' 1 <= DIM_NUM <= %d\\n', dim_max );\n fprintf ( 1, ' But this input value is DIM_NUM = %d\\n', dim_num );\n return\n end\n\n dim_num_save = dim_num;\n%\n% Initialize the remaining rows of V.\n%\n for i = 2 : dim_num\n%\n% The bits of the integer POLY(I) gives the form of polynomial I.\n%\n% Find the degree of polynomial I from binary encoding.\n%\n j = poly(i);\n m = 0;\n\n while ( 1 )\n\n j = floor ( j / 2 );\n\n if ( j <= 0 )\n break;\n end\n\n m = m + 1;\n\n end\n%\n% Expand this bit pattern to separate components of the logical array INCLUD.\n%\n j = poly(i);\n for k = m : -1 : 1\n j2 = floor ( j / 2 );\n includ(k) = ( j ~= 2 * j2 );\n j = j2;\n end\n%\n% Calculate the remaining elements of row I as explained\n% in Bratley and Fox, section 2.\n%\n for j = m + 1 : maxcol \n newv = v(i,j-m);\n l = 1;\n for k = 1 : m\n l = 2 * l;\n if ( includ(k) )\n newv = bitxor ( newv, l * v(i,j-k) );\n end\n end\n v(i,j) = newv;\n end\n end\n%\n% Multiply columns of V by appropriate power of 2.\n%\n l = 1;\n for j = maxcol-1 : -1 : 1\n l = 2 * l;\n v(1:dim_num,j) = v(1:dim_num,j) * l;\n end\n%\n% RECIPD is 1/(common denominator of the elements in V).\n%\n recipd = 1.0 / ( 2 * l );\n\n lastq(1:dim_num) = 0;\n\n end\n\n seed = floor ( seed );\n\n if ( seed < 0 )\n seed = 0;\n end\n\n if ( seed == 0 )\n\n l = 1;\n lastq(1:dim_num) = 0;\n\n elseif ( seed == seed_save + 1 )\n%\n% Find the position of the right-hand zero in SEED.\n%\n l = i4_bit_lo0 ( seed );\n\n elseif ( seed <= seed_save )\n\n seed_save = 0;\n l = 1;\n lastq(1:dim_num) = 0;\n\n for seed_temp = seed_save : seed - 1\n l = i4_bit_lo0 ( seed_temp );\n for i = 1 : dim_num\n lastq(i) = bitxor ( lastq(i), v(i,l) );\n end\n end\n\n l = i4_bit_lo0 ( seed );\n\n elseif ( seed_save + 1 < seed )\n\n for seed_temp = seed_save + 1 : seed - 1\n l = i4_bit_lo0 ( seed_temp );\n for i = 1 : dim_num\n lastq(i) = bitxor ( lastq(i), v(i,l) );\n end\n end\n\n l = i4_bit_lo0 ( seed );\n\n end\n%\n% Check that the user is not calling too many times!\n%\n if ( maxcol < l )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4_SOBOL - Fatal error!\\n' );\n fprintf ( 1, ' Too many calls!\\n' );\n fprintf ( 1, ' MAXCOL = %d\\n', maxcol );\n fprintf ( 1, ' L = %d\\n', l );\n return\n end\n%\n% Calculate the new components of QUASI.\n%\n for i = 1 : dim_num\n quasi(i) = lastq(i) * recipd;\n lastq(i) = bitxor ( lastq(i), v(i,l) );\n end\n\n seed_save = seed;\n seed = seed + 1;\n\n return\nend\n", "meta": {"author": "acerbilab", "repo": "bads", "sha": "019f0b432b9e157a31defbbd303aadcdf57862e7", "save_path": "github-repos/MATLAB/acerbilab-bads", "path": "github-repos/MATLAB/acerbilab-bads/bads-019f0b432b9e157a31defbbd303aadcdf57862e7/init/private/i4_sobol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.5984829374562382}} {"text": "\t\t% Se sterge spatiul de lucru\nclear;\n % Stabilirea numarului de necunoscute\nN=1000;\n % Se genereaza matricea coeficientilor (a)\na=rand(N);\n\t\t% Se incarca vectorul termenilor liberi b\nb=randn(N,1);\n % Setarea cronometrului\nt0=cputime;\n % Se rezolva sistemul de ecuatii liniare cu prima metoda prezentata\nx1=a\\b;\n % Se calculeaza timpul de calcul necesar\nt1=cputime-t0;\n % Setarea cronometrului\nt0=cputime;\n % Se rezolva sistemul de ecuatii liniare cu a doua metoda prezentata\nx2=inv(a)*b;\n % Se calculeaza timpul de calcul necesar\nt2=cputime-t0;\n % Se afiseaza timpii de calcul\ndisp('Timp de calcul metoda 1:'); disp(t1');\ndisp('Timp de calcul metoda 2:'); disp(t2');\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/8416-widely-used-programming-environments-in-electrical-engineering-matlab/3/Ex_3_7.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5984784070410487}} {"text": "function [beta_gibbs omega_gibbs F_gibbs L_gibbs phi_gibbs sigma_gibbs lambda_t_gibbs sigma_t_gibbs sbar]=tvbvar2gibbs(G,sigmahat,T,chi,psi,kappa,betahat,q,n,It,Bu,I_tau,I_om,H,Xbar,y,alpha0,yt,Xbart,upsilon0,f0,delta0,gamma,pick,pickf)\n\n\n\n\n\n% preliminary elements for the algorithm\n% compute the product G'*I_gamma*G (to speed up computations of deltabar)\nGIG=G'*I_om*G;\n% set tau as a large value\ntau=10000;\n% set omega as a large value\nom=5;\n% compute psibar\nchibar=(chi+T)/2;\n% compute alphabar\nkappabar=T+kappa;\n% compute alphabar\nalphabar=T+alpha0;\n\n\n% initiate the Gibbs sampler\n% initiate the counting of iterations\ncount=1;\npickcount=1;\n% initiate the record matrices and cells\nbeta_gibbs=[];\nomega_gibbs=[];\nF_gibbs=[];\nL_gibbs=[];\nphi_gibbs=[];\nsigma_gibbs=[];\nlambda_t_gibbs={};\nsigma_t_gibbs={};\n\n\n% step 1: determine initial values for the algorithm\n\n% initial value for B\nB=kron(ones(T,1),betahat);\n% initial value Omega\nomega=diag(diag(betahat*betahat'));\n% invert Omega\ninvomega=diag(1./diag(omega));\n% initial value for f_2,...,f_n\n% obtain the triangular factorisation of sigmahat\n[Fhat Lambdahat]=bear.triangf(sigmahat);\n% obtain the inverse of Fhat\n[invFhat]=bear.invltod(Fhat,n);\n% create the cell storing the different vectors of invF\nFinv=cell(n,1);\n% store the vectors\nfor ii=2:n\n Finv{ii,1}=invFhat(ii,1:ii-1);\nend\n% initial values for L_1,...,L_n\nL=zeros(T,n);\n% initial values for phi_1,...,phi_n\nphi=ones(1,n);\n% initiate invsigmabar\ninvsigmabar=sparse(kron(eye(T),inv(sigmahat)));\n\n\n\n% step 2: determine the sbar values and Lambda\nsbar=diag(Lambdahat);\nLambda=sparse(diag(sbar));\n\n\n\n% step 3: recover the series of initial values for lambda_1,...,lambda_T and sigma_1,...,sigma_T\nlambda_t=repmat(diag(sbar),1,1,T);\nsigma_t=repmat(sigmahat,1,1,T);\n\nhbar = bear.parfor_progressbar(It,'Progress of the Gibbs sampler'); %create the progress bar\n\n% run the Gibbs sampler\nwhile count<=It\n % count\n\n hbar.iterate(1); % update progress by one iteration\n\n\n % step 4: draw B\n invomegabar=H'*kron(I_tau,invomega)*H+Xbar'*invsigmabar*Xbar;\n % compute the choleski of invomegabar\n C=chol(bear.nspds(invomegabar),'Lower');\n % compute temporary value\n temp=Xbar'*invsigmabar*y;\n % smoothing phase: solve by back substitution\n temp1=C\\temp;\n % smoothing phase: solve by forward substitution\n Bbar=C'\\temp1;\n % simulation phase:\n B=Bbar+C'\\randn(q*T,1);\n % reshape\n Beta=reshape(B,q,T);\n\n\n\n % step 5: draw omega from its posterior\n % compute the summ\n summ=(1/tau)*Beta(:,1)*Beta(:,1)';\n for ii=2:T\n summ=summ+(Beta(:,ii)-Beta(:,ii-1))*(Beta(:,ii)-Beta(:,ii-1))';\n end\n summ=diag(summ);\n % obtain Qbar\n psibar=summ+psi;\n % draw omega\n omega=diag(arrayfun(@bear.igrandn,kron(ones(q,1),chibar),psibar));\n % invert it for next iteration\n invomega=diag(1./diag(omega));\n\n\n\n % step 6: draw the series f_2,...,f_n from their conditional posteriors\n % recover first the residuals\n for jj=1:T\n epst(:,:,jj)=yt(:,:,jj)-Xbart{jj,1}*Beta(:,jj);\n end\n % then draw the vectors in turn\n for jj=2:n\n % first compute the summations required for upsilonbar and fbar\n summ1=zeros(jj-1,jj-1);\n summ2=zeros(jj-1,1);\n % run the summation\n for kk=1:T\n prodt=epst(1:jj-1,1,kk)*exp(-L(kk,jj));\n summ1=summ1+prodt*epst(1:jj-1,1,kk)';\n summ2=summ2+prodt*epst(jj,1,kk)';\n end\n summ1=(1/sbar(jj,1))*summ1;\n summ2=(-1/sbar(jj,1))*summ2;\n % then obtain the inverse of upsilon0\n invupsilon0=diag(1./diag(upsilon0{jj,1}));\n % obtain upsilonbar\n invupsilonbar=summ1+invupsilon0;\n C=chol(bear.nspd(invupsilonbar));\n invC=C\\speye(jj-1);\n upsilonbar=full(invC*invC');\n % recover fbar\n fbar=upsilonbar*(summ2+invupsilon0*f0{jj,1});\n % finally draw f_i^(-1)\n Finv{jj,1}=fbar+chol(bear.nspd(upsilonbar),'lower')*randn(jj-1,1);\n end\n % recover the inverse of F\n invF=eye(n);\n for jj=2:n\n invF(jj,1:jj-1)=Finv{jj,1};\n end\n % eventually recover F\n F=bear.invltod(invF,n);\n % then update sigma\n sigma=F*Lambda*F';\n\n\n\n % step 7: draw the series phi_1,...,phi_n from their conditional posteriors\n % draw the parameters in turn\n for jj=1:n\n % estimate deltabar\n deltabar=L(:,jj)'*GIG*L(:,jj)+delta0;\n % draw the value phi_i\n phi(1,jj)=bear.igrandn(alphabar/2,deltabar/2);\n end\n\n\n\n\n % step 8: draw the series lambda_i,t from their conditional posteriors, i=1,...,n and t=1,...,T\n % consider variables in turn\n for jj=1:n\n % consider periods in turn\n for kk=1:T\n % a candidate value will be drawn from N(lambdabar,phibar)\n % the definitions of lambdabar and phibar varies with the period, thus define them first\n % if the period is the first period\n if kk==1\n lambdabar=(gamma*L(2,jj))/(1/om+gamma^2);\n phibar=phi(1,jj)/(1/om+gamma^2);\n % if the period is the final period\n elseif kk==T\n lambdabar=gamma*L(T-1,jj);\n phibar=phi(1,jj);\n % if the period is any period in-between\n else\n lambdabar=(gamma/(1+gamma^2))*(L(kk-1,jj)+L(kk+1,jj));\n phibar=phi(1,jj)/(1+gamma^2);\n end\n % now draw the candidate\n cand=lambdabar+phibar^0.5*randn;\n % compute the acceptance probability\n prob=bear.mhprob2(jj,cand,L(kk,jj),sbar(jj,1),epst(:,1,kk),Finv{jj,1});\n % draw a uniform random number\n draw=rand;\n % keep the candidate if the draw value is lower than the prob\n if draw<=prob\n L(kk,jj)=cand;\n % if not, just keep the former value\n end\n end\n end\n % then recover the series of matrices lambda_t and sigma_t\n for jj=1:T\n lambda_t(:,:,jj)=diag(sbar).*diag(exp(L(jj,:)));\n sigma_t(:,:,jj)=F*lambda_t(:,:,jj)*F';\n end\n\n\n\n\n\n\n\n % record phase\n % if the burn-in sample phase is not yet over\n if count<=Bu\n % simply add 1 to the iteration count\n count=count+1;\n % on the other hand, if the burn-in sample phase is over\n elseif count>Bu\n % adding one iteration to the count will depend on wether post-burn selection applies\n % if there is no post burn selection\n if pick==0\n % record the results\n beta_gibbs(:,count-Bu)=B;\n omega_gibbs(:,count-Bu)=diag(omega);\n F_gibbs(:,:,count-Bu)=F;\n L_gibbs(:,:,count-Bu)=L;\n phi_gibbs(count-Bu,:)=phi;\n sigma_gibbs(:,count-Bu)=sigma(:);\n for jj=1:T\n lambda_t_gibbs{jj,1}(:,:,count-Bu)=lambda_t(:,:,jj);\n sigma_t_gibbs{jj,1}(:,:,count-Bu)=sigma_t(:,:,jj);\n end\n % then add one to the count\n count=count+1;\n % if there is post burn selection, only one draw over 'fpick' draws will be retained\n elseif pick==1\n % if the iteration does not correspond to fpick, don't record the results, don't increase the regular count, but do increase pickcount by 1, and do record the acceptance rate of the Metropolis-Hastings step\n if pickcount~=pickf\n pickcount=pickcount+1;\n % on the other hand, if the iteration does correspond to fpick\n elseif pickcount==pickf\n % do record the results\n beta_gibbs(:,count-Bu)=B;\n omega_gibbs(:,count-Bu)=diag(omega);\n F_gibbs(:,:,count-Bu)=F;\n L_gibbs(:,:,count-Bu)=L;\n phi_gibbs(count-Bu,:)=phi;\n sigma_gibbs(:,count-Bu)=sigma(:);\n for jj=1:T\n lambda_t_gibbs{jj,1}(:,:,count-Bu)=lambda_t(:,:,jj);\n sigma_t_gibbs{jj,1}(:,:,count-Bu)=sigma_t(:,:,jj);\n end\n % then increase the regular count by 1 and re-initialise pickcount\n count=count+1;\n pickcount=1;\n end\n end\n end\nend\nclose(hbar); %close progress bar\n\n\n% turn beta_gibbs into cell\nbeta_gibbs=mat2cell(beta_gibbs,repmat(q,T,1),It-Bu);\n\n\n\n\n\n", "meta": {"author": "european-central-bank", "repo": "BEAR-toolbox", "sha": "f33aae80c40f7a2e78a54de99b2ce3663f59aa75", "save_path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox", "path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox/BEAR-toolbox-f33aae80c40f7a2e78a54de99b2ce3663f59aa75/tbx/bear/+bear/tvbvar2gibbs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631476836816, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.5984783900283854}} {"text": "function [cst,cstJac] = autoGen_cst_footVel(q1p,q2p,q4p,q5p,q1m,q2m,q4m,q5m,dq1p,dq2p,dq4p,dq5p,dq1m,dq2m,dq4m,dq5m,l1,l2,l4,l5)\n%AUTOGEN_CST_FOOTVEL\n% [CST,CSTJAC] = AUTOGEN_CST_FOOTVEL(Q1P,Q2P,Q4P,Q5P,Q1M,Q2M,Q4M,Q5M,DQ1P,DQ2P,DQ4P,DQ5P,DQ1M,DQ2M,DQ4M,DQ5M,L1,L2,L4,L5)\n\n% This function was generated by the Symbolic Math Toolbox version 6.3.\n% 25-Oct-2015 18:36:52\n\nt2 = sin(q1p);\nt3 = sin(q2p);\nt4 = sin(q4p);\nt5 = sin(q5p);\nt6 = sin(q1m);\nt7 = sin(q2m);\nt8 = sin(q4m);\nt9 = sin(q5m);\ncst = [dq1p.*l1.*t2+dq2p.*l2.*t3-dq4p.*l4.*t4-dq5p.*l5.*t5;-dq1m.*l1.*t6-dq2m.*l2.*t7+dq4m.*l4.*t8+dq5m.*l5.*t9];\nif nargout > 1\n cstJac = reshape([0.0,0.0,dq1p.*l1.*cos(q1p),0.0,dq2p.*l2.*cos(q2p),0.0,0.0,0.0,-dq4p.*l4.*cos(q4p),0.0,-dq5p.*l5.*cos(q5p),0.0,l1.*t2,0.0,l2.*t3,0.0,0.0,0.0,-l4.*t4,0.0,-l5.*t5,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,-dq1m.*l1.*cos(q1m),0.0,-dq2m.*l2.*cos(q2m),0.0,0.0,0.0,dq4m.*l4.*cos(q4m),0.0,dq5m.*l5.*cos(q5m),0.0,-l1.*t6,0.0,-l2.*t7,0.0,0.0,0.0,l4.*t8,0.0,l5.*t9,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0],[2,32]);\nend\n", "meta": {"author": "MatthewPeterKelly", "repo": "OptimTraj", "sha": "c97b57fda511dacc6a6187f683428f0f3a1965f2", "save_path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj", "path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj/OptimTraj-c97b57fda511dacc6a6187f683428f0f3a1965f2/demo/fiveLinkBiped/costOfTransport/autoGen_cst_footVel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5984576985070783}} {"text": "function writeGrid(filename, grid_size, grid_spacing, pml_size, pml_alpha, Nt, dt, c_ref) \n%WRITEGRID Write grid and PML properties to a k-Wave HDF5 file.\n%\n% DESCRIPTION:\n% writeGrid creates and writes the wavenumber grids and PML variables\n% required by the k-Wave C++ code to the HDF5 file specified by the\n% user. \n%\n% List of parameters that are written:\n% Nx\n% Ny\n% Nz\n% Nt\n% dt\n% dx\n% dy\n% dz\n% c_ref\n% ddx_k_shift_pos_r\n% ddx_k_shift_neg_r\n% ddy_k_shift_pos\n% ddy_k_shift_neg\n% ddz_k_shift_pos\n% ddz_k_shift_neg\n% x_shift_neg_r\n% y_shift_neg_r\n% z_shift_neg_r\n% pml_x_sgx\n% pml_y_sgy\n% pml_z_sgz\n% pml_x\n% pml_y\n% pml_z\n% pml_x_alpha\n% pml_y_alpha\n% pml_z_alpha\n% pml_x_size\n% pml_y_size\n% pml_z_size\n%\n% USAGE:\n% writeGrid(filename, grid_size, grid_spacing, pml_size, pml_alpha, Nt, dt, c_ref) \n%\n% INPUTS:\n% filename - filename and location of the input HDF5 file\n% grid_size - [Nx, Ny, Nz]\n% grid_spacing - [dx, dy, dz]\n% pml_size - [pml_x_size, pml_y_size, pml_z_size]\n% pml_alpha - [pml_x_alpha, pml_y_alpha, pml_z_alpha]\n% Nt - number of time points\n% dt - time step\n% c_ref - scalar sound speed used in the k-space\n% operator and to define the pml variables\n%\n% ABOUT:\n% author - Bradley Treeby\n% date - 30th May 2013\n% last update - 21st 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% See also h5writeatt, writeAttributes, writeFlags, writeMatrix\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\n%#ok<*INUSL>\n%#ok<*NASGU>\n\n% get literals\ngetH5Literals;\n\n% unpack grid size inputs to make code easier to read\nNx = grid_size(1);\nNy = grid_size(2);\nNz = grid_size(3);\ndx = grid_spacing(1);\ndy = grid_spacing(2);\ndz = grid_spacing(3);\npml_x_size = pml_size(1);\npml_y_size = pml_size(2);\npml_z_size = pml_size(3);\npml_x_alpha = pml_alpha(1);\npml_y_alpha = pml_alpha(2);\npml_z_alpha = pml_alpha(3);\n\n% =========================================================================\n% CREATE WAVENUMBER AND PML VECTORS\n% =========================================================================\n\n% create the wavenumber grids (assuming Nx, Ny and Nz are even)\nnx = ((-Nx/2:Nx/2-1)/Nx).';\nnx(floor(Nx/2) + 1) = 0;\nkx_vec = (2*pi/dx).*nx; \n\nny = ((-Ny/2:Ny/2-1)/Ny).';\nny(floor(Ny/2) + 1) = 0;\nky_vec = (2*pi/dy).*ny; \n\nnz = ((-Nz/2:Nz/2-1)/Nz).';\nnz(floor(Nz/2) + 1) = 0;\nkz_vec = (2*pi/dz).*nz; \n\n% force the vector operators be in the correct direction (Nx, 1, 1), (1, Ny, 1), (1, 1, Nz) \nky_vec = ky_vec.'; \nkz_vec = permute(kz_vec, [2 3 1]);\n\n% create vector derivative and shift variables\nddx_k_shift_pos = ifftshift( 1i*kx_vec .* exp( 1i*kx_vec*dx/2), 1);\nddx_k_shift_neg = ifftshift( 1i*kx_vec .* exp(-1i*kx_vec*dx/2), 1);\nddy_k_shift_pos = ifftshift( 1i*ky_vec .* exp( 1i*ky_vec*dy/2), 2); \nddy_k_shift_neg = ifftshift( 1i*ky_vec .* exp(-1i*ky_vec*dy/2), 2);\nddz_k_shift_pos = ifftshift( 1i*kz_vec .* exp( 1i*kz_vec*dz/2), 3);\nddz_k_shift_neg = ifftshift( 1i*kz_vec .* exp(-1i*kz_vec*dz/2), 3);\n \n% create vector shift operators\nx_shift_neg = ifftshift( exp(-1i*kx_vec*dx/2), 1);\ny_shift_neg = ifftshift( exp(-1i*ky_vec*dy/2), 2);\nz_shift_neg = ifftshift( exp(-1i*kz_vec*dz/2), 3);\n\n% create reduced variables for use with real-to-complex FFT\nNx_r = floor(Nx/2) + 1;\nNy_r = floor(Ny/2) + 1;\nNz_r = floor(Nz/2) + 1;\nddx_k_shift_pos_r = ddx_k_shift_pos(1:Nx_r);\nddx_k_shift_neg_r = ddx_k_shift_neg(1:Nx_r);\nx_shift_neg_r = x_shift_neg(1:Nx_r);\ny_shift_neg_r = y_shift_neg(1:Ny_r);\nz_shift_neg_r = z_shift_neg(1:Nz_r);\n\n% create vector PML variables\npml_x = getPML(Nx, dx, dt, c_ref, pml_x_size, pml_x_alpha, false, 1);\npml_x_sgx = getPML(Nx, dx, dt, c_ref, pml_x_size, pml_x_alpha, true, 1);\npml_y = getPML(Ny, dy, dt, c_ref, pml_y_size, pml_y_alpha, false, 2);\npml_y_sgy = getPML(Ny, dy, dt, c_ref, pml_y_size, pml_y_alpha, true, 2);\npml_z = getPML(Nz, dz, dt, c_ref, pml_z_size, pml_z_alpha, false, 3);\npml_z_sgz = getPML(Nz, dz, dt, c_ref, pml_z_size, pml_z_alpha, true, 3);\n\n% cleanup unused variables\nclear ddx_k_shift_pos ddx_k_shift_neg x_shift_neg y_shift_neg z_shift_neg;\n\n% =========================================================================\n% STORE FLOATS\n% =========================================================================\n\n% list of variables stored as floats\nvariable_names = {...\n 'dt', 'dx', 'dy', 'dz', ...\n 'ddx_k_shift_pos_r', 'ddx_k_shift_neg_r', 'x_shift_neg_r', ...\n 'ddy_k_shift_pos', 'ddy_k_shift_neg', 'y_shift_neg_r', ...\n 'ddz_k_shift_pos', 'ddz_k_shift_neg', 'z_shift_neg_r', ...\n 'pml_x_sgx', 'pml_y_sgy', 'pml_z_sgz', ...\n 'pml_x', 'pml_y', 'pml_z', ...\n 'pml_x_alpha', 'pml_y_alpha', 'pml_z_alpha', ...\n 'c_ref'};\n\n% change float variables to be in single precision (float in C++), then\n% add to HDF5 file\nfor index = 1:length(variable_names)\n\n % cast matrix to single precision\n eval([variable_names{index} ' = ' MATRIX_DATA_TYPE_MATLAB '(' variable_names{index} ');']);\n\n % write to HDF5 file\n writeMatrix(filename, eval(variable_names{index}), variable_names{index});\n\nend\n\n% =========================================================================\n% STORE INTEGERS\n% =========================================================================\n\n% integer variables\nvariable_names = {'Nx', 'Ny', 'Nz', 'Nt',...\n 'pml_x_size' , 'pml_y_size' , 'pml_z_size'};\n\n% change all the index variables to be in 64-bit unsigned integers (long in C++)\nfor index = 1:length(variable_names)\n\n % cast matrix to 64-bit unsigned integer\n eval([variable_names{index} ' = ' INTEGER_DATA_TYPE_MATLAB '(' variable_names{index} ');']);\n\n % write to HDF5 file\n writeMatrix(filename, eval(variable_names{index}), variable_names{index});\n\nend", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/K-wave/k-Wave/writeGrid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5983862085148126}} {"text": "function [ kn, fn, wn ] = r4_nor_setup ( )\n\n%*****************************************************************************80\n%\n%% R4_NOR_SETUP sets data needed by R4_NOR.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 October 2013\n%\n% Author:\n%\n% Original C version by George Marsaglia, Wai Wan Tsang\n% MATLAB version by John Burkardt\n%\n% Reference:\n%\n% George Marsaglia, Wai Wan Tsang,\n% The Ziggurat Method for Generating Random Variables,\n% Journal of Statistical Software,\n% Volume 5, Number 8, October 2000, seven pages.\n%\n% Parameters:\n%\n% Output, uint32 KN(128), data needed by R4_NOR.\n%\n% Output, real FN(128), WN(128), data needed by R4_NOR.\n%\n kn = zeros ( 128, 'uint32' );\n fn = zeros ( 128 );\n wn = zeros ( 128 );\n\n m1 = 2147483648.0;\n vn = 9.91256303526217E-03;\n\n dn = 3.442619855899;\n tn = 3.442619855899;\n\n q = vn / exp ( - 0.5 * dn * dn );\n kn(1) = uint32 ( ( dn / q ) * m1 );\n kn(2) = 0;\n\n wn(1) = q / m1;\n wn(128) = dn / m1;\n\n fn(1) = 1.0;\n fn(128) = exp ( - 0.5 * dn * dn );\n\n for i = 127 : -1 : 2\n dn = sqrt ( - 2.0 * log ( vn / dn + exp ( - 0.5 * dn * dn ) ) );\n kn(i+1) = uint32 ( ( dn / tn ) * m1 );\n tn = dn;\n fn(i) = exp ( - 0.5 * dn * dn );\n wn(i) = dn / m1;\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/ziggurat/r4_nor_setup.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5983377853747127}} {"text": "% TTeMPS Toolbox. \n% Michael Steinlechner, 2013-2016\n% Questions and contact: michael.steinlechner@epfl.ch\n% BSD 2-clause license, see LICENSE.txt\n\nfunction X = construct_initial_guess(L, F, r, n)\n% Basicially only the first micro-step of ALS\n\nX = TTeMPS_rand( r, n );\nX = 1/norm(X) * X;\n\n\nd = X.order;\nn = X.size;\n\n\nX = orthogonalize(X, 1);\nFi = contract( X, F, 1 );\nsz = [X.rank(1), X.size(1), X.rank(2)];\n\n[left, right] = Afun_prepare( L, X, 1 );\nB1 = prepare_precond( L.A{1}, X, 1 );\n\nUi = pcg( @(y) Afun( L, y, 1, sz, left, right), ...\n Fi(:), ...\n 1e-10, 1000, ...\n @(y) apply_precond( L.A{1}, B1, y, sz ), [],...\n X.U{1}(:) ); \n\nX.U{1} = reshape( Ui, sz );\n\nX = orth_at( X, 1, 'left', true );\n\n\nend\n\n\n\n\nfunction [left, right] = Afun_prepare( A, x, idx )\n y = A.apply(x); \n if idx == 1\n right = innerprod( x, y, 'RL', idx+1 );\n left = [];\n elseif idx == x.order\n left = innerprod( x, y, 'LR', idx-1 );\n right = [];\n else\n left = innerprod( x, y, 'LR', idx-1 );\n right = innerprod( x, y, 'RL', idx+1 ); \n end\nend\n\nfunction res = Afun( A, U, idx, sz, left, right )\n\n V = reshape( U, sz );\n V = A.apply( V, idx );\n \n if idx == 1\n tmp = tensorprod_ttemps( V, right, 3 );\n elseif idx == A.order\n tmp = tensorprod_ttemps( V, left, 1 );\n else\n tmp = tensorprod_ttemps( V, right, 3);\n tmp = tensorprod_ttemps( tmp, left, 1);\n end\n\n res = tmp(:);\nend\n\n\nfunction B1 = prepare_precond( L0, X, idx )\n\n if idx == 1\n B1 = [];\n return\n end\n\n n = size(L0, 1);\n r = X.rank;\n\n X1 = matricize( X.U{1}, 2);\n Y = X;\n Y.U{1} = tensorize( L0*X1, 2, [r(1), n(1), r(2)] );\n B1 = innerprod( X, Y, 'LR', idx-1);\nend\n\nfunction res = apply_precond( L0, B1, rhs, sz )\n \n n = size(L0, 1);\n rhs = reshape( rhs, sz );\n if isempty(B1) %idx == 1\n res = L0 \\ unfold( rhs, 'left' );\n res = reshape( res, sz );\n else\n res = B1 \\ unfold(rhs, 'right');\n res = reshape( res, sz );\n end\n res = res(:);\nend\n\n\n\n\n\n\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/manifolds/ttfixedrank/TTeMPS_1.1/algorithms/linearsystem/construct_initial_guess_rankOne.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5983377801859839}} {"text": "function rs = realifft(data, N)\n\n% inverse fft for fourier coefficents from real valued original data\n% needs the length of the original time series from which the fft was computed\n% see also : realfft\n\ndata = data(:);\nif mod(N,2) \t% odd length\n\tdata = [data ; conj(data(end:-1:2))]; \nelse\t\t\t% even length\n\tdata = [data ; conj(data(end-1:-1:2))]; \nend \n\nrs = real(ifft(data)); % remove small imaginary components introduced by rounding errors\n", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Toolboxes/OpenTSTOOL/tstoolbox/@core/private/realifft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.5983377794288814}} {"text": "% =========================================================================\n% This code is part of the Matlab-based toolbox \n% LagLDDDM - A Lagrangian Gauss--Newton--Krylov Solver for Mass- and \n% Intensity-Preserving Diffeomorphic Image Registration\n% \n% For details and license info see \n% - https://github.com/C4IR/FAIR.m/tree/master/add-ons/LagLDDMM\n%\n% 2D Multilevel Mass-Preserving LDDMM Example using stationary velocity\n% field and diffusion regularizer as described in Sec. 4 of the paper:\n%\n% @article{MangRuthotto2017,\n% Title = {A {L}agrangian {G}auss--{N}ewton--{K}rylov solver for mass- and intensity-preserving diffeomorphic image registration},\n% Year = {2017},\n% Journal = {SIAM Journal on Scientific Computing},\n% Author = {A. Mang, L. Ruthotto},\n% }\n%\n% =========================================================================\nclose all; clc; clear all;\nsetup3DmouseData;\nalpha = [50 0];\nlvl = 4;\npad = 0;\nmV = @(m) m;\nnt = 0;\nN = 2;\nminLevel = 4;\nmaxLevel = 6;\nimgModel('reset','imgModel','linearInterMex')\n% 1) setup grid for velocities (padded)\nomegaV = omega; omegaV(1:2:end) = omegaV(1:2:end)-pad; omegaV(2:2:end) = omega(2:2:end)+pad;\n\n% 2) setup regularizer (and decide for stationary or nonstationary velocity)\nregularizer('reset','regularizer','mfDiffusionCC','alpha',alpha,'nt',nt,'HessianShift',1e-2); % nonstationary velocity\n\n%%\nplots = 1;\nNPIRpara = optPara('NPIR-GN');\nNPIRpara.maxIter = 40;\nNPIRpara.scheme = @GaussNewtonLDDMM;\n\n[vc,~,wc,his] = MLLDDMM(ML,'minLevel',minLevel,'maxLevel',maxLevel,'omegaV',omegaV,...\n 'mV',mV,'N',N,'parametric',0,'plots',plots,'NPIRpara',NPIRpara,'NPIRobj',@MPLDDMMobjFctn);\nswitch regularizer\n case {'mfDiffusionST','mfCurvatureST'}\n yInv = getTrafoFromInstationaryVelocityRK4(vc,getNodalGrid(omega,m),'omega',omegaV,'m',m,'N',N,'nt',nt,'tspan',[1 0]);\n case {'mfDiffusionCC','mfCurvatureCC'}\n yInv = getTrafoFromVelocityRK4(vc,getNodalGrid(omega,m),'omega',omegaV,'m',m,'N',N,'tspan',[1 0]);\n nt = 0;\nend\n\n%%\nyc = getTrafoFromVelocityRK4(vc,getNodalGrid(omega,m),'omega',omegaV,'m',m,'nt',nt,'tspan',[1,0],'N',N);\nJac = geometry(yInv,m,'Jac','omega',omega);\nTopt = linearInterMex(dataT,omega,center(yInv,m)) .* Jac;\nD0 = distance(dataT(:),dataR(:),omega,m);\nDOpt = distance(Topt(:),dataR(:),omega,m);\n\nfig = figure(); clf;\nfig.Name = sprintf('Results for %s',mfilename);\n\nsubplot(2,3,1);\nviewImage(dataR,omega,m);\ntitle('reference');\n\nsubplot(2,3,4);\nviewImage(dataT,omega,m);\ntitle('template');\n\nsubplot(2,3,2);\nviewImage(Topt,omega,m);\ntitle('T(yc)')\n\nsubplot(2,3,3);\nimgmontage(dataT(:)-dataR(:),omega,m);\ntitle('init. residual, SSD=100%');\n\nsubplot(2,3,5);\nimgmontage(Jac,omega,m);\ntitle(sprintf('Jac, min=%1.2f max=%1.2f',min(Jac(:)),max(Jac(:))));\n\nsubplot(2,3,6);\nimgmontage(Topt(:)-dataR(:),omega,m);\ntitle(sprintf('opt residual, SSD=%1.2f%%',100*DOpt/D0));", "meta": {"author": "C4IR", "repo": "FAIR.m", "sha": "975edebd37b833ae76696792870de5c05efcb9cb", "save_path": "github-repos/MATLAB/C4IR-FAIR.m", "path": "github-repos/MATLAB/C4IR-FAIR.m/FAIR.m-975edebd37b833ae76696792870de5c05efcb9cb/add-ons/LagLDDMM/examples/EMPLDDMM_3Dmouse_mfDiffusionCC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.5982901547392484}} {"text": "function [PC,CC,DC,IC] = trim_with_spline(PA,CA,PB,CB,tol)\n % TRIM_WITH_SPLINE Trim a given spline (PA,CA) with a \"solid\" spline (PB,CB)\n %\n % [PC,CC,DC,IC] = trim_with_spline(PA,CA,PB,CB,tol)\n %\n % Inputs:\n % PA #PA by dim list of control point locations\n % CA #CA by 4 list of indices into PA of cubic Bezier curves\n % PB #PB by dim list of control point locations\n % CB #CB by 4 list of indices into PB of cubic Bezier curves\n % tol tolerance for intersection {1e-7}\n % Outputs:\n % PC #PC by dim list of control point locations\n % CC #CC by 4 list of indices into PC of cubic Bezier curves\n % DC #CC list of flags whether inside B\n % IC #CC list of indices into CA\n %\n\n function [PA,CA,DA,IA] = trim_with_spline_helper(PA,CA,PB,CB)\n\n [A1,A2] = box_each_element(PA,CA);\n [B1,B2] = box_each_element(PB,CB);\n I = box_intersect(A1,A2,B1,B2);\n T = cell(size(CA,1),1);\n % consider each intersection, gather splits\n for ii = 1:size(I,1)\n ca = I(ii,1);\n cb = I(ii,2);\n Tii = cubic_cubic_intersect(PA(CA(ca,:),:),PB(CB(cb,:),:),tol);\n if ~isempty(Tii)\n T{ca} = [T{ca};Tii(:,1)];\n end\n end\n % conduct all splits\n IA = (1:size(CA,1))';\n for ca = 1:size(CA,1)\n if ~isempty(T{ca})\n Tca = sort(T{ca});\n [PAa,CAa] = cubic_subdivide(PA(CA(ca,:),:),Tca);\n CAa = reshape([CA(ca,1) CAa(2:end-1)+size(PA,1)-2 CA(ca,end)],size(CAa));\n IA([ca size(CA,1)+(1:size(CAa,1)-1)],:) = IA(ca);\n CA([ca size(CA,1)+(1:size(CAa,1)-1)],:) = CAa;\n PA = [PA;PAa(3:end,:)];\n end\n end\n\n %%fprintf('trim_with_spline...\\n');\n %% loop order is imporant \n %IA = (1:size(CA,1))';\n %for cb = 1:size(CB,1)\n % %fprintf(' %04d/%04d:\\n',cb,size(CB,1));\n % for ca = 1:size(CA,1)\n % %progressbar(ca,size(CA,1));\n % T = cubic_cubic_intersect(PA(CA(ca,:),:),PB(CB(cb,:),:),tol);\n % if ~isempty(T)\n % [PAa,CAa] = cubic_subdivide(PA(CA(ca,:),:),T(:,1));\n % CAa = reshape([CA(ca,1) CAa(2:end-1)+size(PA,1)-2 CA(ca,end)],size(CAa));\n % IA([ca size(CA,1)+(1:size(CAa,1)-1)],:) = IA(ca);\n % CA([ca size(CA,1)+(1:size(CAa,1)-1)],:) = CAa;\n % PA = [PA;PAa(3:end,:)];\n % end\n % end\n %end\n\n % midpoints of each cubic\n %fprintf('midpoints...\\n');\n M = zeros(size(CA,1),2);\n for ca = 1:size(CA,1)\n M(ca,:) = cubic_eval(PA(CA(ca,:),:),0.5);\n end\n %fprintf('spline_winding_number...\\n');\n DA = abs(spline_winding_number(PB,CB,M))>0.5;\n end\n\n m = size(CA,1);\n embed = @(P,C) reshape(P(C,:),size(C,1),8);\n CB8 = embed(PB,CB);\n % In either direction\n RB8 = embed(PB,fliplr(CB));\n CA8 = embed(PA,CA);\n % find perfect matches (only considering that every control point is exactly\n % the same; not finding partial co-incidence )\n [idx,dist] = rangesearch([CB8;RB8],CA8,0);\n perfect = cellfun(@(i) ~isempty(i),idx);\n JN = find(~perfect);\n [PA,CN,DN,IN] = trim_with_spline_helper(PA,CA(JN,:),PB,CB);\n CA = [CN;CA(perfect,:)];\n JP = find(perfect);\n IA = [JN(IN);JP];\n DA = [DN;true(numel(JP),1)];\n assert(size(CA,1) == numel(IA));\n assert(max(IA) <= m);\n assert(size(CA,1) == numel(DA));\n\n % rename\n PC = PA;\n CC = CA;\n DC = DA;\n IC = IA;\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/trim_with_spline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5982901493180531}} {"text": "function label = LSC(data,k,opts)\n% label = LSC(data,k,opts): Landmark-based Spectral Clustering\n% Input:\n% - data: the data matrix of size nSmp x nFea, where each row is a sample\n% point\n% - k: the number of clusters\n% opts: options for this algorithm\n% - p: the number of landmarks picked (default 1000)\n% - r: the number of nearest landmarks for representation (default 5)\n% - numRep: the number of replicates for the final kmeans (default 10)\n% - maxIter: the maximum number of iterations for final kmeans (default 100)\n% - mode: landmark selection method, currently support\n% - 'kmeans': use centers of clusters generated by kmeans (default)\n% - 'random': use randomly sampled points from the original\n% data set \n% The following parameters are effective ONLY in mode 'kmeans'\n% - kmNumRep: the number of replicates for initial kmeans (default 1)\n% - kmMaxIter: the maximum number of iterations for initial kmeans (default 5)\n% Output:\n% - label: the cluster assignment for each point\n% Requre:\n% litekmeans.m\n% Usage:\n% data = rand([100,50]);\n% label = LSC(data,10);\n%Reference:\n%\n%\t[1] Xinlei Chen, Deng Cai, \"Large Scale Spectral Clustering with\n%\tLandmark-Based Representation,\" AAAI 2011. \n%\n% [2] Deng Cai, Xinlei Chen: Large Scale Spectral Clustering Via\n% Landmark-Based Sparse Representation. IEEE Trans. Cybernetics 45(8):\n% 1669-1680 (2015) \n%\n% version 2.0 --Dec./2011 \n% version 1.0 --Oct./2010 \n%\n% Written by Xinlei Chen (endernewton AT gmail.com)\n% Deng Cai (dengcai AT gmail.com)\n\n\n\n% Set and parse parameters\nif (~exist('opts','var'))\n opts = [];\nend\n\n\np = 1000;\nif isfield(opts,'p')\n p = opts.p;\nend\n\nr = 5;\nif isfield(opts,'r')\n r = opts.r;\nend\n\nmaxIter = 100;\nif isfield(opts,'maxIter')\n maxIter = opts.maxIter;\nend\n\nnumRep = 10;\nif isfield(opts,'numRep')\n numRep = opts.numRep;\nend\n\nmode = 'kmeans';\nif isfield(opts,'mode')\n mode = opts.mode;\nend\n\nnSmp=size(data,1);\n\n% Landmark selection\nif strcmp(mode,'kmeans')\n kmMaxIter = 5;\n if isfield(opts,'kmMaxIter')\n kmMaxIter = opts.kmMaxIter;\n end\n kmNumRep = 1;\n if isfield(opts,'kmNumRep')\n kmNumRep = opts.kmNumRep;\n end\n [~,marks]=litekmeans(data,p,'MaxIter',kmMaxIter,'Replicates',kmNumRep);\n clear kmMaxIter kmNumRep\nelseif strcmp(mode,'random')\n indSmp = randperm(nSmp);\n marks = data(indSmp(1:p),:);\n clear indSmp\nelse\n error('mode does not support!');\nend\n\n% Z construction\nD = EuDist2(data,marks);\n\nif isfield(opts,'sigma')\n sigma = opts.sigma;\nelse\n sigma = mean(mean(D));\nend\n\ndump = zeros(nSmp,r);\nidx = dump;\nfor i = 1:r\n [dump(:,i),idx(:,i)] = min(D,[],2);\n temp = (idx(:,i)-1)*nSmp+[1:nSmp]';\n D(temp) = 1e100; \nend\n\ndump = exp(-dump/(2*sigma^2));\nsumD = sum(dump,2);\nGsdx = bsxfun(@rdivide,dump,sumD);\nGidx = repmat([1:nSmp]',1,r);\nGjdx = idx;\nZ=sparse(Gidx(:),Gjdx(:),Gsdx(:),nSmp,p);\n\n% Graph decomposition\nfeaSum = full(sqrt(sum(Z,1)));\nfeaSum = max(feaSum, 1e-12);\nZ = Z./feaSum(ones(size(Z,1),1),:);\nU = mySVD(Z,k+1);\nU(:,1) = [];\n\nU=U./repmat(sqrt(sum(U.^2,2)),1,k);\n\n% Final kmeans\nlabel=litekmeans(U,k,'MaxIter',maxIter,'Replicates',numRep);\n\n\n\n\n", "meta": {"author": "ZJULearning", "repo": "MatlabFunc", "sha": "97504df0f597c1980ab76ddc0c9c5d669043c6c9", "save_path": "github-repos/MATLAB/ZJULearning-MatlabFunc", "path": "github-repos/MATLAB/ZJULearning-MatlabFunc/MatlabFunc-97504df0f597c1980ab76ddc0c9c5d669043c6c9/Clustering/LSC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5982901493180531}} {"text": "function [y1, y2] = vl_nnpdist(x, x0, p, varargin)\n%VL_NNPDIST CNN p-distance from target.\n% VL_NNPDIST(X, X0, P) computes the P distance raised of each feature\n% vector in X to the corresponding feature vector in X0:\n%\n% Y(i,j,1) = (SUM_d (X(i,j,d) - X0(i,j,d))^P)^(1/P)\n%\n% X0 should have the same size as X; the outoput Y has the same\n% height and width as X, but depth equal to 1. Optionally, X0 can\n% be a 1 x 1 x D x N array, in which case the same target feature\n% vector in X0 is compared to all feature vectors in X. In that case,\n% however, the DZDX0 are of size of X.\n%\n% Setting the `noRoot` option to `true` does not take the 1/P power\n% in the formula, computing instead\n%\n% Y(i,j,1) = SUM_d (X(i,j,d) - X0(i,j,d))^P\n%\n% For example, `vl_nnpdist(x, x0, 2, 'noRoot', true)` computes the\n% squared L2 distance.\n%\n% [DZDX, DZDX0] = VL_NNPDISTP(X, X0, P, DZDY) computes the derivative\n% of the block inputs projected onto DZDY. DZDX, DZDX0 and DZDY have the\n% same dimensions as X and Y, respectively.\n%\n% VL_NNPDIST(___, 'OPT', VAL, ...) accepts the following options:\n%\n% `NoRoot`:: `false`\n% If set to true, compute the P-distance to the P-th power.\n%\n% `Epsilon`:: 1e-6\n% When computing derivatives, quantities that are divided in are\n% lower boudned by this value. For example, the L2 distance is\n% not smooth at the origin; this option prevents the\n% derivative from diverging.\n%\n% `Aggregate`:: false\n% Instead of returning one scalar for each spatial location in\n% the inputs, sum all of them into a single scalar.\n%\n% `InstanceWeights``:: `[]`\n% Optionally weight individual instances. This parameter can be\n% eigther a scalar or a weight mask, one for each pixel in the\n% input tensor.\n\n% Copyright (C) 2015 Karel Lenc and Andrea Vedaldi.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\n% -------------------------------------------------------------------------\n% Parse options\n% -------------------------------------------------------------------------\n\nopts.noRoot = false ;\nopts.epsilon = 1e-6 ;\nopts.aggregate = false ;\nopts.instanceWeights = [] ;\nbackMode = numel(varargin) > 0 && ~ischar(varargin{1}) ;\nif backMode\n dzdy = varargin{1} ;\n opts = vl_argparse(opts, varargin(2:end), 'nonrecursive') ;\nelse\n dzdy = [] ;\n opts = vl_argparse(opts, varargin, 'nonrecursive') ;\nend\n\n% -------------------------------------------------------------------------\n% Parse options\n% -------------------------------------------------------------------------\n\nd = bsxfun(@minus, x, x0) ;\n\nif ~isempty(dzdy) && ~isempty(opts.instanceWeights)\n dzdy = bsxfun(@times, opts.instanceWeights, dzdy) ;\nend\n\nif ~opts.noRoot\n if isempty(dzdy)\n if p == 1\n y1 = sum(abs(d),3) ;\n elseif p == 2\n y1 = sqrt(sum(d.*d,3)) ;\n else\n y1 = sum(abs(d).^p,3).^(1/p) ;\n end\n else\n if p == 1\n y1 = bsxfun(@times, dzdy, sign(d)) ;\n elseif p == 2\n y1 = max(sum(d.*d,3), opts.epsilon).^(-0.5) ;\n y1 = bsxfun(@times, bsxfun(@times, dzdy, y1), d) ;\n elseif p < 1\n y1 = sum(abs(d).^p,3).^((1-p)/p) ;\n y1 = bsxfun(@times, bsxfun(@times, dzdy, y1), max(abs(d), opts.epsilon).^(p-1) .* sign(d)) ;\n else\n y1 = max(sum(abs(d).^p,3), opts.epsilon).^((1-p)/p) ;\n y1 = bsxfun(@times, bsxfun(@times, dzdy, y1), abs(d).^(p-1) .* sign(d)) ;\n end\n end\nelse\n if isempty(dzdy)\n if p == 1\n y1 = sum(abs(d),3) ;\n elseif p == 2\n y1 = sum(d.*d,3) ;\n else\n y1 = sum(abs(d).^p,3) ;\n end\n else\n if p == 1\n y1 = bsxfun(@times, dzdy, sign(d)) ;\n elseif p == 2\n y1 = bsxfun(@times, 2 * dzdy, d) ;\n elseif p < 1\n y1 = bsxfun(@times, p * dzdy, max(abs(d), opts.epsilon).^(p-1) .* sign(d)) ;\n else\n y1 = bsxfun(@times, p * dzdy, abs(d).^(p-1) .* sign(d)) ;\n end\n end\nend\n\nif isempty(dzdy)\n if ~isempty(opts.instanceWeights)\n y1 = bsxfun(@times, opts.instanceWeights, y1) ;\n end\n if opts.aggregate\n y1 = sum(sum(y1)) ;\n end\nend\nif ~isempty(dzdy), y2 = -y1; end\n", "meta": {"author": "ybsong00", "repo": "CREST-Release", "sha": "e331e6763e6b683b1696e1d61420e902bfce4ef7", "save_path": "github-repos/MATLAB/ybsong00-CREST-Release", "path": "github-repos/MATLAB/ybsong00-CREST-Release/CREST-Release-e331e6763e6b683b1696e1d61420e902bfce4ef7/matconvnet/matlab/vl_nnpdist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637361282707, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5982901393090266}} {"text": "%PARZENC Optimisation of the Parzen classifier\n% \n% [W,H] = PARZENC(A,H)\n% [W,H] = A*PARZENC([],H)\n% [W,H] = A*PARZENC(H)\n% \n% INPUT\n% A dataset\n% H smoothing parameter (may be scalar, vector of per-class\n% parameters, or matrix with parameters for each class (rows) and\n% dimension (columns))\n%\n% OUTPUT\n% W trained mapping\n% H estimated smoothing (scalar value)\n%\n% DESCRIPTION\n% Computation of the optimum smoothing parameter H for the Parzen \n% classifier between the classes in the dataset A. The leave-one-out \n% Lissack & Fu estimate is used for the classification error E. The \n% final classifier is stored as a mapping in W. It may be converted\n% into a classifier by W*CLASSC. PARZENC cannot be used for density\n% estimation.\n% \n% In case smoothing H is specified, no learning is performed, just the\n% discriminant W is produced for the given smoothing parameters H.\n% Smoothing parameters may be scalar, vector of per-class parameters, or \n% a matrix with individual smoothing for each class (rows) and feature\n% directions (columns)\n%\n% EXAMPLES\n% See PREX_DENSITY for densities and PREX_PARZEN for differences between\n% PARZENC, PARZENDC and PARZENM.\n%\n% REFERENCES\n% T. Lissack and K.S. Fu, Error estimation in pattern recognition via\n% L-distance between posterior density functions, IEEE Trans. Inform. \n% Theory, vol. 22, pp. 34-45, 1976.\n% \n% SEE ALSO (PRTools Guide)\n% DATASETS, MAPPINGS, PARZEN_MAP, PARZENML, PARZENDC, PARZENM, CLASSC, \n% PREX_PARZEN \n \n% Copyright: R.P.W. Duin, r.p.w.duin@37steps.com\n% Faculty EWI, Delft University of Technology\n% P.O. Box 5031, 2600 GA Delft, The Netherlands\n\n% $Id: parzenc.m,v 1.6 2008/07/03 09:11:44 duin Exp $\n\nfunction [W,h] = parzenc(varargin)\n \n\tmapname = 'ParzenC';\n argin = shiftargin(varargin,'scalar');\n argin = setdefaults(argin,[],[]);\n \n if mapping_task(argin,'definition')\n W = define_mapping(argin,'untrained',mapname);\n \n elseif mapping_task(argin,'training')\t\t\t% Train a mapping.\n \n [a,h] = deal(argin{:});\n islabtype(a,'crisp','soft');\n isvaldfile(a,2,2); % at least 2 objects per class, 2 classes\n a = testdatasize(a);\n a = testdatasize(a,'objects');\n\n [m,k,c] = getsize(a);\n nlab = getnlab(a);\n\n if ~isempty(h) % take user setting for smoothing parameter\n\n if size(h,1) == 1, h = repmat(h,c,1); end\n if size(h,2) == 1, h = repmat(h,1,k); end\n if any(size(h) ~= [c,k])\n error('Array with smoothing parameters has wrong size');\n end\n W = prmapping('parzen_map','trained',{a,h},getlablist(a),k,c);\n W = setname(W,'Parzen Classifier');\n return\n\n end\n\n % compute all object distances\n % make diagonal inf to exclude objects own contribution\n D = +distm(a) + diag(inf*ones(1,m));\n\n % find object frequencies\n if islabtype(a,'crisp')\n csize = classsizes(a);\n of = csize(nlab);\n else\n csize = sum(gettargets(a),1);\n end\n\n % find object weights q\n p = getprior(a);\n a = setprior(a,p);\n q = p(nlab)./csize(nlab);\n\n % initialise\n h = max(std(a)); % for sure a too high value\n L = -inf;\n Ln = 0;\n z = 0.1^(1/k); % initial step size\n\n % iterate\n\n iter = 0;\n prwaitbar(100,'parzenc: Optimizing smoothing parameter',m > 100);\n while abs(Ln-L) > 0.001 & z < 1\n\n % In L we store the best performance estimate found so far.\n % Ln is the actual performance (for the actual h)\n % If Ln > L we improve the bound L, and so we rest it.\n\n if Ln > L, L = Ln; end\n iter = iter+1;\n prwaitbar(100,100-100*exp(-iter/10));\n\n r = -0.5/(h^2);\n F = q(ones(1,m),:)'.*exp(D*r); % density contributions\n FS = sum(F)*((m-1)/m); IFS = find(FS>0); % joint density distribution\n if islabtype(a,'crisp');\n G = sum(F .* (nlab(:,ones(1,m)) == nlab(:,ones(1,m))'));\n G = G.*(of-1)./of; % true-class densities\n else\n % here we are for soft labels (stored in targets)\n G = zeros(1,m);\n for j=1:c\n G = G + sum(F .* (a.targets(:,j) * a.targets(:,j)'));\n % to be corrected for bias?\n end\n end\n\n % performance estimate\n en = max(p)*ones(1,m);\n en(IFS) = (G(IFS))./FS(IFS);\n Ln = exp(sum(log(en))/m);\n\n if Ln < L % compute next estimate\n z = sqrt(z); % adjust stepsize up (recall: 0 < z < 1)\n h = h / z; % if we don't improve, increase h (approach h_opt from below)\n else\n h = h * z; % if we improve, decrease h (approach h_opt from above)\n end\n end\n prwaitbar(0);\n W = prmapping('parzen_map','trained',{a,repmat(h,c,k);},getlablist(a),k,c);\n W = setname(W,mapname);\n W = setcost(W,a);\n \n end\n\nreturn\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/prtools/parzenc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213691605411, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5982848466684932}} {"text": "function [dP] = GradJacobiP(r, alpha, beta, N);\n\n% function [dP] = GradJacobiP(r, alpha, beta, N);\n% Purpose: Evaluate the derivative of the Jacobi polynomial of type (alpha,beta)>-1,\n%\t at points r for order N and returns dP[1:length(r))] \n\ndP = zeros(length(r), 1);\nif(N == 0)\n dP(:,:) = 0.0; \nelse\n dP = sqrt(N*(N+alpha+beta+1))*JacobiP(r(:),alpha+1,beta+1, N-1);\nend;\nreturn\n", "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/JSHesthaven&TWarburton/Codes1D/GradJacobiP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5982186121891774}} {"text": "% Hoer's code (P. O. Hoyer. Non-negative Matrix Factorization with sparseness constraints. \n% Journal of Machine Learning Research 5:1457-1469, 2004.) is modified \n\nfunction [W, H, objhistory, objhistory_v] = nmf( V, rdim, showflag, ttt )\n%% INPUT\n% V: data matrix\n% rdim : matrix factorization rank\n% showflag: if it is 1. than it plots the change of reconstruction error\n% for each iteration\n% ttt: maximum number of iterations allowed\n\n%% OUTPUT\n% W: Mixing matrix (V=WH)\n% H: Encoding matrix (V=WH)\n% objhistory: change of total reconstruction error\n% objhistory_v: reconstruction error for each individual sample\n\n\n\n\n% Check that we have non-negative data\nif min(V(:))<0, error('Negative values in data!'); end\n \n% Dimensions\nvdim = size(V,1);\nsamples = size(V,2);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% initialization %%%\nfname2=['initials/Initials' num2str(vdim) 'x' num2str(rdim) '.txt'];\nfid=fopen(fname2,'r');\nif (fid==-1)\n ssbinitial(vdim,rdim);\nend\nfidW2 = fopen(fname2,'r');\nW = fscanf(fidW2,'%f', [vdim inf]);\nfclose(fidW2);\n\nclear fname2\n\nfname2=['initials/Initials' num2str(rdim) 'x' num2str(samples) '.txt'];\nfid=fopen(fname2,'r');\nif (fid==-1)\n ssbinitial(rdim,samples);\nend\nfidW2 = fopen(fname2,'r');\nH = fscanf(fidW2,'%f', [rdim inf]);\nfclose(fidW2);\n\nclear fname2\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif (showflag==1)\n objhistory = ((sum(sum((V-W*H).^2))))/(vdim*samples);\n figure(2); clf;\n drawnow;\nend\n\n\n% Start iteration\niter = 0;\nwhile 1,\n \n if (iter==ttt)\n break\n end\n iter = iter+1; \n % Compute new W and H (Lee and Seung; NIPS*2000)\n H = H.*(W'*V)./(W'*W*H + 1e-9);\n W = W.*(V*H')./(W*H*H' + 1e-9);\n \n% norms = sqrt(sum(W.^2));\n% H = H.*(norms'*ones(1,samples));\n% W = W./(ones(vdim,1)*norms);\n\n newobj = ((sum(sum((V-W*H).^2))))/(vdim*samples);\n newobj_v = ((sum(sum((V(:,end)-W*H(:,end)).^2))))/(vdim);\n if iter==1\n objhistory = [newobj];\n objhistory_v = [newobj_v];\n else\n objhistory = [objhistory newobj];\n objhistory_v = [objhistory_v newobj_v];\n end\n \n if(showflag==1)\n if (iter>1)\n plot(objhistory(2:end)); \n end\n drawnow;\n end \nend", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/nmf/iNMF/nmf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.5981106457499131}} {"text": "function [ n_data, n, x, fx ] = laguerre_polynomial_values ( n_data )\n\n%*****************************************************************************80\n%\n%% LAGUERRE_POLYNOMIAL_VALUES returns some values of the Laguerre polynomial.\n%\n% Discussion:\n%\n% In Mathematica, the function can be evaluated by:\n%\n% LaguerreL[n,x]\n%\n% Differential equation:\n%\n% X * Y'' + (1-X) * Y' + N * Y = 0\n%\n% First terms:\n%\n% 1\n% -X + 1\n% ( X^2 - 4 X + 2 ) / 2\n% ( -X^3 + 9 X^2 - 18 X + 6 ) / 6\n% ( X^4 - 16 X^3 + 72 X^2 - 96 X + 24 ) / 24\n% ( -X^5 + 25 X^4 - 200 X^3 + 600 X^2 - 600 X + 120 ) / 120\n% ( X^6 - 36 X^5 + 450 X^4 - 2400 X^3 + 5400 X^2 - 4320 X + 720 ) / 720\n% ( -X^7 + 49 X^6 - 882 X^5 + 7350 X^4 - 29400 X^3 + 52920 X^2 - 35280 X + 5040 ) / 5040\n%\n% Recursion:\n%\n% L(0)(X) = 1,\n% L(1)(X) = 1-X,\n% N * L(N)(X) = (2*N-1-X) * L(N-1)(X) - (N-1) * L(N-2)(X)\n%\n% Orthogonality:\n%\n% Integral ( 0 <= X < oo ) exp ( - X ) * L(N)(X) * L(M)(X) dX\n% = 0 if N /= M\n% = 1 if N == M\n%\n% Special values:\n%\n% L(N)(0) = 1.\n%\n% Relations:\n%\n% L(N)(X) = (-1)^N / N! * exp ( x ) * (d/dx)^n ( exp ( - x ) * X^n ) \n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 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 of the polynomial.\n%\n% Output, real X, the point where the polynomial is evaluated.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 17;\n\n fx_vec = [ ...\n 0.1000000000000000E+01, ...\n 0.0000000000000000E+00, ...\n -0.5000000000000000E+00, ...\n -0.6666666666666667E+00, ...\n -0.6250000000000000E+00, ...\n -0.4666666666666667E+00, ...\n -0.2569444444444444E+00, ...\n -0.4047619047619048E-01, ...\n 0.1539930555555556E+00, ...\n 0.3097442680776014E+00, ...\n 0.4189459325396825E+00, ...\n 0.4801341790925124E+00, ...\n 0.4962122235082305E+00, ...\n -0.4455729166666667E+00, ...\n 0.8500000000000000E+00, ...\n -0.3166666666666667E+01, ...\n 0.3433333333333333E+02 ];\n\n n_vec = [ ...\n 0, 1, 2, ...\n 3, 4, 5, ...\n 6, 7, 8, ...\n 9, 10, 11, ...\n 12, 5, 5, ...\n 5, 5 ];\n\n x_vec = [ ...\n 1.0E+00, ...\n 1.0E+00, ...\n 1.0E+00, ...\n 1.0E+00, ...\n 1.0E+00, ...\n 1.0E+00, ...\n 1.0E+00, ...\n 1.0E+00, ...\n 1.0E+00, ...\n 1.0E+00, ...\n 1.0E+00, ...\n 1.0E+00, ...\n 1.0E+00, ...\n 0.5E+00, ...\n 3.0E+00, ...\n 5.0E+00, ...\n 1.0E+01 ];\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 x = 0.0;\n fx = 0.0;\n else\n n = n_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/laguerre_polynomial_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.5981106389074764}} {"text": "function X = slpcarecon(S, Y)\n%SLPCARECON Reconstructs the samples in original space\n%\n% $ Syntax $\n% - Xr = slpcarecon(S, Y)\n%\n% $ Arguments $\n% - S: the PCA model struct\n% - Y: the principal component features\n% - Xr: the reconstructed samples\n%\n% $ Description $\n% - Xr = slpcarecon(S, Y) reconstructs the original samples approximately\n% using the principal components Y. If the dimension of Y is less than\n% the subspace dimension, the leading space dimensions will be used.\n%\n% $ History $\n% - Created by Dahua Lin, on Aug 17, 2006\n% - Modified by Dahua Lin, on Sep 10, 2006\n% - replace sladd by sladdvec to increase efficiency\n%\n\n%% parse and verify input\n\nif ~isstruct(S)\n error('sltoolbox:invalidarg', ...\n 'S should be a PCA model struct');\nend\n\nif ~isnumeric(Y) || ndims(Y) ~= 2\n error('sltoolbox:invalidarg', ...\n 'The features Y should be a 2D numeric matrix');\nend\n\ndy = size(Y, 1);\nif dy > S.feadim\n error('sltoolbox:sizmismatch', ...\n 'The feature dimension of Y exceeds the subspace dimension preserved in model');\nend\n\n%% reconstruct\n\nif dy == S.feadim\n X = S.P * Y;\nelse\n X = S.P(:, 1:dy) * Y;\nend\n\nX = sladdvec(X, S.vmean, 1);\n\n\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/slpcarecon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.7122321720225279, "lm_q1q2_score": 0.5980855477162942}} {"text": "function stroud_test2075 ( )\n\n%*****************************************************************************80\n%\n%% STROUD_TEST2075 tests the rules for EPN with GLG weight on monomials.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 January 2010\n%\n% Author:\n%\n% John Burkardt\n%\n test_num = 5;\n\n alpha_test = [ - 0.5, 0.0, 0.5, 1.0, 2.0 ];\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'STROUD_TEST2075\\n' );\n fprintf ( 1, ' Demonstrate the use of quadrature rules for the region\\n' );\n fprintf ( 1, ' EPN_GLG, that is, the positive half space [0,+oo)^N, with the\\n' );\n fprintf ( 1, ' weight W(ALPHA;X) = product ( 1 <= I <= N ) X(I)^ALPHA exp ( -X(I) )\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' We use the formulas to integrate various monomials of\\n' );\n fprintf ( 1, ' the form X(1)^E(1) * X(2)^E(2) * ... X(N)^E(N)\\n' );\n fprintf ( 1, ' and compare to the exact integral.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The precision of each formula is known, and we only use\\n' );\n fprintf ( 1, ' a formula if its precision indicates it should be able to\\n' );\n fprintf ( 1, ' produce an exact result.\\n' );\n\n for n = 1 : 6\n\n expon = zeros ( n, 1 );\n for test = 1 : test_num\n alpha = alpha_test(test);\n epn_glg_test ( n, expon, alpha );\n end\n\n expon = zeros ( n, 1 );\n expon(n) = 1;\n for test = 1 : test_num\n alpha = alpha_test(test);\n epn_glg_test ( n, expon, alpha );\n end\n\n if ( 2 <= n )\n expon = zeros ( n, 1 );\n expon(1) = 1;\n expon(2) = 1;\n for test = 1 : test_num\n alpha = alpha_test(test);\n epn_glg_test ( n, expon, alpha );\n end\n end\n\n expon = zeros ( n, 1 );\n expon(1) = 2;\n for test = 1 : test_num\n alpha = alpha_test(test);\n epn_glg_test ( n, expon, alpha );\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/stroud/stroud_test2075.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.5979115106318221}} {"text": "function b = ismonom(a)\n% function B = ismonom(A)\n%\n% DESCRIPTION\n% Returns true for a monomial or a vector or matrix of monomials.\n%\n% INPUTS\n% A: polynomial\n%\n% OUTPUTS\n% B: 1 if A is a monomial or a vector or matrix of monomials. Returns\n% 0 otherwise.\n%\n% SYNTAX\n% B = ismonom(A);\n\n% 1/29/2008: PJS Initial Coding\n\nif isa(a,'double') && a==1\n b = true;\n return;\nelseif ~isa(a,'polynomial')\n b = false;\n return;\nend\n\n% acoef will be Nterms-by-(Nrows*Ncols)\nacoef = a.coefficient;\n\nif all(nonzeros(acoef)==1) && all(sum(acoef,1)==1)\n b = true;\nelse\n b = false;\nend\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/SOSTOOLS.300/SOSTOOLS.300/multipoly/ismonom.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867585368344, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.5979114855553294}} {"text": "function example4 ( )\n\n%*****************************************************************************80\n%\n%% EXAMPLE4 uses BVP4C to solve the EXAMPLE4 problem.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 September 2013\n%\n% Author:\n%\n% Original MATLAB version by Shampine, Kierzenka, Reichelt.\n% This version by John Burkardt.\n%\n% Reference:\n%\n% Lawrence Shampine, Jacek Kierzenka, Mark Reichelt,\n% Solving boundary value problems for ordinary differential equations\n% in MATLAB with bvp4c.\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'EXAMPLE4:\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, ' Use BVP4C to solve a boundary value problem with\\n' );\n fprintf ( 1, ' a periodic solution of unknown period P.\\n' );\n fprintf ( 1, ' We solve this on [0,1], with P an additional unknown.\\n' );\n fprintf ( 1, ' y'' = 3 ( y + z - y^3/3 - 1.3\\n' );\n fprintf ( 1, ' z'' = - ( y - 0.7 + 0.8 * z ) / 3\\n' );\n fprintf ( 1, ' y(0) = y(P), z(0) = z(P)\\n' );\n fprintf ( 1, ' Use initial guess y = sin ( 2 pi x ), z = cos ( 2 pi x ).\\n' );\n%\n% Set SOLINIT, the structure defining the initial guess.\n%\n x_init = linspace ( 0.0, 1.0, 5 );\n p_init = 2.0 * pi;\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Initial estimate for P is %g\\n', p_init );\n solinit = bvpinit ( x_init, @example4_init, p_init );\n%\n% Have BVP4C solve the problem.\n%\n sol = bvp4c ( @example4_ode, @example4_bc, solinit );\n%\n% Retrieve the updated value of the period.\n%\n p = sol.parameters;\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Period P = %g\\n', p );\n%\n% Use DEVAL to evaluate the solution.\n%\n x = linspace ( 0.0, 1.0, 101 );\n px = p * x;\n sol = deval ( sol, x );\n%\n% Evaluate the initial guess on the initial grid [0,1].\n%\n y_init = example4_init ( x );\n%\n% Display a plot of Y versus initial guess.\n%\n plot ( px, sol(1,:), 'r-', ...\n px, y_init(1,:), 'g-', 'Linewidth', 2 );\n xlabel ( '<--- X --->', 'Fontsize', 16 );\n ylabel ( '<--- Y --->', 'Fontsize', 16 );\n title ( 'EXAMPLE4: Y(red) versus initial guess (green)', 'Fontsize', 16 )\n grid on\n filename = 'example4.png';\n print ( '-dpng', filename );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Saving plot file as \"%s\"\\n', filename );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'EXAMPLE4:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction y = example4_init ( x )\n\n%*****************************************************************************80\n%\n%% EXAMPLE4_INIT evaluates the initial guess for the solution.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 September 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the point at which the ODE is to be evaluated.\n%\n% Output, real Y(M,1), the value of the initial guess.\n%\n y(1,:) = sin ( 2.0 * pi * x );\n y(2,:) = cos ( 2.0 * pi * x );\n\n return\nend\nfunction dydx = example4_ode ( x, y, p )\n\n%*****************************************************************************80\n%\n%% EXAMPLE4_ODE evaluates the right hand side of the ODE.\n%\n% Discussion:\n%\n% We assume that the differential equation has been rewritten as a\n% system of first order equations of the form\n%\n% dydx = f(x,y)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 September 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the point at which the ODE is to be evaluated.\n%\n% Input, real Y(M), the value of the solution at X.\n%\n% Input, real P, the estimate for the period.\n%\n% Output, real DYDX(M), the value of the right hand side given X and Y.\n%\n dydx(1,1) = p * 3.0 * ( y(1) + y(2) - ( y(1) )^3 / 3.0 - 1.3 );\n dydx(2,1) = - p * ( y(1) - 0.7 + 0.8 * y(2) ) / 3.0;\n\n return\nend\nfunction bc = example4_bc ( ya, yb, p )\n\n%*****************************************************************************80\n%\n%% EXAMPLE4_BC evaluates the boundary conditions.\n%\n% Discussion:\n%\n% The third boundary condition applies the phase condition, and eliminates\n% the spurious solution y'(x) = 0, and solutions with p = 0.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 September 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real YA(M), YB(M), the solution value at the left and right endpoints.\n%\n% Input, real P, the estimate for the period.\n%\n% Output, real BC(M), the value of the boundary conditions.\n%\n bc(1,1) = ya(1) - yb(1);\n bc(2,1) = ya(2) - yb(2);\n bc(3,1) = p * ( ya(1) - 0.7 + 0.8 * ya(2) ) / 3.0 - 1.0;\n\n return\nend\nfunction timestamp ( )\n\n%*****************************************************************************80\n%\n%% TIMESTAMP prints the current YMDHMS date as a timestamp.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n t = now;\n c = datevec ( t );\n s = datestr ( c, 0 );\n fprintf ( 1, '%s\\n', s );\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/bvp4c/example4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.5978571566346172}} {"text": "function [ x, seed ] = r8vec_uniform_01 ( n, seed )\n\n%*****************************************************************************80\n%\n%% R8VEC_UNIFORM_01 returns a unit pseudorandom R8VEC.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 21 September 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Paul Bratley, Bennett Fox, Linus Schrage,\n% A Guide to Simulation,\n% Second Edition,\n% Springer, 1987,\n% ISBN: 0387964673,\n% LC: QA76.9.C65.B73.\n%\n% Bennett Fox,\n% Algorithm 647:\n% Implementation and Relative Efficiency of Quasirandom\n% Sequence Generators,\n% ACM Transactions on Mathematical Software,\n% Volume 12, Number 4, December 1986, pages 362-376.\n%\n% Pierre L'Ecuyer,\n% Random Number Generation,\n% in Handbook of Simulation,\n% edited by Jerry Banks,\n% Wiley, 1998,\n% ISBN: 0471134031,\n% LC: T57.62.H37.\n%\n% Peter Lewis, Allen Goodman, James Miller,\n% A Pseudo-Random Number Generator for the System/360,\n% IBM Systems Journal,\n% Volume 8, Number 2, 1969, pages 136-143.\n%\n% Parameters:\n%\n% Input, integer N, the number of entries in the vector.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, real X(N,1), the vector of pseudorandom values.\n%\n% Output, integer SEED, an updated seed for the random number generator.\n%\n x = zeros ( n, 1 );\n\n i4_huge = 2147483647;\n\n if ( seed == 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8VEC_UNIFORM_01 - Fatal error!\\n' );\n fprintf ( 1, ' Input SEED = 0!\\n' );\n error ( 'R8VEC_UNIFORM_01 - Fatal error!' );\n end\n\n r = zeros ( n, 1 );\n\n for i = 1 : n\n\n k = floor ( seed / 127773 );\n\n seed = 16807 * ( seed - k * 127773 ) - k * 2836;\n\n if ( seed < 0 )\n seed = seed + i4_huge;\n end\n\n x(i) = seed * 4.656612875E-10;\n\n end\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/normal/r8vec_uniform_01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.5978571526670677}} {"text": "function [ x, seed ] = r4vec_uniform_ab ( n, a, b, seed )\n\n%*****************************************************************************80\n%\n%% R4VEC_UNIFORM_AB returns a scaled pseudorandom R4VEC.\n%\n% Discussion:\n%\n% Each dimension ranges from A to B.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 September 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Paul Bratley, Bennett Fox, Linus Schrage,\n% A Guide to Simulation,\n% Springer Verlag, pages 201-202, 1983.\n%\n% Bennett Fox,\n% Algorithm 647:\n% Implementation and Relative Efficiency of Quasirandom\n% Sequence Generators,\n% ACM Transactions on Mathematical Software,\n% Volume 12, Number 4, pages 362-376, 1986.\n%\n% Peter Lewis, Allen Goodman, James Miller,\n% A Pseudo-Random Number Generator for the System/360,\n% IBM Systems Journal,\n% Volume 8, pages 136-143, 1969.\n%\n% Parameters:\n%\n% Input, integer N, the number of entries in the vector.\n%\n% Input, real A, B, the range of the pseudorandom values.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, real X(N), the vector of pseudorandom values.\n%\n% Output, integer SEED, an updated seed for the random number generator.\n%\n x = zeros ( n, 1 );\n\n if ( seed == 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4VEC_UNIFORM_AB - Fatal error!\\n' );\n fprintf ( 1, ' Input SEED = 0!\\n' );\n error ( 'R4VEC_UNIFORM_AB - Fatal error!' );\n end\n\n for i = 1 : n\n\n k = floor ( seed / 127773 );\n\n seed = 16807 * ( seed - k * 127773 ) - k * 2836;\n\n if ( seed < 0 )\n seed = seed + 2147483647;\n end\n\n x(i) = a + ( b - a ) * seed * 4.656612875E-10;\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/uniform/r4vec_uniform_ab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.5978571445855144}} {"text": "function niederreiter2_test01 ( )\n\n%*****************************************************************************80\n%\n%% NIEDERREITER2_TEST01 tests SETFLD2.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 November 2008\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'NIEDERREITER2_TEST01\\n' );\n fprintf ( 1, ' SETFLD2 returns the addition, multiplication, and\\n' );\n fprintf ( 1, ' subtraction tables for base 2.\\n' );\n\n [ add, mul, sub ] = setfld2 ( 0 );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Addition table:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, '+ 0 1\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, '0 %d %d\\n', add(1,1), add(1,2) );\n fprintf ( 1, '1 %d %d\\n', add(2,1), add(2,2) );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Multiplication table:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, '* 0 1\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, '0 %d %d\\n', mul(1,1), mul(1,2) );\n fprintf ( 1, '1 %d %d\\n', mul(2,1), mul(2,2) );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Subtraction table:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, '- 0 1\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, '0 %d %d\\n', sub(1,1), sub(1,2) );\n fprintf ( 1, '1 %d %d\\n', sub(2,1), sub(2,2) );\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/niederreiter2/niederreiter2_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.5978059572467667}} {"text": "function [c, s, active_set] = oasisAR1(y, g, lam, smin, active_set)\n%% Infer the most likely discretized spike train underlying an AR(1) fluorescence trace\n% Solves the sparse non-negative deconvolution problem\n% min 1/2|c-y|^2 + lam |s|_1 subject to s_t = c_t-g c_{t-1} >=s_min or =0\n\n%% inputs:\n% y: T*1 vector, One dimensional array containing the fluorescence intensities\n%withone entry per time-bin.\n% OR %%\n% len_active_set*4 matrix, active set\n\n% g: scalar, Parameter of the AR(1) process that models the fluorescence ...\n%impulse response.\n% lam: scalar, sparsity penalty parameter lambda.\n% smin: scalar, optional, default 0\n%miniumal non-zero activity within each bin (minimal 'spike size').\n% active_set: npool x 4 matrix, warm stared active sets\n\n%% outputs\n% c: T*1 vector, the inferred denoised fluorescence signal at each time-bin.\n% s: T*1 vector, discetized deconvolved neural activity (spikes)\n% active_set: npool x 4 matrix, active sets\n\n%% Authors: Pengcheng Zhou, Carnegie Mellon University, 2016\n% ported from the Python implementation from Johannes Friedrich\n\n%% References\n% Friedrich J et.al., NIPS 2016, Fast Active Set Method for Online Spike Inference from Calcium Imaging\n\n%% initialization\ny = reshape(y, [], 1);\nif isempty(y)\n T = sum(active_set(:,4)); \nelse\nT = length(y);\nend\nif ~exist('g', 'var') || isempty(g)\n g = estimate_time_constant(y);\nelseif length(g)>1\n c = zeros(T,1); \n s = zeros(T,1); \n active_set = []; \n return; \nend\nif ~exist('lam', 'var') || isempty(lam); lam = 0; end\nif ~exist('smin', 'var') || isempty(smin); smin = 0; end\nif ~exist('active_set', 'var') || isempty(active_set)\n len_active_set = T;\n active_set = [y-lam*(1-g),ones(T,1),(1:T)',ones(T,1),(1:T)'-1, (1:T)'+1]; % each row is one pool: (vi, wi, t, l)\n active_set(end, :) = [y(end)-lam,1,T,1,T-1,nan] ;\n active_set(1,5) = nan;\nelse\n len_active_set = size(active_set,1);\n active_set(:,5) = [nan; (1:len_active_set-1)']; \n active_set(:,6) = [(2:len_active_set)';nan]; \nend\nidx = true(len_active_set,1);\n\n%% run OASIS\nii = 1;\nii_next = active_set(ii,6);\nwhile ~isnan(ii_next)\n % find the active set\n while (~isnan(ii_next)) && (active_set(ii_next,1)/active_set(ii_next,2)...\n >=active_set(ii,1)/active_set(ii,2)*g^(active_set(ii,4))+smin)\n active_set(ii_next,5) = ii;\n ii = ii_next; \n ii_next = active_set(ii,6);\n end\n \n if isnan(ii_next); break; end\n \n %% merge pools\n active_set(ii,1) = active_set(ii,1) + active_set(ii_next,1)* (g^(active_set(ii,4)));\n active_set(ii,2) = active_set(ii,2) + active_set(ii_next,2)*(g^(2*active_set(ii,4)));\n active_set(ii,4) = active_set(ii,4) + active_set(ii_next,4);\n active_set(ii,6) = active_set(ii_next,6);\n idx(ii_next) = false;\n ii_next = active_set(ii,6);\n ii_prev = active_set(ii, 5);\n\n %% backtrack until violations fixed\n while (~isnan(ii_prev)) && (active_set(ii,1)/active_set(ii,2)<...\n max(0, active_set(ii_prev,1)/active_set(ii_prev,2)*g^(active_set(ii_prev,4)))+smin)\n ii_next = ii;\n ii = ii_prev;\n active_set(ii,1) = active_set(ii,1) + active_set(ii_next,1)* (g^(active_set(ii,4)));\n active_set(ii,2) = active_set(ii,2) + active_set(ii_next,2)*(g^(2*active_set(ii,4)));\n active_set(ii,4) = active_set(ii,4) + active_set(ii_next,4);\n active_set(ii,6) = active_set(ii_next,6);\n idx(ii_next) = false;\n \n ii_prev = active_set(ii, 5);\n ii_next = active_set(ii,6);\n end\nend\nactive_set(~idx, :) = [];\nlen_active_set = size(active_set,1);\n\n%% construct solution for all t\nc = zeros(T, 1);\ns = c;\nfor ii=1:len_active_set\n t0 = active_set(ii,3);\n tau = active_set(ii, 4);\n c(t0:(t0+tau-1)) = max(0,active_set(ii,1)/active_set(ii,2)) * (g.^(0:(tau-1)));\nend\n\ns(active_set(2:end,3)) = c(active_set(2:end,3)) - g*c(active_set(2:end,3)-1);\n", "meta": {"author": "zhoupc", "repo": "CNMF_E", "sha": "ccca6f9db7d1d15b7dd1266eb9b29e417f92e79f", "save_path": "github-repos/MATLAB/zhoupc-CNMF_E", "path": "github-repos/MATLAB/zhoupc-CNMF_E/CNMF_E-ccca6f9db7d1d15b7dd1266eb9b29e417f92e79f/OASIS_matlab/packages/oasis/oasisAR1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5977891962095994}} {"text": "function out = ij2xy(in, maxy)\n% out = xy2ij(in, maxy)\n%\n% Converts shapes from \"image\" coordinates to cartesian coordinates.\n% In cartesian coordinates, the origin is on the lower-left corner of\n% the image and y moves vertically while x moves horizontally.\n% Image coordinates follow a matrix notation where the origin is in\n% the upper left corner and the first coordinate 'i' moves vertically\n% (in the opposite direction of y), while the second 'j' coordinate\n% moves horizontally in the same direction as x.\n% \n% PARAMETERS\n%\n% in A Nx2xS matrix containing S shapes and N landmarks,\n% in images coordinates: [i j]\n% maxy Number of rows of the image matrix, or height of the displayed image,\n% in pixels.\n%\n% RETURNS\n% \n% out A Nx2xS matrix containing S shapes and N landmarks,\n% in cartesian coordinates: [x y]\n%\n% Author: Luca Vezzaro (elvezzaro@gmail.com)\n\n\tout(:,1,:) = in(:,2,:);\n\tout(:,2,:) = repmat(maxy, [size(in, 1) 1 size(in,3)]) - in(:,1,:);", "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/32704-icaam-inverse-compositional-active-appearance-models/icaam/ij2xy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.5977249771790457}} {"text": "function [U,Out] = RecPF(m,n,aTV,aL1,picks,B,PsiT,Psi,opts,varargin)\n% [U,Out] = RecPF(m,n,aTV,aL1,picks,B,PsiT,Psi,opts,varargin)\n%\n% RecPF solves the TVL1-L2 model:\n%\n% min aTV*TV(u) + aL1*|PsiT*U|_1 + 0.5|Fp*U - B|_2^2\n%\n% Inputs:\n%\n% m, n -- size of image\n% aTV, aL1 -- regularization parameters in the model\n% picks -- sample positions in Fourier domain\n% B -- measurment vector\n% PsiT -- sparsifying basis, PsiT*U is the sparse representation of U\n% Psi -- inverse of PsiT, Psi*x = U reconstructs the image\n% opts --- contains parameters for algorithm\n% * opts.mit_inn: maxium inner iteration number for each beta {default 30}\n% * opts.mit_out: maxium outer iteration number {default 10} \n% * opts.tol_inn: inner iteration error tolerance {1.e-3}\n% (this option is effective only when \"opts.stc = 2\", see below)\n% * opts.tol_rel_inn: tolerance of relative change in an inner iteration {5.e-2}\n% * opts.tol_rel_out: tolerance of relative change in an outer iteration {1.e-2}\n% (the above two options are effective only when \"opts.stc = 1\", see below)\n% * opts.beta0: initial penalty parameter {2^5}\n% * opts.beta_max: final penalty parameter {2^15}\n% * opts.beta_rate: increase rate of beta\n% * opts.idisp: 0 or nonzero, display inner iteration info or not\n% * opts.recordf: 0 or 1, keep (or not) history of function values, TV and fidelity;\n% * opts.U0: starting poing {default \"a least squares solution\"} \n% * opts.wbarflag: 1 (on) or 0 (off), controls wait bar.\n% * opts.stc: 1 (stopping criterion based on Relative Change) \n% or 2 (stopping criterion based on optimality conditions) {default 1}\n% * opts.TVtype: 1 or 2, corresponding to anisotropic/isotropic TV {default 2}\n% varargin{1} -- a m x n matrix contains local weights of TV. Specifically, the local weigthed \n% TV is discretized as:\n% TV(u) = sum_i w_i ||D_i u||. \n% If all w_i == 1, then it is just the isotropic discritization of normal TV. \n% We require all w_i > 0.\n% varargin{2} -- true image (used to compute relative errors when it is present)\n%\n% Outputs:\n% U --- reconsctructed image\n% Out --- a structrue contains\n% * Out.iter: total iteration number\n% * Out.Inner: inner iteration numbers for each beta\n% * Out.ftrue: function values at each iteration \n% * Out.Fvalvscpu: function values decrease with respect to CPU time \n% * Out.TVhist: total variation changes with iteration \n% * Out.FIDhist: fidelity history\n% {the above four subfields are present only when opts.recordf = 1}\n% * Out.ITvsERR: relative error vs. iteration number \n% * Out.CPUvsERR: CPU time vs. relative error \n% {the above two subfields are present only when the original image is present}\n\n%\n% Yin Zhang, 11-10-2007\n% CAAM, Rice University, Copyright (2007)\n%\n% Junfeng Yang, last modified on Feb. 2, 2009\n%\n\nglobal Ux Uy FU PsiTU\nglobal Wx Wy\nglobal Z PsiZ\nglobal beta\nglobal remain\n\nif aTV == 0 && aL1 == 0; error('No regularization' ); end\nif aTV < 0 || aL1 < 0; error('Regularization < 0'); end\nif ~exist('opts','var'); opts = []; end\n\n[mit_inn,mit_out,tol_inn,tol_rel_inn,tol_rel_out,beta0,beta_max, ...\n beta_rate,TVtype,idisp,recordf,U0,wbarflag,stc] = setopts(opts);\n\n[Nomin1,Denom1,Denom2] = getC(picks,B,aTV,m,n);\n\nremain = setdiff(1:m*n,picks);\nif isempty(U0); U = zeros(m,n); else U = U0; clear U0; end\n\nif ~isempty(varargin)\n Weights = varargin{1};\n [mm,nn] = size(Weights);\n if mm~=m || nn~= n\n Weights = ones(m,n);\n elseif find(Weights < 0,1)\n error('negative weights are not allowed!');\n end\nelse\n Weights = ones(m,n);\nend\nif length(varargin) == 2\n I = varargin{2};\n nrmI = norm(I(:)); rer = norm(U(:)-I(:))/nrmI;\n RER = zeros(500,2); RER(1,:) = [0,rer];\n CPUvsRER = zeros(500,2); CPUvsRER(1,:) = [0,rer];\nend\n\nif aL1 > 0; PsiTU = PsiT(U); end\n\nif aTV > 0\n Ux = [diff(U,1,2), U(:,1) - U(:,n)];\n Uy = [diff(U,1,1); U(1,:) - U(m,:)];\nend\n\nif recordf\n fval_true = funcval(U,aTV,aL1,B,picks);\n FVAL = zeros(500,2);\n FVAL(1,:) = [0,fval_true];\n Fvalvscpu = zeros(500,2);\n Fvalvscpu(1,:) = [0,fval_true];\n TVhist = zeros(500,1);\n FIDhist = zeros(500,1);\nend\n\n% initialization \nInn = zeros(100,1);\nbeta = beta0;\ntotalIter = 0;\nOutiter = 0;\nstopc = 0;\nt0 = cputime;\n\nif wbarflag == 1\n wbar = waitbar(0, 'RecPF is running, please wait ...');\nend\n\n%% Main loop\nwhile ~stopc\n Outiter = Outiter + 1;\n if stc == 1; Uo = U; end\n \n Denom = Denom1;\n if aTV > 0; Denom = Denom + (aTV*beta)*Denom2; end\n if aL1 > 0; Denom = Denom + aL1*beta; end\n\n stopci = 0; Inniter = 0; \n while ~stopci\n\n % ================================\n % Begin Alternating Minimization\n % ----------------\n % W-subprolem\n % ----------------\n if aTV > 0;\n switch TVtype\n case 1; % anisotropic TV\n Wx = sign(Ux).* max(abs(Ux)-Weights./beta,0);\n Wy = sign(Uy).* max(abs(Uy)-Weights./beta,0);\n case 2; % isotropic TV\n V = sqrt(Ux.^2 + Uy.^2);\n S = max(V - Weights./beta, 0);\n S = S ./ max(V,eps);\n Wx = S.*Ux; Wy = S.*Uy;\n clear V S\n otherwise; error('TVtype must be 1 or 2');\n end\n end\n\n % ----------------\n % Z-subprolem\n % ----------------\n if aL1 > 0;\n Z = sign(PsiTU).*max(abs(PsiTU)-1/beta,0);\n PsiZ = Psi(Z);\n end\n\n % ----------------\n % U-subprolem\n % ----------------\n if stc == 1; Ui = U; end\n rhs = 0;\n if aTV > 0\n rhs = [Wx(:,end) - Wx(:, 1), -diff(Wx,1,2)];\n rhs = rhs + [Wy(end,:) - Wy(1, :); -diff(Wy,1,1)];\n rhs = (aTV*beta)*rhs;\n end\n if aL1 > 0\n rhs = rhs + (aL1*beta)*PsiZ;\n end\n\n Nomin = Nomin1 + fft2(rhs);\n\n FU = Nomin./Denom;\n U = real(ifft2(FU));\n Inniter = Inniter + 1;\n totalIter = totalIter + 1;\n %\n % End Alternating Minimization\n % ================================\n\n % -----------------------------------------\n % check if inner stopping criterion is met\n %\n if stc == 1\n if aTV > 0\n Ux = [diff(U,1,2), U(:,1) - U(:,n)];\n Uy = [diff(U,1,1); U(1,:) - U(m,:)];\n end\n if aL1 > 0; PsiTU = PsiT(U); end\n chg_inn = norm(Ui(:) - U(:))/norm(U(:));\n stopci = ((chg_inn < tol_rel_inn) || (Inniter >= mit_inn));\n elseif stc == 2\n [res_wn,res_wz,wzr,res_Zn,res_Zz,Zzr,res_u] = checkopt(U,aTV,aL1,PsiT,picks,B,0,Weights);\n res = [res_wn,res_wz,res_Zn,res_Zz,res_u];\n stopci = (max(res) < tol_inn || (Inniter >= mit_inn));\n else\n error('please specify a stopping criterion.');\n end \n \n if recordf && totalIter < 500\n [fval_true,tvu,fidu] = funcval(U,aTV,aL1,B,picks);\n TVhist(totalIter) = tvu;\n FIDhist(totalIter) = fidu;\n FVAL(totalIter+1,:) = [totalIter,fval_true];\n Fvalvscpu(totalIter+1,:) = [cputime - t0, fval_true];\n end\n if exist('I','var') && totalIter < 500\n rer = norm(U(:)-I(:))/nrmI;\n RER(totalIter+1,:) = [totalIter,rer];\n CPUvsRER(totalIter+1,:) = [cputime - t0, rer];\n end\n if idisp && stc == 2\n fprintf('Iter: %d, res_ wn: %4.1e, wz: %4.1e, Zn: %4.1e, Zz: %4.1e, u: %4.1e, wzr %2.0f%%, Zzr %2.0f%%\\n', ...\n totalIter, res_wn,res_wz,res_Zn,res_Zz,res_u,100*wzr,100*Zzr);\n elseif idisp && stc == 1\n fprintf('Iter: %d, chg_inn %4.2f\\n',totalIter,chg_inn);\n end\n\n end % inner\n Inn(Outiter) = Inniter;\n\n % ------------------------------------------\n % check if outer stopping criterion is met\n %\n beta = beta_rate*beta;\n if stc == 1\n chg_out = norm(U(:)-Uo(:))/norm(U(:));\n stopc = ((chg_out < tol_rel_out) || (Outiter >= mit_out));\n elseif stc == 2\n stopc = ((beta > beta_max) || (Outiter >= mit_out));\n else\n error('please specify a stopping criterion.');\n end\n if wbarflag == 1\n waitbar(log2(beta)/(log2(beta_max)+1), wbar)\n end\n \nend % outer\nOut.iter = totalIter;\nOut.Inner = Inn(1:Outiter);\nif wbarflag == 1\n close(wbar);\nend\nif recordf\n Out.ftrue = FVAL(1:totalIter+1,:);\n Out.Fvalvscpu = Fvalvscpu(1:totalIter+1,:);\n Out.TVhist = TVhist(1:totalIter);\n Out.FIDhist = FIDhist(1:totalIter);\nend\nif exist('I','var')\n Out.ITvsRER = RER(1:totalIter+1,:);\n Out.CPUvsRER = CPUvsRER(1:totalIter+1,:);\nend\n\n%% ----------------- SUBFUNCTION ---------------------------\nfunction [res_wn,res_wz,wzr,res_Zn,res_Zz,Zzr,res_u] = ...\n checkopt(U,aTV,aL1,PsiT,picks,f,flag,Weights)\n%\n% This function checks the optimality of\n% ( beta )\n% min aTV * sum_i (||(W_i)||_2 + ---- ||D_iu - W_i||^2)\n% ( 2 )\n%\n% ( beta )\n% + aL1 * ( |Z|_1 + ---- |Z-PsiT*u|^2 )\n% ( 2 )\n%\n% + .5 |F_p*u - f|^2\n%\n% where W_i = (Wx_i;Wy_i);\n%\n% U --- current point\n% f --- measurment vector\n% flag --- 0 (do not check res_u), otherwise check res_u;\n% Generally, res_u << 0, so setting flag = 0 is fine.\n% Weights -- local weights of TV\n%\n\n% Junfeng Yang, Aug. 08, 2008\n\nglobal Ux Uy FU PsiTU\nglobal Wx Wy\nglobal beta\nglobal remain\nglobal Z PsiZ\n\n[m,n] = size(U);\nmn = m*n;\n\n% res_wn, res_wz, wzr\nif aTV > 0\n Ux = [diff(U,1,2), U(:,1) - U(:,n)];\n Uy = [diff(U,1,1); U(1,:) - U(m,:)];\n\n Dx = Wx - Ux;\n Dy = Wy - Uy;\n\n V = sqrt(Wx.^2 + Wy.^2);\n Iz = find(V == 0);\n\n if isempty(Iz)\n In = 1:mn;\n else\n In = find(V ~= 0);\n V(Iz) = 1;\n end\n\n V = V*beta;\n\n RWx = Dx + Weights.*Wx./V;\n RWy = Dy + Weights.*Wy./V;\n S = sqrt(RWx.^2 + RWy.^2);\n\n wzr = length(Iz)/mn;\n if isempty(In)\n res_wn = 0;\n else\n res_wn = max(S(In));\n end\n\n if isempty(Iz);\n res_wz = -1;\n else\n res_wz = max(S(Iz) - Weights(Iz)/beta);\n end\n\nelse\n res_wn = 0;\n res_wz = 0;\n wzr = 0;\nend\n\n\n% res_Zn, res_Zz, Zzr\nif aL1 > 0\n PsiTU = PsiT(U);\n absPsiTU = abs(PsiTU);\n\n ZIn = find(Z ~= 0);\n if isempty(ZIn)\n res_Zn = 0;\n else\n R3 = (1/beta)*sign(Z(ZIn)) + Z(ZIn) - PsiTU(ZIn);\n res_Zn = max(abs(R3));\n end\n\n ZIz = find(Z == 0);\n if isempty(ZIz)\n res_Zz = -1;\n else\n R4 = absPsiTU(ZIz) - 1/beta;\n res_Zz = max(R4);\n end\n\n Zzr = length(ZIz)/m/n;\n\nelse\n PsiTU = 0;\n res_Zn = 0;\n res_Zz = -1;\n Zzr = 0;\nend\n\n% res_u\nres_u = 0;\nif flag == 0\n return;\nelse\n % res_u\n FU(picks) = -f + FU(picks);\n FU(remain) = 0;\n Ru = ifft2(FU);\n Ru = real(Ru);\n\n if aTV > 0\n Dxx = [Dx(:,1) - Dx(:,n), diff(Dx,1,2)];\n Dyy = [Dy(1,:) - Dy(m,:); diff(Dy,1,1)];\n Ru = Ru + (beta*aTV)*(Dxx + Dyy);\n end\n\n if aL1 > 0\n Ru = Ru + (aL1*beta)*(U - PsiZ);\n end\n res_u = max(abs(Ru(:)));\nend\n%% ------------- SUBFUNCTION ---------------\nfunction [Nomin1,Denom1,Denom2] = getC(picks,B,aTV,m,n)\n\n% compute fixed quantities\nNomin1 = zeros(m,n);\nNomin1(picks) = B;\nDenom1 = zeros(m,n);\nDenom1(picks) = 1;\nDenom2 = 0;\nif aTV > 0\n Denom2 = abs(psf2otf([1,-1],[m,n])).^2 + abs(psf2otf([1;-1],[m,n])).^2;\nend\n%% ---------- SUBFUNCTION ---------------\nfunction [mit_inn,mit_out,tol_inn,tol_rel_inn,tol_rel_out,beta0,beta_max, ...\n beta_rate,TVtype,idisp,recordf,U0,wbarflag,stc] = setopts(opts)\n\n% define default option fields\nmit_inn = 30;\nmit_out = 10;\ntol_inn = 1.e-3;\ntol_rel_inn = 5.e-3;\ntol_rel_out = 1.e-2;\nbeta0 = 2^5;\nbeta_max = 2^15;\nbeta_rate = 2;\nTVtype = 2;\nidisp = 0;\nrecordf = 0;\nU0 = [];\nwbarflag = 0;\nstc = 1;\n\n% change to specified option fields if exist\nif ~isempty(opts);\n if ~isa(opts,'struct'); error('L1pfi: opts not a struct'); end\n if isfield(opts,'mit_inn'); mit_inn = opts.mit_inn; end\n if isfield(opts,'mit_out'); mit_out = opts.mit_out; end\n if isfield(opts,'tol_inn'); tol_inn = opts.tol_inn; end\n if isfield(opts,'tol_rel_inn'); tol_rel_inn = opts.tol_rel_inn; end\n if isfield(opts,'tol_rel_out'); tol_rel_out = opts.tol_rel_out; end\n if isfield(opts,'beta0'); beta0 = opts.beta0; end\n if isfield(opts,'beta_max'); beta_max = opts.beta_max; end\n if isfield(opts,'beta_rate'); beta_rate = opts.beta_rate; end\n if isfield(opts,'TVtype'); TVtype = opts.TVtype; end\n if isfield(opts,'idisp'); idisp = opts.idisp; end\n if isfield(opts,'recordf'); recordf = opts.recordf; end\n if isfield(opts,'U0'); U0 = opts.U0; end\n if isfield(opts,'wbarflag'); wbarflag = opts.wbarflag; end\n if isfield(opts,'stc'); stc = opts.stc; end\nend\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/NESTA-1.1/RecPF_v1.1/solver/RecPF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5977249705258505}} {"text": "function d = cohens_d_2sample(input_values,binary_outcome)\n% d = cohens_d_2sample(input_values,binary_outcome)\n%\n% This is for the two-sample case\n% By Phil Kragel\n%\n% input_values: Continuous input values to test\n% binary_outcome: Logical vector of 1/0 values for group A/B assignment\n\nn1 = sum(~isnan(input_values(binary_outcome)) & ~isinf(input_values(binary_outcome)));\nn0 = sum(~isnan(input_values(~binary_outcome)) & ~isinf(input_values(~binary_outcome)));\n\nmeanpres = mean(input_values(binary_outcome));\nmeanabs = mean(input_values(~binary_outcome));\n\nv1 = var(input_values(binary_outcome));\nv0 = var(input_values(~binary_outcome));\n\npooledsd = sqrt((v1.*(n1-1) + v0.*(n0-1)) ./ (n1 + n0 - 2));\n\nd = (meanpres - meanabs) ./ pooledsd;\n\nend\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Statistics_tools/cohens_d_2sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5977249697339129}} {"text": "function [germs, germPaths] = centroidalVoronoi2d(germs, poly, varargin)\n%CENTROIDALVORONOI2D Centroidal Voronoi tesselation within a polygon\n%\n% PTS = centroidalVoronoi2d(NPTS, POLY)\n% Generate points in a polygon based on centroidal voronoi tesselation.\n% Centroidal germs can be computed by using the Llyod's algorithm:\n% 1) initial germs are chosen at random within polygon\n% 2) voronoi polygon of the germs is computed\n% 3) the centroids of each domain are computed, and used as germs of the\n% next iteration\n%\n% [PTS, PATHLIST] = centroidalVoronoi2d(NPTS, POLY)\n% Also returns the path of each germs at each iteration. The result\n% PATHLIST is a cell array with as many cells as the number of germs,\n% containing in each cell the successive positions of the germ.\n%\n% PTS = centroidalVoronoi2d(.., PARAM, VALUE)\n% Specify one or several optional arguments. PARAM can be one of:\n% * 'nIter' specifies the number of iterations of the algorithm\n% (default is 50)\n% * 'verbose' display iteration number. Default is false.\n%\n% Example\n% poly = ellipseToPolygon([50 50 40 30 20], 200);\n% nGerms = 100;\n% germs = centroidalVoronoi2d(nGerms, poly);\n% figure; hold on;\n% drawPolygon(poly, 'k');\n% drawPoint(germs, 'bo');\n% axis equal; axis([0 100 10 90]);\n% % extract regions of the CVD\n% box = polygonBounds(poly);\n% [n, e] = boundedVoronoi2d(box, germs);\n% [n2, e2] = clipGraphPolygon(n, e, poly);\n% drawGraphEdges(n2, e2, 'b');\n%\n% See also\n% graphs, boundedVoronoi2d, centroidalVoronoi2d_MC\n%\n% Rewritten from programs found in\n% http://people.scs.fsu.edu/~burkardt/m_src/cvt/cvt.html\n%\n% Reference:\n% Qiang Du, Vance Faber, and Max Gunzburger,\n% Centroidal Voronoi Tessellations: Applications and Algorithms,\n% SIAM Review, Volume 41, 1999, pages 637-676.\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2012-02-23, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2012 INRA - Cepia Software Platform.\n\n\n%% Parse input arguments\n\n% Number of germs\nif isscalar(germs)\n nGerms = germs;\n germs = [];\nelse\n nGerms = size(germs, 1);\nend\n\n% Number of iterations\nnIter = 50;\n\nverbose = false;\n\nkeepPaths = nargout > 1;\n\nwhile length(varargin) > 1\n paramName = varargin{1};\n switch lower(paramName)\n case 'verbose'\n verbose = varargin{2};\n case 'niter'\n nIter = varargin{2};\n \n otherwise\n error(['Unknown parameter name: ' paramName]);\n end\n\n varargin(1:2) = [];\nend\n\n\n%% Initialisations\n\n% bounding box of polygon\nbbox = polygonBounds(poly);\n\n% init germs if needed\nif isempty(germs)\n germs = generatePointsInPoly(nGerms);\nend\ngermIters = cell(nIter, 1);\n\n\n%% Iteration of the Lloyd algorithm\n\nfor i = 1:nIter\n if verbose\n disp(sprintf('Iteration: %d/%d', i, nIter)); %#ok\n end\n \n if keepPaths\n germIters{i} = germs;\n end\n \n % Compute Clipped Voronoi diagram of germs\n if verbose\n disp(' compute Voronoi Diagram');\n end\n [n, e, f] = boundedVoronoi2d(bbox, germs);\n [n2, e2, f2] = clipMesh2dPolygon(n, e, f, poly); %#ok\n\n % update the position of each germ\n if verbose\n disp(' compute centroids');\n end\n for iGerm = 1:nGerms\n polygon = n2(f2{iGerm}, :);\n germs(iGerm,:) = polygonCentroid(polygon);\n end\n \nend\n\n\n%% Evenutally compute germs trajectories\n\nif nargout > 1\n % init\n germPaths = cell(nGerms, 1);\n path = zeros(nIter+1, 2);\n \n % Iteration on germs\n for i = 1:nGerms\n \n % create path corresponding to germ\n for j = 1:nIter\n pts = germIters{j};\n path(j,:) = pts(i,:);\n end\n path(nIter+1, :) = germs(i,:);\n \n germPaths{i} = path;\n end\nend\n\nfunction pts = generatePointsInPoly(nPts)\n % extreme coordinates\n xmin = bbox(1); xmax = bbox(2);\n ymin = bbox(3); ymax = bbox(4);\n \n % compute size of box\n dx = xmax - xmin;\n dy = ymax - ymin;\n \n % allocate memory for result\n pts = zeros(nPts, 2);\n\n % iterate until all points have been sampled within the polygon\n ind = (1:nPts)';\n while ~isempty(ind)\n NI = length(ind);\n x = rand(NI, 1) * dx + xmin;\n y = rand(NI, 1) * dy + ymin;\n pts(ind, :) = [x y];\n \n ind = ind(~polygonContains(poly, pts(ind, :)));\n end\nend\n\nend\n\n", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/matGeom/graphs/centroidalVoronoi2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.766293648423189, "lm_q1q2_score": 0.5977036052799041}} {"text": "function [W,H] = nmf(X,K,alg,maxiter,speak)\n%\n% NMF wrapper function\n% function [W,H] = nmf(X,K,alg[,maxiter,speak])\n%\n% INPUT:\n% 'X' Inputmatrix\n% 'K' Number of components\n% 'alg' Algorithm to use: \n% 'mm' multiplicative updates using euclidean\n% distance. Lee, D..D., and Seung, H.S., (2001)\n% 'cjlin' alternative non-negative least squares using \n% projected gradients, author: Chih-Jen Lin, \n% National Taiwan University.\n% 'prob' probabilistic NFM interpretating X as samples\n% from a multinomial, author: Lars Kai Hansen,\n% Technical University of Denmark\n% 'als' Alternating Least Squares. Set negative\n% elements to zero. \n% 'alsobs' Alternating Least Squares. Set negative elements\n% to zero and adjusts the other elements acording\n% to Optimal Brain Surgeon. \n% 'maxiter' Maximum number of iterations, default = 1000.\n% 'speak' Print information to screen unless speak = 0,\n% default = 0\n%\n% OUTPUT:\n% W : N x K matrix\n% H : K x M matrix\n%\n% Kasper Winther Joergensen\n% Informatics and Mathematical Modelling\n% Technical University of Denmark\n% kwj@imm.dtu.dk\n% 2006/12/15\n\nswitch(nargin)\n case {0,1,2}\n error('Missing parameter. Type \"help nmf\" for usage.');\n return\n case 3\n maxiter = 1000;\n speak = 0;\n case 4\n speak = 0;\n case 5\n % empty\n otherwise\n error('Too many parameters. Type \"help nmf\" for usage.');\n return\nend\n\n% find dimensionallity of X\n[D,N] = size(X);\n\n% switch algorithm \nswitch lower(alg)\n case 'mm'\n if speak, disp('Using mm algorithm'),end\n [W,H]=nmf_mm(X,K,maxiter,speak);\n case 'prob' \n if speak, disp('Using prob algorithm'),end\n [W,H]=nmf_prob(X,K,maxiter,speak);\n case 'cjlin'\n if speak, disp('Using cjlin algorithm'),end\n [W,H]=nmf_cjlin(X,rand(D,K),rand(K,N),0.000001,10000,maxiter);\n case 'als'\n if speak, disp('Using als algorithm'),end\n [W,H]=nmf_als(X,K,maxiter,speak);\n case 'alsobs'\n if speak, disp('Using alsobs algorithm'),end\n [W,H]=nmf_alsobs(X,K,maxiter,speak);\n otherwise\n error('Unknown method. Type \"help nmf\" for usage.');\n return\nend\n\n[W,H,nrgy] = order_comp(W,H);\n\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/nmf/NMF-DTU-Toolbox/nmf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.5977035974419505}} {"text": "%% Misorientation Distribution Function\n% Explains how to compute and analyze misorientation distribution\n% functions. \n%\n%% TODO\n% Please help to redo the section\n%\n%% \n% When speaking about the misorientation distribution function (MDF) one\n% has to differentiate to cases\n%\n% # the boundary (correlated) misorientation distribution function\n% # the uncorelated misorientation distribution function\n%\n% While the first one considers only misorientations at grain boundaries\n% the second one considers misorietation between arbitrary crystal\n% orientations. To illustrate the difference lets consider the following\n% EBSD data set\n\n% Lets import some EBSD data and reconstruct the grains.\n\nmtexdata forsterite\ngrains = calcGrains(ebsd)\n\n\n%% The boundary misorientation distribution function\n%\n% In order to compute the boundary misorientation distribution function for\n% the phase transition from Forsterite to Enstatite we first extract the\n% misorientations along all Forsterite to Enstatite boundary segements\n\nmori_boundary = grains.boundary('Fo','En').misorientation\n\n%%\n% and second compute the corresponding density function using the command\n% \n\nmdf_boundary = calcDensity(mori_boundary,'halfwidth',5*degree)\n\n%%\n\nadf_boundary = mdf_boundary.calcAxisDistribution\n\nplot(adf_boundary)\n\n%%\n\n\n\n\n\n%%\n% The misorientation distribution function can be processed as any other\n% ODF. E.g. we can compute the prefered misorientation via\n\n[v,mori] = max(mdf_boundary)\n\n\n%%\n% or plot the pole figure corresponding to the crystal axis (1,0,0)\n\nplotPDF(mdf_boundary,Miller(1,0,0,ebsd('Fo').CS))\n\n\n\n\n\n%% The uncorrelated misorientation distribution function\n% \n% Alternatively the uncorrelated misorientation distribution function can be\n% computed by providing the option *uncorrelated*\n\nmori = calcMisorientation(ebsd('En'),ebsd('Fo'))\nmdf_uncor = calcDensity(mori)\n\n%%\n% Obviously it is different from the boundary misorientation distribution\n% function.\n\nplotPDF(mdf_uncor,Miller(1,0,0,ebsd('Fo').CS))\n\n%% Computing the uncorrelated misorientation function from two ODFs\n%\n% Let given two odfs\n\nodf_fo = calcDensity(ebsd('fo').orientations,'halfwidth',10*degree)\nodf_en = calcDensity(ebsd('en').orientations,'halfwidth',10*degree)\n\n%%\n% Then the uncorrelated misorientation function between these two ODFs can\n% be computed by\n\nmdf = calcMDF(odf_en,odf_fo)\n\n%%\n% This misorientation distribution function should be similar to the\n% uncorrelated misorientation function computed directly from the ebsd data\n\nplotPDF(mdf,Miller(1,0,0,ebsd('Fo').CS))\n\n%% Analyzing misorientation functions\n%\n% \n\n%% SUB: Angle distribution\n%\n% Let us first compare the actual angle distribution of the boundary\n% misorientations with the theoretical angle distribution of the\n% uncorrelated MDF.\n\nclose all\nplotAngleDistribution(grains.boundary('fo','en').misorientation)\n\nhold on\n\nplotAngleDistribution(mdf)\n\nhold off\n\n%%\n% For computing the exact values see the commands\n% and\n% .\n \n%% SUB: Axis distribution\n%\n% The same we can do with the axis distribution. First the actual angle distribution of the boundary\n% misorientations\n\nplotAxisDistribution(grains.boundary('fo','en').misorientation,'smooth')\n\n%%\n% Now the theoretical axis distribution of the\n% uncorrelated MDF.\n\nplotAxisDistribution(mdf)\n\n%%\n% For computing the exact values see the commands\n% and\n% .\n\naD = calcDensity(axis(grains.boundary('fo','en').misorientation))", "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/Misorientations/MDFAnalysis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.5976948296997245}} {"text": "function h = complex(f, g)\n%COMPLEX Construct complex CHEBFUN3 from real and imaginary parts.\n% H = COMPLEX(F, G) returns the complex CHEBFUN3 F + i G, where F and G \n% are real valued CHEBFUN3 objects with the same domain.\n%\n% See also CHEBFUN3/IMAG, CHEBFUN3/CONJ, CHEBFUN3/ABS and CHEBFUN3/REAL.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nif ( ~isreal(f) || ~isreal(g) )\n error('CHEBFUN:CHEBFUN3:complex:notReal1', ...\n 'Inputs must be real.');\nend\nh = f + 1i*g;\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebfun3/complex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5976948214923351}} {"text": "% This is material illustrating the methods from the book\n% Financial Modelling - Theory, Implementation and Practice with Matlab\n% source\n% Wiley Finance Series\n% ISBN 978-0-470-74489-5\n%\n% Date: 02.05.2012\n%\n% Authors: Joerg Kienitz\n% Daniel Wetterau\n%\n% Please send comments, suggestions, bugs, code etc. to\n% kienitzwetterau_FinModelling@gmx.de\n%\n% (C) Joerg Kienitz, Daniel Wetterau\n% \n% Since this piece of code is distributed via the mathworks file-exchange\n% it is covered by the BSD license \n%\n% This code is being provided solely for information and general \n% illustrative purposes. The authors will not be responsible for the \n% consequences of reliance upon using the code or for numbers produced \n% from using the code.\n\nfunction [value] = BinarySABR_3(f, k, t, a, b, r, n)\n% the value of a digital option within a SABR model\n epsilon = 1e-004;\n kp = k + epsilon;\n km = k - epsilon;\n sigmap = svol_2(a,b,r,n,f,kp,t);\n sigmam = svol_2(a,b,r,n,f,km,t);\n d1p = 1./(sigmap .* sqrt(t)).*(log(f./kp)+0.5*sigmap.^2*t);\n d2p = 1./(sigmap .* sqrt(t)).*(log(f./kp)-0.5*sigmap.^2*t);\n d1m = 1./(sigmam .* sqrt(t)).*(log(f./km)+0.5*sigmam.^2*t);\n d2m = 1./(sigmam .* sqrt(t)).*(log(f./km)-0.5*sigmam.^2*t);\n pp = f * normcdf(d1p) - kp .* normcdf(d2p);\n pm = f * normcdf(d1m) - km.* normcdf(d2m);\n value = (pm-pp) / (2*epsilon);\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/38322-the-sabr-model-densities-and-mc/Densities_Prices_MC/BinarySABR_3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5976526349898673}} {"text": "% Reeds Shepp path planner sample code\n%\n% based on python code from Python Robotics by Atsushi Sakai(@Atsushi_twi)\n%\n% Peter 3/18\n%\n% Finds the shortest path between 2 configurations:\n% - robot can move forward or backward\n% - the robot turns at zero or maximum curvature\n% - there are discontinuities in velocity and steering commands (cusps)\n% to see what it does run\n%\n% >> ReedsShepp.test\n%\n% References::\n% - Reeds, J. A.; Shepp, L. A.\n% Optimal paths for a car that goes both forwards and backwards.\n% Pacific J. Math. 145 (1990), no. 2, 367--393.\n% https://projecteuclid.org/euclid.pjm/1102645450\n\n% each path is described by a 3-letter word.\n% the algorithm finds a bunch of possible paths, then chooses the shortest\n% one. Each word is represented by a structure with fields:\n% - word a 3-letter sequence drawn from the letters LRLS\n% - L total path length\n% - lengths a 3-vector of lengths, signed to indicate the direction of\n% curvature\n% - traj a cell array of 3xN matrices giving the path for each segment\n% - dir the direction of travel: +1 or -1\n%\n% TODO: display all the solutions in one figure, as subplots\n\nclassdef ReedsShepp < handle\n properties\n best % the best path\n words\n maxc\n end\n \n methods\n function obj = ReedsShepp(q0, qf, maxcurv, dl)\n \n obj.maxc = maxcurv;\n \n % return the word describing the shortest path\n obj.words = generate_path(q0, qf, maxcurv);\n \n if isempty(obj.words)\n error('no path');\n end\n \n % find shortest path\n [~,k] = min( [obj.words.L] );\n \n obj.best = obj.words(k);\n \n % add the trajectory\n obj.best = generate_trajectories(obj.best, maxcurv, dl, q0);\n end\n \n function p = path(obj)\n p = [obj.best.traj{:}]';\n end\n \n function show(obj)\n for w=obj.words\n fprintf('%s (%g): [%g %g %g]\\n', w.word, w.L, w.lengths);\n end\n end\n \n function plot(obj, varargin)\n \n opt.circles = [];\n opt.join = [];\n \n opt = tb_optparse(opt, varargin);\n \n if ~ishold\n clf\n end\n hold on\n word = obj.best;\n \n for i=1:3\n \n if word.dir(i) > 0\n color = 'b';\n else\n color = 'r';\n end\n if i == 1\n x = word.traj{i}(1,:);\n y = word.traj{i}(2,:);\n else\n % ensure we join up the lines in the plot\n x = [x(end) word.traj{i}(1,:)];\n y = [y(end) word.traj{i}(2,:)];\n end\n \n if ~isempty(opt.join) && i<3\n plot(x(end), y(end), opt.join{:});\n end\n if ~isempty(opt.circles)\n T = SE2(word.traj{i}(:,1));\n R = 1/obj.maxc;\n c = T*[0; word.dir(i)*R];\n \n plot_circle(c, R, opt.circles)\n plot_point(c, 'k+')\n end\n \n plot(x, y, color, 'LineWidth', 2);\n end\n grid on; xlabel('X'); ylabel('Y')\n hold off\n axis equal\n title('Reeds-Shepp path');\n end\n \n function s = char(obj)\n s = '';\n s = strvcat(s, sprintf('Reeds-Shepp path: %s, length %f', obj.best.word, obj.best.L));\n s = strvcat(s, sprintf(' segment lengths: %f %f %f', obj.best.lengths));\n end\n \n function display(obj)\n disp( char(obj) );\n end\n end\n \n methods(Static)\n function test()\n maxcurv = 1;\n dl = 0.05;\n q0 = [0 0 pi/4]'; qf = [0 0 pi]';\n p = ReedsShepp(q0, qf, maxcurv, dl)\n \n p.plot('circles', 'k--', 'join', {'Marker', 'o', 'MarkerFaceColor', 'k'});\n end\n end\nend % class ReedsShepp\n\nfunction out = generate_trajectories(word, maxc, d, q0)\n \n % initialize the configuration\n p0 = q0;\n \n % output struct is same as input struct, but we will add:\n % - a cell array of trajectories\n % - a vector of directions -1 or +1\n out = word;\n \n for i=1:3\n m = word.word(i);\n l = word.lengths(i);\n \n x = [0:d:abs(l) abs(l)];\n \n p = pathseg(x, sign(l), m, maxc, p0);\n \n % add new fields to the struct\n \n if i == 1\n out.traj{i} = p;\n else\n % for subsequent segments skip the first point, same as last\n % point of previous segment\n out.traj{i} = p(:,2:end);\n end\n out.dir(i) = sign(l);\n \n % initial state for next segment is last state of this segment\n p0 = p(:,end);\n end\nend\n\nfunction q = pathseg(l, dir, m, maxc, p0)\n q0 = p0(:);\n switch m\n case 'S'\n f = @(t,q) dir*[cos(q(3)), sin(q(3)), 0]';\n case {'L', 'R'}\n f = @(t,q) dir*[cos(q(3)), sin(q(3)), dir*maxc]';\n end\n [t,q] = ode45(f, l, q0);\n q = q'; % points are column vectors\nend\n\n\nfunction words = generate_path(q0, q1, maxc)\n % return a list of all possible words\n q0 = q0(:); q1 = q1(:);\n dq = q1 - q0;\n dth = dq(3);\n \n xy = rot2(q0(3))' * dq(1:2) * maxc;\n x = xy(1); y = xy(2);\n \n words = [];\n words = SCS(x, y, dth, words);\n words = CSC(x, y, dth, words);\n words = CCC(x, y, dth, words);\n \n % account for non-unit curvature\n for i=1:numel(words)\n words(i).lengths = words(i).lengths / maxc;\n words(i).L = words(i).L / maxc;\n end\n \nend\n\n%%\nfunction owords = SCS(x, y, phi, words)\n \n words = SLS([ x y phi], 1, 'SLS', words);\n words = SLS([ x -y -phi], 1, 'SRS', words);\n \n owords = words;\nend\n\nfunction owords = CCC(x, y, phi, words)\n \n words = LRL([ x y phi], 1, 'LRL', words);\n words = LRL([-x y -phi], -1, 'LRL', words);\n words = LRL([ x -y -phi], 1, 'RLR', words);\n words = LRL([-x -y phi], -1, 'RLR', words);\n \n % backwards\n xb = x * cos(phi) + y * sin(phi);\n yb = x * sin(phi) - y * cos(phi);\n \n flip = [0 1 0; 1 0 0; 0 0 1]; % flip u and v\n \n words = LRL([ xb yb phi], flip, 'LRL', words);\n words = LRL([-xb yb -phi], -flip, 'LRL', words);\n words = LRL([ xb -yb -phi], flip, 'RLR', words);\n words = LRL([-xb -yb phi], -flip, 'RLR', words);\n \n owords = words;\nend\n\nfunction owords = CSC(x, y, phi, words)\n \n words = LSL([ x y phi], 1, 'LSL', words);\n words = LSL([-x y -phi], -1, 'LSL', words);\n words = LSL([ x -y -phi], 1, 'RSR', words);\n words = LSL([-x -y phi], -1, 'RSR', words);\n words = LSR([ x y phi], 1, 'LSR', words);\n words = LSR([-x y -phi], -1, 'LSR', words);\n words = LSR([ x -y -phi], 1, 'RSL', words);\n words = LSR([-x -y phi], -1, 'RSL', words);\n \n owords = words;\nend\n\n% requires LSL, LSR, SLS, LRL\n\n%%\n\n\nfunction owords = SLS(q, sign, word, words)\n x = q(1); y = q(2); phi = mod(q(3), 2*pi);\n \n if y > 0.0 && phi > 0.0 && phi < pi * 0.99\n xd = - y / tan(phi) + x;\n t = xd - tan(phi / 2.0);\n u = phi;\n v = norm( [(x - xd) y]) - tan(phi / 2.0);\n owords = addpath(words, sign*[t, u, v], word);\n elseif y < 0.0 && phi > 0.0 && phi < pi * 0.99\n xd = - y / tan(phi) + x;\n t = xd - tan(phi / 2.0);\n u = phi;\n v = -norm([(x - xd) y]) - tan(phi / 2.0);\n owords = addpath(words, sign*[t, u, v], word);\n else\n owords = words;\n end\nend\n\nfunction owords = LSL(q, sign, word, words)\n x = q(1); y = q(2); phi = mod(q(3), 2*pi);\n \n [t,u] = cart2pol(x - sin(phi), y - 1.0 + cos(phi));\n if t >= 0.0\n v = angdiff(phi - t);\n if v >= 0.0\n owords = addpath(words, sign*[t, u, v], word);\n return\n end\n end\n \n owords = words;\nend\n\nfunction owords = LRL(q, sign, word, words)\n x = q(1); y = q(2); phi = mod(q(3), 2*pi);\n \n [t1,u1] = cart2pol(x - sin(phi), y - 1.0 + cos(phi));\n \n if u1 <= 4.0\n u = -2.0 * asin(0.25 * u1);\n t = angdiff(t1 + 0.5 * u + pi);\n v = angdiff(phi - t + u);\n \n if t >= 0.0 && u <= 0.0\n owords = addpath(words, [t, u, v]*sign, word);\n return\n end\n end\n \n owords = words;\nend\n\nfunction owords = LSR(q, sign, word, words)\n x = q(1); y = q(2); phi = mod(q(3), 2*pi);\n \n [t1,u1] = cart2pol(x + sin(phi), y - 1.0 - cos(phi));\n u1 = u1^2;\n if u1 >= 4.0\n u = sqrt(u1 - 4.0);\n theta = atan2(2.0, u);\n t = angdiff(t1 + theta);\n v = angdiff(t - phi);\n \n if t >= 0.0 && v >= 0.0\n owords = addpath(words, sign*[t, u, v], word);\n return\n end\n end\n \n owords = words;\nend\n\n\n%%\nfunction owords = addpath(words, lengths, ctypes)\n \n % create a struct to represent this segment\n word.word = ctypes;\n word.lengths = lengths;\n \n % check same path exist\n for p = words\n if strcmp(p.word, word.word)\n if sum(p.lengths) - sum(word.lengths) <= 0.01\n owords = words;\n return %not insert path\n end\n end\n end\n \n word.L = sum(abs(lengths));\n \n % long enough to add?\n if word.L >= 0.01\n owords = [words word];\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/ReedsShepp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5976526239220412}} {"text": "function yp = p25_fun ( neqn, t, y )\n\n%*****************************************************************************80\n%\n%% P25_FUN evaluates the function for problem P25.\n%\n% Discussion:\n%\n% 2 equations\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 February 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Wayne Enright, John Pryce,\n% Algorithm 648,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 1, pages 28-34.\n%\n% Parameters:\n%\n% Input, integer NEQN, the number of equations.\n%\n% Input, real T, Y(NEQN), the arguments of the derivative\n% function.\n%\n% Output, real YP(NEQN), the value of the derivative function.\n%\n yp = zeros ( neqn, 1 );\n\n yp(1) = y(2);\n yp(2) = sqrt ( 1.0 + y(2).^2 ) / ( 25.0 - t );\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_ode/p25_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624890918021, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.5975501027645794}} {"text": "function order = order_table ( rule )\n\n%*****************************************************************************80\n%\n%% ORDER_TABLE returns the order of a Lebedev rule.\n%\n% Modified:\n%\n% 13 September 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Vyacheslav Lebedev, Dmitri Laikov,\n% A quadrature formula for the sphere of the 131st\n% algebraic order of accuracy,\n% Russian Academy of Sciences Doklady Mathematics,\n% Volume 59, Number 3, 1999, pages 477-481.\n%\n% Parameters:\n%\n% Input, integer RULE, the index of the rule, between 1 and 65.\n%\n% Output, integer ORDER, the order of the rule.\n%\n rule_max = 65;\n\n table = [ ...\n 6, 14, 26, 38, 50, 74, 86, 110, 146, 170, ...\n 194, 230, 266, 302, 350, 386, 434, 482, 530, 590, ...\n 650, 698, 770, 830, 890, 974, 1046, 1118, 1202, 1274, ...\n 1358, 1454, 1538, 1622, 1730, 1814, 1910, 2030, 2126, 2222, ...\n 2354, 2450, 2558, 2702, 2810, 2930, 3074, 3182, 3314, 3470, ...\n 3590, 3722, 3890, 4010, 4154, 4334, 4466, 4610, 4802, 4934, ...\n 5090, 5294, 5438, 5606, 5810 ]';\n\n if ( rule < 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'ORDER_TABLE - Fatal error!\\n' );\n fprintf ( 1, ' RULE < 1.\\n' );\n error ( 'ORDER_TABLE - Fatal error!' );\n elseif ( rule_max < rule )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'ORDER_TABLE - Fatal error!\\n' );\n fprintf ( 1, ' RULE_MAX < RULE.\\n' );\n error ( 'ORDER_TABLE - Fatal error!' );\n end\n\n order = table(rule);\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/sphere_lebedev_rule/order_table.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.5975500957068043}} {"text": "function dt = EulerDT2D(Q, gamma)\n\n% function dt = EulerDT2D(Q, gamma)\n% purpose: compute the time step dt for the compressible Euler equations\n\nGlobals2D;\n\nrho = Q(:,:,1); rhou = Q(:,:,2); rhov = Q(:,:,3); Ener = Q(:,:,4);\nrho = rho(vmapM); rhou = rhou(vmapM); rhov = rhov(vmapM); Ener = Ener(vmapM);\n\nu = rhou./rho; v = rhov./rho;\np = (gamma-1.0)*(Ener - rho.*(u.^2+v.^2)/2); c = sqrt(abs(gamma*p./rho));\n\ndt = 1/max( ((N+1)^2)*.5*Fscale(:).*(sqrt ( u(:).^2 + v(:).^2 ) + c(:)));\n\nrhoprange = [min(min(rho)), max(max(rho)), min(min(p)), max(max(p))]\nreturn\n", "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/JSHesthaven&TWarburton/CFD2D/EulerDT2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5975496352025236}} {"text": "function [R,T,Xc,best_solution,opt]=efficient_pnp_gauss(x3d_h,x2d_h,A)\n\n% EFFICIENT_PNP_GAUSS Main Function to solve the PnP problem \n% as described in:\n%\n% Francesc Moreno-Noguer, Vincent Lepetit, Pascal Fua.\n% Accurate Non-Iterative O(n) Solution to the PnP Problem. \n% In Proceedings of ICCV, 2007. \n%\n% Note: In this version of the software we perform a final\n% optimization using Gauss-Newton,which is not described in the\n% paper.\n%\n% x3d_h: homogeneous coordinates of the points in world reference\n% x2d_h: homogeneous position of the points in the image plane\n% A: intrincic camera parameters\n% R: Rotation of the camera system wrt world reference\n% T: Translation of the camera system wrt world reference\n% Xc: Position of the points in the camera reference\n% best solution: dimension of the kernel for the best solution\n% (before applying Gauss Newton).\n% opt: some parameters of the optimization process\n%\n% Copyright (C) <2007> \n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the version 3 of the GNU General Public License\n% as published by the Free Software Foundation.\n% \n% This program is distributed in the hope that it will be useful, but\n% WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n% General Public License for more details. \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% Francesc Moreno-Noguer, CVLab-EPFL, October 2007.\n% fmorenoguer@gmail.com, http://cvlab.epfl.ch/~fmoreno/ \n\n\n\nXw=x3d_h(:,1:3);\nU=x2d_h(:,1:2);\n\nTHRESHOLD_REPROJECTION_ERROR=20;%error in degrees of the basis formed by the control points. \n%If we have a larger error, we will compute the solution using a larger\n%number of vectors in the kernel\n\n%define control points in a world coordinate system (centered on the 3d\n%points centroid)\nCw=define_control_points();\n\n%compute alphas (linear combination of the control points to represent the 3d\n%points)\nAlph=compute_alphas(Xw,Cw);\n\n%Compute M\nM=compute_M_ver2(U,Alph,A);\n\n%Compute kernel M\nKm=kernel_noise(M,4); %in matlab we have directly the funcion km=null(M);\n \n\n\n%1.-Solve assuming dim(ker(M))=1. X=[Km_end];------------------------------\ndim_kerM=1;\nX1=Km(:,end);\n[Cc,Xc,sc]=compute_norm_sign_scaling_factor(X1,Cw,Alph,Xw);\n\n[R,T]=getrotT(Xw,Xc); %solve exterior orientation\nerr(1)=reprojection_error_usingRT(Xw,U,R,T,A);\n\nsol(1).Xc=Xc;\nsol(1).Cc=Cc;\nsol(1).R=R;\nsol(1).T=T;\nsol(1).error=err(1);\nsol(1).betas=[1];\nsol(1).sc=sc;\nsol(1).Kernel=X1;\n\n\n%2.-Solve assuming dim(ker(M))=2------------------------------------------\nKm1=Km(:,end-1);\nKm2=Km(:,end);\n\n%control points distance constraint\nD=compute_constraint_distance_2param_6eq_3unk(Km1,Km2);\ndsq=define_distances_btw_control_points();\nbetas_=inv(D'*D)*D'*dsq;\nbeta1=sqrt(abs(betas_(1)));\nbeta2=sqrt(abs(betas_(3)))*sign(betas_(2))*sign(betas_(1));\nX2=beta1*Km1+beta2*Km2;\n\n[Cc,Xc,sc]=compute_norm_sign_scaling_factor(X2,Cw,Alph,Xw);\n\n[R,T]=getrotT(Xw,Xc); %solve exterior orientation\nerr(2)=reprojection_error_usingRT(Xw,U,R,T,A);\n\nsol(2).Xc=Xc;\nsol(2).Cc=Cc;\nsol(2).R=R;\nsol(2).T=T;\nsol(2).error=err(2);\nsol(2).betas=[beta1,beta2];\nsol(2).sc=sc;\nsol(2).Kernel=[Km1,Km2];\n\n\n\n%3.-Solve assuming dim(ker(M))=3------------------------------------------\nif min(err)>THRESHOLD_REPROJECTION_ERROR %just compute if we do not have good solution in the previus cases\n\n Km1=Km(:,end-2);\n Km2=Km(:,end-1);\n Km3=Km(:,end);\n\n %control points distance constraint\n D=compute_constraint_distance_3param_6eq_6unk(Km1,Km2,Km3);\n dsq=define_distances_btw_control_points();\n betas_=inv(D)*dsq;\n beta1=sqrt(abs(betas_(1)));\n beta2=sqrt(abs(betas_(4)))*sign(betas_(2))*sign(betas_(1));\n beta3=sqrt(abs(betas_(6)))*sign(betas_(3))*sign(betas_(1));\n\n X3=beta1*Km1+beta2*Km2+beta3*Km3;\n\n [Cc,Xc,sc]=compute_norm_sign_scaling_factor(X3,Cw,Alph,Xw);\n \n [R,T]=getrotT(Xw,Xc); %solve exterior orientation\n err(3)=reprojection_error_usingRT(Xw,U,R,T,A);\n\n sol(3).Xc=Xc;\n sol(3).Cc=Cc;\n sol(3).R=R;\n sol(3).T=T;\n sol(3).error=err(3);\n sol(3).betas=[beta1,beta2,beta3];\n sol(3).sc=sc;\n sol(3).Kernel=[Km1,Km2,Km3];\n\nend\n\n\n\n%4.-Solve assuming dim(ker(M))=4------------------------------------------\nif min(err)>THRESHOLD_REPROJECTION_ERROR %just compute if we do not have good solution in the previus cases\n Km1=Km(:,end-3);\n Km2=Km(:,end-2);\n Km3=Km(:,end-1);\n Km4=Km(:,end);\n\n\n D=compute_constraint_distance_orthog_4param_9eq_10unk(Km1,Km2,Km3,Km4);\n dsq=define_distances_btw_control_points();\n lastcolumn=[-dsq',0,0,0]';\n D_=[D,lastcolumn];\n Kd=null(D_);\n\n P=compute_permutation_constraint4(Kd);\n lambdas_=kernel_noise(P,1);\n lambda(1)=sqrt(abs(lambdas_(1)));\n lambda(2)=sqrt(abs(lambdas_(6)))*sign(lambdas_(2))*sign(lambdas_(1));\n lambda(3)=sqrt(abs(lambdas_(10)))*sign(lambdas_(3))*sign(lambdas_(1));\n lambda(4)=sqrt(abs(lambdas_(13)))*sign(lambdas_(4))*sign(lambdas_(1));\n lambda(5)=sqrt(abs(lambdas_(15)))*sign(lambdas_(5))*sign(lambdas_(1));\n\n betass_=lambda(1)*Kd(:,1)+lambda(2)*Kd(:,2)+lambda(3)*Kd(:,3)+lambda(4)*Kd(:,4)+lambda(5)*Kd(:,5);\n beta1=sqrt(abs(betass_(1)));\n beta2=sqrt(abs(betass_(5)))*sign(betass_(2));\n beta3=sqrt(abs(betass_(8)))*sign(betass_(3));\n beta4=sqrt(abs(betass_(10)))*sign(betass_(4));\n X4=beta1*Km1+beta2*Km2+beta3*Km3+beta4*Km4;\n\n [Cc,Xc,sc]=compute_norm_sign_scaling_factor(X4,Cw,Alph,Xw);\n \n [R,T]=getrotT(Xw,Xc); %solve exterior orientation\n err(4)=reprojection_error_usingRT(Xw,U,R,T,A);\n\n sol(4).Xc=Xc;\n sol(4).Cc=Cc;\n sol(4).R=R;\n sol(4).T=T;\n sol(4).error=err(4);\n sol(4).betas=[beta1,beta2,beta3,beta4];\n sol(4).sc=sc;\n sol(4).Kernel=[Km1,Km2,Km3,Km4];\nend\n\n\n%5.-Gauss Newton Optimization------------------------------------------------------ \n[min_err,best_solution]=min(err);\nXc=sol(best_solution).Xc;\nR=sol(best_solution).R;\nT=sol(best_solution).T;\nBetas=sol(best_solution).betas;\nsc=sol(best_solution).sc;\nKernel=sol(best_solution).Kernel;\n \nif best_solution==1\n Betas=[0,0,0,Betas];\nelseif best_solution==2\n Betas=[0,0,Betas];\nelseif best_solution==3\n Betas=[0,Betas];\nend\n\nKm1=Km(:,end-3);\nKm2=Km(:,end-2);\nKm3=Km(:,end-1);\nKm4=Km(:,end);\nKernel=[Km1,Km2,Km3,Km4];\n\n\n%refine the solution iterating over the betas\nBeta0=Betas/sc;\n[Xc_opt,R_opt,T_opt,err_opt,iter]=optimize_betas_gauss_newton(Kernel,Cw,Beta0,Alph,Xw,U,A);\n\n%Just update R,T,Xc if Gauss Newton improves results (which is almost\n%always)\nif err_opt6 | Mtype<1\n error('Band-importance function type takes values between 1 and 6');\nend\n\n%================== DEFINE INPUT VARIABLES ==============================\n\nG=zeros(1,18); % insertion gains - needed if used in the context of amplification devices (hearing aids)\nT=G; % threshold levels in dB HL (for normal-hearing listeners, T=[0 0 ...0] )\nVocalEffort = 'normal'; % or \"raised\", \"loud\" and \"shout\"\n\n% Standard speech spectrum level for different vocal efforts (Table 3)\n%\nSpV=[32.41\t33.81\t35.29\t30.77;\n\t34.48\t33.92\t37.76\t36.65;\n\t34.75\t38.98\t41.55\t42.5;\n\t33.98\t38.57\t43.78\t46.51;\n\t34.59\t39.11\t43.3\t47.4;\n\t34.27\t40.15\t44.85\t49.24;\n\t32.06\t38.78\t45.55\t51.21;\n\t28.3\t36.37\t44.05\t51.44;\n\t25.01\t33.86\t42.16\t51.31;\n\t23\t\t31.89\t40.53\t49.63;\n\t20.15\t28.58\t37.7\t47.65;\n\t17.32\t25.32\t34.39\t44.32;\n\t13.18\t22.35\t30.98\t40.8;\n\t11.55\t20.15\t28.21\t38.13;\n\t9.33\t16.78\t25.41\t34.41;\n\t5.31\t11.47\t18.35\t28.24;\n\t2.59\t7.67\t13.87\t23.45;\n\t1.13\t5.07\t11.39\t20.72];\n\nswitch lower(VocalEffort)\n\tcase 'normal', EV = SpV(:,1)';\n\tcase 'raised', EV = SpV(:,2)';\n\tcase 'loud', EV = SpV(:,3)';\n\tcase 'shout', EV = SpV(:,4)';\n\totherwise, error('Unknown level of vocal effort')\nend;\n\n% Define band center frequencies for 1/3rd octave procedure (Table 3)\nf = [160 200 250 315 400 500 630 800 1000 1250 1600 2000, ...\n 2500 3150 4000 5000 6300 8000];\n\n\n% Define Internal Noise Spectrum Level (Table 3) \nX = [0.6 -1.7 -3.9 -6.1 -8.2 -9.7 -10.8 -11.9 -12.5 -13.5 -15.4 -17.7, ...\n\t-21.2 -24.2 -25.9 -23.6 -15.8 -7.1];\n\n\n% ----------------- start processing ----------------------\n%\n% Equivalent Speech Spectrum Level (5.1.3, Eq. 17)\t\nE = E + G;\n\n% Self-Speech Masking Spectrum (Sec 4.3.2.1, Eq. 5)\nV = E - 24;\n\n% 4.3.2.2\t\nB = max(V,N+G);\n\t\n% Calculate Equivalent Masking Spectrum Level (Sec 4.3.2.5, Eq. 9)\n%\nC = 0.6.*(B+10*log10(f)-6.353) - 80; % slope parameter Ci (4.3.2.3 Eq. 7)\nZ(1) = B(1);\n\nfor i = 2:18\n\tZ(i) = 10*log10(10.^(0.1*N(i)) + ...\n\tsum(10.^(0.1*(B(1:(i-1))+3.32.*C(1:(i-1)).*log10(0.89*f(i)./f(1:(i-1)))))));\nend;\t\n\n\n% Equivalent Internal Noise Spectrum Level (Sec 4.4 Eq. 10)\nX = X + T;\n\t\n% Compute disturbance Spectrum Level (4.5)\nD = max(Z,X);\n\n% Level Distortion Factor (Sec 4.6, Eq. 11)\n%\nL = 1 - (E - EV - 10)./160;\nL = max(0,min(L,1)); \n\n\n% 4.7.1 Eq. 12\nK = (E-D+15)/30;\nK=max(0,min(K,1));\n\n% Band Audibility Function (7.7.2 Eq. 13)\n%\nA = L.*K;\n\n% Speech Intelligibility Index (4.8 Eq. 14)\n%\nSIIval = sum(BandImportance(Mtype).*A);\n\nreturn;\n\n\n%==================================================================\n\nfunction BIF = BandImportance(type)\n%\n% Band importance functions, taken from Table B.2:\n% type = \n%\t\t1:\tNonsense syllable tests where most English\n%\t\t\tphonemes occur equally often\n%\t\t2:\tCID-22\n%\t\t3:\tNU6 (monosyllables)\n%\t\t4:\tDiagnostic Rhyme test (DRT)\n%\t\t5:\tshort passages of easy reading material\n%\t\t6:\tSPIN (monosyllables)\n\nif (nargin ~= 1) | (type>6) | (type<1)\n\terror('Incorrect argument to BandImportance');\nend;\n\nIFu = [\t0\t\t0.0365\t0.0168\t0\t\t0.0114\t0\n\t\t\t0\t\t0.0279\t0.013\t0.024\t0.0153\t0.0255\n 0.0153 0.0405\t0.0211\t0.033\t0.0179\t0.0256\n\t\t\t0.0284\t0.0500\t0.0344\t0.039\t0.0558\t0.036\n\t\t\t0.0363\t0.0530\t0.0517\t0.0571\t0.0898\t0.0362\n\t\t\t0.0422\t0.0518\t0.0737\t0.0691\t0.0944\t0.0514\n\t\t\t0.0509\t0.0514\t0.0658\t0.0781\t0.0709\t0.0616\n\t\t\t0.0584\t0.0575\t0.0644\t0.0751\t0.066\t0.077\n\t\t\t0.0667\t0.0717\t0.0664\t0.0781\t0.0628\t0.0718\n\t\t\t0.0774\t0.0873\t0.0802\t0.0811\t0.0672\t0.0718\n\t\t\t0.0893\t0.0902\t0.0987\t0.0961\t0.0747\t0.1075\n\t\t\t0.1104\t0.0938\t0.1171\t0.0901\t0.0755\t0.0921\n\t\t\t0.112\t0.0928\t0.0932\t0.0781\t0.082\t0.1026\n\t\t\t0.0981\t0.0678\t0.0783\t0.0691\t0.0808\t0.0922\n\t\t\t0.0867\t0.0498\t0.0562\t0.048\t0.0483\t0.0719\n\t\t\t0.0728\t0.0312\t0.0337\t0.033\t0.0453\t0.0461\n\t\t\t0.0551\t0.0215\t0.0177\t0.027\t0.0274\t0.0306\n\t\t\t0\t\t0.0253\t0.0176\t0.024\t0.0145\t0];\n\nBIF = IFu(:,type)';\n", "meta": {"author": "jtkim-kaist", "repo": "Speech-enhancement", "sha": "84f1a3c1273fb4952522b911dd62cbb4476a534d", "save_path": "github-repos/MATLAB/jtkim-kaist-Speech-enhancement", "path": "github-repos/MATLAB/jtkim-kaist-Speech-enhancement/Speech-enhancement-84f1a3c1273fb4952522b911dd62cbb4476a534d/SE/lib/sub_lib/MATLAB_code/objective_measures/intelligibility/SII.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5974307165962724}} {"text": "function x=ibm2num(b)\n% ibm2num : convert IBM 32 bit floating point format to doubles\n% x=num2ibm(b)\n% b is a matrix of uint32\n% x is a corresponding matrix of doubles\n%\n%\n% See also num2ibm\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 should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n%\n%\n% (C) Brian Farrelly, 22 October 2001\n% mailto:Brian.Farrelly@nho.hydro.com Norsk Hydro Research Centre\n% phone +47 55 99 68 74 ((( Postboks 7190\n% fax +47 55 99 69 70 2oooS N-5020 Bergen\n% home +47 55 13 78 49 HYDRO Norway\n%\n\n\n\nx=repmat(NaN,size(b));\n\nsign=bitget(b,32); % get sign from first bit\nsign=double(sign);\n\n% format hex\nexp=bitand(b,uint32(hex2dec('7f000000'))); % get exponent from first byte, last 7 bits\nexp=bitshift(exp,-24);\n%format long\n\nexp=double(exp)- 64; % remove bias from exponent \n\n%format hex\nfrac=bitand(b,uint32(hex2dec('00ffffff'))); % get mantissa from last 3 bytes\n%format long\nfrac=double(frac);\nfrac=frac/2^24;\n\n\nx=(1-2*sign).*16.^exp .* frac;\n\nerr = frac==0 & (exp~=-64 | sign~=0); % bias removal is incorrect for zero\nif any(err)\n % TMH 19/06/2003\n disp(['WARNING : ',mfilename,' Invalid zero input --> Sure data are IBM FLOAT formatted ?'])\t\n return;\t\t\t\t\t\t\t \n %warning('Invalid zero input in ibm2num for the following:')\n % format hex; disp(b(err)); format\t\t\t\t\t\t\t \nend\n\nerr = frac~=0 & (frac<1/16 | frac>=1);\nif any(err)\n % TMH 19/06/2003\n disp(['WARNING : ',mfilename,' Invalid mantissa input --> Sure data are IBM FLOAT formatted ?'])\t\n return;\n % warning('Invalid mantissa input in ibm2num for the following:')\n % format hex; disp(b(err)); format\t\t\t\t\t\t\t \nend \n\n\n\n\n", "meta": {"author": "cultpenguin", "repo": "segymat", "sha": "6470f59fd8184f0fff0d89383265417b461cc1da", "save_path": "github-repos/MATLAB/cultpenguin-segymat", "path": "github-repos/MATLAB/cultpenguin-segymat/segymat-6470f59fd8184f0fff0d89383265417b461cc1da/ibm2num.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.5974275286915774}} {"text": "function [x, fx, exitFlag] = bisection(f,lb,ub,target,options)%#codegen\n % BISECTION Fast and robust root-finding method that handles n-dim arrays.\n %\n % [x,fVal,ExitFlag] = BISECTION(f,LB,UB,target,options) finds x +/- TolX\n % (LB < x < UB) such that f(x) = target +/- TolFun.\n %\n % x = BISECTION(f,LB,UB) finds the root(s) of function f on the interval\n % [LB, UB], i.e. finds x such that f(x) = 0 where LB <= x <= UB. f will\n % never be evaluated outside of the interval specified by LB and UB. f\n % should have only one root and f(UB) and f(LB) must bound it. Elements\n % of x are NaN for instances where a solution could not be found.\n %\n % x = BISECTION(f,LB,UB,target) finds x such that f(x) = target.\n %\n % x = BISECTION(f,LB,UB,target,TolX) will terminate the search when the\n % search interval is smaller than TolX (TolX must be positive).\n %\n % x = BISECTION(f,LB,UB,target,options) solves with the default\n % parameters replaced by values in the structure OPTIONS, an argument\n % created with the OPTIMSET function. Used options are TolX and TolFun.\n % Note that OPTIMSET will not allow arrays for tolerances, so set the\n % fields of the options structure manually for non-scalar TolX or TolFun.\n %\n % [x,fVal] = BISECTION(f,...) returns the value of f evaluated at x.\n %\n % [x,fVal,ExitFlag] = BISECTION(...) returns an ExitFlag that describes\n % the exit condition of BISECTION. Possible values of elements of\n % ExitFlag and the corresponding exit conditions are\n %\n % 1 Search interval smaller than TolX.\n % 2 Function value within TolFun of target.\n % 3 Search interval smaller than TolX AND function value within\n % TolFun of target.\n % -1 No solution found.\n %\n % Any or all of f(scalar), f(array), LB, UB, target, TolX, or TolFun may\n % be scalar or n-dim arrays. All non-scalar arrays must be the same size.\n % All outputs will be this size.\n %\n % Default values are target = 0, TolX = 1e-6, and TolFun = 0.\n %\n % There is no iteration limit. This is because BISECTION (with a TolX\n % that won't introduce numerical issues) is guaranteed to converge if f\n % is a continuous function on the interval [UB, LB] and f(x)-target\n % changes sign on the interval.\n %\n % The bisection method is very robust root-finding method. The absolute\n % error is halved at each step so the method converges linearly. However,\n % Brent's method (such as implemented in FZERO) can converge\n % superlinearly and is as robust. FZERO also has more features and input\n % checking, so use BISECTION in cases where either the optimization\n % toolbox is unavailable or if FZERO would have to be implemented in a\n % loop to solve multiple cases, in which case BISECTION will be much\n % faster because of vectorization.\n %\n % Define LB, UB, target, TolX, and TolFun for each specific application\n % using great care for the following reasons:\n % - There is no iteration limit, so given an unsolvable task, such as\n % TolX = TolFun = 0, BISECTION remains in an unending loop.\n % - Spacing between very large floating point numbers is likely to be\n % greater than TolX.\n % - There is no initial check to make sure that f(x) - target changes\n % sign between LB and UB.\n % - Very large or very small numbers can introduce numerical issues.\n %\n % Example 1: Find cube root of array 'target' without using NTHROOT and\n % compare speed to using FZERO.\n % options = optimset('TolX', 1e-9);\n % target = [(-100:.1:100)' (-1000:1:1000)'];\n %\n % tic;\n % xfz = zeros(size(target));\n % for ii = 1:numel(target)\n % xfz(ii) = fzero(@(x) x.^3-target(ii), [-20 20], options);\n % end\n % fzero_time = toc\n %\n % tic;\n % xbis = bisection(@(x) x.^3, -20, 20, target, options);\n % bisection_time = toc\n %\n % fprintf('FZERO took %0.0f times longer than BISECTION.\\n',...\n % fzero_time/bisection_time)\n %\n % Example 2: Find roots by varying the function coefficients.\n % [A, B] = meshgrid(linspace(1,2,6), linspace(4,12,10));\n % f = @(x) A.*x.^0.2 + B.*x.^0.87 - 15;\n % xstar = bisection(f,0,5);\n %\n % See also FZERO, FMINBND, OPTIMSET, FUNCTION_HANDLE.\n %\n % [x,fVal,ExitFlag] = BISECTION(f,LB,UB,target,options)\n \n % Copyright 2010-2013 Sky Sartorius\n % Author - Sky Sartorius\n % Contact - www.mathworks.com/matlabcentral/fileexchange/authors/101715\n \n % --- Process inputs. ---\n % Set default values \n tolX = 1e-6;\n tolFun = 0;\n if nargin == 5\n if isstruct(options)\n if isfield(options,'TolX') && ~isempty(options.TolX)\n tolX = options.TolX;\n end\n if isfield(options,'TolFun') && ~isempty(options.TolFun)\n tolFun = options.TolFun;\n end\n else\n tolX = options;\n end\n end\n if nargin<4 || isempty(target); target=0; end\n \n \n ub_in = ub; lb_in = lb;\n f = @(x) f(x) - target;\n \n % --- Flip UB and LB if necessary. ---\n isFlipped = lb>ub;\n if any(isFlipped(:))\n ub(isFlipped) = lb_in(isFlipped);\n lb(isFlipped) = ub_in(isFlipped);\n ub_in = ub; lb_in = lb;\n end\n \n % --- Make sure everything is the same size for a non-scalar problem. ---\n if isscalar(lb) && isscalar(ub)\n % Test if f returns multiple outputs for scalar input.\n if ~isscalar(target)\n ub = ub + zeros(size(target));\n else\n jnk = f(ub);\n if ~isscalar(jnk)\n ub = ub + zeros(size(jnk));\n end\n end\n end\n \n % Check if lb and/or ub need to be made into arrays.\n if isscalar(lb) && ~isscalar(ub)\n lb = lb + zeros(size(ub));\n elseif ~isscalar(lb) && isscalar(ub)\n ub = ub + zeros(size(lb));\n end\n \n x = zeros(size(lb));\n [x, fx, outsideTolFun, outsideTolX, stillNotDone] = testconvergence(f, ub, lb, tolFun, tolX);\n % --- Iterate ---\n iterations = 0;\n while any(stillNotDone(:))\n bigger = fx.*f(ub) > 0;\n ub(bigger)= x(bigger);\n lb(~bigger)= x(~bigger);\n \n [x, fx, outsideTolFun, outsideTolX, stillNotDone] = testconvergence(f, ub, lb, tolFun, tolX);\n iterations = iterations + 1;\n \n if(iterations > 10000)\n % error('Too many iterations in bisection!');\n break;\n end\n end\n \n % --- Check that f(x+tolX) and f(x-tolX) have opposite sign. ---\n fu = f(min(x+tolX,ub_in));\n fl = f(max(x-tolX,lb_in));\n unboundedRoot = (fu.*fl) > 0;\n \n % Throw out unbounded results if not meeting TolFun convergence criteria.\n \n x(unboundedRoot & outsideTolFun) = NaN;\n \n % --- Catch NaN elements of UB, LB, target, or other funky stuff. ---\n x(isnan(fx)) = NaN;\n \n % --- Characterize results. ---\n fx = fx + target;\n if nargout > 2\n exitFlag = +~outsideTolX;\n exitFlag(~outsideTolFun) = 2;\n exitFlag(~outsideTolFun & ~outsideTolX) = 3;\n exitFlag(isnan(x)) = -1;\n end\nend\n\nfunction [x, fx, outsideTolFun, outsideTolX, stillNotDone] = testconvergence(f, ub, lb, tolFun, tolX)\n x=(ub+lb)/2;\n fx=f(x);\n outsideTolFun = abs(fx) > tolFun;\n outsideTolX = (ub - lb) > tolX;\n stillNotDone = outsideTolX & outsideTolFun;\nend\n\n% V2: July 2010\n% V3: December 2012\n% don't remember when\n% typo line 39; added fn handle to see also; made array in example 2\n% smaller; changed wording in example 1\n% 2013-08-23\n% -changed scalar*ones(...) calls to scalar+zeros(...) calls based on\n% http://undocumentedmatlab.com/blog/allocation-performance-take-2/\n% -rearranged help block and formatted a tiny bit", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/math/bisection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.5974275196517252}} {"text": "function [vals, pos] = minandmax(f)\n%MINANDMAX Global minimum and maximum of the SINGFUN F on [-1,1].\n% VALS = MINANDMAX(F) returns a 2-vector VALS = [MIN(F); MAX(F)] with the\n% global minimum and maximum of the SINGFUN F on [-1,1].\n%\n% [VALS, POS] = MINANDMAX(F) returns also the 2-vector POS where the minimum\n% and maximum of F occur.\n%\n% See also MIN, MAX.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers. \n% See http://www.chebfun.org/ for Chebfun information.\n\ntol = chebfunpref().blowupPrefs.exponentTol;\n\nif ( ~any(f.exponents) || all(abs(f.exponents) < tol) )\n \n % The function is actually smooth!\n [vals, pos] = minandmax(f.smoothPart);\n \nelse\n \n % Initialise:\n minF = [];\n maxF = [];\n minLoc = [];\n maxLoc = []; \n \n % Look for blow up at the left:\n if ( f.exponents(1) < -tol ) % Singularity at the left end.\n fVal = feval(f, -1);\n if ( fVal == inf )\n maxF = inf;\n maxLoc = -1;\n elseif ( fVal == -inf )\n minF = -inf;\n minLoc = -1;\n else\n % NaNs may occur and then we can not conclude anything.\n error('CHEBFUN:SINGFUN:minandmax:boundedness', ...\n ['Function has a singularity but isn''t infinite at the left ' ...\n 'endpoint']);\n end\n end\n \n % Look for blow up at the right:\n if ( f.exponents(2) < -tol ) % Singularity at the right end.\n fVal = feval(f, 1);\n if ( fVal == inf )\n maxF = inf;\n maxLoc = 1;\n elseif ( fVal == -inf )\n minF = -inf;\n minLoc = 1;\n else\n % NaNs may occur and then we can not conclude anything.\n error('CHEBFUN:SINGFUN:minandmax:boundedness', ...\n ['Function has a singularity but isn''t infinite at the right ' ...\n 'endpoint']);\n end\n end\n \n % If min or max is empty, then we need to do more work:\n if ( isempty(minF) || isempty(maxF) ) \n % Find the roots of the derivative for local minima:\n fp = diff(f);\n r = roots(fp);\n % Append the end points and remove duplicates:\n r = unique([-1 ; r ; 1]);\n if ( isempty(maxF) )\n % Take the maximum of the local maxima:\n [maxF, maxIndex] = max(feval(f, r));\n maxLoc = r(maxIndex);\n end\n if ( isempty(minF) )\n % Take the minimum of the local minima:\n [minF, minIndex] = min(feval(f, r));\n minLoc = r(minIndex);\n end \n end \n vals = [ minF; maxF ];\n pos = [ minLoc; maxLoc ];\n \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/@singfun/minandmax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.5973454931272776}} {"text": "function [vol,dist] = volume(psi,radius,dist)\n\nif nargin < 3\n N = 60;\n dist = zeros(numel(radius),N);\n for i = 1:length(radius)\n \n if radius(i) + 5 * psi.halfwidth < pi\n dist(i,1:N-9) = linspace(0,radius(i) + 5 * psi.halfwidth,N-9);\n dist(i,N-9:end) = linspace(radius(i) + 5 * psi.halfwidth,pi,10);\n else\n dist(i,:) = linspace(0,pi,N);\n end\n \n end\n\nend\n\n% make radius square as well\nradius = repmat(radius(:),1,size(dist,2));\n\n% weight function\nweight = @(rot_angle,quat_dist,volume_radius) (max(0,min(4*pi,2*pi*(1-(cos(volume_radius/2) - ...\n cos(quat_dist/2) * cos(rot_angle/2))./...\n (sin(quat_dist/2) * sin(rot_angle/2))))) ...\n + max(0,min(4*pi,2*pi*(1-(cos(volume_radius/2) + ...\n cos(quat_dist/2) * cos(rot_angle/2))./...\n (sin(quat_dist/2) * sin(rot_angle/2))))))./pi./4;\n\n% integrant\nKV = @(rot_angle,quat_dist,volume_radius) weight(rot_angle,quat_dist,volume_radius) ...\n .* sin(rot_angle ./2).^2 .* psi.eval(cos(rot_angle./2)) ./pi.*2 ;\n\n% perform quadrature\n%vol = zeros(size(dist));\n%for j = 1:length(dist)\n% vol(j) = quad(@(rot_angle) KV(rot_angle,dist(j),radius),0,min(pi,5*k.hw),1e-6);\n%end\n\n%vol = quadv(@(rot_angle) KV(rot_angle,dist,radius),0,min(pi,5*psi.halfwidth),1e-7);\nvol = integral(@(rot_angle) KV(rot_angle,dist,radius),0,min(pi,5*psi.halfwidth),'AbsTol',1e-7,'ArrayValued',true);\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/SO3Fun/SO3KernelFunctions/@SO3Kernel/volume.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952948443461, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5973359217704017}} {"text": "function [ccf,pst] = spm_csd2ccf(csd,Hz,dt)\n% Converts cross spectral density to cross covariance function\n% FORMAT [ccf,pst] = spm_csd2ccf(csd,Hz,dt)\n%\n% csd (n,:,:) - cross spectral density (cf, mar.P)\n% Hz (n x 1) - vector of frequencies (Hz)\n% dt - samping interval (default = 1/(2*Hz(end)))\n%\n% ccf - cross covariance functions\n% pst (N,1) - vector of lags for evaluation (seconds)\n%\n% Note that because this scheme uses FFT one can only change dt.\n%\n% See also: \n% spm_ccf2csd.m, spm_ccf2mar, spm_csd2ccf.m, spm_csd2mar.m, spm_mar2csd.m,\n% spm_csd2coh.m, spm_Q.m, spm_mar.m and spm_mar_spectral.m\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: spm_csd2ccf.m 6395 2015-03-26 15:05:04Z adeel $\n\n% Nyquist\n%--------------------------------------------------------------------------\nif nargin < 3, dt = 1/(2*Hz(end)); end\n \n% unpack cells\n%--------------------------------------------------------------------------\nif iscell(csd)\n for i = 1:length(csd)\n [ccfi,pst] = spm_csd2ccf(csd{i},Hz,dt);\n ccf{i} = ccfi;\n end\n return\nend\n \n% unpack time bins (for time-frequency responses)\n%--------------------------------------------------------------------------\nif ndims(csd) == 4\n for i = 1:size(csd,1)\n [ccfi,pst] = spm_csd2ccf(squeeze(csd(i,:,:,:)),Hz,dt);\n ccf(i,:,:,:) = ccfi;\n end\n return\nend\n\n\n% indices for FFT\n%--------------------------------------------------------------------------\ndw = Hz(2) - Hz(1);\nHz = Hz/dw;\nns = 1/dt;\nN = ceil(ns/2/dw);\ngj = find(Hz > 0 & Hz < (N + 1));\ngi = gj + ceil(Hz(1)) - 1;\ng = zeros(N,1);\n\n% Fourier transform cross-spectral density\n%==========================================================================\nfor i = 1:size(csd,2)\n if ismatrix(csd)\n g(gi) = csd(gj,i);\n f = ifft([0; g; flipud(conj(g))]);\n ccf(:,i) = real(fftshift(f))*N*dw;\n else\n for j = 1:size(csd,3)\n g(gi) = csd(gj,i,j);\n f = ifft([0; g; flipud(conj(g))]);\n ccf(:,i,j) = real(fftshift(f))*N*dw;\n end\n end\nend\n \n% Compute time bins\n%--------------------------------------------------------------------------\npst = dt*(-N:N);\n\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/spectral/spm_csd2ccf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5972547396264021}} {"text": " function rot\n% ***************************************************************\n% P r o g r a m ROT\n% ***************************************************************\n%\n% PURPOSE:\n% Resolve numerically differential equation of rotational motion\n% of a body\n% Jz*d2f/dt2 = Mz(t,f,w)\n% and plots graphics of coordinate, velocity and phase plane.\n% If possible, the program could solve the problem analytically.\n%\n% INPUT DATA:\n% Jz - moment of inertia of the body ;\n% Mz - rotational moment Mz = Mz(t,f,w);\n% f0 - initial value of the coordinate ;\n% w0 - initial value of the angular velocity ;\n% Tend - upper bound of the integration ;\n% eps - precision of the integration ;\n% np - number of parameters .\n% P{1}, P{2}, ..., P{np} - names of the parameters (array of cells);\n%\n% NOTES:\n% 1. The coordinate is designed by the symbol 'f' and velocity by 'w';\n% 2. The physical names of the parameters are assigned to the\n% cells of the array P like this: P{1}='Jz', P{2}='c',...;\n% 3. For analytical solution the values of Tend, eps, np and P are not\n% needed. \n% 4. The parameters Jz, f0 and w0 have to be entered only as\n% strings, even though they represent numbers!\n% 5. All the data can be input from file or in interactive mode.\n%\n% EXAMPLE of DATA FILE:\n% % Data File for problem ...\n% Jz = 'Jz'; ( or Jz = '0.15';)\n% Mz = '-k*w - c*f'; % k, c - parameters\n% f0 = 'f0'; ( or f0 = '0.33';)\n% w0 = 'w0'; ( or w0 = '7';)\n% Tend = 20;\n% eps = 1.e-8;\n% np = 3;\n% P{1} = 'Jz';\n% P{2} = 'k';\n% P{3} = 'c';\n\n% ---------------------------------------------------------\n% DATA INPUT OF THE PROBLEM\n% =========================================================\n\n clear\n disp(' ');\n disp(' How will you input the data ? ');\n disp(' 1. From a data file; ');\n disp(' 2. In interactive mode. ');\n ans = input(' Number of Your choice : ' );\n flag = 0;\n if ans == 1\n while 1\n disp(' ');\n indat = input(' Input the name of the data file :', 's');\n if exist([cd,'\\',indat]) % Search only in current directory\n eval(indat);\n flag = 1; break % Successful\n else % Unsuccessful\n disp(' ');\n disp([' File ',indat,' not exist!'])\n disp(' You have to:')\n disp(' 1. Enter another DATA file name, or')\n disp(' 2. Input the DATA interactively !')\n ans2 = input(' Your choice, please: ');\n if ans2 == 2, break , end\n end\n end\n end\nif flag == 0 \n %Input of the data in-line mode\n disp(' ');\n Jz = input(' Moment of inertia of the body Jz : ','s' );\n Mz = input(' Expression of the rotational moment Mz : ','s');\n f0 = input(' Initial coordinate f0 : ' );\n w0 = input(' Initial velocity w0 : ' );\n Tend = input(' Upper bound of the integration Tend : ' );\n eps = input(' Precision of the calculations eps : ' );\n np = input(' Number of parameters np : ' );\n % Asigning names of the parameters\n if np > 0\n disp(' ');\n disp(' Enter names of the parameters:')\n for i = 1:np\n ii = num2str(i);\n P{i} = input([' Name of parameter P',ii,': '],'s');\n end\n end \n end\n \n% ---------------------------------------------------------\n% Differential Equation of Motion\n% =========================================================\n\n syms f w D2f \n Mz = subs(Mz, 'w', 'Df');\n deq = Jz*D2f - Mz;\n\n% ---------------------------------------------------------\n% ANALYTICAL SOLUTION\n% =========================================================\n\n disp(' ');\n ans = input(' Would you like analytical solution? (Y/N): ','s');\n if ans =='Y' | ans == 'y'\n if ~isstr(f0), f0 = num2str(f0); end % Repairing user\n if ~isstr(w0), w0 = num2str(w0); end % input errors!\n syms f\n inicond = ['f(0)=',f0,',Df(0)=',w0];\n f = dsolve(char(deq), inicond, 't');\n if ~isempty(f)\n disp(' ');\n disp(' Low of Motion ');\n disp(' ***************** ');\n disp(' ');\n disp('f = '); pretty(f)\n disp(' ');\n fname = input(' Name of file to write solution: ','s');\n save(fname, 'f');\n end\n disp(' ');\n ans = input(' Would you like numerical solution? (Y/N): ','s');\n if ans == 'N' | ans == 'n', return, end \n f = 'f'; % Clear contents of f\n end\n\n% ---------------------------------------------------------\n% NUMERICAL SOLUTION\n% ========================================================= \n\n% Input the name of the file-function\ndisp(' ');\nfname = input(' Name of the File-function to be generated: ','s');\nflag1 = 'Y';\nif exist([cd,'\\',fname]) % Search only in current directory!\n disp(' ');\n disp([' A file-function with name ',fname,' already exist !'])\n flag1 = input(' Overwrite it ? (Y/N): ', 's');\nend\n\n% ---------------------------------------------------------\n% GENERATING THE FILE-FUNCTION\n% ---------------------------------------------------------\n\nif ( flag1 == 'Y' | flag1 == 'y' )\n Mz = subs(Mz,{'f','Df'},{'y(1)','y(2)'});\n% Opening the file for writing file-function\n [Fid,mes] = fopen([fname,'.m'],'wt');\n% Generating the string with physical parameters: Jz, c ...\n strpar = '';\n for j = 1:np\n strpar = [strpar,',',P{j}];\n end\n titl = input(' Denomination of the Problem: ','s');\n% Writing the headline of the File-function\n fprintf(Fid,['function yt = ',fname,'(t,y',strpar,')\\n']);\n fprintf(Fid,['%% ',titl]);\n% Writing the first derivatives\n fprintf(Fid,'\\n%% The first derivatives\\n');\n fprintf(Fid, ' yt(1) = y(2); \\n');\n fprintf(Fid,[' yt(2) = ',char(Mz/Jz),'; \\n']);\n fprintf(Fid,' yt = yt'';\\n');\n fprintf(Fid,['%% *** End of File-function ',fname,' ***']);\n fclose(Fid);\n edit(fname)\nend\n\n% ---------------------------------------------------------\n% INTEGRATION AND VISUALIZATION OF THE REZULTS\n% ---------------------------------------------------------\n\nflag2 = 0;\n% Initial entering values of the parameters and generating\n% the string with parameters 'P{1}, P{2}, ..., P{np}' to be\n% passed to the File-function as actual arguments \nif np > 0\n PP = P; % Saving the physical names of the parameters in PP \n parameters = ' ';\n disp(' ');\n disp(' Input the numerical values of the parameters: ')\n for i = 1:np\n i = num2str(i);\n eval(['P{',i,'}=input(['' '',P{',i,'},'' = '']);']);\n parameters = [parameters,',P{',i,'}'];\n end \nelse\n parameters = [];\nend\n% Check-up type of f0 and w0 and correct\n% it if needed\nif ischar(f0)\n f0 = str2num(f0);\n if isempty(f0), f0 = input(' f0 = '); end\nend\nif ischar(w0)\n w0 = str2num(w0);\n if isempty(w0), w0 = input(' w0 = '); end\nend\nwhile 1\n if flag2 == 1\n disp(' ');\n eps = input(' Precision of the computations eps: ');\n Tend = input(' Upper bound of the integration Tend: ');\n f0 = input(' Initial coordinate f0: ');\n w0 = input(' Initial velocity w0: ');\n if np > 0\n P = PP; % Restoring the names of the parameters !\n disp(' ');\n disp(' Input the numerical values of the parameters: ')\n for i = 1:np\n i = num2str(i);\n eval(['P{',i,'}=input(['' '',P{',i,'},'' = '']);']);\n end \n end\n end\n y0 = [f0 w0]; % initial conditions\n options = odeset('AbsTol',eps,'RelTol',100*eps);\n % Choosing of the Solver\n disp(' ');\n disp(' Choose the proper Solver: ');\n disp(' ------------------------------- ');\n disp(' A. Non stiff differential equations ');\n disp(' 1. ode45 - middle precision; ');\n disp(' 2. ode23 - low precision; ');\n disp(' 3. ode113 - from low to upper. ');\n disp(' ');\n disp(' B. Stiff differential equations ');\n disp(' 1. ode15s - from low to upper; ');\n disp(' 2. ode23s - low precision; ');\n disp(' 3. ode23t - middle precision; ');\n disp(' 4. ode23tb - low precision. ');\n disp(' ');\n solver = input(' The name of the Solver: ','s');\n \n % Integration of the Differential Equations\n \n eval(['[t,y] = feval(solver,eval([''@'',fname]),',...\n '[0 Tend],y0,options',parameters,');']);\n % Plotting graphs\n \n tmin = min(t); \n tmax = max(t);\n y1min = min(y(:,1)); \n y1max = max(y(:,1));\n y2min = min(y(:,2)); \n y2max = max(y(:,2));\n dy1 = y1max - y1min;\n dy2 = y2max - y2min;\n xmin = y1min - 0.1*dy1;\n xmax = y1max + 0.1*dy1;\n ymin = y2min - 0.1*dy2;\n ymax = y2max + 0.1*dy2;\n % Coordinate f = f(t)\n figure % 1\n comet(t,y(:,1))\n plot(t,y(:,1),[tmin tmax],[0 0],'k'), grid on\n axis([tmin, tmax, xmin, xmax]);\n set(gca,'FontName','Arial Cyr','FontSize',12);\n title('Low of motion {\\phi} = {\\phi}({\\itt})')\n xlabel('{\\itt}'); ylabel('{\\phi}'); pause\n % Angular velocity w = w(t)\n figure % 2\n comet(t,y(:,2))\n plot(t,y(:,2),[tmin tmax],[0 0],'k'), grid on\n axis([tmin, tmax, ymin, ymax]);\n set(gca,'FontName','Arial','FontSize',12);\n title('Angular velocity {\\omega} = {\\omega}({\\itt})')\n xlabel('{\\itt}'); ylabel('{\\omega}'); pause\n % Coordinate and Velocity\n figure % 3\n subplot(2,1,1), plot(t,y(:,1),[tmin tmax],[0 0],'k')\n grid on, axis([tmin, tmax, xmin, xmax]);\n set(gca,'FontName','Arial','FontSize',12);\n title('Low of motion {\\phi} = {\\phi}(t)')\n subplot(2,1,2), plot(t,y(:,2),[tmin tmax],[0 0],'k')\n grid on, axis([tmin, tmax, ymin, ymax]);\n set(gca,'FontName','Arial','FontSize',12);\n title('Angular velocity {\\omega} = {\\omega}(t)')\n pause\n % Phase Plane\n figure % 4 \n subplot(1,1,1)\n comet(y(:,1),y(:,2))\n plot(y(:,1),y(:,2), [xmin,xmax],[0 0],'k',...\n [0 0],[ymin,ymax],'k'), grid on\n axis([xmin, xmax, ymin, ymax]); \n set(gca,'FontName','Arial Cyr','FontSize',12);\n title(' Phase Plane {\\omega} = {\\omega}({\\phi})')\n xlabel('{\\phi}'), ylabel('{\\omega}'), pause\n flag2 = 1;\n % close all\n disp(' ');\n ans = input(' Would you like to continue? (Y/N): ','s');\n if ans == 'n' | ans == 'N', break, end\nend\n\n% ***************** End of Program ROT ********************\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/6363-matlab-in-dynamics/Dinp_2004/SORCE Files/ROT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5972547386241382}} {"text": "function [CQcc, LogP_absCQT, TimeVec, FreqVec, Ures_LogP_absCQT, Ures_FreqVec] = ...\n cqcc(x, fs, B, fmax, fmin, d, cf, ZsdD)\n\n% Constant Q cepstral coefficients\n% Usage: CQcc = cqcc(x, fs, B, fmax, fmin, d, cf, ZsdD)\n%\n% Input parameters:\n% x : input signal\n% fs : sampling frequency\n% B : number of bins per octave [default = 96]\n% fmax : highest frequency to be analyzed [default = Nyquist frequency]\n% fmin : lowest frequency to be analyzed [default = ~20Hz to fullfill an integer number of octave]\n% d : number of uniform samples in the first octave [default 16]\n% cf : number of cepstral coefficients excluding 0'th coefficient [default 19]\n% ZsdD : any sensible combination of the following [default ZsdD]:\n% 'Z' include 0'th order cepstral coefficient\n% 's' include static coefficients (c)\n% 'd' include delta coefficients (dc/dt)\n% 'D' include delta-delta coefficients (d^2c/dt^2)\n%\n% Output parameters:\n% CQcc : constant Q cepstral coefficients (nCoeff x nFea)\n% LogP_absCQT : log power magnitude spectrum of constant Q trasform\n% TimeVec : time at the centre of each frame [sec]\n% FreqVec : center frequencies of analysis filters [Hz]\n% Ures_LogP_absCQT : uniform resampling of LogP_absCQT\n% Ures_FreqVec : uniform resampling of FreqVec [Hz]\n%\n% See also: cqt\n%\n%\n% References:\n% M. Todisco, H. Delgado, and N. Evans. A New Feature for Automatic\n% Speaker Verification Anti-Spoofing: Constant Q Cepstral Coefficients.\n% Proceedings of ODYSSEY - The Speaker and Language Recognition\n% Workshop, 2016.\n%\n% C. Sch�rkhuber, A. Klapuri, N. Holighaus, and M. D�fler. A Matlab\n% Toolbox for Efficient Perfect Reconstruction log-f Time-Frequecy\n% Transforms. Proceedings AES 53rd Conference on Semantic Audio, London,\n% UK, Jan. 2014. http://www.cs.tut.fi/sgn/arg/CQT/\n%\n% G. A. Velasco, N. Holighaus, M. D�fler, and T. Grill. Constructing an\n% invertible constant-Q transform with non-stationary Gabor frames.\n% Proceedings of DAFX11, Paris, 2011.\n%\n% N. Holighaus, M. D�fler, G. Velasco, and T. Grill. A framework for\n% invertible, real-time constant-q transforms. Audio, Speech, and\n% Language Processing, IEEE Transactions on, 21(4):775-785, April 2013.\n%\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Copyright (C) 2016 EURECOM, France.\n%\n% This work is licensed under the Creative Commons\n% Attribution-NonCommercial-ShareAlike 4.0 International\n% License. To view a copy of this license, visit\n% http://creativecommons.org/licenses/by-nc-sa/4.0/\n% or send a letter to\n% Creative Commons, 444 Castro Street, Suite 900,\n% Mountain View, California, 94041, USA.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Authors: Massimiliano Todisco {todisco [at] eurecom [dot] fr}\n% Hector Delgado {delgado [at] eurecom [dot] fr}\n%\n% Version: 1.0\n% Date: 22.01.16\n%\n% User are requested to cite the following paper in papers which report \n% results obtained with this software package.\t\n%\n% M. Todisco, H. Delgado, and N. Evans. A New Feature for Automatic\n% Speaker Verification Anti-Spoofing: Constant Q Cepstral Coefficients.\n% Proceedings of ODYSSEY - The Speaker and Language Recognition\n% Workshop, 2016.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%% CHECK INPUT PARAMETERS\nif nargin < 2\n warning('Not enough input arguments.'), return\nend\n\n%%% DEFAULT INPUT PARAMETERS\nif nargin < 3; B = 96; end\nif nargin < 4; fmax = fs/2; end\nif nargin < 5; oct = ceil(log2(fmax/20)); fmin = fmax/2^oct; end\nif nargin < 6; d = 16; end\nif nargin < 7; cf = 19; end\nif nargin < 8; ZsdD = 'ZsdD'; end\ngamma = 228.7*(2^(1/B)-2^(-1/B));\n\n%%% CQT COMPUTING\nXcq = cqt(x, B, fs, fmin, fmax, 'rasterize', 'full', 'gamma', gamma);\n\n%%% LOG POWER SPECTRUM\nabsCQT = abs(Xcq.c);\nTimeVec = (1:size(absCQT,2))*Xcq.xlen/size(absCQT,2)/fs;\nFreqVec = fmin*(2.^((0:size(absCQT,1)-1)/B));\nLogP_absCQT = log(absCQT.^2 + eps);\n\n%%% UNIFORM RESAMPLING\nkl = (B*log2(1+1/d));\n[Ures_LogP_absCQT, Ures_FreqVec] = resample(LogP_absCQT,...\n FreqVec,1/(fmin*(2^(kl/B)-1)),1,1,'spline');\n\n%%% DCT\nCQcepstrum = dct(Ures_LogP_absCQT);\n\n%%% DYNAMIC COEFFICIENTS\nif strfind(ZsdD, 'Z'); scoeff = 1; else scoeff = 2; end\nCQcepstrum_temp = CQcepstrum(scoeff:cf+1,:);\nf_d = 3; % delta window size\nif strcmp(strrep(ZsdD,'Z',''), 'sdD')\n CQcc = [CQcepstrum_temp; Deltas(CQcepstrum_temp,f_d); ...\n Deltas(Deltas(CQcepstrum_temp,f_d),f_d)];\nelseif strcmp(strrep(ZsdD,'Z',''), 'sd')\n CQcc = [CQcepstrum_temp; Deltas(CQcepstrum_temp,f_d)];\nelseif strcmp(strrep(ZsdD,'Z',''), 'sD')\n CQcc = [CQcepstrum_temp; Deltas(Deltas(CQcepstrum_temp,f_d),f_d)];\nelseif strcmp(strrep(ZsdD,'Z',''), 's')\n CQcc = CQcepstrum_temp;\nelseif strcmp(strrep(ZsdD,'Z',''), 'd')\n CQcc = Deltas(CQcepstrum_temp,f_d);\nelseif strcmp(strrep(ZsdD,'Z',''), 'D')\n CQcc = Deltas(Deltas(CQcepstrum_temp,f_d),f_d);\nelseif strcmp(strrep(ZsdD,'Z',''), 'dD')\n CQcc = [Deltas(CQcepstrum_temp,f_d); Deltas(Deltas(CQcepstrum_temp,f_d),f_d)];\nend\nend\n\nfunction D = Deltas(x,hlen)\n\n% Delta and acceleration coefficients\n%\n% Reference:\n% Young S.J., Evermann G., Gales M.J.F., Kershaw D., Liu X., Moore G., Odell J., Ollason D.,\n% Povey D., Valtchev V. and Woodland P., The HTK Book (for HTK Version 3.4) December 2006.\n\nwin = hlen:-1:-hlen;\nxx = [repmat(x(:,1),1,hlen),x,repmat(x(:,end),1,hlen)];\nD = filter(win, 1, xx, [], 2);\n% D = D(:,hlen+1:(end - hlen));\nD = D(:,hlen*2+1:end);\nD = D./(2*sum((1:hlen).^2));\nend\n", "meta": {"author": "nesl", "repo": "asvspoof2019", "sha": "8b780369f7273345c22d979192119198bbf3db13", "save_path": "github-repos/MATLAB/nesl-asvspoof2019", "path": "github-repos/MATLAB/nesl-asvspoof2019/asvspoof2019-8b780369f7273345c22d979192119198bbf3db13/baseline/CQCC_v1.0/cqcc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.5972547336152373}} {"text": "%% Analyzing Investment Strategies with CVaR Portfolio Optimization in MATLAB\n%\n% Robert Taylor\n% The MathWorks, Inc.\n\n% Copyright (C) 2012 The MathWorks, Inc.\n\n%% Introduction\n\n% This script is a \"superscript\" that organizes the scripts for the webinar \"Analyzing Investment\n% Strategies with CVaR Portfolio Optimization in MATLAB.\" It describes what each script does and\n% shows the order in which the scripts should be examined.\n\n%% Instructions\n\n% The file structure for these scripts has a top-level folder that contains these scripts and should\n% have two folders 'data' and 'source' with data and analytics. To add these folders to the path,\n% start in the folder with the scripts and execute the commands\n\nsetlocalpaths\n\n% The script cvarwebinar_scenarios.m, which simulates scenarios, must be run before subsequent\n% scripts can be run because it generates a file BuyWriteScenarios.mat that is needed for these\n% scripts. The script to generate scenarios can take about one hour on a typical computer and\n% requires that the computer be a 64-bit machine. It creates a 12MB file in the ./data folder. Make\n% sure that the script to generate scenarios is run in the folder that contains this script so that\n% the scenarios file ends up in the correct data folder.\n\n%% Theory\n\n% This script illustrates basic features of covered-call strategies and provides a theoretical\n% analysis of issues regarding slippage due to assignment and re-investment.\n\ncvarwebinar_theory\n\n%% From Theory to Reality\n\n% This script illustrates an event-driven simulation of total returns for uncovered and covered\n% positions based on a single realization of an underlying stock. It moves from the simplicity of\n% theory to the messiness of reality as it models and simulates various contributions to slippage.\n\ncvarwebinar_reality\n\n%% Calibration\n\n% This script is the first of the sequence of scripts to illustrate a complete workflow to analyze a\n% covered-call strategy for a universe of 26 stocks. Given total return price data, this script\n% illustrates maximum likelihood calibration of the assumed geometric Brownian motion process for\n% the universe of stocks.\n\ncvarwebinar_calibration\n\n%% Scenario Generation\n\n% This script is the second of the sequence of scripts that generates scenarios for uncovered and\n% covered positions to be used for subsequent portfolio optimization and analysis. This is the\n% slowest script since it generates scenarios by simulation of investment actions during the course\n% of an investment period.\n\ncvarwebinar_scenarios\n\n%% Normality Tests\n\n% This script is the third of the sequence of scripts that examines the statistical properties of\n% the scenarios. As the probability of early exercise increases during an investment period, the\n% distribution of the log of covered-call returns becomes increasingly non-normal.\n\ncvarwebinar_normality\n\n%% Optimization\n\n% This script is the final of the sequence of scripts that performs several portfolio optimization\n% steps with both CVaR and mean-variance portfolio optimization. The difference in results between\n% the two types of optimization is examined to provide greater insights into the normative\n% implications of covered-call strategies.\n\ncvarwebinar_optimization\n\n%% References\n%\n% # P. Bernstein (1998), _Against the Gods: The Remarkable Story of Risk_, Wiley.\n% # F. Black (1975), \"Fact and Fantasy in the Use of Options,\" _Financial Analysts Journal_, Vol. 31,\n% No. 4, pp. 36-41 and 61-72.\n% # P. Glassermann (1991), _Monte Carlo Methods in Financial Engineering_, Springer.\n% # I. Karatzas and S. Shreve (1991), _Brownian Motion and Stochastic Calculus_, 2nd ed., Springer.\n% # H. Markowitz (1952), \"Portfolio Selection,\" _Journal of Finance_, Vol. 7, No. 1, pp. 77-91.\n% # R. Merton, M. Scholes, and M. Gladstein (1978), \"The Returns and Risk of Alternative Call Option \n% Portfolio Investment Strategies,\" _Journal of Business_, Vol. 51, No. 2, pp. 183-242.\n% # R. T. Rockafellar and S. Uryasev (2002). \"Conditional Value-at-Risk for General Loss\n% Distributions,\" _Journal of Banking and Finance_, Vol. 26, pp. 1443-1471.\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/39449-analyzing-investment-strategies-with-cvar-portfolio-optimization/cvarwebinar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.597254727604072}} {"text": "function [LE,J]=CylNeumanLePerp_PGSE(d, R, G, delta, smalldel, roots)\n% Substrate: Parallel, impermeable cylinders with one radius in an empty\n% background.\n% Pulse sequence: Pulsed gradient spin echo\n% Signal approximation: Gaussian phase distribution.\n%\n% [LE,J] = CylNeumanLePerp_PGSE(d, R, G, delta, smalldel, roots)\n%\n% returns the log signal attenuation in perpendicular direction (LePerp) for\n% EACH RADIUS specified in R according to the Neuman model and the Jacobian J\n% of LePerp with respect to the parameters.\n%\n% The Jacobian DOES NOT include derivates with respect to the fibre direction.\n%\n% d is the diffusivity of the material inside the cylinders.\n%\n% R is the list of the radii of the cylinders. It has size [1 m] where m is the\n% number of radii.\n%\n% G, delta and smalldel are the gradient strength, pulse separation and\n% pulse length of each measurement in the protocol. Each has\n% size [N 1].\n%\n% roots contains solutions to the Bessel function equation from function\n% BesselJ_RootsCyl.\n%\n% author: Daniel C Alexander (d.alexander@ucl.ac.uk)\n% Gary Hui Zhang (gary.zhang@ucl.ac.uk)\n%\n\n% When R=0, no need to do any calculation\nif (R == 0.00)\n LE = zeros(size(G,1), size(R,2));\n J = zeros([size(LE), 2]);\n\t J(:,:,:) = 0;\n return;\nend\n\n% Check the roots array is correct\nif(abs(roots(1) - 1.8412)>0.0001)\n error('Looks like the roots array is wrong. First value should be 1.8412, but is %f', roots(1));\nend\n\n% Radial wavenumbers\nGAMMA = 2.675987E8;\n\n% number of gradient directions, i.e. number of measurements\nl_q=size(G,1);\nl_a=numel(R);\nk_max=numel(roots);\n\nR_mat=repmat(R,[l_q 1]);\nR_mat=R_mat(:);\nR_mat=repmat(R_mat,[1 1 k_max]);\nR_matSq=R_mat.^2;\n\nroot_m=reshape(roots,[1 1 k_max]);\nalpha_mat=repmat(root_m,[l_q*l_a 1 1])./R_mat;\namSq=alpha_mat.^2;\namP6=amSq.^3;\n\ndeltamx=repmat(delta,[1,l_a]);\ndeltamx_rep = deltamx(:);\ndeltamx_rep = repmat(deltamx_rep,[1 1 k_max]);\n\nsmalldelmx=repmat(smalldel,[1,l_a]);\nsmalldelmx_rep = smalldelmx(:);\nsmalldelmx_rep = repmat(smalldelmx_rep,[1 1 k_max]);\n\nGmx=repmat(G,[1,l_a]);\nGmxSq = Gmx.^2;\n\n% Perpendicular component (Neuman model)\nsda2 = smalldelmx_rep.*amSq;\nbda2 = deltamx_rep.*amSq;\nemdsda2 = exp(-d*sda2);\nemdbda2 = exp(-d*bda2);\nemdbdmsda2 = exp(-d*(bda2 - sda2));\nemdbdpsda2 = exp(-d*(bda2 + sda2));\n\nsumnum1 = 2*d*sda2;\n% the rest can be reused in dE/dR\nsumnum2 = - 2 + 2*emdsda2 + 2*emdbda2;\nsumnum2 = sumnum2 - emdbdmsda2 - emdbdpsda2;\nsumnum = sumnum1 + sumnum2;\n\nsumdenom = d^2*amP6.*(R_matSq.*amSq - 1);\n\n% Check for zeros on top and bottom\n%sumdenom(find(sumnum) == 0) = 1;\nsumterms = sumnum./sumdenom;\n\ntestinds = find(sumterms(:,:,end)>0);\ntest = sumterms(testinds,1)./sumterms(testinds,end);\nif(min(test)<1E4)\n warning('Ratio of largest to smallest terms in Neuman model sum is <1E4. May need more terms.');\nend\n\ns = sum(sumterms,3);\ns = reshape(s,[l_q,l_a]);\nif(min(s)<0)\n warning('Negative sums found in Neuman sum. Setting to zero.');\n s(find(s<0))=0;\nend\n\nLE = -2*GAMMA^2*GmxSq.*s;\n\n% Compute the Jacobian matrix\nif(nargout>1)\n \n % dLE/dd\n sumnumD = 2*sda2;\n sumnumD = sumnumD - 2*sda2.*emdsda2;\n sumnumD = sumnumD - 2*bda2.*emdbda2;\n sumnumD = sumnumD + (bda2 - sda2).*emdbdmsda2;\n sumnumD = sumnumD + (bda2 + sda2).*emdbdpsda2;\n sumtermsD = sumnumD./sumdenom;\n\n sD = sum(sumtermsD,3);\n sD = reshape(sD,[l_q,l_a]);\n\n dLEdd = -2*GAMMA^2*GmxSq.*(sD - 2*s/d);\n\n % dLE/dR\n sumtermsR = (6*sumterms - 2*d*sumtermsD)./R_mat;\n \n sR = sum(sumtermsR,3);\n sR = reshape(sR,[l_q,l_a]);\n\n dLEdr = -2*GAMMA^2*GmxSq.*sR;\n\n % Construct the jacobian matrix.\n J = zeros([size(LE), 2]);\n J(:,:,1) = dLEdd;\n J(:,:,2) = dLEdr;\nend\n\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/NODDI_toolbox_v1.0/models/CylNeumanLePerp_PGSE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5971857227795617}} {"text": "function lp = wishpdfln(X,a,B,inverse)\n%WISHPDFLN Logarithm of Wishart probability density function.\n% See WISHPDF for argument description.\n\n% Written by Tom Minka\n% (c) Microsoft Corporation. All rights reserved.\n\nif nargin < 3\n B = [];\nend\nif nargin < 4\n inverse = 0;\nend\n\nif inverse\n X = inv(X);\nend\nif isempty(B)\n XB = X;\n logDetB = 0;\nelse\n XB = X*B;\n logDetB = logdet(B);\nend\nd = rows(X);\nd2 = (d+1)/2;\nif inverse\n d2 = -d2;\nend\nlogDetXB = (a-d2)*logdet(XB);\nlp = logDetXB - trace(XB) + d2*logDetB - gammaln(a,d);\n", "meta": {"author": "tminka", "repo": "lightspeed", "sha": "e65560c5aa3aae947a62dd662a6444cdfa96fc4f", "save_path": "github-repos/MATLAB/tminka-lightspeed", "path": "github-repos/MATLAB/tminka-lightspeed/lightspeed-e65560c5aa3aae947a62dd662a6444cdfa96fc4f/wishpdfln.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5971857227795616}} {"text": "function [Dimg,D,X,err,Z] = perform_dictionary_signature_learning(Y, k, options)\n\n% perform_dictionary_signature_learning - compute an image signature\n%\n% [Dimg,D,X,err,options.Z] = perform_dictionary_signature_learning(Y, k, w, options);\n%\n% The algorithm is described in\n% M. Aharon and M. Elad, \n% \" Sparse and Redundant Modeling of Image Content Using an Image-Signature-Dictionary\", \n% Submitted.\n%\n% Y is a set of exemplar, each Y(:,i)=p(:) is a w*w vector where p should \n% be some 2D patch of size (w,w) extracted from some image(s).\n% k is the width of the dictionary signature.\n%\n% The number of iterations is options.niter.\n% The sparse coder used is set in options.sparse_coder to either 'omp' or\n% 'mp'.\n%\n% Copyright (c) 2007 Gabriel Peyre\n\noptions.null = 0;\n\n% width of the patches\nww = size(Y,1);\nw = sqrt(ww);\n% number of exemplar\nm = size(Y,2);\nd = k;\ndd = d^2; % number of atoms in the dictionary\nkk = k^2;\n\nif m<2*dd\n warning('You should increase the number of exemplars.');\nend\n\n% option for OMP\nif not(isfield(options, 'nbr_max_atoms'))\n options.nbr_max_atoms = 4;\nend\nif not(isfield(options, 'use_mex'))\n options.use_mex = 1;\nend\n\nDimg = getoptions(options, 'Dimg', randn(k));\nniter = getoptions(options, 'niter', 40);\nuse_cg = getoptions(options, 'use_cg', 1);\noptions.niter_max = getoptions(options, 'niter_cg', 10);\nsparse_coder = getoptions(options, 'sparse_coder', 'omp');\n\nDimg = Dimg/sqrt( sum(Dimg(:).^2) );\n\nif isfield(options, 'strict_sparsity')\n options.nbr_atoms_max = options.strict_sparsity;\nend\n\n% remove mean\nmu = sum(Y);\nY = Y - repmat( mu/ww, [ww 1] );\n\n% compute the dictionary extraction sparse matrix\nif isfield(options, 'Z')\n Z = options.Z;\nelse\n Z = sparse(ww*dd,kk);\n num = 0;\n for x=1:d\n for y=1:d\n num = num+1;\n selx = x:x+w-1;\n sely = y:y+w-1;\n selx = mod(selx-1,k)+1;\n sely = mod(sely-1,k)+1;\n [Ya,Xa] = meshgrid(sely,selx);\n sel = Xa(:) + k*(Ya(:)-1);\n Z( (1:ww)' + (num-1)*ww + (sel-1)*dd*ww ) = 1;\n end\n end\nend\nerr = []; Dimg = Dimg(:);\nfor i=1:niter\n disp(['--> Iteration ' num2str(i) '/' num2str(niter) '.']); \n % extract dictionary and precompute the matrices\n D = reshape( Z*Dimg, ww, dd);\n % remove zero component and normalize\n D = D - repmat( mean(D), [ww 1] );\n D = D ./ repmat( sqrt( sum(D.^2) ), [ww 1] );\n % sparse coding\n disp('-> Sparse coding.');\n if strcmp(sparse_coder, 'omp')\n X = perform_omp(D,Y,options);\n else\n X = perform_mp(D,Y,options);\n end\n X = full(X);\n err(end+1) = norm(Y-D*X, 'fro');\n % update dictionary\n if not(use_cg)\n % pseudo inverion\n D = Y * pinv(X);\n else\n options.x = D';\n [D,err1] = perform_conjugate_gradient(X*X',X*Y',options);\n D = D';\n end\n % reconstruct\n Dimg = 1/ww * Z'*D(:);\nend\nDimg = reshape(Dimg,k,k);\nD = reshape( Z*Dimg(:), ww, dd);\nD = D - repmat( mean(D), [ww 1] );\nD = D ./ repmat( sqrt( sum(D.^2) ), [ww 1] );\n\n% add the low pass DC\nD = [ones(ww,1)/sqrt(ww) D];\nX = [mu/sqrt(ww); X];", "meta": {"author": "gpeyre", "repo": "matlab-toolboxes", "sha": "0cd622c988cda6f63f64d35cd7bd096fa578e5c6", "save_path": "github-repos/MATLAB/gpeyre-matlab-toolboxes", "path": "github-repos/MATLAB/gpeyre-matlab-toolboxes/matlab-toolboxes-0cd622c988cda6f63f64d35cd7bd096fa578e5c6/toolbox_sparsity/perform_dictionary_signature_learning.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5971302935252498}} {"text": "%% Check rate of convergence for 3D H1 interface problem\n% -div(A grad u) = f, x\\in \\Omega\n% where A is a piecewise constant on Omega^+ and Omega^-.\n%\n% Domain: Rectangular domain: [xmin,xmax] X [ymin,ymax] X [zmin,zmax]\n% Mesh: Cartesian triangular mesh.\n% Method: VIFE\n\n\n%% Geometry and Boundary Conditions\n%clear\n%close all\n%clc\n\n%path(pathdef)\naddpath(genpath(pwd),'-begin');\nrmpath(genpath('./.git'));\nrmpath(genpath('./docs'));\nsavepath;\n\ndomain = [-1,1,-1,1,-1,1];\nbc = [1,1,1,1,1,1]; % Dirichelet BC\n\n%% Finite Element Type\nfemtype = 'P1';\ndisp(['FEM Type = Conforming ', femtype]);\n\n%% Initial Partition\nnx0 = 10;\nny0 = nx0;\nnz0 = nx0;\n\n%% Task\nshowErr = 0;\nshowMesh = 0;\ncomputErr = 1;\n\n%% PDE\ntest = 5;\nswitch test\n case 0\n pde = poissonNonPoly3D;\n case 1 % circular interface\n %r = pi/5; bm = 1; bp = pi/(2*r^2);\n r = sqrt(pi/2); bm = 1; bp = pi/(2*r^2);domain = [-2,2,-2,2,-2,2];\n x0 = 0; y0 = 0; z0 = 0; rx = r; ry = r; rz = r;\n pde = elli3DcircIntf(bm,bp,r,x0,y0,z0,rx,ry,rz);\n case 2 % orthotorus interface\n domain = [-1.2,1.2,-1.2,1.2,-1.2,1.2];\n bm = 1; bp = 1;\n rx = 1; ry = 0.075; rz = 3;\n pde = elli3DorthocircIntf(bm,bp,rx,ry,rz);\n case 3 % line interface\n bm = 1; bp = 10;\n rx = 1; ry = 0; rz = 0; cx = pi/10; cy = 0; cz = 0;\n cm = 1; cp = 1; a = 1;\n pde = elli3DlinIntf(bm,bp,cx,cy,cz,rx,ry,rz,a,cm,cp);\n case 4 % line interface but with zero boundary conditions\n bm = 1; bp = 10^(2); delta = pi/10; % delta can not be -1,1\n pde = elli3DlinIntf2(bm,bp,delta);\n case 5 % circular interface\n r = pi/4; bm = 1; bp = 10; domain = [-1,1,-1,1,-1,1];\n x0 = 0; y0 = 0; z0 = 0;\n pde = elli3DcircIntf5(bm,bp,r,x0,y0,z0);\n case 6 % circular interface\n bm = 1; bp = 10; domain = [-1.3,1.3,-1.3,1.3,-1.3,1.3];\n x1 = -0.3; y1 = 0; z1 = 0; r11 = pi/5; r12 = 0.2;\n x2 = 0.3; y2 = 0; z2 = 0; r21 = pi/5; r22 = 0.2;\n pde = elli3DtorusTwin(bm,bp,x1,y1,z1,r11,r12,x2,y2,z2,r21,r22);\nend\n\n%% Max Iteration\nmaxIt = 4;\ntime = zeros(9,maxIt);\nerror = zeros(maxIt,4);\nratio = zeros(maxIt,4);\n\nfor i = 1:maxIt\n \n %% 1. Generate Mesh\n tic\n nx = nx0 + 10*(i-1); h = (domain(2) - domain(1))/nx;\n ny = ny0 + 10*(i-1);\n nz = nz0 + 10*(i-1);\n time(1,i) = nx;\n disp(' ')\n disp('**************************************************************************************')\n disp(['Partition = ',int2str(nx),' X ',int2str(ny),' X ',int2str(nz)]);\n disp(' ')\n \n mesh = genMesh3D(domain, nx, ny, nz);\n mesh = enrichMesh3D(mesh,1); % Mesh detail level = 2 (for PPIFE).\n disp(['number of element = ', int2str(length(mesh.t))]); \n mesh = genIntfMesh3D(mesh,pde.intf);\n disp(['number of interface element = ', int2str(-min(mesh.tLoc)),...\n ', is ', num2str(100*-min(mesh.tLoc)/length(mesh.t)), '% of all elements']);\n time(2,i) = toc;\n \n tic\n fem = genFEM3D(mesh,femtype,bc);\n disp(['number of DoF = ', int2str(length(fem.p))]);\n time(3,i) = toc;\n \n %% 2. Generate FEMI data including IFE functions and their matrices\n tic\n meshI = genIVmesh(mesh);\n time(4,i) = toc;\n length(unique(union(union(meshI.tface(:,1),meshI.tface(:,2)),meshI.tface(:,3))))\n \n tic\n option.mass = 0; % generate mass matrix\n option.rhs = 1;\n femI = genP1VIFEM3D(meshI,mesh,pde,option);\n time(5,i) = toc;\n \n %% 3. Assemble Matrix\n tic\n disp(' '); disp('Start Assembling Matrix');\n option.mass = 0; % generate mass matrix\n matrix = genMatVIFE3D(pde,mesh,fem,meshI,femI);\n time(6,i) = toc;\n \n %% 4. Solve the linear system Au = f\n tic\n disp(' ')\n\n disp('Start Solving Linear System: using PCG with ichol precond');\n %L = ichol(matrix.A);\n alpha = 10;\n L = ichol(matrix.A,struct('type','ict','droptol',1e-3,'diagcomp',alpha));\n [u,flag,relres,iter,resvec] = pcg(matrix.A,matrix.f,1e-8,1000,L,L');\n \n time(7,i) = toc;\n tu = matrix.tu;\n uh = tu; %uh(matrix.mapper) = u;\n \n %% 5. Postprocess: Calculating Errors\n tic\n errND = max(abs(uh - tu)); % Error on nodes\n err.nd = errND; err.inf = 0; err.l2 = 0; err.h1 = 0;\n if computErr == 1\n disp(' '); disp('Start computing error in Inf norm');\n eNorm = 'inf';\n errInfN = getErrVIFE3D(uh, pde, mesh, meshI, femI, fem, eNorm);\n eNorm = 'L2'; disp(['Start computing error in ',eNorm,' norm']);\n errL2 = getErrVIFE3D(uh, pde, mesh, meshI, femI, fem, eNorm);\n eNorm = 'H1x'; disp(['Start computing error in ',eNorm,' norm']);\n errH1x = getErrVIFE3D(uh, pde, mesh, meshI, femI, fem, eNorm);\n eNorm = 'H1y'; disp(['Start computing error in ',eNorm,' norm']);\n errH1y = getErrVIFE3D(uh, pde, mesh, meshI, femI, fem, eNorm);\n eNorm = 'H1z'; disp(['Start computing error in ',eNorm,' norm']);\n errH1z = getErrVIFE3D(uh, pde, mesh, meshI, femI, fem, eNorm);\n \n disp(' ')\n err.inf = max([errND,errInfN]);\n err.l2 = errL2;\n err.h1 = sqrt(errH1x^2+errH1y^2+errH1z^2);\n end\n time(8,i) = toc;\n time(9,i) = 1e6*sum(time(2:8,i))/length(mesh.t);\n error(i,1) = errND; error(i,2) = err.inf;\n error(i,3) = err.l2; error(i,4) = err.h1;\n \n %% 6: Display Output\n disp(' ')\n disp('Errors')\n disp('Node Inf norm L2 norm H1 norm')\n formatSpec = '%6.4e %6.4e %6.4e %6.4e\\n';\n fprintf(formatSpec, err.nd, err.inf, err.l2, err.h1)\n \n if i > 1\n format short\n rNd = log(err0.nd/err.nd)./log(h0/h);\n rInf = log(err0.inf/err.inf)./log(h0/h);\n rL2 = log(err0.l2/err.l2)./log(h0/h);\n rH1 = log(err0.h1/err.h1)./log(h0/h);\n disp(' ')\n disp('Convergence Rate')\n disp('Node Inf norm L2 norm H1 norm')\n formatSpec = '%6.4f %6.4f %6.4f %6.4f\\n';\n fprintf(formatSpec, rNd, rInf, rL2, rH1)\n ratio(i,:) = [rNd,rInf,rL2,rH1];\n end\n err0 = err; h0 = h;\n \n disp(' '); disp('CPU Time')\n disp(' N Mesh FEM MeshI FemI Matrix Solve Error Time/1M cell')\n formatSpec = '%4i %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f\\n';\n fprintf(formatSpec, time(:,1:i))\n \n %% 6. Plot Solution and Error\n if showErr == 1\n end\n \nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/IVEM/checkVIFEMrate3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5971022623481568}} {"text": "function [rh,rg,h,g]=rh2rg(rh)\n\n%RH2RG Calculates all the filters from the synthesis lowpass\n%\t in the orthogonal case.\n%\n%\t [RH,RG,H,G]=RH2RG(RH) begins with the synthesis lowpass\n%\t filter (RH) and returns the synthesis highpass filter (RG),\n%\t the analysis lowpass filter (H) and the analysis highpass\n%\t filter (G).\n%\t\n%\t It is an auxiliary function for orthogonal filters design.\n\n%--------------------------------------------------------\n% Copyright (C) 1994, 1995, 1996, by Universidad de Vigo \n% \n% \n% Uvi_Wave is free software; you can redistribute it and/or modify it \n% under the terms of the GNU General Public License as published by the \n% Free Software Foundation; either version 2, or (at your option) any \n% later version. \n% \n% Uvi_Wave is distributed in the hope that it will be useful, but WITHOUT \n% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or \n% FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License \n% for more details. \n% \n% You should have received a copy of the GNU General Public License \n% along with Uvi_Wave; see the file COPYING. If not, write to the Free \n% Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. \n% \n% Author: Nuria Gonzalez Prelcic\n% e-mail: Uvi_Wave@tsc.uvigo.es\n%--------------------------------------------------------\n\n% Calculate rg from rh.\n\nfor i=1:length(rh) \n\trg(i) = -(-1)^i*rh(length(rh)-i+1);\nend \n\n% Calculate h and g\n\nh=rh(length(rh):-1:1);\ng=rg(length(rg):-1:1);\n", "meta": {"author": "alexandrebarachant", "repo": "kaggle-seizure-prediction-challenge-2016", "sha": "00f937cc7710977dc812d9fc675864e2b8288658", "save_path": "github-repos/MATLAB/alexandrebarachant-kaggle-seizure-prediction-challenge-2016", "path": "github-repos/MATLAB/alexandrebarachant-kaggle-seizure-prediction-challenge-2016/kaggle-seizure-prediction-challenge-2016-00f937cc7710977dc812d9fc675864e2b8288658/Andriy/code/rh2rg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5971022623481568}} {"text": "function [x_cplx,opt_val,lb_seq,ub_seq] = CE_similarity_ComRad( H,y,power,ee,x0,cle )\n% Branch and Bound Method for ComRad CEP\n% Detailed explanation goes here\nN = length(x0);\namp = sqrt(power/N); % Amplitude of the Transmit Signal\ny_wave = sqrt(power*cle)*[real(y);imag(y)]; % Equivalent Real Desired Symbol\nH_wave = amp*[real(H),imag(H);-imag(H),real(H)]; % Equivalent Real Channel\nx0_wave = [real(x0);imag(x0)];\ndelta = acos(1-ee^2/2);\nfor ii = 1:N\n l(ii,1) = angle(x0(ii))-delta;\n u(ii,1) = angle(x0(ii))+delta; %Initialized Upper and Lower Bound\nend \n\nA = zeros(N,2*N);\nfor ii = 1:N\n A(ii,ii) = cos((l(ii)+u(ii))/2)/cos(delta);\n A(ii,ii+N) = sin((l(ii)+u(ii))/2)/cos(delta);\nend \n\nmax_iternum = 200; %Maximum Iteration Number\nepsl = 1e-3; %Tolerence\nepsl1 = 1e-6;\n\n[x,LB] = QCQP_LB1( H_wave,y_wave,N,l,u); %Initialized LB and x\n[x_nml1,UB1] = normalize_UB( H_wave,y_wave,x,N,l,u); %Initialized Normalization UB\n[x_nml2,UB2] = QCQP_UB( H_wave,y_wave,N,l,u,x_nml1); % fmincon UB\n[x_nml,UB] = QCQP_UB( H_wave,y_wave,N,l,u,x_nml2); % fmincon UB\nLB_start = LB;\nUB_start = UB;\n\nprob_list = zeros(max_iternum+100,4*N+1); %Problem list initialization\nprob_list(1,:)=[x',l',u',LB];\nused = 1;\nlbest = LB;\nubest = UB;\nx_opt = x_nml;\n\nlb_seq = lbest;\nub_seq = ubest;\n\n% if (ubest-lbest)/abs(ubest)tMin)\n xA=xA+s*t1;\n end\n end\n\n xAL(:,curPt)=xA;\n xBL(:,curPt)=xB;\nend\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Geometry/clipLine2ConvexPolygon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5971022571489016}} {"text": "function [beta,betastar] = igls_orig(y, x, Vy, type)\n% function [betastar] = igls(y, x, Vy)\n%\n% Variance Component Estimation using IGLS/RIGLS\n%\n% y = d + cx + epsilon where epsilon ~ N(0,sigma*Vy)\n%\n% d ~ N(0, sigma_d) and c ~ N(0, sigma_c)\n%\n% Calculate d, c, sigma, sigma_d and sigma_c using Maximum Likelihood\n% methods (IGLS) and Restricted Maximum Likelihood methods (RIGLS).\n%\n% y - matrix T x subjects\n% x - matrix T x subjects\n% Vy - matrix T x T x subjects\n% type = 'i' IGLS\n% type = 'r' RIGLS\n%\n% By Martin Lindquist, April 2007\n%\n% Example:\n% \n% len = 200; sub =20;\n% x = zeros(len,sub);\n% x(11:20,:) = 2;\n% x = x+ normrnd(0,0.1,len,sub);\n% c = normrnd(0.5,0.1,sub,1);\n% d = normrnd(3,0.2,sub,1);\n% y=x;\n% for i=1:sub, y(:,i) = d(i) + c(i).*x(:,i) + normrnd(0,0.5,len,1); end;\n% Vy = zeros(len,len,sub);\n% for i=1:sub, Vy(:,:,i) = eye(len,len).*0.5; end;\n% \n% [beta, betastar] = igls(y, x, Vy,'i')\n%\nc1= clock;\n[T, sub] = size(y); % Length of y vector and Number of subjects\n\none = zeros(T,1)+1; % Vector of ones\nnull = zeros(T,1); % Vector of zeros\n\nepsilon = 0.001; \nnum_iter = 5;\n\nlen = sub*T; % Total number of observations\nz = reshape(y,len,1); % Concatenated data\nD = [zeros(len,1)+1 reshape(x,len,1)]; % Design matrix\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Step 1: Find the OLS solution \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nbeta = pinv(D)*z; % Beta values\nresid = z - D*beta; % Residuals\n\nystar = [];\nif (type == 'i'), % IGLS\n for i=1:sub,\n tmp = vech(resid(((i-1)*T+1):(i*T))*resid(((i-1)*T+1):(i*T))'); % Find vech of estimated covariance\n ystar = [ystar; tmp];\n end; \nelseif (type == 'r'), % RIGLS\n for i=1:sub,\n Dtmp = D((((i-1)*T+1):(i*T)),:);\n rtmp = resid(((i-1)*T+1):(i*T));\n rig = rtmp*rtmp' + Dtmp*inv(Dtmp'*Dtmp)*Dtmp';\n tmp = vech(rig); % Find vech of estimated covariance \n ystar = [ystar; tmp];\n end;\nend;\n \nclear tmp rtmp rig Dtmp \nG = Create_Design_Eq2(y, x, Vy); % Create design matrix for variance estimation\nbetastar = pinv(G)*ystar; % Estimate variance components\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Step 2: Iterate \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\ncnt = 0;\nbetastar_old = betastar+10;\n\niSigma = zeros(len,len); \n\nwhile(cnt < num_iter | sum((betastar-betastar_old).^2)> epsilon),\n\n num = size(G,1)/sub;\n \n for i=1:sub,\n iSigma(((i-1)*T+1):(i*T),((i-1)*T+1):(i*T)) = ivech(G(((i-1)*num+1):(i*num),:)*betastar);\n end;\n \n beta = inv(D'*iSigma*D)*D'*iSigma*z; % Beta values\n resid = z - D*beta; % Residuals\n\n ystar = [];\n\n if (type == 'i'), % IGLS \n for i=1:sub,\n tmp = vech(resid(((i-1)*T+1):(i*T))*resid(((i-1)*T+1):(i*T))'); % Find vech of estimated covariance\n ystar = [ystar; tmp];\n end;\n elseif (type == 'r'), % RIGLS\n for i=1:sub,\n Dtmp = D((((i-1)*T+1):(i*T)),:);\n rtmp = resid(((i-1)*T+1):(i*T));\n rig = rtmp*rtmp' + Dtmp*inv(Dtmp'*iSigma((((i-1)*T+1):(i*T)),(((i-1)*T+1):(i*T)))*Dtmp)*Dtmp';\n tmp = vech(rig); % Find vech of estimated covariance\n ystar = [ystar; tmp];\n end; \n end;\n\n clear tmp rtmp rig Dtmp \n\n betastar_old = betastar;\n betastar = pinv(G)*ystar; % Estimate variance components\n\n cnt = cnt+1\nend;\n\nc2 = clock;\nc2 - c1\nreturn;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Subfunctions\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [G] = Create_Design_Eq2(y, x, Vy)\n% function [G] = Create_Design(y, x, Vy)\n%\n% Create Design matrix for estimation of variance componets\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[T, sub] = size(x);\nlen = T*(T+1)/2;\nONE = zeros(len,1)+1;\n\nG = [];\nH = [];\n\nfor i=1:sub,\n \n XX = x(:,i)*x(:,i)';\n\n Gtmp = zeros(len,3);\n Gtmp(:,1) = ONE;\n Gtmp(:,2) = vech(XX);\n Gtmp(:,3) = vech(Vy(:,:,i)); \n G = [G; Gtmp];\n \nend;\n\n\nreturn;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction V = vech(Mat)\n% function V = vech(Mat)\n%\n% Calculate vech for the matrix Mat\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nV = Mat(logical(tril(ones(size(Mat)))));\n\nreturn;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction Mat = ivech(V)\n% function Mat = vech(V)\n%\n% Calculate the \"inverse\" of the vech function\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nlen = length(V);\ndim = -0.5 + sqrt(0.25 + 2*len);\nMat = zeros(dim,dim);\nind=1;\n\nfor i=1:dim\n for j=i:dim\n Mat(j,i)=V(ind);\n ind=ind+1;\n end\nend\n\nreturn;\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/Statistics_tools/Iterative_Generalized_Least_Squares/igls_orig.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5970977479312484}} {"text": "function D = computeDistMatrix_AVFC (data,T,options)\n%\n% It uses KL-divergence to compute a subject-by-subject distance matrix\n% of average FC matrices (on fMRI). \n%\n% INPUT\n% data observations; in this case it has to be a cell, each with\n% the data for one subject\n% T length of series, also a cell. \n% \n% OUTPUT\n% D (N by N) distance matrix, with the distance between each\n% pair of subjects in \"HMM space\"\n%\n% Author: Diego Vidaurre, OHBA, University of Oxford (2020)\n\nif ~iscell(data) || ~iscell(T), error('X and T must both be cells'); end \n\nif nargin<3, options = struct(); end\n\nN = length(data);\n\nfor n = 1:N\n if ischar(data{n})\n fsub = data{n};\n loadfile_sub;\n else\n X = data{n};\n end\n X = preprocdata(X,T{n},options);\n if n == 1\n ndim = size(X,2);\n V = zeros(ndim,ndim,N);\n end\n V(:,:,n) = X' * X;\nend\n\nD = NaN(N);\ntry\n for n1 = 1:N-1\n for n2 = n1+1:N\n D(n1,n2) = ( wishart_kl(V(:,:,n1),V(:,:,n2),sum(T{n1}),sum(T{n2})) + ...\n wishart_kl(V(:,:,n2),V(:,:,n1),sum(T{n2}),sum(T{n1})) ) /2;\n D(n2,n1) = D(n1,n2);\n end\n end\ncatch\n for n = 1:N\n V(:,:,n) = V(:,:,n) + 0.0001*eye(ndim);\n end\n for n1 = 1:N-1\n for n2 = n1+1:N\n D(n1,n2) = ( wishart_kl(V(:,:,n1),V(:,:,n2),sum(T{n1}),sum(T{n2})) + ...\n wishart_kl(V(:,:,n2),V(:,:,n1),sum(T{n2}),sum(T{n1})) ) /2;\n D(n2,n1) = D(n1,n2);\n end\n end \nend\n\nend\n\n\nfunction X = preprocdata(X,T,options)\n\n% Filtering\nif isfield(options,'filter') && ~isempty(options.filter)\n X = filterX(X,T,options.Fs,options.filter);\nend\n% Detrend X\nif isfield(options,'detrend') && options.detrend\n X = detrendX(X,T);\nend\n% Hilbert envelope\nif isfield(options,'onpower') && options.onpower\n X = rawsignal2power(X,T);\nend\n% Embedding\nif isfield(options,'embeddedlags') && length(options.embeddedlags) > 1\n X = embeddata(X,T,options.embeddedlags);\nend\nX = zscore(X);\n\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/utils/prediction/computeDistMatrix_AVFC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5970535173819085}} {"text": "function [u,w,AE,AI,isExteriorTElem,isExteriorSElem] = interfacefittedPoisson(node,telem,selem,pde,interfaceEdge,bdEdge,option)\n%% INTERFACEFITTEDPOISSON Poisson equation: P1 linear element.\n%\n% u = INTERFACEPOISSON(node,telem,selem,pde,E) produces the linear finite element\n% approximation of the interface Poisson equation\n% \n% input:\n% node, N*2 matrix, node(i,:) are the xy coordinates of i-th node;\n% telem, NTT*3 matrix, telem(j,:) are the three global indices of the\n% vertices ofj-th triangle element;\n% selem,NTS*4 matrix, selem(j,:) are the four global indices of the\n% vertices of j-th quad element;\n%\n% \n\n[N,Dim] = size(node); \nNdof = N;\n\n%% Geometry structures of interface meshes\n\nNTS = size(selem,1);\nisExteriorSElem = false(NTS,1);\nc = (node(selem(:,1),:) + node(selem(:,2),:) + node(selem(:,3),:)+node(selem(:,4),:))/4;\nisExteriorSElem(pde.phi(c)>0) = true;\n\nNTT = size(telem,1);\nisExteriorTElem = false(NTT,1);\nc = (node(telem(:,1),:) + node(telem(:,2),:) + node(telem(:,3),:))/3;\nisExteriorTElem(pde.phi(c)>0) = true;\n\n[sAE,sbE] = getstiffmatrixandrhsonquad(node,selem(isExteriorSElem,:));\n[sAI,sbI] = getstiffmatrixandrhsonquad(node,selem(~isExteriorSElem,:));\n[tAE,tbE] = getstiffmatrixandrhsontri(node,telem(isExteriorTElem,:));\n[tAI,tbI] = getstiffmatrixandrhsontri(node,telem(~isExteriorTElem,:));\n\n\nA = sAE + sAI + tAE + tAI;\nb = sbE + sbI + tbE + tbI;\n\nAI = sAI + tAI;\nAE = sAE + tAE;\n\nflux = getfluxconditiononinterface(node,interfaceEdge);\nb = b - flux;\n\n\n\n%% Extend w to the whole domain\nisInterfaceNode = false(Ndof,1);\nisInterfaceNode(interfaceEdge(:)) = true;\ninterfaceNode = find(isInterfaceNode);\n\nisInNode = false(Ndof,1);\ninteriorSElem = selem(~isExteriorSElem,:);\ninteriorTElem = telem(~isExteriorTElem,:);\nisInNode([interiorSElem(:);interiorTElem(:)]) = true;\ninNode = find(isInNode & ~isInterfaceNode);\n\nw = zeros(Ndof,1);\nFI= zeros(Ndof,1);\nw(interfaceNode) = pde.exactw(node(interfaceNode,:));\nFI = FI - AI*w;\nextensionoption.printlevel = 0;\nw(inNode) = amg(AI(inNode, inNode),FI(inNode),extensionoption);\n\n%% Dirichlet boundary condition\nisBdNode = false(Ndof,1); \nisBdNode(bdEdge(:)) = true;\nbdNode = find(isBdNode);\n\nu = zeros(Ndof,1); \nu(bdNode) = pde.g_D(node(bdNode,:));\nb = b - A*u+AI*w;\nb(bdNode) = u(bdNode);\n\nfreeNode = find(~isBdNode);\nbdidx = zeros(Ndof,1); \nbdidx(bdNode) = 1;\nTbd = spdiags(bdidx,0,Ndof,Ndof);\nT = spdiags(1-bdidx,0,Ndof,Ndof);\nAD = T*A*T + Tbd;\n\n%% Solve the system of linear equations\nif isempty(freeNode), return; end\n% Set up solver type\nif isempty(option) || ~isfield(option,'solver') % no option.solver\n if Ndof <= 1e3 % Direct solver for small size systems\n option.solver = 'direct';\n else % MGCG solver for large size systems\n option.solver = 'mg';\n end\nend\nsolver = option.solver;\n% solve\nswitch solver\n case 'direct'\n tic;\n u(freeNode) = AD(freeNode,freeNode)\\b(freeNode);\n residual = norm(b - AD*u);\n info = struct('solverTime',toc,'itStep',0,'err',residual,'flag',2,'stopErr',residual);\n case 'none'\n info = struct('solverTime',[],'itStep',0,'err',[],'flag',3,'stopErr',[]);\n case 'amg'\n option.solver = 'CG';\n [u(freeNode),info] = amg(AD(freeNode,freeNode),b(freeNode),option); \nend\n\n%%\neqn = struct('A',AD,'b',b,'freeNode',freeNode);\n\n %% Assemble stiffness matrix and rhs on quad mesh\n function [A,b] = getstiffmatrixandrhsonquad(node,elem)\n [NT,NV] = size(elem);\n % generate sparse pattern\n ii = zeros(10*NT,1); jj = zeros(10*NT,1);\n index = 0;\n for i = 1:4\n for j = i:4\n ii(index+1:index+NT) = double(elem(:,i));\n jj(index+1:index+NT) = double(elem(:,j));\n index = index + NT;\n end\n end\n % quadrature points\n if ~isfield(pde,'d'), pde.d = []; end\n if ~isfield(option,'dquadorder')\n option.dquadorder = 2; % default order is exact for quadratic function\n end\n [pts, weight] = quadptsquad(option.dquadorder);\n nQuad = size(pts,1);\n % compute non-zeros\n sA = zeros(10*NT,nQuad);\n for p = 1:nQuad\n % Dphi at quadrature points\n [phi, Dphip, J] = quadbasis(node,elem,pts(p,:));\n index = 0;\n for i = 1:4\n for j = i:4\n Aij = 0;\n if isempty(pde.d) || isnumeric(pde.d)\n Aij = Aij + weight(p)*dot(Dphip(:,:,i),Dphip(:,:,j),2);\n else\n pxy = zeros(NT, Dim);\n for ip = 1:Dim\n xi = node(:,ip);\n pxy(:,ip) = xi(elem)*phi;\n end\n Aij = Aij + weight(p)*dot(Dphip(:,:,i),Dphip(:,:,j),2).*pde.d(pxy);\n end\n if ~isempty(pde.d) && isnumeric(pde.d) % d is piecewise constant\n Aij = pde.d.*Aij;\n end\n Aij = Aij.*J;\n sA(index+1:index+NT,p) = Aij;\n index = index + NT;\n end\n end\n end\n sA = sum(sA,2);\n % assemble the matrix\n diagIdx = (ii == jj); upperIdx = ~diagIdx;\n A = sparse(ii(diagIdx),jj(diagIdx),sA(diagIdx),Ndof,Ndof);\n AU = sparse(ii(upperIdx),jj(upperIdx),sA(upperIdx),Ndof,Ndof);\n A = A + AU + AU';\n clear Aij ii jj Dphip\n \n %% Assemble the right hand side\n b = zeros(Ndof,1);\n if ~isfield(option,'fquadorder')\n option.fquadorder = 3; % default order\n end\n if ~isfield(pde,'f') || (isreal(pde.f) && (pde.f==0))\n pde.f = [];\n end\n \n if ~isempty(pde.f)\n [pts, weight] = quadptsquad(option.fquadorder);\n nQuad = size(pts,1);\n bt = zeros(NT,NV);\n for p = 1:nQuad\n % quadrature points in the x-y coordinate\n [phi, ~, J] = quadbasis(node,elem, pts(p,:));\n pxy = zeros(NT, Dim);\n for i = 1:Dim\n xi = node(:,i);\n pxy(:,i) = xi(elem)*phi; % ? questionable\n end\n fp = pde.f(pxy);\n bt = bt + (weight(p)*fp.*J)*phi';\n end\n b = accumarray(elem(:),bt(:),[Ndof 1]);\n end\n \n end\n\n %% Assemble the stiffmatrix and right hand side on triangle mesh\n function [A,b] = getstiffmatrixandrhsontri(node,elem)\n NT = size(elem,1);\n % quadrature points\n center = (node(elem(:,1),:) + node(elem(:,2),:) + node(elem(:,3),:))/3;\n % Diffusion coefficient\n if isfield(pde,'d') && ~isempty(pde.d)\n if isnumeric(pde.d)\n K = pde.d; % d is an array\n else % d is a function\n K = pde.d(center);\n end\n else\n K = [];\n end\n [Dphi,area] = gradbasis(node,elem);\n A = sparse(Ndof,Ndof);\n for i = 1:3\n for j = i:3\n Aij = (Dphi(:,1,i).*Dphi(:,1,j)+Dphi(:,2,i).*Dphi(:,2,j)).*area;\n if ~isempty(K)\n Aij = K.*Aij;\n end\n if (j==i)\n A = A + sparse(elem(:,i),elem(:,j),Aij,Ndof,N);\n else\n A = A + sparse([elem(:,i);elem(:,j)],[elem(:,j);elem(:,i)],[Aij; Aij],Ndof,Ndof);\n end\n end\n end\n\n b = zeros(Ndof,1);\n if ~isfield(option,'fquadorder')\n option.fquadorder = 3; % default order\n end\n if ~isfield(pde,'f') || (isreal(pde.f) && (pde.f==0))\n pde.f = [];\n end\n if ~isempty(pde.f)\n [lambda,weight] = quadpts(option.fquadorder);\n nQuad = size(lambda,1);\n ft = zeros(NT,3);\n for p = 1:nQuad\n % quadrature points in the x-y coordinate\n pxy = lambda(p,1)*node(elem(:,1),:) ...\n + lambda(p,2)*node(elem(:,2),:) ...\n + lambda(p,3)*node(elem(:,3),:);\n % function values at quadrature points\n fp = pde.f(pxy);\n % evaluate fp outside.\n for j = 1:3\n ft(:,j) = ft(:,j) + lambda(p,j)*weight(p)*fp;\n end\n end\n ft = ft.*[area,area,area];\n b = accumarray(elem(:),ft(:),[Ndof 1]);\n end \n end\n\n %% Neumann boundary condition on interface edges\n function b = getfluxconditiononinterface(node,interfaceEdge)\n ve = node(interfaceEdge(:,1),:) - node(interfaceEdge(:,2),:);\n ve = [-ve(:,2), ve(:,1)];\n edgeLen = sqrt(sum(ve.^2,2));\n if ~isfield(option,'gNquadorder')\n option.gNquadorder = 5; % default order\n end\n [lambda,weight] = quadpts1(option.gNquadorder);\n nQuad = length(weight);\n ge = zeros(size(interfaceEdge,1),2);\n for i = 1:nQuad\n pxy=lambda(i,1)*node(interfaceEdge(:,1),:)+lambda(i,2)*node(interfaceEdge(:,2),:);\n leftpt = pxy - ve/2;\n rightpt = pxy + ve/2;\n pxy = findintersectbisect(pde.phi,leftpt,rightpt);\n q = pde.exactq(pxy);\n ge(:,1)=ge(:,1)+weight(i)*lambda(i,1)*q;\n ge(:,2)=ge(:,2)+weight(i)*lambda(i,2)*q;\n end\n ge = ge.*[edgeLen,edgeLen];\n b = accumarray(interfaceEdge(:), ge(:),[Ndof,1]);\n end\n\nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/equation/interfacefittedPoisson.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.5970535016764943}} {"text": "function pos2 = nutate (tjd, pos1)\n\n% this function nutates equatorial rectangular coordinates from\n% the mean dynamical equator and equinox of epoch to the true\n% equator and equinox of epoch. see explanatory supplement to the\n% astronomical almanac, pp. 114-115.\n\n% input\n\n% tjd = tdb julian date of epoch\n\n% pos1 = position vector, geocentric equatorial rectangular\n% coordinates, referred to mean dynamical equator and\n% equinox of epoch\n\n% output\n\n% pos2 = position vector, geocentric equatorial rectangular\n% coordinates, referred to true equator and equinox of epoch\n\n% note: if tjd is negative, inverse nutation (true to mean) is applied.\n\n% ported from NOVAS 3.0\n\n%%%%%%%%%%%%%%%%%%%%%%%\n\nseccon = 180.d0 * 3600.d0 / pi;\n\ntjd1 = abs(tjd);\n\n[oblm, oblt, eqeq, dpsi, deps] = etilt (tjd1);\n\noblm = oblm * 3600.d0 / seccon;\n\noblt = oblt * 3600.d0 / seccon;\n\ndpsi = dpsi / seccon;\n\ndeps = deps / seccon;\n\ncobm = cos(oblm);\n\nsobm = sin(oblm);\n\ncobt = cos(oblt);\n\nsobt = sin(oblt);\n\ncpsi = cos(dpsi);\n\nspsi = sin(dpsi);\n\n% compute elements of nutation rotation matrix\n\nxx = cpsi;\nyx = -spsi * cobm;\nzx = -spsi * sobm;\n\nxy = spsi * cobt;\nyy = cpsi * cobm * cobt + sobm * sobt;\nzy = cpsi * sobm * cobt - cobm * sobt;\n\nxz = spsi * sobt;\nyz = cpsi * cobm * sobt - sobm * cobt;\nzz = cpsi * sobm * sobt + cobm * cobt;\n\nif (tjd < 0.0d0)\n\n % perform rotation from true to mean\n\n pos2(1) = xx * pos1(1) + xy * pos1(2) + xz * pos1(3);\n\n pos2(2) = yx * pos1(1) + yy * pos1(2) + yz * pos1(3);\n\n pos2(3) = zx * pos1(1) + zy * pos1(2) + zz * pos1(3);\n\nelse\n\n % perform rotation from mean to true\n\n pos2(1) = xx * pos1(1) + yx * pos1(2) + zx * pos1(3);\n\n pos2(2) = xy * pos1(1) + yy * pos1(2) + zy * pos1(3);\n\n pos2(3) = xz * pos1(1) + yz * pos1(2) + zz * pos1(3);\n\nend\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/nutate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5970019279970055}} {"text": "% A Thin Plate Subjected to Uniform Traction\n% T3 Implementation\n% 2 elements\n% clear memory\nclear all; \nclc;\nclose all;\n% materials\nE = 30e6; poisson = 0.30; thickness = 1;\n\n% matrix D\nD=E/(1-poisson^2)*[1 poisson 0;poisson 1 0;0 0 (1-poisson)/2];\n \n% trivial preprocessing\n% numberElements: number of elements\nnumberElements=2; \n% numberNodes: number of nodes\nnumberNodes=4;\n% coordinates and connectivities\nelementNodes=[1 3 2; 1 4 3];\nnodeCoordinates=[0, 0; 0, 10; 20, 10; 20, 0];\ndrawingMesh(nodeCoordinates,elementNodes,'T3','k-o');\n\n% GDof: global number of degrees of freedom\nGDof=2*numberNodes; \n\n% boundary conditions \nprescribedDof=[1 2 3 4]';\n% force vector \nforce=zeros(GDof,1);\nforce(5)=5000; force(7) =5000;\n\n% calculation of the system stiffness matrix\nstiffness=formStiffness2D(GDof,numberElements,...\n elementNodes,numberNodes,nodeCoordinates,D,thickness);\n\n% solution\ndisplacements=solution(GDof,prescribedDof,stiffness,force);\n\n% output displacements\noutputDisplacements(displacements, numberNodes, GDof);\n\noutputStress(displacements,numberElements,...\n elementNodes,nodeCoordinates,D)", "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/FEM/T3Simple_solution/Problem_1/problem2dTensileT3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506726044381, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5969934338619092}} {"text": "function area = polySgnArea(x,y)\n% area of an orientation with sign depending of orientation\n\narea = 0.5*sum((y(2:end)-y(1:end-1)) .* (x(2:end)+x(1:end-1)));\n \nend\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/EBSDAnalysis/@grain2d/private/polySgnArea.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5969708485551023}} {"text": "function res = imGeodesicPropagation(img, varargin)\n%IMGEODESICPROPAGATION Compute geodesic propagation for each foreground pixel\n%\n% RES = imGeodesicPropagation(IMG);\n% IMG is a binary image. For each foreground pixel, the geodesic\n% progagation is defined as the maximum geodesic distance to another\n% pixel of the foreground. If the foreground is not connected this\n% distance equals infinity.\n%\n% RES = imGeodesicPropagation(IMG, WEIGHTS);\n% use different weights for the computation of distances. See\n% imChamferDistance for further details.\n%\n% Note:\n% * As the algorithm propagates geodesic distances from each foreground\n% pixel, the computation time may be expensive.\n% * the function is defined for both 2D and 3D images\n%\n%\n% Example \n% % Compute geodesic propagation in a L-shape\n% img = zeros(20, 20);\n% img(4:16, 4:9) = 1;\n% img(11:16, 4:16) = 1;\n% prop = imGeodesicPropagation(img);\n% imagesc(prop);\n% colormap([1 1 1 ; jet]);\n%\n% % Compute geodesic propagation in a set of particles\n% prop = zeros(size(img));\n% lbl = bwlabel(img);\n% for i = 1:max(lbl(:))\n% prop = max(prop, imGeodesicPropagation(lbl==i));\n% end\n% imagesc(prop);\n% colormap([1 1 1 ; jet]);\n%\n% See also\n% imGeodesics, imGeodesicDistanceMap, imGeodesicRadius, imGeodesicExtremities\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2009-05-22, using Matlab 7.7.0.471 (R2008b)\n% Copyright 2009 INRA - Cepia Software Platform.\n\nimg = img > 0;\nres = zeros(size(img));\n\ndim = size(img);\nif length(dim) == 2\n for i = 1:dim(1)\n for j = 1:dim(2)\n if ~img(i,j)\n continue;\n end\n \n marker = false(size(img));\n marker(i, j) = true;\n \n dist = imGeodesicDistanceMap(img, marker, varargin{:});\n res(i, j) = max(dist(img));\n end\n end\n \nelseif length(dim) == 3\n for k = 1:dim(3)\n for j = 1:dim(2)\n for i = 1:dim(1)\n if ~img(i,j,k)\n continue;\n end\n \n marker = false(size(img));\n marker(i, j, k) = true;\n \n dist = imGeodesicDistanceMap3d(img, marker, varargin{:});\n res(i, j, k) = max(dist(img));\n end\n end\n end\n\nelse\n error('Requires a 2D or a 3D image');\nend\n", "meta": {"author": "mattools", "repo": "matImage", "sha": "94d892c7beac0db32daadf2646ce37f58e894caf", "save_path": "github-repos/MATLAB/mattools-matImage", "path": "github-repos/MATLAB/mattools-matImage/matImage-94d892c7beac0db32daadf2646ce37f58e894caf/matImage/imGeodesics/imGeodesicPropagation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.5968930778108887}} {"text": "function [cepstra,aspectrum,pspectrum] = melfcc(samples, sr, varargin)\n%[cepstra,aspectrum,pspectrum] = melfcc(samples, sr[, opts ...])\n% Calculate Mel-frequency cepstral coefficients by:\n% - take the absolute value of the STFT\n% - warp to a Mel frequency scale\n% - take the DCT of the log-Mel-spectrum\n% - return the first components\n% This version allows a lot of options to be controlled, as optional \n% 'name', value pairs from the 3rd argument on: (defaults in parens)\n% 'wintime' (0.025): window length in sec\n% 'hoptime' (0.010): step between successive windows in sec\n% 'numcep' (13): number of cepstra to return\n% 'lifterexp' (0.6): exponent for liftering; 0 = none; < 0 = HTK sin lifter\n% 'sumpower' (1): 1 = sum abs(fft)^2; 0 = sum abs(fft)\n% 'preemph' (0.97): apply pre-emphasis filter [1 -preemph] (0 = none)\n% 'dither' (0): 1 = add offset to spectrum as if dither noise\n% 'minfreq' (0): lowest band edge of mel filters (Hz)\n% 'maxfreq' (4000): highest band edge of mel filters (Hz)\n% 'nbands' (40): number of warped spectral bands to use\n% 'bwidth' (1.0): width of aud spec filters relative to default\n% 'dcttype' (2): type of DCT used - 1 or 2 (or 3 for HTK or 4 for feac)\n% 'fbtype' ('mel'): frequency warp: 'mel','bark','htkmel','fcmel'\n% 'usecmp' (0): apply equal-loudness weighting and cube-root compr.\n% 'modelorder' (0): if > 0, fit a PLP model of this order\n% 'broaden' (0): flag to retain the (useless?) first and last bands\n% 'useenergy' (0): overwrite C0 with true log energy\n% The following non-default values nearly duplicate Malcolm Slaney's mfcc\n% (i.e. melfcc(d,16000,opts...) =~= log(10)*2*mfcc(d*(2^17),16000) )\n% 'wintime': 0.016\n% 'lifterexp': 0\n% 'minfreq': 133.33\n% 'maxfreq': 6855.6\n% 'sumpower': 0\n% The following non-default values nearly duplicate HTK's MFCC\n% (i.e. melfcc(d,16000,opts...) =~= 2*htkmelfcc(:,[13,[1:12]])'\n% where HTK config has PREEMCOEF = 0.97, NUMCHANS = 20, CEPLIFTER = 22, \n% NUMCEPS = 12, WINDOWSIZE = 250000.0, USEHAMMING = T, TARGETKIND = MFCC_0)\n% 'lifterexp': -22\n% 'nbands': 20\n% 'maxfreq': 8000\n% 'sumpower': 0\n% 'fbtype': 'htkmel'\n% 'dcttype': 3\n% For more detail on reproducing other programs' outputs, see\n% http://www.ee.columbia.edu/~dpwe/resources/matlab/rastamat/mfccs.html\n%\n% 2005-04-19 dpwe@ee.columbia.edu after rastaplp.m. \n% Uses Mark Paskin's process_options.m from KPMtools\n% $Header: /Users/dpwe/matlab/rastamat/RCS/melfcc.m,v 1.3 2012/09/03 14:01:26 dpwe Exp dpwe $\n\nif nargin < 2; sr = 16000; end\n\n% Parse out the optional arguments\n[wintime, hoptime, numcep, lifterexp, sumpower, preemph, dither, ...\n minfreq, maxfreq, nbands, bwidth, dcttype, fbtype, usecmp, modelorder, ...\n broaden, useenergy] = ...\n process_options(varargin, 'wintime', 0.025, 'hoptime', 0.010, ...\n 'numcep', 13, 'lifterexp', 0.6, 'sumpower', 1, 'preemph', 0.97, ...\n\t 'dither', 0, 'minfreq', 0, 'maxfreq', 4000, ...\n\t 'nbands', 40, 'bwidth', 1.0, 'dcttype', 2, ...\n\t 'fbtype', 'mel', 'usecmp', 0, 'modelorder', 0, ...\n 'broaden', 0, 'useenergy', 0);\n\nif preemph ~= 0\n samples = filter([1 -preemph], 1, samples);\nend\n\n% Compute FFT power spectrum\n[pspectrum,logE] = powspec(samples, sr, wintime, hoptime, dither);\n\naspectrum = audspec(pspectrum, sr, nbands, fbtype, minfreq, maxfreq, sumpower, bwidth);\n\nif (usecmp)\n % PLP-like weighting/compression\n aspectrum = postaud(aspectrum, maxfreq, fbtype, broaden);\nend\n\nif modelorder > 0\n\n if (dcttype ~= 1) \n disp(['warning: plp cepstra are implicitly dcttype 1 (not ', num2str(dcttype), ')']);\n end\n \n % LPC analysis \n lpcas = dolpc(aspectrum, modelorder);\n\n % convert lpc to cepstra\n cepstra = lpc2cep(lpcas, numcep);\n\n % Return the auditory spectrum corresponding to the cepstra?\n% aspectrum = lpc2spec(lpcas, nbands);\n % else return the aspectrum that the cepstra are based on, prior to PLP\n\nelse\n \n % Convert to cepstra via DCT\n cepstra = spec2cep(aspectrum, numcep, dcttype);\n\nend\n\ncepstra = lifter(cepstra, lifterexp);\n\nif useenergy\n cepstra(1,:) = logE;\nend\n \n\n", "meta": {"author": "stephencwelch", "repo": "Perceptual-Coding-In-Python", "sha": "2993f57570663768c02745019185091a23f021fe", "save_path": "github-repos/MATLAB/stephencwelch-Perceptual-Coding-In-Python", "path": "github-repos/MATLAB/stephencwelch-Perceptual-Coding-In-Python/Perceptual-Coding-In-Python-2993f57570663768c02745019185091a23f021fe/matlabCode/bark_domain_exploration/rastamat/melfcc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.5968622208353669}} {"text": "function [ m, p, t ] = naca4_mpt ( code )\n\n%*****************************************************************************80\n%\n%% NACA4_MPT returns the parameters stored in a NACA 4 digit airfoil code.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 May 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer CODE, the NACA4 code.\n% 0 <= CODE <= 9999.\n%\n% Output, real M, the maximum camber, as a percentage of the chord length.\n% 0 <= M <= 1.0.\n%\n% Output, real P, the relative distance of the occurrence of the maximum \n% camber from the beginning of the chord.\n% 0 <= P <= 1.0.\n%\n% Output, real T, the maximum thickness relative to the chord length.\n% 0 <= T <= 1.0.\n%\n if ( code < 0 || 9999 < code )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'NACA4_MPT - Fatal error!\\n' );\n fprintf ( 1, ' CODE should be an integer between 0 and 9999.\\n' );\n error ( 'NACA4_MPT - Fatal error!' );\n end\n\n m = floor ( code / 1000 );\n code = code - m * 1000;\n m = m / 100.0;\n\n p = floor ( code / 100 );\n code = code - p * 100;\n p = p / 10.0;\n\n t = code / 100.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/naca/naca4_mpt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303384097948, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.596783200039092}} {"text": "function eps = eps_RCUs( i_s, n, r )\neps = mean( exp( - max(0, i_s - log(2^(n*r)-1) ) ) ); % avg pr err \n% eps = mean( exp( - max(0, i_s - log(2^(n*r)-1)-log(2)) ) ); % max pr err\nend", "meta": {"author": "yp-mit", "repo": "spectre", "sha": "57af76799e4eb43aa707cc13c4c5220d281e0b78", "save_path": "github-repos/MATLAB/yp-mit-spectre", "path": "github-repos/MATLAB/yp-mit-spectre/spectre-57af76799e4eb43aa707cc13c4c5220d281e0b78/block-fading-PAT-SNN/eps_RCUs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037221561136, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5967481013902}} {"text": "%% \n% \\documentclass[12pt]{article}\n%\n% \\title{ODEbox: A Toolbox for Ordinary Differential Equations\\\\\n% Sturm Liouville Example 2\\\\\n% The Mathieu Differential Equation}\n% \n% \\author{Matthew Harker and Paul O'Leary\\\\\n% Institute for Automation\\\\\n% University of Leoben\\\\\n% A-8700 Leoben,\n% Austria\\\\\n% URL: automation.unileoben.ac.at\\\\\n% \\\\\n% Original: January 9, 2013\\\\\n% $\\copyright$ 2013\\\\\n% \\\\\n% Last Modified: \\today}\n%%\n% \\section{The Mathieu Differential Equation}\n%\n% This example addresses the solution of the Mathieu differential equation.\n% This equation occurs in conjunction with the modelling of the vibration\n% of a ellptical membrane. The problem has no known analytical solution.\n% %\n% \\begin{equation}\n% -\\ddot{y} + 2 \\,r \\, \\cos( 2 \\, x )= \\lambda \\, y\n% \\hspace{5mm}\n% \\text{with}\n% \\hspace{5mm}\n% y(0) = 0}\n% \\hspace{5mm}\n% \\text{and} \n% \\hspace{5mm}\n% \\dot{y}(\\pi) = 0\n% \\end{equation}\n% %\n% in the closed interval $0 \\leq x \\leq \\pi$.\n%\n%%\n% \\section{tidy up the Workspace}\n%\nclear all;\nclose all;\nsetUpGraphics;\n%%\n% \\section{Define the Nodes and Compute the Basis Functions}\n%\n% Define the number of nodes and the number of basis functions used.\n%\nnoPts = 1000;\nnoBfs = round( noPts/2);\n%%\n% Compute the Chebyshev points, but scaled to form a closed interval\n% $0 \\leq x \\leq \\pi$.\n%\nx = dopNodes( noPts, 'chebyends' );\nx = pi * (x + 1)/2;\n%%\n% Synthesize a complete set of basis functions\n%\nB = dop(x);\n%%\n% \\subsection{Generate the Differentiating Matrix}\n%\n% Synthesize the differentiating matrix with support length $l_s$\n%\nls = 13;\nD = dopDiffLocal( x, ls, ls );\n%%\n% \\subsection{Define the Constraints and Compute the Admissible Functions}\n%\n% Define the constraints\n%\nC = zeros( noPts, 2 );\nC(1,1) = 1;\nC(end,end) = 1;\n%%\n% Compute the set of constrained basis functions, i.e., admissible\n% functions.\n%\nBc = dopConstrain( C, B );\n%%\n% Trucate the basis functions\n%\nBc = Bc(:,1:noBfs);\n%\n%%\n% \\section{Setup the Sturm-Liouville Matrix Linear Differential Operator}\n%\n% Setup the Linear differential operator for the Mathieu differential\n% equation.\n%\nc1 = 0;\nc2 = -50;\ngx = diag(c1 + c2 * cos(2*x)) ;\nL = Bc' * (D * D - gx )* Bc;\n%\n%%\n% \\section{Solve the Eigenvector Problem}\n%\n% Solve the eigenvalue problem\n%\n[Vec, Val] = eig( L );\nvals = -diag( Val );\n%%\n% and sort the solutions.\n%\n[vals, inds] = sort(vals);\nVec = Vec(:,inds);\n%%\n% and compute the final eigenfunctions.\n%\nsols = Bc * Vec;\n%%\n% \\section{Close Pair of Eigenvalues}\n%\n% The Mathieu differential equation as paramatized here is known to produce\n% a close pair of eigenvalues. We now show this pair.\n%\nnoEVals = 2;\nfor k=1:noEVals\n numStr = num2str(vals(k),'%2.10E') ;\n str = ['\\lambda_{', int2str(k-1), '} = ', numStr]\nend;\n%noV = length(vals);\n%n = [1:noV]';\n%valsT = n.^2;\n%\n%%\n% \\section{Plot a Few Eigenfunctions}\n%\nsetUpGraphics(10)\nFigureSize=[1 1 10 6];\nset(0,'DefaultFigureUnits','centimeters');\nset(0,'DefaultFigurePosition',FigureSize);\nset(0,'DefaultFigurePaperUnits','centimeters');\nset(0,'DefaultFigurePaperPosition',FigureSize);\nMyAxesPosition=[0.18 0.17 0.8 0.8];\nset(0,'DefaultaxesPosition',MyAxesPosition);\n%\nfig1 = figure;\nplot( x, sols(:,1), 'r');\nhold on\nplot( x, sols(:,2), 'g');\nplot( x, sols(:,3), 'b');\nplot( x, sols(:,4), 'k');\ngrid on;\nxlabel('$$x$$');\nylabel('$$y8x)$$');\naxis([0,pi,-0.1,0.1]);\n%\n% \\caption{The first $4$ eigen functions of the Mathieu differential equation.}\n%%\n%\nsetUpGraphics(10)\nFigureSize=[1 1 10 10];\nset(0,'DefaultFigureUnits','centimeters');\nset(0,'DefaultFigurePosition',FigureSize);\nset(0,'DefaultFigurePaperUnits','centimeters');\nset(0,'DefaultFigurePaperPosition',FigureSize);\nMyAxesPosition=[0.16 0.17 0.8 0.8];\nset(0,'DefaultaxesPosition',MyAxesPosition);\n%\nfig2 = figure;\nP1 = [0.16 0.4 0.8 0.55] ;\nA = axes('position',P1);\nimagesc( log10(abs(Vec) ));\ncolorbar;\nylabel(['Basis function number $$m$$, $$n_b = ',int2str(noBfs),'$$']);\nP2 = [0.16 0.1 0.615 0.25] ;\nA = axes('position',P2);\nplot( vals(1:noBfs), 'k');\nrange = axis;\naxis([0,noBfs,-1000,900000]);\ngrid on;\nxlabel('Eigenvector number $$n$$');\nylabel('$$\\lambda$$');\n%\n% \\caption{The Rayleigh-Ritz Spectrum of the Eigenfunvtions with respect to \n% the admissible functions and the eigenvalues for the Mathieu differential \n% equation.}\n%%\n% \\section{Save the Figure to Disk.}\nfileType = 'eps';\nprintFigure( fig1, ['SLEx2EigFnsNb',int2str(noBfs)], fileType);\nprintFigure( fig2, ['SLEx2SpectrumNb',int2str(noBfs)], fileType);\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/41354-ordinary-differential-equation-toolbox-odebox-version-1-1/ODEBoxV1-1/SturmLiouville/SturmLiouvilleEx2/SturmLiouville2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.5967417852525643}} {"text": "function [ n_data, mu, sigma, x, fx ] = cauchy_cdf_values ( n_data )\n\n%*****************************************************************************80\n%\n%% CAUCHY_CDF_VALUES returns some values of the Cauchy CDF.\n%\n% Discussion:\n%\n% In Mathematica, the function can be evaluated by:\n%\n% Needs[\"Statistics`ContinuousDistributions`\"]\n% dist = CauchyDistribution [ mu, sigma ]\n% CDF [ dist, 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, real MU, the mean of the distribution.\n%\n% Output, real SIGMA, the standard deviation of the distribution.\n%\n% Output, real X, the argument of the function.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 12;\n\n fx_vec = [ ...\n 0.5000000000000000E+00, ...\n 0.8524163823495667E+00, ...\n 0.9220208696226307E+00, ...\n 0.9474315432887466E+00, ...\n 0.6475836176504333E+00, ...\n 0.6024163823495667E+00, ...\n 0.5779791303773693E+00, ...\n 0.5628329581890012E+00, ...\n 0.6475836176504333E+00, ...\n 0.5000000000000000E+00, ...\n 0.3524163823495667E+00, ...\n 0.2500000000000000E+00 ];\n\n mu_vec = [ ...\n 0.1000000000000000E+01, ... \n 0.1000000000000000E+01, ... \n 0.1000000000000000E+01, ... \n 0.1000000000000000E+01, ... \n 0.1000000000000000E+01, ... \n 0.1000000000000000E+01, ... \n 0.1000000000000000E+01, ... \n 0.1000000000000000E+01, ... \n 0.2000000000000000E+01, ... \n 0.3000000000000000E+01, ... \n 0.4000000000000000E+01, ... \n 0.5000000000000000E+01 ]; \n\n sigma_vec = [ ...\n 0.5000000000000000E+00, ... \n 0.5000000000000000E+00, ...\n 0.5000000000000000E+00, ...\n 0.5000000000000000E+00, ...\n 0.2000000000000000E+01, ...\n 0.3000000000000000E+01, ...\n 0.4000000000000000E+01, ...\n 0.5000000000000000E+01, ...\n 0.2000000000000000E+01, ...\n 0.2000000000000000E+01, ...\n 0.2000000000000000E+01, ...\n 0.2000000000000000E+01 ];\n\n x_vec = [ ...\n 0.1000000000000000E+01, ... \n 0.2000000000000000E+01, ... \n 0.3000000000000000E+01, ... \n 0.4000000000000000E+01, ... \n 0.2000000000000000E+01, ... \n 0.2000000000000000E+01, ... \n 0.2000000000000000E+01, ... \n 0.2000000000000000E+01, ... \n 0.3000000000000000E+01, ... \n 0.3000000000000000E+01, ... \n 0.3000000000000000E+01, ... \n 0.3000000000000000E+01 ];\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 mu = 0.0;\n sigma = 0.0;\n x = 0.0;\n fx = 0.0;\n else\n mu = mu_vec(n_data);\n sigma = sigma_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/cauchy_cdf_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.7341195327172401, "lm_q1q2_score": 0.5967417688759915}} {"text": "function [omckk,Tckk,Rckk] = compute_extrinsic_init_fisheye(x_kk,X_kk,fc,cc,kc,alpha_c)\n\n%compute_extrinsic\n%\n%[omckk,Tckk,Rckk] = compute_extrinsic_init_fisheye(x_kk,X_kk,fc,cc,kc,alpha_c)\n%\n%Computes the extrinsic parameters attached to a 3D structure X_kk given its projection\n%on the image plane x_kk and the intrinsic camera parameters fc, cc and kc.\n%Works with planar and non-planar structures.\n%\n%INPUT: x_kk: Feature locations on the images\n% X_kk: Corresponding grid coordinates\n% fc: Camera focal length\n% cc: Principal point coordinates\n% kc: Distortion coefficients\n% alpha_c: Skew coefficient\n%\n%OUTPUT: omckk: 3D rotation vector attached to the grid positions in space\n% Tckk: 3D translation vector attached to the grid positions in space\n% Rckk: 3D rotation matrices corresponding to the omc vectors\n%\n%Method: Computes the normalized point coordinates, then computes the 3D pose\n%\n%Important functions called within that program:\n%\n%normalize_pixel: Computes the normalize image point coordinates.\n%\n%pose3D: Computes the 3D pose of the structure given the normalized image projection.\n%\n%project_points.m: Computes the 2D image projections of a set of 3D points\n\n\n\nif nargin < 6,\n alpha_c = 0;\n\tif nargin < 5,\n \tkc = zeros(5,1);\n \tif nargin < 4,\n \tcc = zeros(2,1);\n \tif nargin < 3,\n \tfc = ones(2,1);\n \tif nargin < 2,\n \terror('Need 2D projections and 3D points (in compute_extrinsic.m)');\n \treturn;\n \tend;\n \tend;\n \tend;\n\tend;\nend;\n\n\n%keyboard;\n\n% Compute the normalized coordinates:\n\nxn = normalize_pixel_fisheye(x_kk,fc,cc,kc,alpha_c);\n\n\n\nNp = size(xn,2);\n\n%% Check for planarity of the structure:\n%keyboard;\n\nX_mean = mean(X_kk')';\n\nY = X_kk - (X_mean*ones(1,Np));\n\nYY = Y*Y';\n\n[U,S,V] = svd(YY);\n\nr = S(3,3)/S(2,2);\n\n%keyboard;\n\n\nif (r < 1e-3)|(Np < 5), %1e-3, %1e-4, %norm(X_kk(3,:)) < eps, % Test of planarity\n \n %fprintf(1,'Planar structure detected: r=%f\\n',r);\n\n % Transform the plane to bring it in the Z=0 plane:\n \n R_transform = V';\n \n %norm(R_transform(1:2,3))\n \n if norm(R_transform(1:2,3)) < 1e-6,\n R_transform = eye(3);\n end;\n \n if det(R_transform) < 0, R_transform = -R_transform; end;\n \n\tT_transform = -(R_transform)*X_mean;\n\n\tX_new = R_transform*X_kk + T_transform*ones(1,Np);\n \n \n % Compute the planar homography:\n \n H = compute_homography(xn,X_new(1:2,:));\n \n % De-embed the motion parameters from the homography:\n \n sc = mean([norm(H(:,1));norm(H(:,2))]);\n \n H = H/sc;\n \n % Extra normalization for some reasons...\n %H(:,1) = H(:,1)/norm(H(:,1));\n %H(:,2) = H(:,2)/norm(H(:,2));\n \n if 0, %%% Some tests for myself... the opposite sign solution leads to negative depth!!!\n \n % Case#1: no opposite sign:\n \n omckk1 = rodrigues([H(:,1:2) cross(H(:,1),H(:,2))]);\n Rckk1 = rodrigues(omckk1);\n Tckk1 = H(:,3);\n \n Hs1 = [Rckk1(:,1:2) Tckk1];\n xn1 = Hs1*[X_new(1:2,:);ones(1,Np)];\n xn1 = [xn1(1,:)./xn1(3,:) ; xn1(2,:)./xn1(3,:)];\n e1 = xn1 - xn;\n \n % Case#2: opposite sign:\n \n omckk2 = rodrigues([-H(:,1:2) cross(H(:,1),H(:,2))]);\n Rckk2 = rodrigues(omckk2);\n Tckk2 = -H(:,3);\n \n Hs2 = [Rckk2(:,1:2) Tckk2];\n xn2 = Hs2*[X_new(1:2,:);ones(1,Np)];\n xn2 = [xn2(1,:)./xn2(3,:) ; xn2(2,:)./xn2(3,:)];\n e2 = xn2 - xn;\n \n if 1, %norm(e1) < norm(e2),\n omckk = omckk1;\n Tckk = Tckk1;\n Rckk = Rckk1;\n else\n omckk = omckk2;\n Tckk = Tckk2;\n Rckk = Rckk2;\n end;\n \n else\n \n u1 = H(:,1);\n u1 = u1 / norm(u1);\n u2 = H(:,2) - dot(u1,H(:,2)) * u1;\n u2 = u2 / norm(u2);\n u3 = cross(u1,u2);\n RRR = [u1 u2 u3];\n omckk = rodrigues(RRR);\n\n %omckk = rodrigues([H(:,1:2) cross(H(:,1),H(:,2))]);\n Rckk = rodrigues(omckk);\n Tckk = H(:,3);\n \n end;\n \n \n \n %If Xc = Rckk * X_new + Tckk, then Xc = Rckk * R_transform * X_kk + Tckk + T_transform\n \n Tckk = Tckk + Rckk* T_transform;\n Rckk = Rckk * R_transform;\n\n omckk = rodrigues(Rckk);\n Rckk = rodrigues(omckk);\n \n \nelse\n \n %fprintf(1,'Non planar structure detected: r=%f\\n',r);\n\n % Computes an initial guess for extrinsic parameters (works for general 3d structure, not planar!!!):\n % The DLT method is applied here!!\n \n J = zeros(2*Np,12);\n\t\n\txX = (ones(3,1)*xn(1,:)).*X_kk;\n\tyX = (ones(3,1)*xn(2,:)).*X_kk;\n\t\n\tJ(1:2:end,[1 4 7]) = -X_kk';\n\tJ(2:2:end,[2 5 8]) = X_kk';\n\tJ(1:2:end,[3 6 9]) = xX';\n\tJ(2:2:end,[3 6 9]) = -yX';\n\tJ(1:2:end,12) = xn(1,:)';\n\tJ(2:2:end,12) = -xn(2,:)';\n\tJ(1:2:end,10) = -ones(Np,1);\n\tJ(2:2:end,11) = ones(Np,1);\n\t\n\tJJ = J'*J;\n\t[U,S,V] = svd(JJ);\n \n RR = reshape(V(1:9,12),3,3);\n \n if det(RR) < 0,\n V(:,12) = -V(:,12);\n RR = -RR;\n end;\n \n [Ur,Sr,Vr] = svd(RR);\n \n Rckk = Ur*Vr';\n \n sc = norm(V(1:9,12)) / norm(Rckk(:));\n Tckk = V(10:12,12)/sc;\n \n\tomckk = rodrigues(Rckk);\n Rckk = rodrigues(omckk);\n \nend;\n", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/toolbox_calib/compute_extrinsic_init_fisheye.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515258, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5967375547085817}} {"text": "%-------------------------------------------------------------------------\n% Coupling Kinetic and Fluid System of Euler Equations\n% To solve Shock Tube Problem\n%\n% Kinetic equation use SBBGK and Hydrodynamic equation use Roe Euler\n%\n% Based on: \n% [1] Pierre Degond, Giacomo Dimarco and Luc Mieussens\n% A moving interface method for dynamic kinetic-fluid coupling\n% Journal of Computation Physics 227(2007)1176-1208\n%\n% By Manuel Diaz and Yun-Da Tsai \n% 007@IAM 25.01.2013\n%-------------------------------------------------------------------------\n\nclear all; clc; close all;\n\n%% Global Variables\nglobal CFL r_time theta dt dtdx nx\nglobal w k nv\nglobal gamma etpfix\n\n%% Controling Parameters\nname ='SBBGK1d'; % Simulation Name\nCFL = 0.05; % CFL condition\nr_time = 1/10000; % Relaxation time\ntEnd = 0.04; % End time\ntheta = 0; % {-1} BE, {0} MB, {1} FD.\nquad = 2; % for NC = 1 , GH = 2\nmethod = 1; % for TVD = 1, WENO3 = 2, WENO5 = 3\nIC_case = 1; % IC: {1}Sod's, {2}LE, {3}RE, {4}DS, {5}SS, {6}Cavitation\nplot_figs = 1; % 0: no, 1: yes please!\nwrite_ans = 0; % 0: no, 1: yes please!\ngamma = 2; % Ratio of specific heats\nflxtype = 2; % {1} Roe, {2} LF, {3} LLF, {4} Upwind <-non-conservative!\netpfix = 0.90; % {#} Harten's sonic entropy fix value, {0} no entropy fix\n\n%% Space Discretization\nnx = 100; % number of cells\nx = linspace(0,1,nx); % Physical domain -x\ndx = max(x(2:end)-x(1:end-1)); % delta x\n\n%% Load Initial Condition\n[z0,ux0,t0,p0,rho0,E0] = SSBGK_IC1d(x,IC_case);\n\n%% Load Initial Cut Function\n xa = 0.5; % buffer left boundary\n xb = 0.5125; % buffer right boundary\n h0 = cutfunc(x,xa,xb); % Physical Cut Function\n \n% h0 = ones(size(x));\n% h0 = zeros(size(x));\n\n%% Discretization of the Velocity Space\n% Microscopic Velocity Discretization (using Discrete Ordinate Method)\n% that is to make coincide discrete values of microscopic velocities with\n% values as the value points for using a quadrature method, so that we can\n% integrate the velocity probability distribution to recover our\n% macroscopics properties.\nswitch quad\n\n case{1} % Newton Cotes Quadrature:\n V = [-20,20]; % range: a to b\n nv = 200; % nodes desired (may not the actual value)\n [c,w,k] = cotes_xw(V(1),V(2),nv,5); % Using Netwon Cotes Degree 5\n \n case{2} % Gauss Hermite Quadrature:\n nv = 100; % nodes desired (the actual value)\n [c,w] = GaussHermite(nv); % for integrating range: -inf to inf\n k = 1; % quadrature constant.\n w = w.*exp(c.^2); % weighting function of the Gauss-Hermite quadrature\n \n otherwise\n error('Order must be between 1 and 2');\nend\n\n%% Applying DOM\n% The actual nv value will be computed using 'lenght' vector function:\nnv = length(c); \n% Remap velocity points\n c = repmat(c,1,nx); w = repmat(w,1,nx);\n% Remap classical IC\n [rho0,ux0,p0] = apply_DOM(rho0,ux0,p0,nv);\n% Remap Semiclassical IC\n [z0,t0,E0] = apply_DOM(z0,t0,E0,nv);\n% Remap h coeficient\n h0 = repmat(h0,nv,1);\n\n%% Semi0-classical Equilibrium Distribution Function\nM0 = f_equilibrium_1d(z0,ux0,c,t0,theta); \n\n%% Load initial Conditions and Spliting of information\nM = M0; rho = rho0; ux = ux0; t = t0; p = p0; z = z0; h = h0; E = E0;\n\n%% Split ICs in R and L\nrhor = h.*rho0; rhol = (1-h).*rho0;\nuxr = h.*ux0; uxl = (1-h).*ux0;\npr = h.*p0; pl = (1-h).*p0;\n\n% [zr,~,tr,~] = macroproperties1d(rhor,rhor.*uxr,pr+0.5*rhor.*uxr.^2,nx,nv,theta);\n% [zl,~,tl,~] = macroproperties1d(rhol,rhol.*uxl,pl+0.5*rhol.*uxl.^2,nx,nv,theta);\n% Ml = f_equilibrium_1d(zl,uxl,c,tl,theta) ;\n% fr = f_equilibrium_1d(zr,uxr,c,tr,theta);\n fr=h.*M; \n Ml=(1-h).*M;\n%% Main Loop \n% Compute next time step\n dt = dx*CFL/max(c(:,1));\n \n \n% dt =1/20000;\ntime = 0:dt:tEnd;\ndtdx = dt/dx;\n% Ml(isnan(Ml)) = 0; fr(isnan(fr)) = 0;\nf = fr + Ml; % computed here for ploting purposes\n\ncount = 1; % iteration counter\ntic;\nfor tsteps = time\n\n CFL=dtdx*max(c(:,1));\n% Plot IC\n if plot_figs == 1; surf(f); end;\n \n\n% Compute vector 'q'\n q = [rhol(1,:) ; rhol(1,:).*uxl(1,:) ; pl(1,:)+0.5*rhol(1,:).*uxl(1,:).^2];\n \n% Update Physical cut function 'h'\n h_next = h; % this means: fixed buffer assumption\n\n% Evaluate Modified Boltzmann BGK\n [fr_next] = ModSBBGK(h,h_next,M,fr,Ml,c,flxtype);\n \n\n% Evaluate Modificed Roe Euler Solver\n [rhol,rhoul,El] = ModEuler(h,h_next,q,fr_next,c);\n \n% plot partial result\n% if plot_figs == 1; \n% subplot(1,3,1); plot(x,rhol,'o'); title('Density');\n% subplot(1,3,2); plot(x,rhoul./rhol,'o'); title('Velocity');\n% subplot(1,3,3); plot(x,El,'o'); title('Energy');\n% end\n \n% macroscopic properties\n [zl,uxl,tl,pl] = macroproperties1d(rhol,rhoul,El,nx,nv,gamma,theta);\n \n % Apply DOM\n [tl,zl,uxl] = apply_DOM(tl,zl,uxl,nv);\n \n % Compute Ml_next\n Ml_next = f_equilibrium_1d(zl,uxl,c,tl,theta) ;\n% **************************************************** \n \n % New time step info: sum left and righ values with 'NaN' filter sum\n % function. \n Ml_next(isnan(Ml_next)) = 0; fr_next(isnan(fr_next)) = 0;\n % Total f\n f = fr_next + Ml_next; \n \n % Update New macroquantity \n [rho,rhou,E] = macromoments1d(k,w,f,c);\n \n %Apply Neumann BC's in total variables\n f(:,1) = f(:,2); f(:,end) = f(:,end-1);\n rho(:,1)= rho(:,2); rho(:,end)= rho(:,end-1);\n rhou(:,1) = rhou(:,2); rhou(:,end) = rhou(:,end-1);\n E(:,1) = E(:,2); E(:,end) = E(:,end-1);\n \n [rho,rhou,E] = apply_DOM(rho,rhou,E,nv);\n \n % Recover Semiclassical Conditions for next time step\n [z,ux,t,p] = macroproperties1d(rho,rhou,E,nx,nv,gamma,theta); \n \n \n% update New equilibrium\n M=f_equilibrium_1d(z,ux,c,t,theta); \n fr=h.*M; \n \n% preparing new Ml\n rhol = (1-h).*rho;\n uxl = (1-h).*ux;\n pl = (1-h).*p;\n [zl,~,tl,~] = macroproperties1d(rhol,rhol.*uxl,pl+0.5*rhol.*uxl.^2,nx,nv,gamma,theta);\n% update New Ml \n Ml= f_equilibrium_1d(zl,uxl,c,tl,theta) ;\n Ml(isnan(Ml)) = 0;\n \n% update counter\n count = count+1;\n \n% update plot\n drawnow\nend\ntoc;\n\n% write/plot final output\n%plot(x,r_total,'o');\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/Coupled/Main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515258, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5967375492424762}} {"text": "%% This script is used to generate the Brain Network for user to perform further analysis by themselves.\n\n\nclear all\naddpath(genpath(pwd));\ninput_folder='./data/'; % this is the directory of the time course data for all subjects, each file for each subject, similar as you prepared for GUI\noutput_dir='./Generated_BrainNet/'; %this is the output directory;\nmeth_Net='aHOFC'; %Here you can set the brain network construction method;\n%[\"PC\",\"aHOFC\",\"tHOFC\",\"SR\",\"WSR\",\"SLR\",\"SGR\",\"WSGR\",\"GSR\",\"SSGSR\",\"dHOFC\"];\nswitch meth_Net\n case {'SR','WSR','GSR'}\n lambda=0.01:0.01:0.1; %User can change the parameter range by themselves;\n case {'SLR','SGR','WSGR','SSGSR'}\n lambda_1=0.01:0.01:0.1; %User can change the parameter range by themselves;\n lambda_2=0.01:0.01:0.1;\n case 'dHOFC'\n C=100:100:800;\n W=20:10:70;\n s=1; %step size is usually set to 1 or 2;\n case {'PC','tHOFC','aHOFC'}\n \nend\n\n\n\n\ndirOutput=dir(fullfile(input_folder,'*.txt'));\nfileName={dirOutput.name}';\n%folder={dirOutput.folder}';\nfor i=1:length(fileName)\n BOLD{i,1}=load([input_folder,'/',fileName{i}]);\nend\n%label=importdata(label_input);\n\n[~,nROI]=size(BOLD{1});\nnSubj=length(BOLD);\n\nfprintf('Begin network construction\\n');\n\nswitch meth_Net\n case 'PC' % Pearson's correlation\n BrainNet{1}=PC(BOLD);\n case 'tHOFC' % Topographical high-order FC\n BrainNet{1}=tHOFC(BOLD);\n case 'aHOFC' % Associated high-order FC\n BrainNet{1}=aHOFC(BOLD);\n case 'SR' % Sparse representation\n parfor i=1:length(lambda)\n BrainNet{i}=SR(BOLD,lambda(i));\n end\n \n case 'WSR' % PC weighted SR\n parfor i=1:length(lambda)\n BrainNet{i}=WSR(BOLD,lambda(i));\n end\n \n case 'SLR' % Sparse low-rank representation\n lambda1=lambda_1;\n lambda2=lambda_2;\n num_lambda1=length(lambda1);\n num_lambda2=length(lambda2);\n parfor i=1:num_lambda1\n for j=1:num_lambda2\n BrainNet{i,j}=SLR(BOLD,lambda1(i),lambda2(j));\n end\n end\n BrainNet=reshape(BrainNet,1,num_lambda1*num_lambda2);\n \n case 'SGR' % Sparse group representation\n lambda1=lambda_1;\n lambda2=lambda_2;\n num_lambda1=length(lambda1);\n num_lambda2=length(lambda2);\n parfor i=1:num_lambda1\n for j=1:num_lambda2\n BrainNet{i,j}=SGR(BOLD,lambda1(i),lambda2(j));\n end\n end\n \n BrainNet=reshape(BrainNet,1,num_lambda1*num_lambda2);\n \n case 'WSGR' % PC weighted SGR\n lambda1=lambda_1; % parameter for sparsity\n lambda2=lambda_2; % parameter for group sparsity\n num_lambda1=length(lambda1);\n num_lambda2=length(lambda2);\n \n parfor i=1:num_lambda1\n for j=1:num_lambda2\n BrainNet{i,j}=WSGR(BOLD,lambda1(i),lambda2(j));\n end\n end\n BrainNet=reshape(BrainNet,1,num_lambda1*num_lambda2);\n \n case 'GSR' % Group sparse representation\n parfor i=1:length(lambda)\n BrainNet{i}=GSR(BOLD,lambda(i));\n end\n \n case 'SSGSR' % Strength and Similarity guided GSR\n %lambda1=lambda_1(1:6); % parameter for group sparsity\n lambda1=lambda_1;\n lambda2=lambda_2; % parameter for inter-subject LOFC-pattern similarity\n num_lambda1=length(lambda1);\n num_lambda2=length(lambda2);\n parfor i=1:num_lambda1\n for j=1:num_lambda2\n BrainNet{i,j}=SSGSR(BOLD,lambda1(i),lambda2(j));\n end\n end\n BrainNet=reshape(BrainNet,1,num_lambda1*num_lambda2);\n \n case 'dHOFC' % Dynamic high-order FC\n num_W=length(W);\n num_C=length(C);\n parfor i=1:num_W % number of clusters\n for j=1:num_C\n [BrainNet{i,j},IDX{i,j}]=dHOFC(BOLD,W(i),s,C(j));\n end\n end\n BrainNet=reshape(BrainNet,1,num_W*num_C);\nend\nsave(char(strcat(output_dir,meth_Net,'.mat')),'BrainNet','-v7.3');\n% All the generated networks (and those resulted from different parameters) are saved as a cell array, nROIxnROIxnSubject in each cell, different cells for results with different combinations of parameters \nfprintf('Network construction finished\\n');\n", "meta": {"author": "zzstefan", "repo": "BrainNetClass", "sha": "556cda9516429a964100e1ac0bace4258194b4a1", "save_path": "github-repos/MATLAB/zzstefan-BrainNetClass", "path": "github-repos/MATLAB/zzstefan-BrainNetClass/BrainNetClass-556cda9516429a964100e1ac0bace4258194b4a1/BatchExamples/save_BrainNet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5967375339266622}} {"text": "function [ySqrtEst, PInvSqrtEst]=sqrtInfoBatchSmoother(ySqrtPred,PInvSqrtPred,z,u,H,F,SR,SQ,Gamma,kD)\n%%SQRTINFOBATCHSMOOTHER Run the square root information smoother for linear\n% dynamic and measurement models on a batch of\n% measurements. The smoothed result at one time step or\n% along the entire batch are available. The initial\n% predicted states can not be uninformative.\n%\n%INPUTS: ySqrtPred The xDimX1 predicted square root information state at\n% the time of the initial measurement in z. The predicted\n% information state is always PInvSqrtPred times the\n% predicted target state estimate.\n% PInvSqrtPred The inverse square root information matrix associated\n% with the predicted information state at the time of the\n% initial measurement in z. If P is the covariance matrix\n% of a Gaussian state x, then P=PSqrt*PSqrt' and\n% PInvSqrtPred=inv(PSqrt). This can be either upper\n% triangular or lower triangular.\n% z The zDim X N matrix of measurements for the whole batch.\n% u The xDim X(N-1) matrix of control inputs for the whole\n% batch. If there are no control inputs, then set u=[];\n% H The zDim X xDim X N hypermatrix of measurement matrices\n% such that H(:,:,k)*x+w is the measurement at time k, \n% where x is the state and w is zero-mean Gaussian noise \n% with covariance matrix R (:,:,k). Alternatively, if all\n% of the measurement matrices are the same, one can just\n% pass a single zDim X xDim matrix.\n% F The xDim X xDim X (N-1) hypermatrix of state transition\n% matrices. The state at discrete-time k+1 is modeled as\n% F(:,:,k) times the state at time k plus zero-mean\n% Gaussian process noise with covariance matrix Q(:,:,k).\n% Alternatively, if all of the state transition matrices\n% are the same, one can just pass a single xDim X xDim\n% matrix.\n% SR The zDim X zDim X N hypermatrix of lower-triangular\n% square-root of the measurement covariance matrices. The\n% matrices must be invertible. Alternatively, if all of the\n% measurement covariance matrices are the same, one can\n% just pass a single zDim X zDim matrix.\n% SQ The xDim X xDim X (N-1) hypermatrix of lower-triangular\n% square-root of the process noise covariance matrices.\n% The matrices must be invertible. Alternatively, if all of\n% the measurement covariance matrices are the same, one can\n% just pass a single xDim X xDim matrix.\n% Gamma An optional xDim X xDim X (N-1) hypermatrix of matrices\n% that transform the process noise to the state domain if\n% the process noise covariance matrix is singular.\n% Alternatively, if all of the transform matrices are the\n% same, one can just pass a single xDim X xDim matrix. If\n% this is omitted entirely, an identity matrix is used\n% (i.e. there is no Gamma).\n% kD The discrete time-step at which the smoothed state\n% estimate is desired, where z(:,1) is at discrete\n% time-step 1 (not 0). If kD is omitted ot an empty matrix\n% is passed, then results along the entire batch are\n% obtained.\n%\n%OUTPUTS: ySqrtEst The xDimXN smoothed square root information state\n% estimates at all steps if kD is not provided or the\n% xDimX1 smoothed information state estimate at step kD if\n% kD is provided.\n% PSqrtInvEst The inverse square root covariance matrices associated\n% with the smoothed information state estimates. This is\n% xDimXxDimXN for the whole batch if kD is not provided\n% and is xDimXxDim if kD is provided.\n%\n%The algorithm is that of the linear square root information filter and\n%smoother that is described in the book [1]. The forward pass steps can be\n%found in Chapter IV, and the backwards smoother in Chapter X.\n%\n%The algorithm works by running a square root information filter forward\n%in time and then smoothing backwards. The smoothing step depends on\n%information stored during the forward pass. The smoothing step here is\n%performed on a state residual rather than the state itself and applies the\n%smoothed output to the previous updated measurement. This was based off of\n%NASA's Orbit Determination Toolbox.\n%\n%z*(j+1)=PInvSqrt*(j+1)(x*(j+1)-xPred(j+1)\n%A=[Rw(j)+Rwx(j), Rwx(j)F(j+1,j), u(j)\n% PInvSqrt*(j+1), PInvSqrt*(j+1)F(j+1,j), z*(j+1)]\n%qr(A)=[Rw*(j), Rwx*(j), u*(j)\n% 0, PInvSqrt*(j), z*(j)]\n%x*(j)=xUpd(j)+PInvSqrt*(j)\\z*(j)\n%\n%where xPred is the forward predicted state, xUpd is the forward updated\n%state, Rw and Rwx are outputs from the forward prediction step, u is the\n%the control input (often zero), and x* and PInvSqrt* are the smoothed\n%states. x*(N)=xUpd(N) and PInvSqrt*(N)=PInvSqrtUpd(N)\n%\n%REFERENCES:\n%[1] G. J. Bierman, \"Factorization Methods for Discrete Sequential\n% Estimation. Academic Press, New York, 1977.\n%\n%March 2015, David Karnick, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nxDim=size(H,2);\nN=size(z,2);\n\nif(nargin<9||isempty(Gamma))\n Gamma=eye(xDim);\nend\nif(nargin<10||isempty(kD))\n kD=[];\nend\nif(isempty(ySqrtPred))\n ySqrtPred=zeros(xDim,1); \nend\nif(isempty(PInvSqrtPred))\n PInvSqrtPred=zeros(xDim,xDim);\nend\nif(isempty(u))\n u=zeros(xDim,N-1); \nend\nif(size(H,3)==1)\n H=repmat(H,[1,1,N]);\nend\nif(size(F,3)==1)\n F=repmat(F,[1,1,N-1]);\nend\nif(size(SR,3)==1)\n SR=repmat(SR,[1,1,N]); \nend\nif(size(SQ,3)==1)\n SQ=repmat(SQ,[1,1,N-1]);\nend\nif(size(Gamma,3)==1)\n Gamma=repmat(Gamma,[1,1,N-1]);\nend\n\n%Run the SRIF forward until we have the predictions of step kD|kD-1 (going forwards).\nySqrtFwdPred=zeros(xDim,N);\nPInvSqrtFwdPred=zeros(xDim,xDim,N);\nySqrtFwdUpd=zeros(xDim,N);\nPInvSqrtFwdUpd=zeros(xDim,xDim,N);\nRw=zeros(xDim,xDim,N);\nRwx=zeros(xDim,xDim,N);\n\n%The first step uses the priors\nySqrtFwdPred(:,1)=ySqrtPred;\nPInvSqrtFwdPred(:,:,1)=PInvSqrtPred;\n\n%The rest of the steps\nfor curStep=1:(N-1)\n [ySqrtFwdUpd(:,curStep),PInvSqrtFwdUpd(:,:,curStep)]=sqrtInfoFilterUpdate(ySqrtFwdPred(:,curStep),PInvSqrtFwdPred(:,:,curStep),z(:,curStep),SR(:,:,curStep),H(:,:,curStep));\n [ySqrtFwdPred(:,curStep+1),PInvSqrtFwdPred(:,:,curStep+1),Rw(:,:,curStep+1),Rwx(:,:,curStep+1)]=sqrtInfoFilterDiscPred(ySqrtFwdUpd(:,curStep),PInvSqrtFwdUpd(:,:,curStep),F(:,:,curStep),SQ(:,:,curStep),u(:,curStep),Gamma(:,:,curStep));\nend\n\n%Run the SRIS backwards until we have the updated information state of\n%step kD|kD (going backwards).\nySqrtEst=zeros(xDim,N);\nPInvSqrtEst=zeros(xDim,xDim,N);\n\n%ODTBX method\n[ySqrtEst(:,end),PInvSqrtEst(:,:,end)]=sqrtInfoFilterUpdate(ySqrtFwdPred(:,N),PInvSqrtFwdPred(:,:,N),z(:,N),SR(:,:,N),H(:,:,N));\nfor curStep=(N-1):-1:1\n xPred=PInvSqrtFwdPred(:,:,curStep+1)\\ySqrtFwdPred(:,curStep+1); %Forward predicted state_j+1\n xStar=PInvSqrtEst(:,:,curStep+1)\\ySqrtEst(:,curStep+1); %Backward smoothed state_j+1\n zStar=PInvSqrtEst(:,:,curStep+1)*(xStar-xPred);\n \n [zSmooth,PInvSqrtEst(:,:,curStep)]=sqrtInfoSmoothStep(zStar,PInvSqrtEst(:,:,curStep+1),F(:,:,curStep),Rw(:,:,curStep),Rwx(:,:,curStep),u(:,curStep),Gamma(:,:,curStep));\n \n xUpd=PInvSqrtFwdUpd(:,:,curStep)\\ySqrtFwdUpd(:,curStep); %Forward updated state_j\n ySqrtEst(:,curStep)=PInvSqrtEst(:,:,curStep)*(xUpd+PInvSqrtEst(:,:,curStep)\\zSmooth);\nend\n\nif(~isempty(kD))\n ySqrtEst=ySqrtEst(:,kD);\n PInvSqrtEst=PInvSqrtEst(:,:,kD);\nend\nend\n\nfunction [ySqrtPred, PInvSqrtPred]=sqrtInfoSmoothStep(ySqrtPrev,PInvSqrtPrev,F,Ru,Rux,u,Gamma)\n%This is the basic Smoothing step shown in Bierman's book\nxDim=size(ySqrtPrev,1);\n\nA=[Ru+Rux*Gamma, Rux*F, u;\n PInvSqrtPrev*Gamma, PInvSqrtPrev*F, ySqrtPrev];\n[~,T]=qr(A);\n\nySqrtPred=T((xDim+1):end,end);\nPInvSqrtPred=T((xDim+1):end,(end-xDim):(end-1));\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Dynamic_Estimation/Batch_and_Smoothing/sqrtInfoBatchSmoother.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.596737533385411}} {"text": "function [TW] = Btuph2TW(Btuph)\n% Convert power from British thermal units per hour to terawatts.\n% Chad A. Greene 2012\nTW = Btuph*2.930710702e-13;\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/35258-unit-converters/unit_converters/Btuph2TW.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615381987656672, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5967375320054855}} {"text": "function [fb_sim] = acc_gen (ref, imu)\n% acc_gen: generates simulated accelerometers measurements from reference\n% data and IMU error profile.\n%\n% INPUT\n%\tref: data structure with true trajectory.\n%\timu: data structure with IMU error profile.\n%\n% OUTPUT\n%\tfb_sim: Nx3 matrix with simulated accelerations in the\n%\t\tbody frame [X Y Z] (m/s^2, m/s^2, m/s^2).\n%\n% Copyright (C) 2014, Rodrigo González, all rights reserved.\n%\n% This file is part of NaveGo, an open-source MATLAB toolbox for\n% simulation of integrated navigation systems.\n%\n% NaveGo is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License (LGPL)\n% version 3 as published by the Free Software Foundation.\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 Lesser General Public License for more details.\n%\n% You should have received a copy of the GNU Lesser General Public\n% License along with this program. If not, see\n% .\n%\n% References:\n%\n%\tR. Gonzalez, J. Giribet, and H. Patiño. NaveGo: a\n% simulation framework for low-cost integrated navigation systems,\n% Journal of Control Engineering and Applied Informatics, vol. 17,\n% issue 2, pp. 110-120, 2015. Sec. 2.2.\n%\n% Aggarwal, P. et al. MEMS-Based Integrated Navigation. Artech\n% House. 2010.\n%\n% Thinking about accelerometers and gravity by Dave Redell\n% http://www.lunar.org/docs/LUNARclips/v5/v5n1/Accelerometers.html\n%\n% Version: 012\n% Date: 2022/08/22\n% Author: Rodrigo Gonzalez \n% URL: https://github.com/rodralez/navego\n\nN = max(size(ref.t));\nM = [N, 3];\n\n%% SIMULATION OF ACC\n\n% If true, accelerations are provided...\nif (isfield(ref, 'fb'))\n \n acc_b = ref.fb;\n \n% If not, accelerations are obtained from velocity\nelseif (isfield(ref, 'vel'))\n \n acc_raw = (diff(ref.vel)) ./ [diff(ref.t) diff(ref.t) diff(ref.t)];\n acc_raw = [ 0 0 0; acc_raw; ];\n \n % Noise introduced by derivatives should be smoothed\n acc_ned = my_sgolayfilt(acc_raw);\n acc_b = acc_nav2body(acc_ned, ref.DCMnb_m);\n \n% If not, accelerations are obtained from position\nelse\n \n % Method: LLH > ECEF > NED\n [~, acc_ned] = pllh2vned (ref);\n acc_b = acc_nav2body(acc_ned, ref.DCMnb_m);\nend\n\n%% SIMULATION OF GRAVITY AND CORIOLIS\n\n% Gravity and Coriolis in nav-ref\ng_n = -gravity(ref.lat, ref.h); % Accelerometer in Z axis senses an \n % acceleration of 1.0 G straight up\ncor_n = coriolis(ref.lat, ref.vel, ref.h);\n\n% Gravity and Coriolis from nav-ref to body-ref\ng_b = zeros(M);\ncor_b = zeros(M);\nfor i = 1:N\n dcmnb = reshape(ref.DCMnb_m(i,:), 3, 3);\n gb = dcmnb * g_n(i,:)';\n corb = dcmnb * cor_n(i,:)';\n g_b(i,:) = gb';\n cor_b(i,:) = corb';\nend\n\n%% SIMULATION OF NOISES\n\n% -------------------------------------------------------------------------\n% Simulation of static bias as a constant random variable\n\nab_sta = noise_b_sta (imu.ab_sta, N);\n\n% -------------------------------------------------------------------------\n% Simulation of white noise\n\nwn = randn(M);\nacc_wn = zeros(M);\n\nfor i=1:3\n\n acc_wn(:, i) = imu.a_std(i).* wn(:,i);\nend\n\n% -------------------------------------------------------------------------\n% Simulation of dynamic bias (bias instability) as a first-order Gauss-Markov model\n\ndt = 1/ref.freq; \nab_dyn = noise_b_dyn (imu.ab_corr, imu.ab_dyn, dt, M);\n\n% -------------------------------------------------------------------------\n% Simulation of rate random walk\n\nacc_rrw = noise_rrw (imu.vrrw, dt, M);\n\n% -------------------------------------------------------------------------\n\nfb_sim = acc_b + cor_b + g_b + acc_wn + ab_sta + ab_dyn + acc_rrw;\n\nend\n", "meta": {"author": "rodralez", "repo": "NaveGo", "sha": "3de9a74ab1597be13255d4649892e68aeff9a8b7", "save_path": "github-repos/MATLAB/rodralez-NaveGo", "path": "github-repos/MATLAB/rodralez-NaveGo/NaveGo-3de9a74ab1597be13255d4649892e68aeff9a8b7/simulation/acc_gen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5967375180695965}} {"text": "function [mh,mw]=tropmapf(time,pos,azel)\n\nif pos(3)<-1000||pos(3)>20000\n mh=0; mw=0; return;\nend\n\n% hydro-ave-a,b,c, hydro-amp-a,b,c, wet-a,b,c at latitude 15,30,45,60,75\ncoef=[ 1.2769934E-3, 1.2683230E-3, 1.2465397E-3, 1.2196049E-3, 1.2045996E-3;...\n 2.9153695E-3, 2.9152299E-3, 2.9288445E-3, 2.9022565E-3, 2.9024912E-3;...\n 62.610505E-3, 62.837393E-3, 63.721774E-3, 63.824265E-3, 64.258455E-3;...\n \n 0.0000000E-0, 1.2709626E-5, 2.6523662E-5, 3.4000452E-5, 4.1202191E-5;...\n 0.0000000E-0, 2.1414979E-5, 3.0160779E-5, 7.2562722E-5, 11.723375E-5;...\n 0.0000000E-0, 9.0128400E-5, 4.3497037E-5, 84.795348E-5, 170.37206E-5;...\n \n 5.8021897E-4, 5.6794847E-4, 5.8118019E-4, 5.9727542E-4, 6.1641693E-4;...\n 1.4275268E-3, 1.5138625E-3, 1.4572752E-3, 1.5007428E-3, 1.7599082E-3;...\n 4.3472961E-2, 4.6729510E-2, 4.3908931E-2, 4.4626982E-2, 5.4736038E-2];\n\n% height correction\naht=[2.53E-5, 5.49E-3, 1.14E-3];\nah=zeros(3,1); aw=zeros(3,1);\n\nif azel(2)<=0,mh=0; mw=0; return;end\n \nlat=pos(1)*180/pi;\nif lat<0,yy=0.5;else,yy=0;end\ny=(time2doy(time)-28.0)/365.25+yy;\ncosy=cos(2.0*pi*y);\nlat=abs(lat);\n\nfor i=1:3\n ah(i)=interpc(coef(i,:),lat)-interpc(coef(i+3,:),lat)*cosy;\n aw(i)=interpc(coef(i+6,:),lat);\n% j=fix(lat/15);\n% ah(i)=(coef(i,j)+(coef(i,j+1)-coef(i,j))*(lat/15-j))-...\n% (coef(i+3,j)+(coef(i+3,j+1)-coef(i+3,j))*(lat/15-j))*cosy;\n% aw(i)=(coef(i+6,j)+(coef(i+6,j+1)-coef(i+6,j))*(lat/15-j));\nend\n\nel=azel(2);\nsinel=sin(el);\n\nmh1=(1+ah(1)/(1+ah(2)/(1+ah(3))))/(sinel+(ah(1)/(sinel+ah(2)/(sinel+ah(3)))));\nmh2=(1+aht(1)/(1+aht(2)/(1+aht(3))))/(sinel+(aht(1)/(sinel+aht(2)/(sinel+aht(3)))));\nmh=mh1+(1/sinel-mh2)*pos(3)/1000;\n\nmw=(1+aw(1)/(1+aw(2)/(1+aw(3))))/(sinel+(aw(1)/(sinel+ah(2)/(sinel+aw(3)))));\n\nreturn\n\n\n", "meta": {"author": "kaichen686", "repo": "GINav", "sha": "bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666", "save_path": "github-repos/MATLAB/kaichen686-GINav", "path": "github-repos/MATLAB/kaichen686-GINav/GINav-bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666/src/common/tropmapf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5967267984123402}} {"text": "seed = 0;\nrand('state', seed);\nrandn('state', seed);\n\nnrows = 3;\nncols = 3;\nnpixels = nrows*ncols;\n\n% we number pixels in transposed raster scan order (top to bottom, left to right)\n\n% hidden var\nHV = reshape(1:npixels, nrows, ncols);\n% observed var\nOV = reshape(1:npixels, nrows, ncols) + length(HV(:));\n\n% observed factor\nOF = reshape(1:npixels, nrows, ncols);\n% vertical edge factor VEF(i,j) is the factor for edge HV(i,j) - HV(i+1,j)\nVEF = reshape((1:(nrows-1)*ncols), nrows-1, ncols) + length(OF(:));\n% horizontal edge factor HEF(i,j) is the factor for edge HV(i,j) - HV(i,j+1)\nHEF = reshape((1:nrows*(ncols-1)), nrows, ncols-1) + length(OF(:)) + length(VEF(:));\n\nnvars = length(HV(:))+length(OV(:));\nassert(nvars == 2*npixels);\nnfac = length(OF(:)) + length(VEF(:)) + length(HEF(:));\n\nK = 2; % number of discrete values for the hidden vars\n%O = 1; % each observed pixel is a scalar\nO = 2; % each observed pixel is binary\n\nfactors = cell(1,3);\n\n% hidden states generate observed 0 or 1 plus noise\n%factors{2} = cond_gauss1_kernel(K, O, 'mean', [0 1], 'cov', [0.1 0.1]);\npnoise = 0.2;\nfactors{1} = tabular_kernel([K O], [1-pnoise pnoise; pnoise 1-pnoise]);\nofactor = 1;\n\n% encourage compatibility between neighboring vertical pixels\nfactors{2} = tabular_kernel([K K], [0.8 0.2; 0.2 0.8]);\nvedge_factor = 2;\n\n%% no constraint between neighboring horizontal pixels\n%factors{3} = tabular_kernel([K K], [0.5 0.5; 0.5 0.5]);\n\nfactors{3} = tabular_kernel([K K], [0.8 0.2; 0.2 0.8]);\nhedge_factor = 3;\n\n\n\nfactor_ndx = zeros(1, 3);\nG = zeros(nvars, nfac);\nns = [K*ones(1,length(HV(:))) O*ones(1,length(OV(:)))];\n\nN = length(ns);\n%cnodes = OV(:);\ncnodes = [];\ndnodes = 1:N;\n\nfor i=1:nrows\n for j=1:ncols\n G([HV(i,j), OV(i,j)], OF(i,j)) = 1;\n factor_ndx(OF(i,j)) = ofactor;\n\n if i < nrows\n G(HV(i:i+1,j), VEF(i,j)) = 1;\n factor_ndx(VEF(i,j)) = vedge_factor;\n end\n\n if j < ncols\n G(HV(i,j:j+1), HEF(i,j)) = 1;\n factor_ndx(HEF(i,j)) = hedge_factor;\n end\n\n end\nend\n\n\nfg = mk_fgraph(G, ns, factors, 'discrete', dnodes, 'equiv_class', factor_ndx);\n\nif 1\n % make image with vertical stripes\n I = zeros(nrows, ncols);\n for j=1:2:ncols\n I(:,j) = 1;\n end\nelse\n % make image with square in middle\n I = zeros(nrows, ncols);\n I(3:6,3:6) = 1;\nend\n\n \n% corrupt image\nO = mod(I + (rand(nrows,ncols)> (1-pnoise)), 2);\n\nmaximize = 1;\nengine = belprop_fg_inf_engine(fg, 'maximize', maximize, 'max_iter', npixels*5);\n\nevidence = cell(1, nvars);\nonodes = OV(:);\nevidence(onodes) = num2cell(O+1); % values must be in range {1,2}\n\nengine = enter_evidence(engine, evidence);\n\nfor i=1:nrows\n for j=1:ncols\n m = marginal_nodes(engine, HV(i,j));\n Ihat(i,j) = argmax(m.T)-1;\n end\nend\n\nIhat\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/examples/static/fgraph/fg_mrf1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5966736320475535}} {"text": "function [A_hat E_hat iter svp elapsed] = ialm_rpca(D, lambda, tol, maxIter, blk)\n\n% Oct 2009\n% This matlab code implements the inexact augmented Lagrange multiplier \n% method for Robust PCA.\n%\n% D - m x n matrix of observations/data (required input)\n%\n% lambda - weight on sparse error term in the cost function\n%\n% tol - tolerance for stopping criterion.\n% - DEFAULT 1e-7 if omitted or -1.\n%\n% maxIter - maximum number of iterations\n% - DEFAULT 1000, if omitted or -1.\n% blk - indicate whether to use BLWS\n% \n% Initialize A,E,Y,u\n% while ~converged \n% minimize (inexactly, update A and E only once)\n% L(A,E,Y,u) = |A|_* + lambda * |E|_1 + + mu/2 * |D-A-E|_F^2;\n% Y = Y + \\mu * (D - A - E);\n% \\mu = \\rho * \\mu;\n% end\n\n%addpath PROPACK;\n\n%elapsed = tic;\n\n[m n] = size(D);\n\nif nargin < 2\n lambda = 1 / sqrt(max(m,n));\nelseif lambda == -1\n lambda = 1 / sqrt(max(m,n));\nend\n\nif nargin < 3\n tol = 1e-7;\nelseif tol == -1\n tol = 1e-7;\nend\n\nif nargin < 4\n maxIter = 1000;\nelseif maxIter == -1\n maxIter = 1000;\nend\n\nif nargin < 5\n blk = 0;\nelseif blk == -1\n blk = 0;\nend\n \n\n% initialize\nY = D;\nnorm_two = lansvd(Y, 1, 'L');\nnorm_inf = norm( Y(:), inf) / lambda;\ndual_norm = max(norm_two, norm_inf);\nY = Y / dual_norm;\n\nA_hat = zeros( m, n);\nE_hat = zeros( m, n);\nmu = 1.25/norm_two % this one can be tuned\nmu_bar = mu * 1e7\nrho = 1.2 % this one can be tuned\nd_norm = norm(D, 'fro');\n\niter = 0;\ntotal_svd = 0;\nconverged = false;\nstopCriterion = 1;\nsv = 10;\nd = min(m, n);\n\nmark = false;\nBlock_mark = false ;\n\nwhile ~converged \n iter = iter + 1;\n \n temp_T = D - A_hat + (1/mu)*Y;\n E_hat = max(temp_T - lambda/mu, 0);\n E_hat = E_hat+min(temp_T + lambda/mu, 0);\n \n% if Block_mark==true\n% uv_temp=[U_temp; V_temp]/sqrt(2);\n% [U S V]=BL_SVD(D - E_hat + (1/mu)*Y, U_temp, V_temp, 1);\n% else \n [U S V] = lansvd(D - E_hat + (1/mu)*Y, sv, 'L');\n% end\n \n if mark==true\n U_temp = U;\n V_temp = V;\n Block_mark=true;\n end\n\n diagS = diag(S);\n svp = length(find(diagS > 1/mu));\n \n len = length(diagS);\n ratio = diagS(1:len-1) ./ diagS(2:len);\n% ind = find(ratio > 2);\n% if blk && length(ind) > 0\n% svp = min(svp, ind(1));\n% mark = true;\n% end \n\n if svp < sv\n sv = min(svp + 1, d);\n else\n sv = min(svp + round(0.05*d), d);\n end\n \n A_hat = U(:, 1:svp) * diag(diagS(1:svp) - 1/mu) * V(:, 1:svp)'; \n\n total_svd = total_svd + 1;\n \n Z = D - A_hat - E_hat;\n \n Y = Y + mu*Z;\n mu = min(mu*rho, mu_bar);\n \n %% stop Criterion \n stopCriterion = norm(Z, 'fro') / d_norm;\n if stopCriterion < tol\n converged = true;\n end \n \n if mod( total_svd, 10) == 0\n disp(['#svd ' num2str(total_svd) ' r(A) ' num2str(svp)...\n ' |E|_0 ' num2str(length(find(abs(E_hat)>0)))...\n ' stopCriterion ' num2str(stopCriterion)]);\n end \n \n if ~converged && iter >= maxIter\n disp('Maximum iterations reached') ;\n converged = 1 ; \n end\nend\n\n%elapsed = toc(elapsed);\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/rpca/L1F/ialm_rpca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706733, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5966736258846418}} {"text": "function [dSf_dV1, dSf_dV2, dSt_dV1, dSt_dV2, Sf, St] = dSbr_dV(branch, Yf, Yt, V, vcart)\n%DSBR_DV Computes partial derivatives of branch power flows w.r.t. voltage.\n%\n% The derivatives can be taken with respect to polar or cartesian coordinates\n% of voltage, depending on the 5th argument.\n%\n% [DSF_DVA, DSF_DVM, DST_DVA, DST_DVM, SF, ST] = DSBR_DV(BRANCH, YF, YT, V)\n% [DSF_DVA, DSF_DVM, DST_DVA, DST_DVM, SF, ST] = DSBR_DV(BRANCH, YF, YT, V, 0)\n%\n% Returns four matrices containing partial derivatives of the complex\n% branch power flows at \"from\" and \"to\" ends of each branch w.r.t voltage\n% magnitude and voltage angle, respectively (for all buses).\n%\n% [DSF_DVR, DSF_DVI, DST_DVR, DST_DVI, SF, ST] = DSBR_DV(BRANCH, YF, YT, V, 1)\n%\n% Returns four matrices containing partial derivatives of the complex\n% branch power flows at \"from\" and \"to\" ends of each branch w.r.t real and\n% imaginary parts of voltage, respectively (for all buses).\n%\n% If YF is a sparse matrix, the partial derivative matrices will be as well.\n% Optionally returns vectors containing the power flows themselves. The\n% following explains the expressions used to form the matrices:\n%\n% If = Yf * V;\n% Sf = diag(Vf) * conj(If) = diag(conj(If)) * Vf\n%\n% Polar coordinates:\n% Partials of V, Vf & If w.r.t. voltage angles\n% dV/dVa = j * diag(V)\n% dVf/dVa = sparse(1:nl, f, j * V(f)) = j * sparse(1:nl, f, V(f))\n% dIf/dVa = Yf * dV/dVa = Yf * j * diag(V)\n%\n% Partials of V, Vf & If w.r.t. voltage magnitudes\n% dV/dVm = diag(V./abs(V))\n% dVf/dVm = sparse(1:nl, f, V(f)./abs(V(f))\n% dIf/dVm = Yf * dV/dVm = Yf * diag(V./abs(V))\n%\n% Partials of Sf w.r.t. voltage angles\n% dSf/dVa = diag(Vf) * conj(dIf/dVa)\n% + diag(conj(If)) * dVf/dVa\n% = diag(Vf) * conj(Yf * j * diag(V))\n% + conj(diag(If)) * j * sparse(1:nl, f, V(f))\n% = -j * diag(Vf) * conj(Yf * diag(V))\n% + j * conj(diag(If)) * sparse(1:nl, f, V(f))\n% = j * (conj(diag(If)) * sparse(1:nl, f, V(f))\n% - diag(Vf) * conj(Yf * diag(V)))\n%\n% Partials of Sf w.r.t. voltage magnitudes\n% dSf/dVm = diag(Vf) * conj(dIf/dVm)\n% + diag(conj(If)) * dVf/dVm\n% = diag(Vf) * conj(Yf * diag(V./abs(V)))\n% + conj(diag(If)) * sparse(1:nl, f, V(f)./abs(V(f)))\n%\n% Cartesian coordinates:\n% Partials of V, Vf & If w.r.t. real part of complex voltage\n% dV/dVr = diag(ones(n,1))\n% dVf/dVr = Cf\n% dIf/dVr = Yf\n% where Cf is the connection matrix for line & from buses\n%\n% Partials of V, Vf & If w.r.t. imaginary part of complex voltage\n% dV/dVi = j * diag(ones(n,1))\n% dVf/dVi = j * Cf\n% dIf/dVi = j * Yf\n%\n% Partials of Sf w.r.t. real part of complex voltage\n% dSf/dVr = conj(diag(If)) * Cf + diag(Vf) * conj(Yf)\n%\n% Partials of Sf w.r.t. imaginary part of complex voltage\n% dSf/dVi = j * (conj(diag(If)) * Cf - diag(Vf) * conj(Yf))\n%\n% Derivations for \"to\" bus are similar.\n%\n% Examples:\n% [Ybus, Yf, Yt] = makeYbus(baseMVA, bus, branch);\n% [dSf_dVa, dSf_dVm, dSt_dVa, dSt_dVm, Sf, St] = ...\n% dSbr_dV(branch, Yf, Yt, V);\n% [dSf_dVr, dSf_dVi, dSt_dVr, dSt_dVi, Sf, St] = ...\n% dSbr_dV(branch, Yf, Yt, V, 1);\n%\n% For more details on the derivations behind the derivative code used\n% in MATPOWER, see:\n%\n% [TN2] R. D. Zimmerman, \"AC Power Flows, Generalized OPF Costs and\n% their Derivatives using Complex Matrix Notation\", MATPOWER\n% Technical Note 2, February 2010. [Online]. Available:\n% https://matpower.org/docs/TN2-OPF-Derivatives.pdf\n% doi: 10.5281/zenodo.3237866\n% [TN4] B. Sereeter and R. D. Zimmerman, \"AC Power Flows and their\n% Derivatives using Complex Matrix Notation and Cartesian\n% Coordinate Voltages,\" MATPOWER Technical Note 4, April 2018.\n% [Online]. Available: https://matpower.org/docs/TN4-OPF-Derivatives-Cartesian.pdf\n% doi: 10.5281/zenodo.3237909\n\n% MATPOWER\n% Copyright (c) 1996-2019, Power Systems Engineering Research Center (PSERC)\n% by Ray Zimmerman, PSERC Cornell\n% and Baljinnyam Sereeter, Delft University of Technology\n%\n% This file is part of MATPOWER.\n% Covered by the 3-clause BSD License (see LICENSE file for details).\n% See https://matpower.org for more info.\n\n%% define named indices into bus, gen, branch matrices\n[F_BUS, T_BUS, BR_R, BR_X, BR_B, RATE_A, RATE_B, RATE_C, ...\n TAP, SHIFT, BR_STATUS, PF, QF, PT, QT, MU_SF, MU_ST, ...\n ANGMIN, ANGMAX, MU_ANGMIN, MU_ANGMAX] = idx_brch;\n\n%% default input args\nif nargin < 5\n vcart = 0; %% default to polar coordinates\nend\n\n%% define\nf = branch(:, F_BUS); %% list of \"from\" buses\nt = branch(:, T_BUS); %% list of \"to\" buses\nnl = length(f);\nnb = length(V);\n\n%% compute intermediate values\nYfc = conj(Yf);\nYtc = conj(Yt);\nVc = conj(V);\nIfc = Yfc * Vc; %% conjugate of \"from\" current\nItc = Ytc * Vc; %% conjugate of \"to\" current\n\nif issparse(Yf) %% sparse version (if Yf is sparse)\n diagVf = sparse(1:nl, 1:nl, V(f), nl, nl);\n diagVt = sparse(1:nl, 1:nl, V(t), nl, nl);\n diagIfc = sparse(1:nl, 1:nl, Ifc, nl, nl);\n diagItc = sparse(1:nl, 1:nl, Itc, nl, nl);\n if ~vcart\n Vnorm = V ./ abs(V);\n diagVc = sparse(1:nb, 1:nb, Vc, nb, nb);\n diagVnorm = sparse(1:nb, 1:nb, Vnorm, nb, nb);\n CVf = sparse(1:nl, f, V(f), nl, nb);\n CVnf = sparse(1:nl, f, Vnorm(f), nl, nb);\n CVt = sparse(1:nl, t, V(t), nl, nb);\n CVnt = sparse(1:nl, t, Vnorm(t), nl, nb);\n end\nelse %% dense version\n diagVf = diag(V(f));\n diagVt = diag(V(t));\n diagIfc = diag(Ifc);\n diagItc = diag(Itc);\n if ~vcart\n Vnorm = V ./ abs(V);\n diagVc = diag(Vc);\n diagVnorm = diag(Vnorm);\n% CVf = zeros(nl, nb); CVf(sub2ind([nl,nb], (1:nl)', f)) = V(f);\n% CVnf = zeros(nl, nb); CVnf(sub2ind([nl,nb], (1:nl)', f)) = Vnorm(f);\n% CVt = zeros(nl, nb); CVt(sub2ind([nl,nb], (1:nl)', t)) = V(t);\n% CVnt = zeros(nl, nb); CVnt(sub2ind([nl,nb], (1:nl)', t)) = Vnorm(t);\n CVf = full(sparse(1:nl, f, V(f), nl, nb));\n CVnf = full(sparse(1:nl, f, Vnorm(f), nl, nb));\n CVt = full(sparse(1:nl, t, V(t), nl, nb));\n CVnt = full(sparse(1:nl, t, Vnorm(t), nl, nb));\n end\nend\nif vcart\n Cf = sparse(1:nl, f, ones(nl, 1), nl, nb); %% connection matrix for line & from buses\n Ct = sparse(1:nl, t, ones(nl, 1), nl, nb); %% connection matrix for line & to buses\n Af = diagIfc * Cf;\n Bf = diagVf * Yfc;\n At = diagItc * Ct;\n Bt = diagVt * Ytc;\n\n dSf_dV1 = Af + Bf; %% dSf_dVr\n dSf_dV2 = 1j * (Af - Bf); %% dSf_dVi\n dSt_dV1 = At + Bt; %% dSt_dVr\n dSt_dV2 = 1j * (At - Bt); %% dSt_dVi\nelse\n dSf_dV1 = 1j * (diagIfc * CVf - diagVf * Yfc * diagVc); %% dSf_dVa\n dSf_dV2 = diagVf * conj(Yf * diagVnorm) + diagIfc * CVnf; %% dSf_dVm\n dSt_dV1 = 1j * (diagItc * CVt - diagVt * Ytc * diagVc); %% dSt_dVa\n dSt_dV2 = diagVt * conj(Yt * diagVnorm) + diagItc * CVnt; %% dSt_dVm\nend\n\nif nargout > 4\n Sf = V(f) .* Ifc;\n St = V(t) .* Itc;\nend\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/dSbr_dV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.5966736048776263}} {"text": "function [ value, ifault ] = xinbta ( p, q, beta, alpha )\n\n%*****************************************************************************80\n%\n%% XINBTA computes inverse of the incomplete Beta function.\n%\n% Discussion:\n%\n% The accuracy exponent SAE was loosened from -37 to -30, because\n% the code would not otherwise accept the results of an iteration\n% with p = 0.3, q = 3.0, alpha = 0.2.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 September 2014\n%\n% Author:\n%\n% Original FORTRAN77 version by GW Cran, KJ Martin, GE Thomas.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% GW Cran, KJ Martin, GE Thomas,\n% Remark AS R19 and Algorithm AS 109:\n% A Remark on Algorithms AS 63: The Incomplete Beta Integral\n% and AS 64: Inverse of the Incomplete Beta Integeral,\n% Applied Statistics,\n% Volume 26, Number 1, 1977, pages 111-114.\n%\n% Parameters:\n%\n% Input, real P, Q, the parameters of the incomplete\n% Beta function.\n%\n% Input, real BETA, the logarithm of the value of\n% the complete Beta function.\n%\n% Input, real ALPHA, the value of the incomplete Beta\n% function. 0 <= ALPHA <= 1.\n%\n% Output, real VALUE, the argument of the incomplete\n% Beta function which produces the value ALPHA.\n%\n% Output, integer IFAULT, error flag.\n% 0, no error occurred.\n% nonzero, an error occurred.\n%\n% Local Parameters:\n%\n% Local, real SAE, requests an accuracy of about 10^SAE.\n%\n sae = -30.0;\n\n fpu = 10.0 ^ sae;\n\n ifault = 0;\n value = alpha;\n%\n% Test for admissibility of parameters.\n%\n if ( p <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'XINBTA - Fatal error!\\n' );\n fprintf ( 1, ' P <= 0.0\\n' );\n ifault = 1;\n error ( 'XINBTA - Fatal error!' );\n end\n\n if ( q <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'XINBTA - Fatal error!\\n' );\n fprintf ( 1, ' Q <= 0.0\\n' );\n ifault = 1;\n error ( 'XINBTA - Fatal error!' );\n end\n\n if ( alpha < 0.0 || 1.0 < alpha )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'XINBTA - Fatal error!\\n' );\n fprintf ( 1, ' ALPHA not between 0 and 1.\\n' );\n ifault = 2;\n error ( 'XINBTA - Fatal error!' );\n end\n%\n% If the answer is easy to determine, return immediately.\n%\n if ( alpha == 0.0 )\n value = 0.0;\n return\n end\n\n if ( alpha == 1.0 )\n value = 1.0;\n return\n end\n%\n% Change tail if necessary.\n%\n if ( 0.5 < alpha )\n a = 1.0 - alpha;\n pp = q;\n qq = p;\n indx = 1;\n else\n a = alpha;\n pp = p;\n qq = q;\n indx = 0;\n end\n%\n% Calculate the initial approximation.\n%\n r = sqrt ( - log ( a * a ) );\n\n y = r - ( 2.30753 + 0.27061 * r ) ...\n / ( 1.0 + ( 0.99229 + 0.04481 * r ) * r );\n\n if ( 1.0 < pp && 1.0 < qq )\n\n r = ( y * y - 3.0 ) / 6.0;\n s = 1.0 / ( pp + pp - 1.0 );\n t = 1.0 / ( qq + qq - 1.0 );\n h = 2.0 / ( s + t );\n w = y * sqrt ( h + r ) / h - ( t - s ) ...\n * ( r + 5.0 / 6.0 - 2.0 / ( 3.0 * h ) );\n value = pp / ( pp + qq * exp ( w + w ) );\n\n else\n\n r = qq + qq;\n t = 1.0 / ( 9.0 * qq );\n t = r * ( 1.0 - t + y * sqrt ( t ) )^3;\n\n if ( t <= 0.0 )\n value = 1.0 - exp ( ( log ( ( 1.0 - a ) * qq ) + beta ) / qq );\n else\n\n t = ( 4.0 * pp + r - 2.0 ) / t;\n\n if ( t <= 1.0 )\n value = exp ( ( log ( a * pp ) + beta ) / pp );\n else\n value = 1.0 - 2.0 / ( t + 1.0 );\n end\n\n end\n\n end\n%\n% Solve for X by a modified Newton-Raphson method,\n% using the function BETAIN.\n%\n r = 1.0 - pp;\n t = 1.0 - qq;\n yprev = 0.0;\n sq = 1.0;\n prev = 1.0;\n\n if ( value < 0.0001 )\n value = 0.0001;\n end\n\n if ( 0.9999 < value )\n value = 0.9999;\n end\n\n iex = max ( - 5.0 / pp / pp - 1.0 / a ^ 0.2 - 13.0, sae );\n\n acu = 10.0 ^ iex;\n%\n% Iteration loop.\n%\n while ( 1 )\n\n [ y, ifault ] = betain ( value, pp, qq, beta );\n\n if ( ifault ~= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'XINBTA - Fatal error!\\n' );\n fprintf ( 1, ' BETAIN returns IFAULT = %d\\n', ifault );\n error ( 'XINBTA - Fatal error!' );\n ifault = 3;\n return\n end\n\n xin = value;\n y = ( y - a ) * exp ( beta + r * log ( xin ) + t * log ( 1.0 - xin ) );\n\n if ( y * yprev <= 0.0 )\n prev = max ( sq, fpu );\n end\n\n g = 1.0;\n\n while ( 1 )\n\n while ( 1 )\n\n adj = g * y;\n sq = adj * adj;\n\n if ( sq < prev )\n\n tx = value - adj;\n\n if ( 0.0 <= tx && tx <= 1.0 )\n break\n end\n\n end\n\n g = g / 3.0;\n\n end\n%\n% Check whether current estimate is acceptable.\n% The change \"VALUE = TX\" was suggested by Ivan Ukhov.\n%\n if ( prev <= acu && y * y <= acu )\n value = tx;\n if ( indx )\n value = 1.0 - value;\n end\n return\n end\n\n if ( tx ~= 0.0 && tx ~= 1.0 )\n break\n end\n\n g = g / 3.0;\n\n end\n\n if ( tx == value )\n break\n end\n\n value = tx;\n yprev = y;\n\n end\n\n if ( indx )\n value = 1.0 - value;\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/asa109/xinbta.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5965798967047176}} {"text": "function [M] = spm_nwcov (M)\n% Get second moments of Normal-Wishart\n% FORMAT [M] = spm_nwcov (M)\n%\n% .mean_prior_cov Prior covariance of mean\n% .sample_prior_cov Prior covariance of samples\n% .mean_post_cov Posterior covariance of mean\n% .sample_pred_cov Predictive covariance of samples\n%\n% The latter quantity is also the covariance of the predictive density\n% The marginal distributions of the mean and of the samples \n% are multivariate-T, not Gaussian.\n%\n% See J. Bernardo and A. Smith (2000) \n% Bayesian Theory, Wiley (page 435)\n%__________________________________________________________________________\n% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny\n% $Id: spm_nwcov.m 6548 2015-09-11 12:39:47Z will $\n\n% Get prior covariances\nM.mean_prior_cov=M.B0/(M.n0*(M.a0-1));\n\nalpha=2*M.a0-M.P+1;\nw_s=(1+1/M.n0)/(0.5*alpha-1);\nM.sample_prior_cov=w_s*M.B0;\n\n% Get posterior covariances\nM.mean_post_cov=M.BN/(M.nN*(M.aN-1));\n\nalpha=2*M.aN-M.P+1;\nw_s=(1+1/M.nN)/(0.5*alpha-1);\nM.sample_pred_cov=w_s*M.BN;", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/mci/inference/spm_nwcov.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.6584175139669998, "lm_q1q2_score": 0.5965195618737015}} {"text": "function Q = ForwardStepBC2D(xin, yin, nxin, nyin, mapI, mapO, mapW, mapC, Q, time);\n \n% function [Q] = ForwardStepBC2D(xin, yin, nxin, nyin, mapI, mapO, mapW, mapC, Q, time);\n% Purpose: Impose channel boundary conditions on 2D Euler equations on weak form\n\n% Example is Mach ** 0.3 ** flow in wind tunnel\ngamma = 1.4;\n\n% extract conserved variables\nrho = Q(:,:,1); rhou = Q(:,:,2); rhov = Q(:,:,3); Ener = Q(:,:,4);\n\n% Inflow conditions -- uniform inflow\nrhoin = gamma; uin = 3.0; vin = 0.0; pin = 1.0;\nEin = pin/(gamma-1.0) + 0.5*rhoin*(uin^2+vin^2);\n\nrho(mapI) = rhoin; rhou(mapI) = rhoin*uin; rhov(mapI) = rhoin*vin; Ener(mapI) = Ein;\n\n% Outflow conditions -- supersonic outflow ( do nothing )\n\n% Wall conditions -- reflective, isothermal, i.e., n.u=0, T=T(t=0)\nrhoW = rho(mapW); rhouW = rhou(mapW); rhovW = rhov(mapW); \nnxW = nxin(mapW); nyW = nyin(mapW);\n\n% reverse flow in normal direction in ghost elements\nrhou(mapW) = rhouW - 2*nxW.*(nxW.*rhouW + nyW.*rhovW);\nrhov(mapW) = rhovW - 2*nyW.*(nxW.*rhouW + nyW.*rhovW);\n\n% pack modified conserved variables\nQ(:,:,1) = rho; Q(:,:,2) = rhou; Q(:,:,3) = rhov; Q(:,:,4) = Ener;\nreturn\n", "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/JSHesthaven&TWarburton/CFD2D/ForwardStepBC2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5965148081209276}} {"text": "function W = nullspaceLUSOLapply2Modes(mode, m, n, V, nullS)\n% Computes the matrix vector product with the operator nullspace\n% function handle of the form `y = pdMat(mode, m, n, x)`\n%\n% USAGE:\n%\n% W = nullspaceLUSOLapply2Modes(mode, m, n, V, nullS)\n%\n% INPUTS:\n% mode: :math:`mode = 1` returns :math:`W = Z V`, `mode = 2` returns :math:`W = Z^T V`\n% m: first dimension of the matrix\n% n: second dimension of the matrix\n% V: one of the components of the multiplication\n% nullS: structure `nullS` from the function `nullspaceLUSOLform(S)`;\n% where `m x n` sparse matrix `S` (:math:`m < n`).\n%\n% OUTPUT:\n% W: Matrix vector product\n%\n% .. 16 May 2008: (MAS) First version of nullspaceLUSOLapply.m. See nullspaceLUSOLtest.m for testing.\n% .. 13 Mar 2009: (RF) Tried to add matrix vector product of the transpose for use with pdco\n\nif mode==1\n %returns W = Z*V (mode=1)\n\n % Second, if V is an (n-m) x k sparse matrix (k >= 1),\n % W = nullspaceLUSOLapply(nullS,V);\n % computes an n x k sparse matrix W from V such that S*W = 0.\n %\n % This is an operator form of finding an n x (n-m) matrix Z\n % such that S*Z = 0 and then computing W = Z*V.\n % The aim is to obtain W without forming Z explicitly.\n\n % 16 May 2008: (MAS) First version of nullspaceLUSOLapply.m.\n % See nullspaceLUSOLtest.m for testing.\n\n Cinv = nullS.Cinv; % Column scales\n L = nullS.L; % Strictly triangular L\n p = nullS.p; % Column permutation for S\n rankS = nullS.rank; % rank(S)\n\n [n ,n ] = size(L);\n [mV,nV] = size(V);\n\n B = [sparse(rankS,nV)\n V ];\n Z = (L')\\B;\n W = Z;\n W(p,:) = Z;\n W = Cinv*W;\nelse\n %returns W = Z'*V (mode=2).\n\n % This is an operator form of finding an n x (n-m) matrix Z\n % such that S*Z = 0 and then computing W = Z'*V.\n % The aim is to obtain W without forming Z explicitly.\n\n % When S is scaled as S = R*A*C, we have Z = Cinv*P'*inv(L')[0;I]\n\n % This was the maths I tried to follow -RF\n % W = A'*V\n % = (Cinv*P'*inv(L')[0;I])'*V\n % = [0,I]'*inv(L)*P*Cinv'*V\n\n\n Cinv = nullS.Cinv; % Column scales\n L = nullS.L; % Strictly triangular L\n p = nullS.p; % Column permutation for S\n rankS = nullS.rank; % rank(S)\n\n [n ,n ] = size(L);\n\n V = Cinv'*V;\n\n % I am not sure how to use these permutations\n % e.g. if P*A = B then is it B(p,:)=A or B=A(p,:)\n V(p,:) = V;\n% V(fliplr(p),:) = V;\n\n W = L\\V;\n\n W = W(rankS+1:n,:);\n\nend\n\nreturn\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/subspaces/nullspace/nullspaceLUSOLapply2Modes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5964957720134906}} {"text": "function dt_stability_limit = checkStability(kgrid, medium)\n% CHECKSTABILITY Compute maximum stable timestep for k-space models \n%\n% DESCRIPTION:\n% checkStability calculates the maximum time step for which the\n% k-space propagation models kspaceFirstOrder1D, kspaceFirstOrder2D\n% and kspaceFirstOrder3D are stable. These models are unconditionally\n% stable when the reference sound speed is equal to or greater than\n% the maximum sound speed in the medium and there is no absorption.\n% However, when the reference sound speed is less than the maximum\n% sound speed the model is only stable for sufficiently small time\n% steps. The criterion is more stringent (the time step is smaller)\n% in the absorbing case. \n%\n% The time steps given are accurate when the medium properties are\n% homogeneous. For a heterogeneous media they give a useful, but not\n% exact, estimate. \n%\n% The timesteps given are accurate when the medium properties are\n% homogeneous. For a heterogeneous media they give a useful, but not\n% exact, estimate.\n%\n% USAGE:\n% dt_stability_limit = checkStability(kgrid, medium)\n%\n% INPUTS:\n%\n% kgrid - structure returned by makeGrid holding grid parameters\n% medium - structure holding the medium properties\n%\n% OUTPUTS:\n% \n% dt_stability_limit - maximum timestep for stability. (Set to Inf\n% when the model is unconditionally stable.) \n%\n% ABOUT:\n% author - Ben Cox\n% date - 12th August 2014\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% See also kspaceFirstOrder1D, kspaceFirstOrder2D, kspaceFirstOrder3D,\n% makeGrid, makeTime\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\n% Find the maximum wavenumber\nkmax = max(kgrid.k(:));\n\n% calculate the reference sound speed for the fluid code, using the\n% maximum by default which ensures the model is unconditionally stable\nif isfield(medium, 'sound_speed_ref')\n if isnumeric(medium.sound_speed_ref)\n c_ref = medium.sound_speed_ref;\n elseif strcmp(medium.sound_speed_ref, 'min')\n c_ref = min(medium.sound_speed(:));\n elseif strcmp(medium.sound_speed_ref, 'mean')\n c_ref = mean(medium.sound_speed(:));\n else strcmp(medium.sound_speed_ref, 'max')\n c_ref = max(medium.sound_speed(:)); \n end\nelse\n c_ref = max(medium.sound_speed(:));\nend\n\n% calculate the timesteps required for stability\nif ~isfield(medium, 'alpha_coeff') || all(medium.alpha_coeff(:) == 0)\n\n % =====================================================================\n % NON-ABSORBING CASE\n % =====================================================================\n \n if c_ref >= max(medium.sound_speed(:))\n \n % set the timestep to Inf when the model is unconditionally stable.\n dt_stability_limit = Inf;\n \n else\n \n % set the timestep required for stability when c_ref~=max(medium.sound_speed(:))\n dt_stability_limit = 2/(c_ref * kmax) * asin(c_ref/max(medium.sound_speed(:)));\n \n end\n \nelse\n\n % =====================================================================\n % ABSORBING CASE\n % =====================================================================\n\n % convert the absorption coefficient to nepers.(rad/s)^-y.m^-1\n medium.alpha_coeff = db2neper(medium.alpha_coeff, medium.alpha_power);\n\n % calculate the absorption constant\n if ~(isfield(medium, 'alpha_mode') && strcmp(medium.alpha_mode, 'no_absorption'))\n absorb_tau = -2*medium.alpha_coeff.*medium.sound_speed.^(medium.alpha_power - 1);\n else\n absorb_tau = 0;\n end\n\n % calculate the dispersion constant\n if ~(isfield(medium, 'alpha_mode') && strcmp(medium.alpha_mode, 'no_dispersion'))\n absorb_eta = 2*medium.alpha_coeff.*medium.sound_speed.^(medium.alpha_power)*tan(pi*medium.alpha_power/2);\n else\n absorb_eta = 0;\n end\n \n % Estimate the timestep required for stability in the absorbing case by\n % assuming the k-space correction factor, kappa = 1;\n % (Note that absorb_tau and absorb_eta are negative quantities.)\n temp1 = max(medium.sound_speed(:)) * min(absorb_tau(:)) * kmax^(medium.alpha_power-1);\n temp2 = 1 - min(absorb_eta(:)) * kmax^(medium.alpha_power-1);\n dt_estimate = (temp1 + sqrt(temp1^2 + 4*temp2))/(temp2 * kmax * max(medium.sound_speed(:)));\n \n % Use a fixed point iteration to find the correct timestep, assuming\n % now that kappa = kappa(dt), using the previous estimate as a starting\n % point\n \n % First define the function to iterate\n kappa = @(dt) sinc(c_ref*kmax*dt/2);\n temp3 = @(dt) max(medium.sound_speed(:))*min(absorb_tau(:))*kappa(dt)*kmax^(medium.alpha_power-1);\n func_to_solve = @(dt) (temp3(dt) + sqrt((temp3(dt))^2 + 4*temp2 ))/(temp2*kmax*kappa(dt)*max(medium.sound_speed(:)));\n\n % run the fixed point iteration \n dt_stability_limit = dt_estimate;\n dt_old = 0;\n accuracy = 1e-12;\n while abs(dt_stability_limit-dt_old)>accuracy\n dt_old = dt_stability_limit;\n dt_stability_limit = func_to_solve(dt_stability_limit);\n end\n \nend\n\n", "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/checkStability.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5964038095849671}} {"text": "function [logp, yhat, res] = tapas_beta_obs(r, infStates, ptrans)\n% Calculates the log-probability of responses representing probabilities on the unit interval\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2013-2016 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% Transform nu-prime to its native space\nnupr = exp(ptrans(1));\n\n% Initialize returned log-probabilities, predictions,\n% and residuals as NaNs so that NaN is returned for all\n% irregualar trials\nn = size(infStates,1);\nlogp = NaN(n,1);\nyhat = NaN(n,1);\nres = NaN(n,1);\n\n% Predictions or posteriors?\nif strcmp(r.c_prc.model,'tapas_rw_binary')\n mu = tapas_sgm(infStates(:,1), 1);\nelse\n mu = infStates(:,1,1); % Default: predictions (ie, mu1hat)\n if r.c_obs.predorpost == 2\n mu = tapas_sgm(infStates(:,2,3), 1); % Alternative: posteriors (ie, sgm(mu2))\n end\nend\n\n% Special cases\nif strcmp(r.c_prc.model,'hgf_whichworld')\n mu = tapas_sgm(infStates(:,2,1,3), 1);\nend\nif strcmp(r.c_prc.model,'ph_binary')\n mu = infStates(:,2);\nend\n\n% Weed irregular trials out from inferred states and responses\nmu(r.irr) = [];\ny = r.y(:,1);\ny(r.irr) = [];\n\n% y has to be in the *open* unit interval\n%y(y==0) = 1e-4;\n%y(y==1) = 1-1e-4;\ny = 0.95.*(y-0.5)+0.5; % Shrink all y values toward 1/2 by a factor of 0.95\n\n% Nu is nu-prime plus two (sometimes)\n%nu = nupr+2;\nnu = nupr;\n\n% Calculate alpha and beta from mu and nu\nal = mu.*nu;\nbe = nu - al;\n\n% Calculate log-probabilities for non-irregular trials\nreg = ~ismember(1:n,r.irr);\nlogp(reg) = log(betaDens(y,al,be));\nyhat(reg) = mu;\nres(reg) = y-mu;\n\nend\n\nfunction p = betaDens(x,alpha,beta)\n% Check whether x is in the unit interval\nif any(x(:)<0) || any(x(:)>1)\n error('tapas:hgf:BetaObs:ArgNotInUnitIntrv', 'Error: first argument to betaDens must be in the unit interval.');\nend\n% Check whether alpha and beta are greater than 0\nif any(alpha(:)<0) || any(beta(:)<0)\n error('tapas:hgf:BetaObs:AlphaOrBetaNeg', 'Error: alpha and beta have to be non-negative.');\nend\n% Calculate beta density\np = gamma(alpha+beta)./(gamma(alpha).*gamma(beta)).*x.^(alpha-1).*(1-x).^(beta-1);\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_beta_obs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.6893056040203136, "lm_q1q2_score": 0.5964038088536905}} {"text": "function [IPPEPoses,refinedPoses,HHat,U,Q] = featureBasedPlanePoseFromImage(planarTemplate,inputImage,K,kc,featureOpts,ransacOpts,IPPEOpts,plottingOpts)\n%featureBasedPlanePoseFromImage: An example of using IPPE to solve a plane's pose given a frontal 'template' image and a single input image. This follows the following pipeline:\n%\n%1. Detect features in the template and input image\n%2. Match features based on their descriptor similarity\n%3. Use the matched features to robustly estimate the homography between the template image and the input image.\n%4. From the inlier matches, use IPPE to estimate the camera's pose.\n%5. (Optionally) Refine the camera's pose with Levenberg–Marquardt.\n%\n% The camera should be intrinsically calibrated a priori. We use a perspective camera model with lens distortion, which\n% is the standard model and used in OpenCV and Bouguet's Matlab camera calibration toolbox\n%(http://www.vision.caltech.edu/bouguetj/calib_doc/). This is parameterised by a 3x3 calibration matrix K and a 5x1 distortion vector\n%kc. You can determine K and kc by running Bouguet's calibration toolbox using a checkerboard calibration target.\n%\n%Inputs\n%\n%planarTemplate: a structure holding the planar object used to compute the\n%camera's pose. See makePlanarTemplate.m for a description of its fields.\n%\n%inputImage: a 2D unit8 input image (grayscale or rgb). This is an image of the plane viewed\n%from the camera. \n%\n%K: The input image's 3x3 intrinsic matrix (5x1 double).\n%\n%kc: The input image's distortion parameters (5x1 double)\n%\n%Note that when using ASIFT, it is best to use an undistorted image (i.e.\n%the effects of lens distortion are undone). This is because ASIFT does som\n%match filtering based on epipolar geometry, and does not handle lens\n%distortion. \n%\n%featureOpts: Options for feature detection and matching. See\n%detectAndMatchFeatures.m for details.\n%\n%ransacOpts: Options for ransac. See basicHomographyRansac.m for details.\n%detectAndMatchFeatures.m for details.\n%\n%IPPEOpts: Options for IPPE pose estimation. See perspectiveIPPE.m for details.\n%\n%plottingOpts: Options for plotting the fitted homography. This has two\n%fields:\n% plottingOpts.doPlot (true or false): true if we want to visualise\n% results, false otherwise\n% plottingOpts.figId (positive integer): the figure number for plotting the results. \n%\n%Outputs:\n%IPPEPoses: structure containing the two pose solutions from IPPE. See\n%perspectiveIPPE.m for details.\n%\n%refinedPoses: structure containing the two refined pose solutions using\n%Levenberg–Marquardt (same format as IPPEPoses). See\n%perspectiveIPPE.m for details. \n%\n%HHat is the homography matrix outputted from ransac (3x3 double). Note\n%that this is the mapping from the template's image to the input image's\n%normalised pixel coordinates. \n%\n%poseResults.U is the set of inlier correspondences detected in the template image (in mm) (2xN double)\n%\n%poseResults.Q is the set of inlier correspondences detected in the input image (in normalised pixels) (2xN double)\n%\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This file is part of the IPPE package for fast plane-based pose\n% estimation from the paper \"Infinitesimal Plane-based Pose Estimation\" by Toby Collins and Adrien Bartoli,\n% published in the International Journal of Computer Vision, September\n% 2014. A copy of the author's pre-print version can be found here:\n%\n% http://isit.u-clermont1.fr/~ab/Publications/Collins_Bartoli_IJCV14.pdf\n%\n% This package is free and covered by the BSD licence without any warranty. We hope you find this code useful and please cite our paper in your work:\n% (c) Toby Collins 2015\n%\n%\n%\n%@article{\n%year={2014},\n%issn={0920-5691},\n%journal={International Journal of Computer Vision},\n%volume={109},\n%number={3},\n%doi={10.1007/s11263-014-0725-5},\n%title={Infinitesimal Plane-Based Pose Estimation},\n%url={http://dx.doi.org/10.1007/s11263-014-0725-5},\n%publisher={Springer US},\n%keywords={Plane; Pose; SfM; PnP; Homography},\n%author={Collins, Toby and Bartoli, Adrien},\n%pages={252-286},\n%language={English}\n%}\n%\n%\n%basic argument checking:\nassert(isa(inputImage,'uint8'));\nassert(size(K,1)==3);\nassert(size(K,2)==3);\nassert(size(kc,1) == 5);\nassert(size(kc,2) == 1);\n\n%first detect and match features:\n[p,q] = detectAndMatchFeatures(planarTemplate.rectifiedImage_g,planarTemplate.roi,...\n inputImage,[],featureOpts);\nqNormalised = normaliseImagePoints(q,K,kc);\n\n%now estimate the homography with RANSAC:\n[HHat,inliers] = basicHomographyRansac(p,qNormalised,ransacOpts);\n\n%lets plot the results:\nif plottingOpts.doPlot\n visualiseHomography(planarTemplate.rectifiedImage_g,planarTemplate.roi,inputImage,HHat,K,kc,p,q,inliers,plottingOpts.figId); \nend\n\n%Now use IPPE to estimate the camera's pose.\n\n%First get the points on the template image into mm, and reject outliers:\nU = planarTemplate.templatImgPixelSize*p(:,inliers);\nQ = qNormalised(:,inliers);\n\n[IPPEPoses,refinedPoses] = perspectiveIPPE(U,Q,[],IPPEOpts);\n", "meta": {"author": "tobycollins", "repo": "IPPE", "sha": "3304dfa40c7cbd046ba0d540b8b1143283c83f4e", "save_path": "github-repos/MATLAB/tobycollins-IPPE", "path": "github-repos/MATLAB/tobycollins-IPPE/IPPE-3304dfa40c7cbd046ba0d540b8b1143283c83f4e/matlab/IPPE_utils/featureBasedPlanePoseFromImage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.865224072151174, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5964038071894304}} {"text": "function [U_final, V_final, nIter_final, objhistory_final] = LCCF(X, k, W, options, U, V)\n% Locally Consistant Concept Factorization (LCCF)\n%\n% where\n% X\n% Notation:\n% X ... (mFea x nSmp) data matrix \n% mFea ... number of words (vocabulary size)\n% nSmp ... number of documents\n% k ... number of hidden factors\n% W ... weight matrix of the affinity graph \n%\n% options ... Structure holding all settings\n%\n% You only need to provide the above four inputs.\n%\n% X = X*U*V'\n%\n% References:\n% [1] Deng Cai, Xiaofei He, Jiawei Han, \"Locally Consistent Concept\n% Factorization for Document Clustering\", IEEE Transactions on Knowledge\n% and Data Engineering, Vol. 23, No. 6, pp. 902-913, 2011. \n%\n%\n% version 2.0 --April/2010 \n% version 1.0 --Dec./2008 \n%\n% Written by Deng Cai (dengcai AT gmail.com)\n%\n\nnSmp=size(X,2);\n\nif ~isfield(options,'error')\n options.error = 1e-5;\nend\nif ~isfield(options, 'maxIter')\n options.maxIter = [];\nend\n\nif ~isfield(options,'nRepeat')\n options.nRepeat = 10;\nend\n\nif ~isfield(options,'minIter')\n options.minIter = 30;\nend\n\nif ~isfield(options,'meanFitRatio')\n options.meanFitRatio = 0.1;\nend\n\nif ~isfield(options,'alpha')\n options.alpha = 100;\nend\n\nif isfield(options,'alpha_nSmp') && options.alpha_nSmp\n options.alpha = options.alpha*nSmp; \nend\n\nif ~exist('U','var')\n U = [];\n V = [];\nend\n\nK = constructKernel(X',[],options);\n\nif isfield(options,'weight') && strcmpi(options.weight,'NCW')\n D_mhalf = sum(K,2).^-.5;\n D_mhalf = spdiags(D_mhalf,0,nSmp,nSmp);\n K = D_mhalf*K*D_mhalf;\nend\n\nif ~isfield(options,'Optimization')\n options.Optimization = 'Multiplicative';\nend\n\nswitch lower(options.Optimization)\n case {lower('Multiplicative')} \n [U_final, V_final, nIter_final,objhistory_final] = LCCF_Multi(K, k, W, options, U, V);\n otherwise\n error('optimization method does not exist!');\nend\n", "meta": {"author": "ZJULearning", "repo": "MatlabFunc", "sha": "97504df0f597c1980ab76ddc0c9c5d669043c6c9", "save_path": "github-repos/MATLAB/ZJULearning-MatlabFunc", "path": "github-repos/MATLAB/ZJULearning-MatlabFunc/MatlabFunc-97504df0f597c1980ab76ddc0c9c5d669043c6c9/MatrixFactorization/LCCF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5963135192815814}} {"text": "% The following is an implementation of \"the HMSD fusion based on the guided filter (HMSD-GF)\"\n% (without visibility enhancement before the fusion).\n% Ref: \"Fusion of infrared and visible images for night-vision context \n% enhancement\", Applied Optics, 55(23), 2016\n% \n% The HMSD (Hybrid-MSD) fusion method was originally proposed in:\n% Zhiqiang Zhou et al. \"Perceptual fusion of infrared and visible images through a hybrid \n% multi-scale decomposition with Gaussian and bilateral filters\", Information Fusion, 30, 2016 \n% \n% Some of the test images were obtained at\n% http://www.imagefusion.org\n% http://www.ece.lehigh.edu/SPCRL/IF/image_fusion.htm\n%\n% Zhiqiang Zhou, Beijing Institute of Technology\n% Apr. 2016\n\nclear all;\n% close all;\nnLevel = 4;\n\n% path_Vis = '.\\image\\b01_1.tif'; path_IR = '.\\image\\b01_2.tif';\n path_Vis = '.\\image\\Camp_Vis.jpg'; path_IR = '.\\image\\Camp_IR.jpg';\n% path_Vis = '.\\image\\Trees4906_Vis.jpg'; path_IR = '.\\image\\Trees4906_IR.jpg';\n% path_Vis = '.\\image\\Octec_Vis.jpg'; path_IR = '.\\image\\Octec_IR.jpg';\n% path_Vis = '.\\image\\Road_Vis.jpg'; path_IR = '.\\image\\Road_IR.jpg';\n% path_Vis = '.\\image\\Kayak_Vis.jpg'; path_IR = '.\\image\\Kayak_IR.jpg';\n% path_Vis = '.\\image\\Steamboat_Vis.jpg'; path_IR = '.\\image\\Steamboat_IR.jpg';\n% path_Vis = '.\\image\\Trees4917_Vis.jpg'; path_IR = '.\\image\\Trees4917_IR.jpg';\n% path_Vis = '.\\image\\Dune_Vis.jpg'; path_IR = '.\\image\\Dune_IR.jpg';\n\n[img1, img2, para.name] = PickName(path_Vis, path_IR);\nparaShow1.fig = 'Visible image';\nparaShow2.fig = 'Infrared image';\nShowImageGrad(img2, paraShow2);\nShowImageGrad(img1, paraShow1);\n\n% %% ---------- Visibility enhancement for visible image--------------\n% img1E = Ehn_GF(img1);\n% img1 = img1E;\n% %% ---------- Infrared image normalization--------------\n% mi = min(img2(:));\n% ma = max(img2(:));\n% img2 = (img2-mi)/(ma-mi)*255;\n\n%% ---------- Automatic parameter selection --------------\nRs = Relative_PS(img2, img1);\nif Rs<0.8\n lambda = 100\nelse\n if Rs>1.6\n lambda = 2000\n else\n lambda = 2500*Rs - 1900\n end\nend \n\n%% ---------- Hybrid multiscale decomposition based on guided filter--------------\nsigma = 2; k = 2;\nr0 = 2; eps0 = 0.1; \nl = 2;\n\nM1 = cell(1, nLevel+1);\nM1L = cell(1, nLevel+1);\nM1{1} = img1/255;\nM1L{1} = M1{1};\nM1D = cell(1, nLevel+1);\nM1E = cell(1, nLevel+1);\nsigma0 = sigma;\nr = r0;\neps = eps0;\nfor ii = 2:nLevel+1,\n \n% % ***using fast guided filter, which has the potential to achieve real-time performance when codes are fully optimized\n% % ***NOTE: large subsampling ratio may cause problem for fusion of some source images.\n% s = max(1, r/2); % subsampling ratio\n% M1{ii} = fastguidedfilter_md(M1{ii-1}, M1{ii-1}, r, 100^2, s); \n% M1L{ii} = fastguidedfilter_md(M1L{ii-1}, M1L{ii-1}, r, eps^2, s);\n \n M1{ii} = guidedfilter(M1{ii-1}, M1{ii-1}, r, 100^2); \n M1L{ii} = guidedfilter(M1L{ii-1}, M1L{ii-1}, r, eps^2); \n \n M1D{ii} = M1{ii-1} - M1L{ii};\n M1E{ii} = M1L{ii} - M1{ii};\n \n sigma0 = k*sigma0;\n r = k*r;\n eps = eps/l;\nend\n\nM2 = cell(1, nLevel+1);\nM2L = cell(1, nLevel+1);\nM2{1} = img2/255;\nM2L{1} = M2{1};\nM2D = cell(1, nLevel+1);\nM2E = cell(1, nLevel+1);\nsigma0 = sigma;\nr = r0;\neps = eps0;\nfor ii = 2:nLevel+1,\n% s = max(1, r/2);\n% M2{ii} = fastguidedfilter_md(M2{ii-1}, M2{ii-1}, r, 100^2, s);\n% M2L{ii} = fastguidedfilter_md(M2L{ii-1}, M2L{ii-1}, r, eps^2, s);\n M2{ii} = guidedfilter(M2{ii-1}, M2{ii-1}, r, 100^2);\n M2L{ii} = guidedfilter(M2L{ii-1}, M2L{ii-1}, r, eps^2); \n \n M2D{ii} = M2{ii-1} - M2L{ii};\n M2E{ii} = M2L{ii} - M2{ii};\n\n sigma0 = k*sigma0;\n r = k*r;\n eps = eps/l;\nend\n\n%% ---------- Fusion --------------\n\nfor j = nLevel+1:-1:3\nD2 = abs(M2E{j});\nD1 = abs(M1E{j});\nR = max(D2-D1, 0);\nRmax = max(R(:));\nP = R/Rmax;\n\nCj = atan(lambda*P)/atan(lambda);\n\nsigma_b = 2*sigma0;\nif j == nLevel+1\n w = floor(3*sigma_b);\n h = fspecial('gaussian', [2*w+1, 2*w+1], sigma_b);\n lambda0 = lambda;\n Cb = atan(lambda0*P)/atan(lambda0);\n Cb = imfilter(Cb, h, 'symmetric');\n MB = Cb.*M2{nLevel+1} + (1-Cb).*M1{nLevel+1};\nend\n\nsigma_c = 1;\nw = floor(3*sigma_c);\nh = fspecial('gaussian', [2*w+1, 2*w+1], sigma_c); \nCj = imfilter(Cj, h, 'symmetric');\n\nmd = Cj.*M2E{j}+ (1-Cj).*M1E{j};\nMB = MB + md;\nmd = Cj.*M2D{j}+ (1-Cj).*M1D{j};\nMB = MB + md;\nend \n\nsigma_t = 1;\nw = floor(3*sigma_t);\nh = fspecial('gaussian', [2*w+1, 2*w+1], sigma_t); \nC11 = double(abs(M1E{2}) < abs(M2E{2}));\nC11 = imfilter(C11, h, 'symmetric');\nmd = C11.*M2E{2}+ (1-C11).*M1E{2};\nMB = MB + md; \nC10 = double(abs(M1D{2}) < abs(M2D{2}));\nmd = C10.*M2D{2}+ (1-C10).*M1D{2};\nMB = MB + md;\nFI = min(round(MB*275), 255);\nFI = max(FI, 0);\n\nparaShow.fig = 'Result';\nShowImageGrad(FI, paraShow);\n\n\n", "meta": {"author": "thfylsty", "repo": "Classic-and-state-of-the-art-image-fusion-methods", "sha": "5d9457df396f1ea6921e1b9b3703995205940862", "save_path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods", "path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods/Classic-and-state-of-the-art-image-fusion-methods-5d9457df396f1ea6921e1b9b3703995205940862/Context-Enhance-via-Fusion-master/Context_Enhance_via_Fusion/HMSD_GF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625322, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5963135072511138}} {"text": "function [ r, z, rho, c, s ] = dchud ( r, ldr, p, x, z, ldz, nz, y, rho )\n\n%*****************************************************************************80\n%\n%% DCHUD updates an augmented Cholesky decomposition.\n%\n% Discussion:\n%\n% DCHUD can also update the triangular part of an augmented QR\n% decomposition.\n%\n% Specifically, given an upper triangular matrix R of order P, a row vector\n% X, a column vector Z, and a scalar Y, DCHUD determines a unitary matrix\n% U and a scalar ZETA such that\n%\n% (R Z) (RR ZZ )\n% U * ( ) = ( ),\n% (X Y) ( 0 ZETA)\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) appended. In this case, if RHO is the\n% norm of the residual vector, then the norm of the residual vector of\n% the updated problem is sqrt ( RHO * RHO + ZETA * ZETA ). DCHUD will\n% simultaneously update several triplets (Z, Y, RHO).\n%\n% For a less terse description of what DCHUD does and how\n% it may be applied, see the LINPACK guide.\n%\n% The matrix U is determined as the product U(P)*...*U(1),\n% where U(I) is a rotation in the (I,P+1) 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% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 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 R(LDR,P), the upper triangular matrix to be\n% updated. 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 equal to P.\n%\n% Input, integer P, the order of the matrix R.\n%\n% Input, real X(P), the row to be added to R.\n%\n% Input, real Z(LDZ,NZ), contains NZ P-vectors to be updated 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 updated. NZ may be\n% zero, in which case Z, Y, and RHO are not referenced.\n%\n% Input, real Y(NZ), the scalars for updating the vectors Z.\n%\n% Input, real RHO(NZ), the norms of the residual vectors to be updated. \n% If RHO(J) is negative, it is left unaltered.\n%\n% Output, real R(LDR,P), the updated matrix.\n%\n% Output, real Z(LDZ,NZ), the updated vectors.\n%\n% Output, real RHO(NZ), the updated norms of the residual vectors.\n%\n% Output, real C(P), S(P), the cosines and sines of the\n% transforming rotations.\n%\n\n%\n% Update R.\n%\n for j = 1: p\n\n xj = x(j);\n%\n% Apply the previous rotations.\n%\n for i = 1 : j-1\n t = c(i) * r(i,j) + s(i) * xj;\n xj = c(i) * xj - s(i) * r(i,j);\n r(i,j) = t;\n end\n%\n% Compute the next rotation.\n%\n [ c(j), s(j), r(j,j), xj ] = drotg ( r(j,j), xj );\n\n end\n%\n% If required, update Z and RHO.\n%\n for j = 1 : nz\n\n zeta = y(j);\n\n for i = 1 : p\n t = c(i) * z(i,j) + s(i) * zeta;\n zeta = c(i) * zeta - s(i) * z(i,j);\n z(i,j) = t;\n end\n\n azeta = abs ( zeta );\n\n if ( azeta ~= 0.0 & 0.0 <= rho(j) )\n scale = azeta + rho(j);\n rho(j) = scale * sqrt ( ( azeta / scale )^2 + ( rho(j) / scale )^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/dchud.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.5961804075731609}} {"text": "classdef prtClassFld < prtClass\n %prtClassFld Fisher linear discriminant classifier\n % \n % CLASSIFIER = prtClassFld returns a Fisher linear discriminant classifier\n %\n % CLASSIFIER = prtClassFld(PROPERTY1, VALUE1, ...) constructs a\n % prtClassFld object CLASSIFIER with properties as specified by\n % PROPERTY/VALUE pairs.\n %\n % A prtClassFld object inherits all properties from the abstract class\n % prtClass. In addition is has the following properties:\n %\n % w - regression weights, estimated during training\n % plotBasis - Flag indicating whether to plot the basis\n % functions when the PLOT function is called\n % plotProjections - Flag indicating whether to plot the projection\n % of points to the basis when the PLOT function is\n % called\n %\n % For information on the Fisher Linear Discriminant algorithm, please\n % refer to the following URL:\n %\n % http://en.wikipedia.org/wiki/Linear_discriminant_analysis#Fisher.27s_linear_discriminant\n %\n % A prtClassFld object inherits the TRAIN, RUN, CROSSVALIDATE and\n % KFOLDS methods from prtAction. It also inherits the PLOT method from\n % prtClass.\n %\n % Example:\n %\n % ds1 = prtDataGenUnimodal; % Create some test and\n % ds2 = prtDataGenUnimodal; % training data\n % classifier = prtClassFld; % Create a classifier\n % classifier = classifier.train(ds1); % Train\n % classified = run(classifier, ds2); % Test\n % subplot(2,1,1);\n % classifier.plot;\n % subplot(2,1,2);\n % [pf,pd] = prtScoreRoc(classified);\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, prtClassKnn, prtClassRvm, prtClassGlrt, prtClassSvm,\n % prtClassTreeBaggingCap, prtClassKmsd, prtClassKnn \n\n\n\n\n% Copyright (c) 2013 New Folder Consulting \n%\n% Permission is hereby granted, free of charge, to any person obtaining a\n% copy of this software and associated documentation files (the\n% \"Software\"), to deal in the Software without restriction, including\n% without limitation the rights to use, copy, modify, merge, publish,\n% distribute, sublicense, and/or sell copies of the Software, and to permit\n% persons to whom the Software is furnished to do so, subject to the\n% 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\n% MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n% NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n% DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n% OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n% USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n \n\n properties (SetAccess=private)\n \n name = 'Fisher Linear Discriminant' % Fisher Linear Discriminant\n nameAbbreviation = 'FLD' % FLD\n isNativeMary = false; % False\n end\n \n properties (SetAccess = protected)\n % w is a dataSet.nDimensions x 1 vector of projection weights\n % learned during Fld.train(dataSet)\n \n w = []; % The vector of weights, learned during training\n \n % plotting options\n plotBasis = false; % Flag indicating whether or not to plot the basis\n plotProjections = false; % Flag indicating whether or not to plot the projections\n end\n \n methods\n \n % Allow for string, value pairs\n function self = prtClassFld(varargin)\n self = prtUtilAssignStringValuePairs(self,varargin{:});\n end\n \n function self = set.plotProjections(self,value)\n if islogical(value) || (isnumeric(value) && (value == 1 || value == 0))\n self.plotProjections = value;\n else\n error('prt:prtClassFld:plotProjections','plotProjections can only take true or false (boolean or 0/1) values; user speficied value %d',value);\n end\n end\n end\n \n methods (Access=protected, Hidden = true)\n \n function self = trainAction(self,dataSet)\n \n n = dataSet.nObservations;\n p = dataSet.nFeatures;\n \n if p > n\n warning('prt:prtClassFld:train:illconditioned','dataSet has n (%d) < p (%d); prtClassFld may not be stable',n,p);\n end\n if ~dataSet.isBinary\n error('prtClassFld:nonBinaryTraining','Input dataSet for prtClassFld.train must be binary');\n end\n \n \n dataH0 = dataSet.getObservationsByClassInd(1);\n dataH1 = dataSet.getObservationsByClassInd(2);\n \n mean0 = mean(dataH0,1);\n mean1 = mean(dataH1,1);\n \n cov0 = cov(dataH0);\n cov1 = cov(dataH1);\n covW = cov1 + cov0;\n \n self.w = covW\\(mean1-mean0)'; %w = covW^-1 * (mean1-mean0)'; But better\n self.w = self.w./norm(self.w);\n \n end\n \n function dataSet = runAction(self,dataSet)\n %dataSet = prtDataSetClass((self.w'*dataSet.getObservations()')');\n dataSet.X = (self.w'*dataSet.getObservations()')';\n end\n \n function imageHandle = plotGriddedEvaledClassifier(self, DS, linGrid, gridSize, cMap)\n \n % Call the original plot function\n imageHandle = plotGriddedEvaledClassifier@prtClass(self, DS, linGrid, gridSize, cMap);\n \n W = self.w;\n limits = axis;\n nDims = length(W);\n \n if self.plotBasis\n hold on\n switch nDims\n case 1\n % Nothing\n case 2\n distances = zeros(4,1);\n distances(1) = sqrt(sum([limits(2); limits(4)].^2));\n distances(2) = sqrt(sum([limits(1); limits(3)].^2));\n distances(3) = sqrt(sum([limits(2); limits(3)].^2));\n distances(4) = sqrt(sum([limits(1); limits(4)].^2));\n \n highPoint = max(distances).*W;\n lowPoint = -max(distances).*W;\n \n h = plot([lowPoint(1),highPoint(1)],[lowPoint(2),highPoint(2)],'k');\n set(h,'linewidth',3);\n case 3\n distances = zeros(8,1);\n distances(1) = sqrt(sum([limits(1); limits(3); limits(5)].^2));\n distances(2) = sqrt(sum([limits(1); limits(3); limits(6)].^2));\n distances(3) = sqrt(sum([limits(1); limits(4); limits(5)].^2));\n distances(4) = sqrt(sum([limits(1); limits(4); limits(6)].^2));\n distances(5) = sqrt(sum([limits(2); limits(3); limits(5)].^2));\n distances(6) = sqrt(sum([limits(2); limits(3); limits(6)].^2));\n distances(7) = sqrt(sum([limits(2); limits(4); limits(5)].^2));\n distances(8) = sqrt(sum([limits(2); limits(4); limits(6)].^2));\n \n highPoint = max(distances).*W;\n lowPoint = -max(distances).*W;\n \n h = plot3([lowPoint(1),highPoint(1)],[lowPoint(2),highPoint(2)],[lowPoint(3), highPoint(3)],'k');\n set(h,'linewidth',3);\n otherwise\n error('prt:prtClassFld:tooManyDimensions','Too many dimensions for plotting.')\n end\n end\n\n if self.plotProjections && ~isempty(self.dataSet)\n OutputDataSet = run(self, self.dataSet);\n hold on;\n switch nDims\n case 2\n for i = 1:double(self.plotProjections):self.dataSet.nObservations\n cX = self.dataSet.X(i,:);\n cYout = OutputDataSet.X(i,:);\n plot([cX(1),cYout*W(1)],[cX(2),cYout*W(2)],'k');\n end\n case 3\n for i = 1:double(self.plotProjections):self.dataSet.nObservations\n cX = self.dataSet.X(i,:);\n cYout = OutputDataSet.X(i,:);\n plot3([cX(1),cYout*W(1)],[cX(2),cYout*W(2)],[cX(3),cYout*W(3)],'k');\n end\n end\n axis(limits);\n end\n hold off;\n end\n \n end\n \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/prtClassFld.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.595982721035929}} {"text": "function [centres, options, post, errlog] = kmeans(centres, data, options)\n%KMEANS\tTrains a k means cluster model.\n%\n%\tDescription\n%\t CENTRES = KMEANS(CENTRES, DATA, OPTIONS) uses the batch K-means\n%\talgorithm to set the centres of a cluster model. The matrix DATA\n%\trepresents the data which is being clustered, with each row\n%\tcorresponding to a vector. The sum of squares error function is used.\n%\tThe point at which a local minimum is achieved is returned as\n%\tCENTRES. The error value at that point is returned in OPTIONS(8).\n%\n%\t[CENTRES, OPTIONS, POST, ERRLOG] = KMEANS(CENTRES, DATA, OPTIONS)\n%\talso returns the cluster number (in a one-of-N encoding) for each\n%\tdata point in POST and a log of the error values after each cycle in\n%\tERRLOG. The optional parameters have the following\n%\tinterpretations.\n%\n%\tOPTIONS(1) is set to 1 to display error values; also logs error\n%\tvalues in the return argument ERRLOG. If OPTIONS(1) is set to 0, then\n%\tonly warning messages are displayed. If OPTIONS(1) is -1, then\n%\tnothing is displayed.\n%\n%\tOPTIONS(2) is a measure of the absolute precision required for the\n%\tvalue of CENTRES at the solution. If the absolute difference between\n%\tthe values of CENTRES between two successive steps is less than\n%\tOPTIONS(2), then this condition is satisfied.\n%\n%\tOPTIONS(3) is a measure of the precision required of the error\n%\tfunction at the solution. If the absolute difference between the\n%\terror functions between two successive steps is less than OPTIONS(3),\n%\tthen this condition is satisfied. Both this and the previous\n%\tcondition must be satisfied for termination.\n%\n%\tOPTIONS(14) is the maximum number of iterations; default 100.\n%\n%\tSee also\n%\tGMMINIT, GMMEM\n%\n\n%\tCopyright (c) Ian T Nabney (1996-2001)\n\n[ndata, data_dim] = size(data);\n[ncentres, dim] = size(centres);\n\nif dim ~= data_dim\n error('Data dimension does not match dimension of centres')\nend\n\nif (ncentres > ndata)\n error('More centres than data')\nend\n\n% Sort out the options\nif (options(14))\n niters = options(14);\nelse\n niters = 100;\nend\n\nstore = 0;\nif (nargout > 3)\n store = 1;\n errlog = zeros(1, niters);\nend\n\n% Check if centres and posteriors need to be initialised from data\nif (options(5) == 1)\n % Do the initialisation\n perm = randperm(ndata);\n perm = perm(1:ncentres);\n\n % Assign first ncentres (permuted) data points as centres\n centres = data(perm, :);\nend\n% Matrix to make unit vectors easy to construct\nid = eye(ncentres);\n\n% Main loop of algorithm\nfor n = 1:niters\n\n % Save old centres to check for termination\n old_centres = centres;\n \n % Calculate posteriors based on existing centres\n d2 = dist2(data, centres);\n % Assign each point to nearest centre\n [minvals, index] = min(d2', [], 1);\n post = id(index,:);\n\n num_points = sum(post, 1);\n % Adjust the centres based on new posteriors\n for j = 1:ncentres\n if (num_points(j) > 0)\n centres(j,:) = sum(data(find(post(:,j)),:), 1)/num_points(j);\n end\n end\n\n % Error value is total squared distance from cluster centres\n e = sum(minvals);\n if store\n errlog(n) = e;\n end\n if options(1) > 0\n fprintf(1, 'Cycle %4d Error %11.6f\\n', n, e);\n end\n\n if n > 1\n % Test for termination\n if max(max(abs(centres - old_centres))) < options(2) & ...\n abs(old_e - e) < options(3)\n options(8) = e;\n return;\n end\n end\n old_e = e;\nend\n\n% If we get here, then we haven't terminated in the given number of \n% iterations.\noptions(8) = e;\nif (options(1) >= 0)\n disp(maxitmess);\nend\n\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/netlab3.3/kmeansNetlab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826789824086, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5959712685543039}} {"text": "function prob = survProbStdModel(t,b,time)\n% survProbStdModel: Computes survival probability using the standard model\n\nprob = ones(size(t));\ntime0 = [0;time];\ndtime = diff(time0);\n\nfor jdx=1:length(time)\n if jdx < length(time)\n tmpidx = t > time0(jdx) & t <= time0(jdx+1);\n else\n tmpidx = t > time0(jdx);\n end\n H = 0;\n if (jdx>1)\n H = dtime(1:jdx-1)'*b(1:jdx-1);\n end\n H = H + (t(tmpidx) - time0(jdx))*b(jdx);\n prob(tmpidx) = exp(-H);\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/26905-fitting-survival-probability-models/survProbStdModel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5959712629763494}} {"text": "function jac = p00_jac ( test, neqn, t, y )\n\n%*****************************************************************************80\n%\n%% P00_JAC evaluates the jacobian for any problem.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 February 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer TEST, the problem number.\n%\n% Input, integer NEQN, the number of equations.\n%\n% Input, real T, Y(NEQN), the arguments of the jacobian.\n%\n% Output, real JAC(NEQN,NEQN), the jacobian matrix.\n%\n if ( test == 1 )\n jac = p01_jac ( neqn, t, y );\n elseif ( test == 2 )\n jac = p02_jac ( neqn, t, y );\n elseif ( test == 3 )\n jac = p03_jac ( neqn, t, y );\n elseif ( test == 4 )\n jac = p04_jac ( neqn, t, y );\n elseif ( test == 5 )\n jac = p05_jac ( neqn, t, y );\n elseif ( test == 6 )\n jac = p06_jac ( neqn, t, y );\n elseif ( test == 7 )\n jac = p07_jac ( neqn, t, y );\n elseif ( test == 8 )\n jac = p08_jac ( neqn, t, y );\n elseif ( test == 9 )\n jac = p09_jac ( neqn, t, y );\n elseif ( test == 10 )\n jac = p10_jac ( neqn, t, y );\n elseif ( test == 11 )\n jac = p11_jac ( neqn, t, y );\n elseif ( test == 12 )\n jac = p12_jac ( neqn, t, y );\n elseif ( test == 13 )\n jac = p13_jac ( neqn, t, y );\n elseif ( test == 14 )\n jac = p14_jac ( neqn, t, y );\n elseif ( test == 15 )\n jac = p15_jac ( neqn, t, y );\n elseif ( test == 16 )\n jac = p16_jac ( neqn, t, y );\n elseif ( test == 17 )\n jac = p17_jac ( neqn, t, y );\n elseif ( test == 18 )\n jac = p18_jac ( neqn, t, y );\n elseif ( test == 19 )\n jac = p19_jac ( neqn, t, y );\n elseif ( test == 20 )\n jac = p20_jac ( neqn, t, y );\n elseif ( test == 21 )\n jac = p21_jac ( neqn, t, y );\n elseif ( test == 22 )\n jac = p22_jac ( neqn, t, y );\n elseif ( test == 23 )\n jac = p23_jac ( neqn, t, y );\n elseif ( test == 24 )\n jac = p24_jac ( neqn, t, y );\n elseif ( test == 25 )\n jac = p25_jac ( neqn, t, y );\n elseif ( test == 26 )\n jac = p26_jac ( neqn, t, y );\n elseif ( test == 27 )\n jac = p27_jac ( neqn, t, y );\n elseif ( test == 28 )\n jac = p28_jac ( neqn, t, y );\n elseif ( test == 29 )\n jac = p29_jac ( neqn, t, y );\n elseif ( test == 30 )\n jac = p30_jac ( neqn, t, y );\n elseif ( test == 31 )\n jac = p31_jac ( neqn, t, y );\n elseif ( test == 32 )\n jac = p32_jac ( neqn, t, y );\n elseif ( test == 33 )\n jac = p33_jac ( neqn, t, y );\n elseif ( test == 34 )\n jac = p34_jac ( neqn, t, y );\n elseif ( test == 35 )\n jac = p35_jac ( neqn, t, y );\n elseif ( test == 36 )\n jac = p36_jac ( neqn, t, y );\n elseif ( test == 37 )\n jac = p37_jac ( neqn, t, y );\n elseif ( test == 38 )\n jac = p38_jac ( neqn, t, y );\n elseif ( test == 39 )\n jac = p39_jac ( neqn, t, y );\n elseif ( test == 40 )\n jac = p40_jac ( neqn, t, y );\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'P00_JAC - Fatal error!\\n' );\n fprintf ( 1, ' Unrecognized problem number = %d\\n', test );\n error ( 'P00_JAC - Fatal error!' );\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_ode/p00_jac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.5957423811056515}} {"text": "function power_method_test ( )\n\n%*****************************************************************************80\n%\n%% POWER_METHOD_TEST tests the POWER_METHOD library.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 25 May 2008\n%\n% Author:\n%\n% John Burkardt\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'POWER_METHOD_TEST\\n' );\n fprintf ( 1, ' MATLAB version:\\n' );\n fprintf ( 1, ' Test the POWER_METHOD library.\\n' );\n\n power_method_test01 ( );\n power_method_test02 ( );\n power_method_test03 ( );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'POWER_METHOD_TEST:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction power_method_test01 ( )\n\n%*****************************************************************************80\n%\n%% POWER_METHOD_TEST01 uses POWER_METHOD on the Fibonacci2 matrix.\n%\n% Discussion:\n%\n% This matrix, despite having a single dominant eigenvalue, will generally\n% converge only very slowly under the power method. This has to do with\n% the fact that the matrix has only 3 eigenvectors.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 20 July 2008\n%\n% Author:\n%\n% John Burkardt\n%\n n = 50;\n\n a = fibonacci2 ( n );\n\n seed = 123456789;\n\n [ x, seed ] = r8vec_uniform_01 ( n, seed );\n\n it_max = 300;\n tol = 0.000001;\n\n phi = ( 1.0 + sqrt ( 5.0 ) ) / 2.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'POWER_METHOD_TEST01\\n' );\n fprintf ( 1, ' Use the power method on the Fibonacci2 matrix.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Matrix order N = %d\\n', n );\n fprintf ( 1, ' Maximum iterations = %d\\n', it_max );\n fprintf ( 1, ' Error tolerance = %g\\n', tol );\n\n ctime1 = cputime;\n\n [ x, lambda, it_num ] = power_method ( n, a, x, it_max, tol );\n\n ctime2 = cputime;\n ctime = ctime2 - ctime1;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of iterations = %d\\n', it_num );\n fprintf ( 1, ' CPU time = %f\\n', ctime );\n fprintf ( 1, ' Estimated eigenvalue = %f\\n', lambda );\n fprintf ( 1, ' Correct value = %f\\n', phi );\n fprintf ( 1, ' Error = %e\\n', abs ( lambda - phi ) );\n%\n% X2 is the exact eigenvector.\n%\n x2(1:n,1) = phi.^(0:n-1);\n x2 = x2 / norm ( x2 );\n%\n% The sine of the angle between X and X2 is a measure of error.\n%\n cos_x1x2 = x' * x2;\n sin_x1x2 = sqrt ( ( 1.0 - cos_x1x2 ) * ( 1.0 + cos_x1x2 ) );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Sine of angle between true and estimated vectors = %e\\n', ...\n sin_x1x2 );\n\n return\nend\nfunction power_method_test02 ( )\n\n%*****************************************************************************80\n%\n%% POWER_METHOD_TEST02 uses POWER_METHOD2 on the Fibonacci2 matrix.\n%\n% Discussion:\n%\n% This matrix, despite having a single dominant eigenvalue, will generally\n% converge only very slowly under the power method. This has to do with\n% the fact that the matrix has only 3 eigenvectors.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 20 July 2008\n%\n% Author:\n%\n% John Burkardt\n%\n n = 50;\n\n a = fibonacci2 ( n );\n\n seed = 123456789;\n\n [ x, seed ] = r8vec_uniform_01 ( n, seed );\n\n it_max = 300;\n tol = 0.000001;\n\n phi = ( 1.0 + sqrt ( 5.0 ) ) / 2.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'POWER_METHOD_TEST02\\n' );\n fprintf ( 1, ' Use the power method2 on the Fibonacci2 matrix.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Matrix order N = %d\\n', n );\n fprintf ( 1, ' Maximum iterations = %d\\n', it_max );\n fprintf ( 1, ' Error tolerance = %g\\n', tol );\n\n ctime1 = cputime;\n\n [ lambda, v, it_num ] = power_method2 ( n, a, x, it_max, tol );\n\n ctime2 = cputime;\n ctime = ctime2 - ctime1;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of iterations = %d\\n', it_num );\n fprintf ( 1, ' CPU time = %f\\n', ctime );\n fprintf ( 1, ' Estimated eigenvalue = %f %f\\n', real ( lambda ), imag ( lambda ) );\n fprintf ( 1, ' Correct value = %f\\n', phi );\n fprintf ( 1, ' Error = %e\\n', abs ( lambda - phi ) );\n\n return\nend\nfunction power_method_test03 ( )\n\n%*****************************************************************************80\n%\n%% POWER_METHOD_TEST03 uses POWER_METHOD2 on the TRIS matrix.\n%\n% Discussion:\n%\n% This matrix, despite having a single dominant eigenvalue, will generally\n% converge only very slowly under the power method. This has to do with\n% the fact that the matrix has only 3 eigenvectors.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 20 July 2008\n%\n% Author:\n%\n% John Burkardt\n%\n n = 50;\n\n alpha = -1.0;\n beta = 10.0;\n gamma = 8.0;\n\n a = tris ( n, n, alpha, beta, gamma );\n\n seed = 123456789;\n\n [ x, seed ] = r8vec_uniform_01 ( n, seed );\n\n it_max = 4000;\n tol = 0.000001;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'POWER_METHOD_TEST03\\n' );\n fprintf ( 1, ' Use the power method2 on the TRIS matrix.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Matrix order N = %d\\n', n );\n fprintf ( 1, ' Maximum iterations = %d\\n', it_max );\n fprintf ( 1, ' Error tolerance = %g\\n', tol );\n\n ctime1 = cputime;\n\n [ lambda, v, it_num ] = power_method2 ( n, a, x, it_max, tol );\n\n ctime2 = cputime;\n ctime = ctime2 - ctime1;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of iterations = %d\\n', it_num );\n fprintf ( 1, ' CPU time = %f\\n', ctime );\n fprintf ( 1, ' Estimated eigenvalue = %f %f\\n', ...\n real ( lambda ), imag ( lambda ) );\n\n lambda_vec = tris_eigenvalues ( n, alpha, beta, gamma );\n\n lambda_max = lambda_vec(1);\n\n for i = 2 : n\n if ( abs ( lambda_max ) < abs ( lambda_vec(i) ) )\n lambda_max = lambda_vec(i);\n end\n end\n\n fprintf ( 1, ' Correct value = %f %f\\n', ...\n real ( lambda_max ), imag ( lambda_max ) );\n fprintf ( 1, ' Error = %e\\n', abs ( lambda - lambda_max ) );\n\n return\nend\nfunction a = fibonacci2 ( n )\n\n%*****************************************************************************80\n%\n%% FIBONACCI2 returns the Fibonacci2 matrix.\n%\n% Example:\n%\n% N = 5\n%\n% 0 1 0 0 0\n% 1 1 0 0 0\n% 0 1 1 0 0\n% 0 0 1 1 0\n% 0 0 0 1 1\n%\n% Properties:\n%\n% A is generally not symmetric: A' /= A.\n%\n% A is tridiagonal.\n%\n% Because A is tridiagonal, it has property A (bipartite).\n%\n% A is banded, with bandwidth 3.\n%\n% A is integral: int ( A ) = A.\n%\n% A is a zero/one matrix.\n%\n% If N = 1 then\n% det ( A ) = 0\n% else\n% det ( A ) = (-1)**(N-1)\n%\n% If 1 < N, then A is unimodular.\n%\n% For 2 <= N, A has the eigenvalues:\n%\n% PHI (once),\n% 1 (N-2) times,\n% 1-PHI (once).\n%\n% When applied to a Fibonacci1 matrix B, the Fibonacci2 matrix\n% A produces the \"next\" Fibonacci1 matrix C = A*B.\n%\n% Let PHI be the golden ratio (1+sqrt(5))/2.\n%\n% For 2 <= N, the eigenvalues and eigenvectors are:\n%\n% LAMBDA(1) = PHI, vector = (1,PHI,PHI^2,...PHI^(N-1));\n% LAMBDA(2:N-1) = 1 vector = (0,0,0,...,0,1);\n% LAMBDA(N) = 1 - PHI. vector = ((-PHI)^(N-1),(-PHI)^(N-2),...,1)\n%\n% Note that there is only one eigenvector corresponding to 1.\n% Hence, for 3 < N, the matrix is defective. This fact means, \n% for instance, that the convergence of the eigenvector in the power \n% method will be very slow.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Output, real A(N,N), the matrix.\n%\n for i = 1 : n\n for j = 1 : n\n\n if ( i == 1 )\n\n if ( j == 2 )\n a(i,j) = 1.0;\n else\n a(i,j) = 0.0;\n end\n\n else\n\n if ( j == i-1 | j == i )\n a(i,j) = 1.0;\n else\n a(i,j) = 0.0;\n end\n\n end\n\n end\n end\n\n return\nend\nfunction [ r, seed ] = r8vec_uniform_01 ( n, seed )\n\n%*****************************************************************************80\n%\n%% R8VEC_UNIFORM_01 returns a unit pseudorandom R8VEC.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 21 September 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Paul Bratley, Bennett Fox, Linus Schrage,\n% A Guide to Simulation,\n% Second Edition,\n% Springer, 1987,\n% ISBN: 0387964673,\n% LC: QA76.9.C65.B73.\n%\n% Bennett Fox,\n% Algorithm 647:\n% Implementation and Relative Efficiency of Quasirandom\n% Sequence Generators,\n% ACM Transactions on Mathematical Software,\n% Volume 12, Number 4, December 1986, pages 362-376.\n%\n% Pierre L'Ecuyer,\n% Random Number Generation,\n% in Handbook of Simulation,\n% edited by Jerry Banks,\n% Wiley, 1998,\n% ISBN: 0471134031,\n% LC: T57.62.H37.\n%\n% Peter Lewis, Allen Goodman, James Miller,\n% A Pseudo-Random Number Generator for the System/360,\n% IBM Systems Journal,\n% Volume 8, Number 2, 1969, pages 136-143.\n%\n% Parameters:\n%\n% Input, integer N, the number of entries in the vector.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, real R(N), the vector of pseudorandom values.\n%\n% Output, integer SEED, an updated seed for the random number generator.\n%\n i4_huge = 2147483647;\n\n if ( seed == 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8VEC_UNIFORM_01 - Fatal error!\\n' );\n fprintf ( 1, ' Input SEED = 0!\\n' );\n error ( 'R8VEC_UNIFORM_01 - Fatal error!' );\n end\n\n for i = 1 : n\n\n k = floor ( seed / 127773 );\n\n seed = 16807 * ( seed - k * 127773 ) - k * 2836;\n\n if ( seed < 0 )\n seed = seed + i4_huge;\n end\n\n r(i) = seed * 4.656612875E-10;\n\n end\n\n return\nend\nfunction timestamp ( )\n\n%*****************************************************************************80\n%\n%% TIMESTAMP prints the current YMDHMS date as a timestamp.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n t = now;\n c = datevec ( t );\n s = datestr ( c, 0 );\n fprintf ( 1, '%s\\n', s );\n\n return\nend\nfunction a = tris ( m, n, x, y, z )\n\n%*****************************************************************************80\n%\n%% TRIS returns the tridiagonal scalar matrix.\n%\n% Formula:\n%\n% if ( J = I-1 )\n% A(I,J) = X\n% elseif ( J = I )\n% A(I,J) = Y\n% elseif ( J = I + 1 )\n% A(I,J) = Z\n% else\n% A(I,J) = 0\n%\n% Example:\n%\n% M = 5, N = 5, X = 1, Y = 2, Z = 3\n%\n% 2 3 0 0 0\n% 1 2 3 0 0\n% 0 1 2 3 0\n% 0 0 1 2 3\n% 0 0 0 1 2\n%\n% Properties:\n%\n% A is generally not symmetric: A' /= A.\n%\n% A is tridiagonal.\n%\n% Because A is tridiagonal, it has property A (bipartite).\n%\n% A is banded, with bandwidth 3.\n%\n% A is Toeplitz: constant along diagonals.\n%\n% If Y is not zero, then for A to be singular, it must be the case that\n%\n% 0.5 * Y / sqrt ( X * Z ) < 1\n%\n% and\n%\n% cos (K*PI/(N+1)) = - 0.5 * Y / sqrt ( X * Z ) for some 1 <= K <= N.\n%\n% If Y is zero, then A is singular when N is odd, or if X or Z is zero.\n%\n% A is persymmetric: A(I,J) = A(N+1-J,N+1-I).\n%\n% A has eigenvalues\n%\n% LAMBDA(I) = Y + 2 * sqrt(X*Z) * COS(I*PI/(N+1))\n%\n% The eigenvalues will be complex if X * Z < 0.\n%\n% If X = Z, the matrix is symmetric.\n%\n% As long as X and Z are nonzero, the matrix is irreducible.\n%\n% If X = Z = -1, and Y = 2, the matrix is a symmetric, positive\n% definite M matrix, the negative of the second difference matrix.\n%\n% Modified:\n%\n% 21 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% John Todd,\n% Basic Numerical Mathematics,\n% Volume 2: Numerical Algebra,\n% Academic Press, 1978, page 155.\n%\n% Parameters:\n%\n% Input, integer M, N, the order of A.\n%\n% Input, real X, Y, Z, the scalars that define A.\n%\n% Output, real A(M,N), the matrix.\n%\n for i = 1 : m\n for j = 1 : n\n\n if ( j == i - 1 )\n a(i,j) = x;\n elseif ( j == i )\n a(i,j) = y;\n elseif ( j == i + 1 )\n a(i,j) = z;\n else\n a(i,j) = 0.0;\n end\n\n end\n end\n\n return\nend\nfunction lambda = tris_eigenvalues ( n, x, y, z )\n\n%*****************************************************************************80\n%\n%% TRIS_EIGENVALUES returns the eigenvalues of the tridiagonal scalar matrix.\n%\n% Discussion:\n%\n% The eigenvalues will be complex if X * Z < 0.\n%\n% Modified:\n%\n% 21 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Input, real X, Y, Z, the scalars that define A.\n%\n% Output, complex LAMBDA(N), the eigenvalues.\n%\n for i = 1 : n\n angle = i * pi / ( n + 1 );\n lambda(i) = y + 2.0 * sqrt ( x * z ) * cos ( angle );\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/power_method/power_method_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434925908524, "lm_q2_score": 0.7718434925908524, "lm_q1q2_score": 0.5957423770548452}} {"text": "function [x,y,z] = doseCOM(doseStruct)\n%\"doseCOM\"\n% Find [x,y,z] center of mass of dose contained in doseStruct. Non\n% uniform slice width is taken into consideration.\n%\n% doseStruct is planC{indexS.dose}(doseNum) where doseNum is the number\n% of the desired dose center of mass.\n%\n%JRA 3/12/04\n%\n%Usage:\n% function [x,y,z] = doseCOM(doseStruct)\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by: Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n% This version of CERR is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR. If not, see .\n\n[xVals, yVals, zVals] = getDoseXYZVals(doseStruct);\n\ndA = getDoseArray(doseStruct);\n\n[xMesh, yMesh] = meshgrid(xVals, yVals);\n\nfor i=1:size(dA, 3);\n slice = dA(:,:,i);\n %Weighted mesh.\n wX = xMesh .* slice;\n wY = yMesh .* slice; \n sliceDose(i) = sum(slice(:));\n if sliceDose(i) == 0\n x(i) = 0;\n y(i) = 0;\n else\n x(i) = sum(wX(:)) / sliceDose(i);\n y(i) = sum(wY(:)) / sliceDose(i);\n end\nend\n\n%Get voxel thickness at each slice.\nzDiff = diff(zVals);\ndividers = [zVals(1)-zDiff(1)/2 zDiff/2 + zVals(1:end-1) zVals(end)+zDiff(end)/2];\nvoxThickness = diff(dividers);\ntotalHeight = sum(voxThickness);\n\ntotalDose = sum(sliceDose);\n%Weight x,y,z values by dose on that slice/voxelThickness.\nx = sum(x .* sliceDose / voxThickness) / totalDose * totalHeight;\ny = sum(y .* sliceDose / voxThickness) / totalDose * totalHeight;\nz = sum(zVals .* sliceDose / voxThickness) / totalDose * totalHeight;", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Utilities/doseCOM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527906914787, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5957317607638577}} {"text": "function y = limiter(a,b,limtype)\n% Limiter function as defined in Sect. 4.8 and as used in Sect. 10.8\nif b==0, y=0; else\n if limtype == 2 \t% van Albada\n y = (a^2 + a*b)/(a^2 + b^2);\n elseif limtype == 1\t\t% Minmod\n y = max(0, min(a/b,1));\n else\t\t\t\t% No limiting, no MUSCL\n y = 0; \n end \nend\n", "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/cfdbook/chap10.8/limiter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5957228379624576}} {"text": "function r=getRange(xCart,useHalfRange,zTx,zRx)\n%%GETRANGE Obtain the bistatic (or monostatic) range measurements of\n% targets in the absence of refraction under non-relativistic\n% mechanics, ignoring atmospheric effects. The transmitter and the\n% target can be collocated.\n%\n%INPUTS: xCart The numDimXN set of N target positions. numDim is typically\n% 2 or 3.\n% useHalfRange A boolean value specifying whether the bistatic range value\n% should be divided by two. This normally comes up when\n% operating in monostatic mode, so that the range reported is\n% a one-way range. The default if this parameter is not\n% provided is false.\n% zTx A numDimXN matrix of the positions of the transmitters . If\n% this parameter is omitted or an empty matrix is passed, the\n% transmitters are assumed to be at the origin. If only a\n% single vector is passed, then the transmitter position is\n% assumed the same for all of the target states being converted.\n% zRx A numDimXN matrix of the positions of the receivers. If this\n% parameter is omitted or an empty matrix is passed, the\n% receivers are assumed to be at the origin. If only a single\n% vector is passed, then the receiver position is assumed the\n% same for all of the target states being converted.\n%\n%OUTPUTS: r The 1XN bistatic ranges of the targets.\n%\n%Bistatic range is discussed in [1].\n%\n%REFERENCES:\n%[1] D. F. Crouse, \"Basic tracking using nonlinear 3D monostatic and\n% bistatic measurements,\" IEEE Aerospace and Electronic Systems\n% Magazine, vol. 29, no. 8, Part II, pp. 4-53, Aug. 2014.\n%\n%February 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nN=size(xCart,2);\nnumDim=size(xCart,1);\n\nif(nargin<4||isempty(zRx))\n zRx=zeros(numDim,N);\nelseif(size(zRx,2)==1)\n zRx=repmat(zRx,[1,N]);\nend\n\nif(nargin<3||isempty(zTx))\n zTx=zeros(numDim,N);\nelseif(size(zTx,2)==1)\n zTx=repmat(zTx,[1,N]);\nend\n\nif(nargin<2||isempty(useHalfRange))\n useHalfRange=false;\nend\n\nr=sqrt(sum((xCart-zTx(1:numDim,:)).^2,1))+sqrt(sum((xCart-zRx(1:numDim,:)).^2,1));\n\nif(useHalfRange)\n r=r/2; \nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Coordinate_Systems/Measurement_Components/getRange.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677622198947, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5957228353803676}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% thermalLB.m: Rayleigh Benard Convection, using a LB method,\n% based on [Z.Guo, e.a., http://dx.doi.org/10.1002/fld.337].\n% Boussinesq approximation is used for the buoyancy term:\n% - Fluid is approximated with incompressible Navier-Stokes\n% equations including a body force term, and simulated\n% with a BGK model\n% - Temperature is approximated with advection-diffusion\n% equation and simulated with a BGK model\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Lattice Boltzmann sample, written in matlab\n% Copyright (C) 2008 Andrea Parmigiani, Orestis Malaspinas, Jonas Latt\n% Address: Rue General Dufour 24, 1211 Geneva 4, Switzerland\n% E-mail: andrea.parmigiani@terre.unige.ch\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This program is free software; you can redistribute it and/or\n% modify it under the terms of the GNU General Public License\n% as published by the Free Software Foundation; either version 2\n% of the License, or (at your option) any later version.\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% You should have received a copy of the GNU General Public\n% License along with this program; if not, write to the Free\n% Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n% Boston, MA 02110-1301, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nclear\n\n% GENERAL FLOW CONSTANTS\n\nly = 51;\naspect_ratio = 2;\nlx = aspect_ratio*ly;\ndelta_x = 1./(ly-2);\nPr = 1.;\nRa = 20000.; % Rayleigh number\ngr = 0.001; % Gravity\nbuoyancy = [0,gr];\n\nThot = 1; % Heating on bottom wall\nTcold = 0; % Cooling on top wall\nT0 = (Thot+Tcold)/2;\n\ndelta_t = sqrt(gr*delta_x);\n% nu: kinematic viscosity in lattice units\nnu = sqrt(Pr/Ra)*delta_t/(delta_x*delta_x);\n% k: thermal diffusivity\nk = sqrt(1./(Pr*Ra))*delta_t/(delta_x*delta_x);\nomegaNS = 1./(3*nu+0.5); % Relaxation parameter for fluid\nomegaT = 1./(3.*k+0.5); % Relaxation parameter for temperature\n\nmaxT = 80000; % total number of iterations\ntPlot = 100; % iterations between successive graphical outputs\ntStatistics = 10; % iterations between successive file accesses\n\n% D2Q9 LATTICE CONSTANTS\ntNS = [4/9, 1/9,1/9,1/9,1/9, 1/36,1/36,1/36,1/36];\ncxNS = [ 0, 1, 0, -1, 0, 1, -1, -1, 1];\ncyNS = [ 0, 0, 1, 0, -1, 1, 1, -1, -1];\noppNS = [ 1, 4, 5, 2, 3, 8, 9, 6, 7];\n\n% D2Q5 LATTICE CONSTANTS\ntT = [1/3, 1/6, 1/6, 1/6, 1/6];\ncxT = [ 0, 1, 0, -1, 0];\ncyT = [ 0, 0, 1, 0, -1];\noppT = [ 1, 4, 5, 2, 3];\n\n[y,x] = meshgrid(1:ly,1:lx);\n\n% INITIAL CONDITION FOR FLUID: (rho=1, u=0) ==> fIn(i) = t(i)\nfIn = reshape( tNS' * ones(1,lx*ly), 9, lx, ly);\n\n% INITIAL CONDITION FOR TEMPERATURE: (T=0) ==> TIn(i) = t(i)\ntIn = reshape( tT' *Tcold *ones(1,lx*ly), 5, lx, ly);\n% Except for bottom wall, where T=1\ntIn(:,:,ly)=Thot*tT'*ones(1,lx);\n% We need a small trigger, to break symmetry\ntIn(:,lx/2,ly-1)= tT*(Thot + (Thot/10.));\n\n% Open file for statistics\nfid = fopen('thermal_statistics.dat','w');\nfprintf(fid,'Thermal Statistics: time-step --- uy[nx/2,ny/2] --- Nu\\n\\n\\n');\n\n% MAIN LOOP (TIME CYCLES)\nfor cycle = 1:maxT\n % MACROSCOPIC VARIABLES\n rho = sum(fIn);\n T = sum(tIn); %temperature\n ux = reshape ( (cxNS * reshape(fIn,9,lx*ly)), 1,lx,ly) ./rho;\n uy = reshape ( (cyNS * reshape(fIn,9,lx*ly)), 1,lx,ly) ./rho;\n\n % MACROSCOPIC BOUNDARY CONDITIONS\n % NO-SLIP for fluid and CONSTANT at lower and upper\n % boundary... periodicity wrt. left-right\n % COLLISION STEP FLUID\n for i=1:9\n cuNS = 3*(cxNS(i)*ux+cyNS(i)*uy);\n fEq(i,:,:) = rho .* tNS(i) .* ...\n ( 1 + cuNS + 1/2*(cuNS.*cuNS) - 3/2*(ux.^2+uy.^2) );\n force(i,:,:) = 3.*tNS(i) .*rho .* (T-T0) .* ...\n (cxNS(i)*buoyancy(1)+cyNS(i)*buoyancy(2))/(Thot-Tcold);\n fOut(i,:,:) = fIn(i,:,:) - omegaNS .* (fIn(i,:,:)-fEq(i,:,:)) + force(i,:,:);\n end\n\n % COLLISION STEP TEMPERATURE\n for i=1:5\n cu = 3*(cxT(i)*ux+cyT(i)*uy);\n tEq(i,:,:) = T .* tT(i) .* ( 1 + cu );\n tOut(i,:,:) = tIn(i,:,:) - omegaT .* (tIn(i,:,:)-tEq(i,:,:));\n end\n\n % MICROSCOPIC BOUNDARY CONDITIONS FOR FLUID\n for i=1:9\n fOut(i,:,1) = fIn(oppNS(i),:,1);\n fOut(i,:,ly) = fIn(oppNS(i),:,ly);\n end\n\n % STREAMING STEP FLUID\n for i=1:9\n fIn(i,:,:) = circshift(fOut(i,:,:), [0,cxNS(i),cyNS(i)]);\n end\n\n % STREAMING STEP FLUID\n for i=1:5\n tIn(i,:,:) = circshift(tOut(i,:,:), [0,cxT(i),cyT(i)]);\n end\n\n % MICROSCOPIC BOUNDARY CONDITIONS FOR TEMEPERATURE\n %\n tIn(5,:,ly) = Tcold-tIn(1,:,ly)-tIn(2,:,ly)-tIn(3,:,ly)-tIn(4,:,ly);\n tIn(3,:,1) = Thot-tIn(1,:,1) -tIn(2,:,1) -tIn(4,:,1) -tIn(5,:,1);\n\n % VISUALIZATION\n if (mod(cycle,tStatistics)==0)\n u = reshape(sqrt(ux.^2+uy.^2),lx,ly);\n uy_Nu = reshape(uy,lx,ly); % vertical velocity\n T = reshape(T,lx,ly);\n Nu = 1. + sum(sum(uy_Nu.*T))/(lx*k*(Thot-Tcold));\n fprintf(fid,'%8.0f %12.8f %12.8f\\n',cycle,u(int8(lx/2),int8(ly/2))^2, Nu);\n if(mod(cycle,tPlot)==0)\n subplot(2,1,1);\n imagesc(u(:,ly:-1:1)');\n title('Fluid velocity');\n axis off; drawnow\n subplot(2,1,2);\n imagesc(T(:,ly:-1:1)')\n title(['Temperature (Nusselt number is ' num2str(Nu) ')']);\n axis off; drawnow\n end\n end\nend\n\nfclose(fid);\n", "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/LBM/rayleighbenard.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5957228326811987}} {"text": "% Figures 6.8-6.10: Quadratic smoothing\n% Section 6.3.3\n% Boyd & Vandenberghe \"Convex Optimization\"\n% Original by Lieven Vandenberghe\n% Adapted for CVX Argyris Zymnis - 10/2005\n%\n% Suppose we have a signal x, which does not vary too rapidly\n% and that x is corrupted by some small, rapidly varying noise v,\n% ie. x_cor = x + v. Then if we want to reconstruct x from x_cor\n% we should solve (with x_hat as the parameter)\n% minimize ||x_hat - x_cor||_2 + lambda*phi_quad(x_hat)\n%\n% where phi_quad(x) = sum(x_(i+1)-x_i)^2 , for i = 1 to n-1.\n% The parameter lambda controls the ''smoothness'' of x_hat.\n%\n% The first figure which is generated shows the original and\n% the corrupted signals. The second figure shows the tradeoff curve\n% obtained when varying lambda and the third figure shows three\n% reconstructed signals.\n%\n% NOTE: This is not a good problem to use CVX on. By exploiting\n% the sparsity in this case, we can solve this problem much more\n% efficiently using least squares.\n\n\nrandn('state',0);\n\nn = 4000; t = (0:n-1)';\nexact = 0.5*sin((2*pi/n)*t).*sin(0.01*t);\ncorrupt = exact + 0.05*randn(size(exact));\n\nfigure(1)\nsubplot(211)\nplot(t,exact,'-');\naxis([0 n -0.6 0.6])\ntitle('original signal');\nylabel('ya');\n\nsubplot(212)\nplot(t,corrupt,'-');\naxis([0 n -0.6 0.6])\nxlabel('x');\nylabel('yb');\ntitle('corrupted signal');\n%print -deps smoothrec_signals.eps % figure 6.8, page 313\n\nA = sparse(n-1,n);\nA(:,1:n-1) = -speye(n-1,n-1); A(:,2:n) = A(:,2:n)+speye(n-1,n-1);\n\n% tradeoff curve, figure 6.9, page 313\nnopts = 100;\nlambdas = logspace(-10,10,nopts);\n\nobj1 = []; obj2 = [];\n\nfprintf('computing 100 points on tradeoff curve ... \\n');\n\nfor i=1:nopts\n\n lambda = lambdas(i);\n cvx_begin quiet\n variable x(n)\n minimize(norm(x-corrupt)+lambda*norm(x(2:n)-x(1:n-1)))\n cvx_end\n obj1 = [obj1, norm(full(A*x))];\n obj2 = [obj2, norm(full(x-corrupt))];\n\n fprintf('tradeoff point %d\\n',i);\nend;\n\nfigure(2)\nplot(obj2,obj1,'-'); hold on;\nplot(0,norm(A*corrupt),'o');\nplot(norm(corrupt),0,'o'); hold off;\nxlabel('x');\nylabel('y');\ntitle('||xhat-xcorr||_2 vs. ||D xhat||_2');\n%print -deps smoothrec_tradeoff.eps % figure 6.9, page 313\n\n%three smooth signals, figure 6.10, page 314\nnopts = 3;\nalphas = [8 3 1];\nxrecon = [];\n\nfor i=1:3\n fprintf(1,'Reconstructed Signals: %d of 3 \\n',i)\n alpha = alphas(i);\n cvx_begin quiet\n variable x(n)\n minimize(norm(x(2:n)-x(1:n-1)))\n subject to\n norm(x-corrupt) <= alpha;\n cvx_end\n xrecon = [xrecon, x];\n\nend\n\nfigure(3)\nsubplot(311), plot(xrecon(:,1));\naxis([0 n -0.6 0.6])\nylabel('ya');\ntitle('||xhat-xcorr||_2=8');\nsubplot(312), plot(xrecon(:,2));\naxis([0 n -0.6 0.6])\nylabel('yb');\ntitle('||xhat-xcorr||_2=3');\nsubplot(313), plot(xrecon(:,3));\naxis([0 n -0.6 0.6])\nxlabel('x');\nylabel('yc');\ntitle('||xhat-xcorr||_2=1');\n%print -deps smoothrec_results.eps % figure 6.10, page 314\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/examples/cvxbook/Ch06_approx_fitting/smoothrec_cvx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5957228273999399}} {"text": "function b = r8gd_to_r8ge ( n, ndiag, offset, a )\n\n%*****************************************************************************80\n%\n%% R8GD_TO_R8GE copies a R8GD matrix to a R8GE matrix.\n%\n% Discussion:\n%\n% The R8GD storage format is suitable for matrices whose only nonzero entries\n% occur along a few diagonals, but for which these diagonals are not all\n% close enough to the main diagonal for band storage to be efficient.\n%\n% In that case, we assign the main diagonal the offset value 0.\n% Each successive superdiagonal gets an offset value 1 higher, until\n% the highest superdiagonal (the A(1,N) entry) is assigned the offset N-1.\n% Similarly, the subdiagonals are assigned offsets of -1 through -(N-1).\n%\n% Now, assuming that only a few of these diagonals contain nonzeros,\n% then for the I-th diagonal to be saved, we stored its offset in\n% OFFSET(I), and its entries in column I of the matrix. \n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n% N must be positive.\n%\n% Input, integer NDIAG, the number of diagonals of the matrix\n% that are stored in the array.\n% NDIAG must be at least 1, and no more than 2 * N - 1.\n%\n% Input, integer OFFSET(NDIAG), the offsets for the diagonal storage.\n%\n% Input, real A(N,NDIAG), the R8GD matrix.\n%\n% Output, real B(N,N), the R8GE matrix.\n%\n b(1:n,1:n) = 0.0E+00;\n\n for i = 1 : n\n for diag = 1 : ndiag\n j = i + offset(diag);\n if ( 1 <= j & j <= n )\n b(i,j) = a(i,diag);\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/linplus/r8gd_to_r8ge.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.5957167606209383}} {"text": "function x = gompertz_cdf_inv ( cdf, a, b )\n\n%*****************************************************************************80\n%\n%% GOMPERTZ_CDF_INV inverts the Gompertz CDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Johnson, Kotz, and Balakrishnan,\n% Continuous Univariate Distributions, Volume 2, second edition,\n% Wiley, 1994, pages 25-26.\n%\n% Parameters:\n%\n% Input, real CDF, the value of the CDF.\n%\n% Input, real A, B, the parameters of the PDF.\n% 1 < A, 0 < B.\n%\n% Output, real X, the corresponding argument.\n%\n if ( cdf < 0.0 )\n x = 0.0;\n elseif ( cdf < 1.0 )\n x = log ( 1.0 - log ( 1.0 - cdf ) * log ( a ) / b ) / log ( a );\n else\n x = r8_huge ( );\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/prob/gompertz_cdf_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.5956733517552073}} {"text": "function [ point_coord, edge_point, face_order, face_point ] = ...\n icos_shape ( point_num, edge_num, face_num, face_order_max )\n\n%*****************************************************************************80\n%\n%% ICOS_SHAPE describes an icosahedron.\n%\n% Discussion:\n%\n% The input data required for this routine can be retrieved from\n% ICOS_SIZE.\n%\n% The vertices lie on the unit sphere.\n%\n% The dual of an icosahedron is a dodecahedron.\n%\n% The data has been rearranged from a previous assignment. \n% The STRIPACK program refuses to triangulate data if the first\n% three nodes are \"collinear\" on the sphere.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 July 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer POINT_NUM, the number of points (12).\n%\n% Input, integer EDGE_NUM, the number of edges (30).\n%\n% Input, integer FACE_NUM, the number of faces (20).\n%\n% Input, integer FACE_ORDER_MAX, the maximum number of vertices per face (3).\n%\n% Output, real POINT_COORD(3,POINT_NUM); the points.\n%\n% Output, integer EDGE_POINT(2,EDGE_NUM), the points that make up each \n% edge, listed in ascending order of their indexes.\n%\n% Output, integer FACE_ORDER(FACE_NUM), the number of vertices per face.\n%\n% Output, 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 points are listed \n% in the counter-clockwise direction defined by the outward normal at the \n% face. The nodes of each face are ordered so that the lowest index \n% occurs first. The faces are then sorted by nodes.\n%\n dim_num = 3;\n%\n% Set point coordinates.\n%\n phi = 0.5 * ( sqrt ( 5.0 ) + 1.0 );\n b = 1.0 / sqrt ( 1.0 + phi * phi );\n a = phi * b;\n z = 0.0;\n%\n% Set the points.\n%\n point_coord(1:dim_num,1:point_num) = [ ...\n a, b, z; ...\n a, -b, z; ...\n b, z, a; ...\n b, z, -a; ...\n z, a, b; ...\n z, a, -b; ...\n z, -a, b; ...\n z, -a, -b; ...\n -b, z, a; ...\n -b, z, -a; ...\n -a, b, z; ...\n -a, -b, z ]';\n%\n% Set the edges.\n%\n edge_point(1:2,1:edge_num) = [ ...\n 1, 2; ...\n 1, 3; ...\n 1, 4; ...\n 1, 5; ...\n 1, 6; ...\n 2, 3; ...\n 2, 4; ...\n 2, 7; ...\n 2, 8; ...\n 3, 5; ...\n 3, 7; ...\n 3, 9; ...\n 4, 6; ...\n 4, 8; ...\n 4, 10; ...\n 5, 6; ...\n 5, 9; ...\n 5, 11; ...\n 6, 10; ...\n 6, 11; ...\n 7, 8; ...\n 7, 9; ...\n 7, 12; ...\n 8, 10; ...\n 8, 12; ...\n 9, 11; ...\n 9, 12; ...\n 10, 11; ...\n 10, 12; ...\n 11, 12 ]';\n%\n% Set the face orders.\n%\n face_order(1:face_num) = [ ...\n 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, ...\n 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 ]';\n%\n% Set the faces.\n%\n face_point(1:face_order_max,1:face_num) = [ ...\n 1, 2, 4; ...\n 1, 3, 2; ...\n 1, 4, 6; ...\n 1, 5, 3; ...\n 1, 6, 5; ...\n 2, 3, 7; ...\n 2, 7, 8; ...\n 2, 8, 4; ...\n 3, 5, 9; ...\n 3, 9, 7; ...\n 4, 8, 10; ...\n 4, 10, 6; ...\n 5, 6, 11; ...\n 5, 11, 9; ...\n 6, 10, 11; ...\n 7, 9, 12; ...\n 7, 12, 8; ...\n 8, 12, 10; ...\n 9, 11, 12; ...\n 10, 12, 11 ]';\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/sphere_quad/icos_shape.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5956707744485197}} {"text": "function [ r, seed ] = r8vec_uniform_01 ( n, seed )\n\n%*****************************************************************************80\n%\n%% R8VEC_UNIFORM_01 returns a unit pseudorandom R8VEC.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 May 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Paul Bratley, Bennett Fox, Linus Schrage,\n% A Guide to Simulation,\n% Springer Verlag, pages 201-202, 1983.\n%\n% Bennett Fox,\n% Algorithm 647:\n% Implementation and Relative Efficiency of Quasirandom\n% Sequence Generators,\n% ACM Transactions on Mathematical Software,\n% Volume 12, Number 4, pages 362-376, 1986.\n%\n% Peter Lewis, Allen Goodman, James Miller,\n% A Pseudo-Random Number Generator for the System/360,\n% IBM Systems Journal,\n% Volume 8, pages 136-143, 1969.\n%\n% Parameters:\n%\n% Input, integer N, the number of entries in the vector.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, real R(N,1), the vector of pseudorandom values.\n%\n% Output, integer SEED, an updated seed for the random number generator.\n%\n i4_huge = 2147483647;\n\n if ( seed == 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8VEC_UNIFORM_01 - Fatal error!\\n' );\n fprintf ( 1, ' Input SEED = 0!\\n' );\n error ( 'R8VEC_UNIFORM_01 - Fatal error!' );\n end\n\n r = zeros ( n, 1 );\n\n for i = 1 : n\n\n k = floor ( seed / 127773 );\n\n seed = 16807 * ( seed - k * 127773 ) - k * 2836;\n\n if ( seed < 0 )\n seed = seed + i4_huge;\n end\n\n r(i,1) = seed * 4.656612875E-10;\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/r8vec_uniform_01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.5956399463430161}} {"text": "function box = intersectBoxes3d(box1, box2)\n%INTERSECTBOXES3D Intersection of two 3D bounding boxes\n%\n% RES = intersectBoxes3d(BOX1, BOX2)\n%\n% Example\n% box1 = [5 20 5 30 10 50];\n% box2 = [0 15 0 15 0 20];\n% intersectBoxes3d(box1, box2)\n% ans = \n% 5 15 5 15 10 20\n%\n% See also\n% boxes3d, drawBox3d, mergeBoxes3d\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(:,2:2:end), box2(:,2:2:end));\nmaxi = max(box1(:,1:2:end), box2(:,1:2:end));\n\n% concatenate result into a new box structure\nbox = [maxi(:,1) mini(:,1) maxi(:,2) mini(:,2) maxi(:,3) mini(:,3)];\n\n", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/matGeom/geom3d/intersectBoxes3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.5956399384365136}} {"text": "function [x, infos] = kl_bmd_nmf(V, rank, in_options)\n% Block mirror descent method for KL-based non-negative matrix factorization (KL-BMD-NMF).\n%\n% The problem of interest is defined as\n%\n% min f(V, W, H),\n% where \n% {V, W, H} >= 0.\n%\n% Given a non-negative matrix V, factorized non-negative matrices {W, H} are calculated.\n%\n%\n% Inputs:\n% V : (m x n) non-negative matrix to factorize\n% rank : rank\n% in_options \n%\n% Output:\n% x : non-negative matrix solution, i.e., x.W: (m x rank), x.H: (rank x n)\n% infos : log information\n% epoch : iteration nuber\n% cost : objective function value\n% optgap : optimality gap\n% time : elapsed time\n% grad_calc_count : number of sampled data elements (gradient calculations)\n%\n%\n% This file is part of NMFLibrary\n%\n% This file has been ported from \n% BMD.m at https://github.com/LeThiKhanhHien/KLNMF written originally by LTK Hien.\n%\n% Ported by H.Kasai on June 28, 2022\n%\n% Change log: \n%\n% Jul. 12, 2022 (Hiroyuki Kasai): Modified code structures.\n%\n\n\n % set dimensions and samples\n [m, n] = size(V);\n \n % set local options\n local_options = [];\n local_options.metric.type = 'kl-div';\n local_options.myeps = 1e-16; \n \n % check input options\n if ~exist('in_options', 'var') || isempty(in_options)\n in_options = struct();\n end \n % merge options\n options = mergeOptions(get_nmf_default_options(), local_options); \n options = mergeOptions(options, in_options); \n\n % initialize factors\n init_options = options;\n [init_factors, ~] = generate_init_factors(V, rank, init_options); \n W = init_factors.W;\n H = init_factors.H; \n \n % initialize\n method_name = 'KL-BMD'; \n epoch = 0; \n grad_calc_count = 0;\n\n if options.verbose > 0\n fprintf('# %s: started ...\\n', method_name); \n end \n\n % initialize for this algorithm\n lambdaH = (1./(sum(V))); % the row which is the sum of columns of X\n lambdaH = repmat(lambdaH, rank, 1);\n lambdaW = (1./(sum(V,2)))';\n lambdaW = repmat(lambdaW, rank , 1); \n \n % store initial info\n clear infos;\n [infos, f_val, optgap] = store_nmf_info(V, W, H, [], options, [], epoch, grad_calc_count, 0);\n \n if options.verbose > 1\n fprintf('KL-BMD: Epoch = 0000, cost = %.16e, optgap = %.4e\\n', f_val, optgap); \n end \n\n % set start time\n start_time = tic();\n\n % main loop\n while true\n \n % check stop condition\n [stop_flag, reason, max_reached_flag] = check_stop_condition(epoch, infos, options);\n if stop_flag\n display_stop_reason(epoch, infos, options, method_name, reason, max_reached_flag);\n break;\n end \n\n % update H\n rj = sum(W)';\n rjc = repmat(rj, 1, n);\n bAv = V./(W*H+eps);\n cj = W' * bAv; \n H = H ./ (1 + (lambdaH .* H) .* (rjc - cj));\n H = H + (H slope.\n [gx, ~, dgdp] = VBA_sigmoid (u,...\n 'center', phi(1), ...\n 'slope', exp (phi(2)) ...\n );\n dgdp(2,:) = dgdp(2,:) * exp (phi(2));\n dgdx = [];\nend\n\n% dimensions\n% -------------------------------------------------------------------------\ndim.n_phi = 2;\ndim.n_t = 1;\ndim.p = N;\n\n% general options\n% -------------------------------------------------------------------------\n% binary observations \noptions.sources.type = 1; \n\n% no display\noptions.DisplayWin = 0;\noptions.verbose = 0;\n\n%% 1) No optimisation\n% =========================================================================\n% here, we'll use the most naive approach, a full swipe of all possible \n% stimulus intensities\n\n% experimental design\n% -------------------------------------------------------------------------\nu = uRange';\n\n% simulate responses\n% -------------------------------------------------------------------------\ny = VBA_simulate (1,[],@g_psychometric,[],phi,u,[],[],options); \n\n% estimate parameters\n% -------------------------------------------------------------------------\nposterior_naive = VBA_NLStateSpaceModel (y,u,[],@g_psychometric,dim,options);\n\n% display results\n% -------------------------------------------------------------------------\nplot_design(1, 'no optimisation', u, y, posterior_naive);\n\n%% 2) Offline optimisation\n% =========================================================================\n% Here, we will try to find a better design before running the experiment\n\n% experimental design\n% -------------------------------------------------------------------------\n% number of designs to try\nnAttempts = 1e4;\n\n% initialization\nfprintf('Offline optimisation: optimizing ( 0%%)');\nefficiency_offOpt = - Inf;\nefficiencyDesign = nan(1, nAttempts);\nkeepDesign = [1];\n\n% loop over designs\nfor attempt = 1 : nAttempts\n \n % draw random design\n u_attempt = uRange(randi (numel (uRange), 1, N))';\n \n % estimate efficiency\n efficiencyDesign(attempt) = VBA_designEfficiency([],@g_psychometric,dim,options,u_attempt,'parameters');\n\n % if better, store and display\n if efficiencyDesign(attempt) > efficiency_offOpt \n efficiency_offOpt = efficiencyDesign(attempt);\n u = sort(u_attempt);\n keepDesign(end+1) = attempt;\n end\n \n if efficiencyDesign(attempt) > efficiency_offOpt || mod(attempt, 50) == 0\n plot_design(2, 'offline optimisation', u, y, [], [], efficiencyDesign(keepDesign));\n end\n \n % progress bar\n fprintf('\\b\\b\\b\\b\\b%3d%%)', round(100* attempt / nAttempts));\nend\n\n% simulate responses\n% -------------------------------------------------------------------------\ny = VBA_simulate (1,[],@g_psychometric,[],phi,u,[],[],options); \n\n% estimate parameters\n% -------------------------------------------------------------------------\nposterior_offline = VBA_NLStateSpaceModel (y,u,[],@g_psychometric,dim,options);\n\n% display results\n% -------------------------------------------------------------------------\nplot_design(2, 'offline optimisation', u, y, posterior_offline);\n\n%% 3) Online optimisation\n% =========================================================================\n% Here, we will optimize the design during the experiment by taking into\n% account trial-by-trial subject's responses to adaptively select the next\n% best stimulus to present\n\n% initialization\nopt = options;\nu = nan(N, 1);\nefficiencyInput = nan(1, length (uRange));\nefficiencyDesign = nan(1, length (uRange));\n\n% run experiment\nfor t = 1 : N\n \n % extend design\n % ---------------------------------------------------------------------\n % start from current posterior belief\n try\n opt.priors = posterior_online;\n end\n \n % compute efficiency of potential stimuli\n dim.p = 1;\n for i = 1 : length (uRange)\n efficiencyInput(i) = VBA_designEfficiency([],@g_psychometric,dim,opt,uRange(i),'parameters');\n end\n \n % find best next stimulus to present\n [efficiencyDesign(t), idxMaxEff] = max (efficiencyInput);\n u(t) = uRange(idxMaxEff);\n\n % simulate 1 responses\n % ---------------------------------------------------------------------\n y(t) = VBA_simulate (1,[],@g_psychometric,[],phi,u(t),Inf,[],options);\n \n % estimate parameters given data acquired so far\n % ---------------------------------------------------------------------\n dim.p = t;\n posterior_online = VBA_NLStateSpaceModel(y(1:t),u(1:t),[],@g_psychometric,dim,options);\n\n % display\n % ---------------------------------------------------------------------\n plot_design(3, 'online optimisation', u, y, posterior_online, efficiencyInput, efficiencyDesign);\n\nend\n\n% display\n% --------------------------------------------------------------------- \nplot_design(3, 'online optimisation', u, y, posterior_online);\n\n%% show results\n% =========================================================================\n\nfprintf('\\nSimulation results:\\n');\n\ndisp (table ( ...\n phi, ...\n posterior_naive.muPhi, ...\n posterior_offline.muPhi, ...\n posterior_online.muPhi, ...\n 'RowNames', {'center','slope'}, ...\n 'VariableNames',{'true','naive','offline','online'}));\n\n%% ########################################################################\n% display subfunction\n% ########################################################################\n\nfunction plot_design(idx, titleTxt, u, y, posterior, uEfficiency, dEfficiency)\n \n % jitter for data display\n persistent jitter;\n if isempty(jitter)\n jitter = 0.1 * (rand(N,1)-0.5);\n end\n\n % experimental design \n subplot(4,3,idx)\n \n if nargin > 5 && ~ isempty (uEfficiency)% if efficiency given\n \n [ax,h1,h2] = plotyy(u,10,uRange,uEfficiency,@myHistogram,@myPlot);\n xlim([uRange(1)-0.05, uRange(end)+0.05]);\n set(get(ax(1), 'YLabel'), 'String', 'freq. of presentation')\n set(get(ax(2), 'YLabel'), 'String', 'efficiency')\n set(ax(1),'YLim', [0 0.4],'YTick',0:.2:.4) \n xlabel('stimulus intensity')\n box off\n\n else\n \n % show stimuli density\n histogram(u, 10, 'EdgeColor','none','FaceColor',[.3 .3 .4],'Normalization','probability');\n xlim([uRange(1)-0.05, uRange(end)+0.05])\n ylim([0 0.4])\n xlabel('stimulus intensity')\n ylabel('freq. of presentation')\n box off\n end\n % show type of optimisation\n VBA_title(gca,titleTxt);\n \n if nargin > 6 % if efficiency given\n subplot(4,3,3+idx)\n plot(dEfficiency);\n xlim([1 numel(dEfficiency)])\n ylim([1.1*min(dEfficiency) 0])\n switch idx\n case 2\n xlabel('selected design');\n case 3\n xlabel('trial');\n end\n\n ylabel('efficiency');\n box off\n end\n\n % show results if any\n if ~isempty(posterior)\n \n % + observations\n \n subplot(4,3,6+idx)\n % predictions\n opt_plot = options;\n opt_plot.priors = posterior;\n dim_opt = dim;\n dim_opt.p = numel(uRange);\n muy = VBA_getLaplace(uRange',[],@g_psychometric,dim_opt,opt_plot);\n plot(uRange,muy,'r','LineWidth',2);\n % true model\n hold on\n plot(uRange,g_psychometric([],phi,uRange),'Color',[0 .8 0],'LineWidth',2);\n % data\n plot(u,y+jitter(1:numel(y)),'.k');\n \n % options\n ylim([-0.1 1.1])\n xlim([uRange(1)-0.05, uRange(end)+0.05])\n xlabel('stimulus intensity')\n ylabel('prob. of detection')\n hold off\n box off\n if idx == 1\n text(.2,.6,'true model','Color',[0 .8 0]);\n text(.2,.4,'observations','Color','k');\n text(.2,.2,'predicted','Color','r');\n end\n \n % + parameters\n\n subplot(4,3,9+idx);\n \n % posterior estimates\n plotUncertainTimeSeries(posterior.muPhi,sqrt(diag(posterior.SigmaPhi)),[],gca);\n % true values\n hold on\n plot(phi,'o','MarkerFaceColor',[0 .8 0], 'MarkerEdgeColor',[0 .8 0]);\n % options\n set(gca,'XTickLabel',{'center','slope'})\n ylim([-2 4])\n xlabel('parameter')\n ylabel('posterior estimate')\n hold off\n box off\n end\n \n drawnow\nend\n\n function h = myHistogram (x,y)\n h = histogram(x,y,'EdgeColor','none','FaceColor',[.3 .3 .4],'Normalization','probability');\n end\n\n function h = myPlot (x,y)\n h = plot(x,y);\n hold on\n [mE, iE] = max (y);\n plot(uRange(iE),mE,'o','MarkerFaceColor',[.3 .3 .3],'MarkerEdgeColor',[.3 .3 .3])\n hold off\n end\nend\n", "meta": {"author": "MBB-team", "repo": "VBA-toolbox", "sha": "01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414", "save_path": "github-repos/MATLAB/MBB-team-VBA-toolbox", "path": "github-repos/MATLAB/MBB-team-VBA-toolbox/VBA-toolbox-01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414/demos/1_advanced/demo_designOptimization.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066295, "lm_q2_score": 0.7057850340255387, "lm_q1q2_score": 0.5956085392123287}} {"text": "function [cellU, S, cellV] = separableFormat(A, xorder, yorder, domain)\n%SEPARATBLEFORMAT Compute separable expression for a linear PDO.\n%\n% Calculate a separable representation of a partial differential \n% operator. These representations can then be using to derive a 2D spectral\n% method from 1D ideas. The linear PDO can have variable coefficients. \n%\n% This uses the tensor-train decomposition and Proposition\n% 4.2 from [1].\n% \n% [1] A. Townsend and S. Olver, The automatic solution of partial differential\n% equations using a global spectral method, submitted, 2014. \n% \n% Author: Alex Townsend September 2014.\n\nif ( nargin == 1 )\n N = A; \n A = N.coeffs; \n xorder = N.xorder; \n yorder = N.yorder; \n domain = N.domain; \nend\n\n% Loop over coefficients of A. Find coefficient of highest degree. We will \n% need this to recover the variable coefficients: \nn = 10; \nfor jj = 1:size(A, 1) \n for kk = 1:size(A, 2); \n if ( isa(A{jj,kk}, 'chebfun2') )\n [xdeg, ydeg] = length(A{jj,kk}); % get degrees \n n = max([xdeg, ydeg, n]) + 1; % take maximum degree we find\n end\n end\nend\n\n% Set up Chebyshev points that we need: \nx = chebpts(xorder+1); \ns = chebpts(n, domain(1:2)); \ny = chebpts(yorder+1); \nt = chebpts(n, domain(3:4)); \n[xx, ss, yy, tt] = ndgrid(x, s, y, t); \n[newx, newy] = meshgrid(s, t); \n\n% We need to apply Proposition 4.2 from [1]. Use the linear operator \n% T motivated by umbral calculus. That is, convert \n% \n% d^j/dx^j-> x^j \n% d^j/dy^j-> y^j\n% x -> s\n% y -> t \n% We obtain a function of 4 variables, H(x,s,y,t). See [1]. \nH = @(x,s,y,t) 0*x;\nfor jj = 1:size(A, 1)\n for kk = 1:size(A, 2)\n if ( isa(A{jj,kk}, 'double') && ~(A{jj,kk} == 0) )\n H = @(x,s,y,t) H(x,s,y,t) + A{jj,kk}*x.^(kk - 1).*y.^(jj - 1);\n elseif ( isa(A{jj,kk}, 'chebfun2') )\n v = zeros(1, n, 1, n);\n v(1,:,1,:) = feval(A{jj,kk}, newx, newy).';\n out = repmat(v, [xorder + 1, 1, yorder + 1, 1]);\n H = @(x,s,y,t) H(x,s,y,t) + out.*x.^(kk-1).*y.^(jj-1);\n end\n end\nend\nH = H(xx, ss, yy, tt);\n\n% Using tensor-train ideas. Calculate the splitting rank of the function\n% H(x,s,y,t): \nA = reshape(H, n*(xorder+1), n*(yorder+1));\n[U, S, V] = svd(A); \nrk = find(abs(diag(S)/S(1,1)) > 1000*eps, 1, 'last' ); % splitting rank\n\n% Restrict to singular vectors of interest. \nS = S(1:rk, 1:rk);\nU = U(:, 1:rk); \nV = V(:, 1:rk); \n\n% We have the splitting rank of the PDO, now we want the corresponding \n% separable representation. The following is tricky to get right... \ncellU = cell(yorder+1, rk);\ncellV = cell(xorder+1, rk); \nc1 = cell(xorder, 1); \nc2 = cell(yorder, 1); \n% Matrices to convert ChebT -> monomials: \nconverty = fliplr(poly(chebpoly(0:yorder))); \nconvertx = fliplr(poly(chebpoly(0:xorder)));\n\n% Figure out the separable representation: \nfor jj = 1:rk \n\n % This is giving us the 1D ODEs that go on the right in the generalized\n % Sylvester matrix equation: \n f1 = chebfun2.vals2coeffs( reshape(U(:,jj), xorder+1, n) ); % @(x, s)\n f1 = f1.' * convertx;\n for kk = 1:xorder+1\n c1{kk} = chebfun(f1(:,kk), domain(1:2), 'coeffs');\n cellV(kk,jj) = c1(kk);\n end\n\n % This is giving us the 1D ODEs that go on the left in the generalized\n % Sylvester matrix equation: \n f2 = chebfun2.vals2coeffs( reshape(conj(V(:,jj)), yorder+1, n) ); % @(y, t) \n f2 = f2.' * converty;\n for kk = 1:yorder+1\n c2{kk} = chebfun(f2(:,kk), domain(3:4), 'coeffs');\n cellU(kk,jj) = c2(kk);\n end \nend\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebop2/separableFormat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.843895106480586, "lm_q2_score": 0.7057850216484837, "lm_q1q2_score": 0.5956085259964498}} {"text": "function [Y, R, E] = Isomap(D, n_fcn, n_size, options); \n\n% ISOMAP Computes Isomap embedding using the algorithm of \n% Tenenbaum, de Silva, and Langford (2000). \n%\n% [Y, R, E] = isomap(D, n_fcn, n_size, options); \n%\n% Input:\n% D = N x N matrix of distances (where N is the number of data points)\n% n_fcn = neighborhood function ('epsilon' or 'k') \n% n_size = neighborhood size (value for epsilon or k) \n%\n% options.dims = (row) vector of embedding dimensionalities to use\n% (1:10 = default)\n% options.comp = which connected component to embed, if more than one. \n% (1 = largest (default), 2 = second largest, ...)\n% options.display = plot residual variance and 2-D embedding?\n% (1 = yes (default), 0 = no)\n% options.overlay = overlay graph on 2-D embedding? \n% (1 = yes (default), 0 = no)\n% options.verbose = display progress reports? \n% (1 = yes (default), 0 = no)\n%\n% Output: \n% Y = Y.coords is a cell array, with coordinates for d-dimensional embeddings\n% in Y.coords{d}. Y.index contains the indices of the points embedded.\n% R = residual variances for embeddings in Y\n% E = edge matrix for neighborhood graph\n%\n\n% BEGIN COPYRIGHT NOTICE\n%\n% Isomap code -- (c) 1998-2000 Josh Tenenbaum\n%\n% This code is provided as is, with no guarantees except that \n% bugs are almost surely present. Published reports of research \n% using this code (or a modified version) should cite the \n% article that describes the algorithm: \n%\n% J. B. Tenenbaum, V. de Silva, J. C. Langford (2000). A global\n% geometric framework for nonlinear dimensionality reduction. \n% Science 290 (5500): 2319-2323, 22 December 2000. \n%\n% Comments and bug reports are welcome. Email to jbt@psych.stanford.edu. \n% I would also appreciate hearing about how you used this code, \n% improvements that you have made to it, or translations into other\n% languages. \n%\n% You are free to modify, extend or distribute this code, as long \n% as this copyright notice is included whole and unchanged. \n%\n% END COPYRIGHT NOTICE\n\n\n%%%%% Step 0: Initialization and Parameters %%%%%\n\nN = size(D,1); \nif ~(N==size(D,2))\n error('D must be a square matrix'); \nend; \nif n_fcn=='k'\n K = n_size; \n if ~(K==round(K))\n error('Number of neighbors for k method must be an integer');\n end\nelseif n_fcn=='epsilon'\n epsilon = n_size; \nelse \n error('Neighborhood function must be either epsilon or k'); \nend\nif nargin < 3\n error('Too few input arguments'); \nelseif nargin < 4\n options = struct('dims',1:10,'overlay',1,'comp',1,'display',1,'verbose',1); \nend\nINF = 1000*max(max(D))*N; %% effectively infinite distance\n\nif ~isfield(options,'dims')\n options.dims = 1:10; \nend\nif ~isfield(options,'overlay')\n options.overlay = 1; \nend\nif ~isfield(options,'comp')\n options.comp = 1; \nend\nif ~isfield(options,'display')\n options.display = 1; \nend\nif ~isfield(options,'verbose')\n options.verbose = 1; \nend\ndims = options.dims; \ncomp = options.comp; \noverlay = options.overlay; \ndispl = options.display; \nverbose = options.verbose; \n\nY.coords = cell(length(dims),1); \nR = zeros(1,length(dims)); \n\n%%%%% Step 1: Construct neighborhood graph %%%%%\ndisp('Constructing neighborhood graph...'); \n\nif n_fcn == 'k'\n [tmp, ind] = sort(D); \n for i=1:N\n D(i,ind((2+K):end,i)) = INF; \n end\nelseif n_fcn == 'epsilon'\n warning off %% Next line causes an unnecessary warning, so turn it off\n D = D./(D<=epsilon); \n D = min(D,INF); \n warning on\nend\n\nD = min(D,D'); %% Make sure distance matrix is symmetric\n\nif (overlay == 1)\n E = int8(1-(D==INF)); %% Edge information for subsequent graph overlay\nend\n\n% Finite entries in D now correspond to distances between neighboring points. \n% Infinite entries (really, equal to INF) in D now correspond to \n% non-neighoring points. \n\n%%%%% Step 2: Compute shortest paths %%%%%\ndisp('Computing shortest paths...'); \n\n% We use Floyd's algorithm, which produces the best performance in Matlab. \n% Dijkstra's algorithm is significantly more efficient for sparse graphs, \n% but requires for-loops that are very slow to run in Matlab. A significantly \n% faster implementation of Isomap that calls a MEX file for Dijkstra's \n% algorithm can be found in isomap2.m (and the accompanying files\n% dijkstra.c and dijkstra.dll). \n\ntic; \nfor k=1:N\n D = min(D,repmat(D(:,k),[1 N])+repmat(D(k,:),[N 1])); \n if ((verbose == 1) & (rem(k,20) == 0)) \n disp([' Iteration: ' num2str(k) ' Estimated time to completion: 'num2str((N-k)*toc/k/60) ' minutes']); \n end\nend\n\n%%%%% Remove outliers from graph %%%%%\ndisp('Checking for outliers...'); \nn_connect = sum(~(D==INF)); %% number of points each point connects to\n[tmp, firsts] = min(D==INF); %% first point each point connects to\n[comps, I, J] = unique(firsts); %% represent each connected component once\nsize_comps = n_connect(comps); %% size of each connected component\n[tmp, comp_order] = sort(size_comps); %% sort connected components by size\ncomps = comps(comp_order(end:-1:1)); \nsize_comps = size_comps(comp_order(end:-1:1)); \nn_comps = length(comps); %% number of connected components\nif (comp>n_comps) \n comp=1; %% default: use largest component\nend\ndisp([' Number of connected components in graph: ' num2str(n_comps)]); \ndisp([' Embedding component ' num2str(comp) ' with ' num2str(size_comps(comp)) ' points.']); \nY.index = find(firsts==comps(comp)); \n\nD = D(Y.index, Y.index); \nN = length(Y.index); \n\n%%%%% Step 3: Construct low-dimensional embeddings (Classical MDS) %%%%%\ndisp('Constructing low-dimensional embeddings (Classical MDS)...'); \n\nopt.disp = 0; \n[vec, val] = eigs(-.5*(D.^2 - sum(D.^2)'*ones(1,N)/N - ones(N,1)*sum(D.^2)/N + sum(sum(D.^2))/(N^2)), max(dims), 'LR', opt); \n\nh = real(diag(val)); \n[foo,sorth] = sort(h); sorth = sorth(end:-1:1); \nval = real(diag(val(sorth,sorth))); \nvec = vec(:,sorth); \n\nD = reshape(D,N^2,1); \nfor di = 1:length(dims)\n if (dims(di)<=N)\n Y.coords{di} = real(vec(:,1:dims(di)).*(ones(N,1)*sqrt(val(1:dims(di)))'))'; \n r2 = 1-corrcoef(reshape(real(L2_distance(Y.coords{di}, Y.coords{di})),N^2,1),D).^2; \n R(di) = r2(2,1); \n if (verbose == 1)\n disp([' Isomap on ' num2str(N) ' points with dimensionality ' num2str(dims(di)) ' --> residual variance = ' num2str(R(di))]); \n end\n end\nend\n\nclear D; \n\n%%%%%%%%%%%%%%%%%% Graphics %%%%%%%%%%%%%%%%%%\n\nif (displ==1)\n %%%%% Plot fall-off of residual variance with dimensionality %%%%%\n figure;\n hold on\n plot(dims, R, 'bo'); \n plot(dims, R, 'b-'); \n hold off\n ylabel('Residual variance'); \n xlabel('Isomap dimensionality'); \n\n %%%%% Plot two-dimensional configuration %%%%%\n twod = find(dims==2); \n if ~isempty(twod)\n figure;\n hold on;\n plot(Y.coords{twod}(1,:), Y.coords{twod}(2,:), 'ro'); \n if (overlay == 1)\n gplot(E(Y.index, Y.index), [Y.coords{twod}(1,:); Y.coords{twod}(2,:)]'); \n title('Two-dimensional Isomap embedding (with neighborhood graph).'); \n else\n title('Two-dimensional Isomap.'); \n end\n hold off;\n end\nend\n\nreturn;\n\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAnatomy/mrFlatMesh/mex/CSource/Isomap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5956085176836218}} {"text": "function line = edgeToLine(edge)\n%EDGETOLINE Convert an edge to a straight line.\n%\n% LINE = edgeToLine(EDGE);\n% Returns the straight line containing the edge EDGE.\n% EDGE is represented as [X1 Y1 X2 Y2]\n% LINE is represented as [X0 Y0 DX DY]\n%\n% Example\n% edge = [2 3 4 5];\n% line = edgeToLine(edge);\n% figure(1); hold on; axis([0 10 0 10]);\n% drawLine(line, 'color', 'g')\n% drawEdge(edge, 'linewidth', 2)\n% \n% See also \n% edges2d, lines2d, lineToEdge\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@inra.fr\n% Created: 2009-07-23, using Matlab 7.7.0.471 (R2008b)\n% Copyright 2009-2022 INRA - Cepia Software Platform\n\nline = [edge(:, 1:2) edge(:, 3:4)-edge(:, 1:2)];\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/geom2d/edgeToLine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.5955582830988849}} {"text": "function showresult(node,elem,u,viewangle)\n%% SHOWRESULT display the mesh and the solution \n%\n% showresult(node,elem,u,viewangle) displays the mesh and the solution in\n% one figure. The left one is the mesh, the middle\n% one is the contour of the solution, and the right one is the graph of\n% the function. The last viewangle is used to adjust the view angle of the\n% graph of the function.\n%\n% Example:\n% f = inline('sin(2*pi*x).*cos(2*pi*y)');\n% node = [0,0; 1,0; 1,1; 0,1];\n% elem = [2,3,1; 4,1,3]; \n% for k = 1:4\n% [node,elem] = uniformrefine(node,elem);\n% end\n% u = f(node(:,1),node(:,2));\n% showresult(node,elem,u,[-62,58]);\n%\n% See also showrate, showmesh, showsolution\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nif (length(u) == size(elem,1)) || (length(u) == size(node,1))\n % show mesh\n set(gcf,'Units','normal'); \n set(gcf,'Position',[0.25,0.25,0.6,0.25]);\n if size(elem,1) < 6e4\n subplot(1,3,1); \n showmesh(node,elem); \n pause(0.05)\n else\n subplot(1,3,1);\n title('The mesh is too dense to display')\n end\n % show solution\n subplot(1,3,2); \n showsolution(node,elem,u,2);\n colorbar;\n pause(0.05)\n subplot(1,3,3); \n showsolution(node,elem,u);\n if nargin>3\n view(viewangle);\n end\n pause(0.05)\nelse\n showmesh(node,elem);\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/tool/showresult.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.595511931236055}} {"text": "function Results = MTrick(TrainX,TrainY,TestX,TestY,alpha,beta,numK,numCircle)\n\nfor id = 1:length(TrainY)\n if TrainY(id) == 2\n TrainY(id) = -1;\n end\nend\n\nfor id = 1:length(TestY)\n if TestY(id) == 2\n TestY(id) = -1;\n end\nend\n\nG0 = [];\nfor i = 1:length(TrainY)\n if TrainY(i) == 1\n G0(i,1) = 1;\n G0(i,2) = 0;\n else\n G0(i,1) = 0;\n G0(i,2) = 1;\n end\nend\n\nTrainXY = scale_cols(TrainX,TrainY);\nfprintf('......start to train logistic regression model1111.........\\n');\nw00 = zeros(size(TrainXY,1),1);\nlambda = exp(linspace(-0.5,6,20));\nwbest = [];\nf1max = -inf;\nfor i = 1:length(lambda)\n w_0 = train_cg(TrainXY,w00,lambda(i));\n f1 = logProb(TrainXY,w_0);\n if f1 > f1max\n f1max = f1;\n wbest = w_0;\n se_lambda = lambda(i);\n end\nend\n% csvwrite(strcat('model_','test','.model'),wbest);\n% wbest = load(strcat('model_','test','.model'));\n\nptemp = 1./(1 + exp(-wbest'*TrainX));\noriA = getResult(ptemp,TrainY);\nfprintf('Test accuracy on source domain is :%g\\n',oriA);\nptemp = 1./(1 + exp(-wbest'*TestX));\noriA = getResult(ptemp,TestY);\nfprintf('Test accuracy on target domain is :%g\\n',oriA);\n\nfprintf('......start to learn PLSA model.........\\n');\nDataSetX = [TrainX TestX];\n% set some variables\nLearn.Verbosity = 1;\nLearn.Max_Iterations = 50;\nLearn.heldout = .1; % for tempered EM only, percentage of held out data\nLearn.Min_Likelihood_Change = 1;\nLearn.Folding_Iterations = 20; % for TEM only: number of fiolding\n% in iterations\nLearn.TEM = 0; %tempered or not tempered\n\n[Pw_z,Pz_d,Pd,Li,perp,eta] = pLSA(DataSetX,[],numK,Learn);\npz = Pz_d*Pd';\npw = Pw_z*pz;\nA = Pw_z;\nfor i = 1:size(Pw_z,1)\n A(i,:) = A(i,:).*pz';\nend\n\nfor i = 1:size(Pw_z,2)\n for j = 1:length(A(:,i))\n if pw(j) > 0\n A(j,i) = A(j,i)./pw(j);\n else\n A(j,i) = 1/size(Pw_z,2);\n end\n end\nend\npwz = A;\nclear A;\n% csvwrite(strcat('pwz_common.pwz'),pwz);\n% \n% pwz = load(strcat('pwz_common.pwz'));\n\nFs = pwz;\nFt = Fs;\n\nGs = G0;\nGt = [];\nfor i = 1:length(TestY)\n Gt(i,1) = ptemp(i);\n Gt(i,2) = 1 - ptemp(i);\nend\n\nXs = TrainX;\nXt = TestX;\nXs = Xs/sum(sum(Xs));\nXt = Xt/sum(sum(Xt));\n\nb = 1/(size(Gs,1));\n\nS = ones(size(Fs,2),size(Gs,2));\nfor i = 1:size(S,1)\n S(i,:) = S(i,:)/sum(S(i,:));\nend\n\nfvalue = trace(Xs'*Xs-2*Xs'*Fs*S*Gs'+Gs*S'*Fs'*Fs*S*Gs')+alpha*b*trace(Gs*Gs'-2*Gs*G0'+G0*G0')+beta*trace(Xt'*Xt-2*Xt'*Ft*S*Gt'+Gt*S'*Ft'*Ft*S*Gt');\ntempf = 0;\nfor circleID = 1:numCircle\n tempM = (Fs*S*Gs'*Gs*S');\n tempM1 = Xs*Gs*S';\n for i = 1:size(Fs,1)\n for j = 1:size(Fs,2)\n if tempM(i,j)~=0\n Fs(i,j) = Fs(i,j)*(tempM1(i,j)/tempM(i,j))^(0.5);\n else\n Fs(i,j) = 0;\n end\n end\n end\n for i = 1:size(Fs,1)\n if sum(Fs(i,:))~= 0\n Fs(i,:) = Fs(i,:)/sum(Fs(i,:));\n else\n for j = 1:size(Fs,2)\n Fs(i,j) = 1/(size(Fs,2));\n end\n end\n end\n tempM = (Gs*S'*Fs'*Fs*S+alpha*b*Gs);\n tempM1 = Xs'*Fs*S + alpha*b*G0;\n for i = 1:size(Gs,1)\n for j = 1:size(Gs,2)\n if tempM(i,j)~=0\n Gs(i,j) = Gs(i,j)*(tempM1(i,j)/tempM(i,j))^(0.5);\n else\n Gs(i,j) = 0;\n end\n end\n end\n for i = 1:size(Gs,1)\n if sum(Gs(i,:))~= 0\n Gs(i,:) = Gs(i,:)/sum(Gs(i,:));\n else\n for j = 1:size(Gs,2)\n Gs(i,j) = 1/(size(Gs,2));\n end\n end\n end\n \n tempM = (Ft*S*Gt'*Gt*S');\n tempM1 = Xt*Gt*S';\n for i = 1:size(Ft,1)\n for j = 1:size(Ft,2)\n if tempM(i,j)~=0\n Ft(i,j) = Ft(i,j)*(tempM1(i,j)/tempM(i,j))^(0.5);\n else\n Ft(i,j) =0;\n end\n end\n end\n for i = 1:size(Ft,1)\n if sum(Ft(i,:))~= 0\n Ft(i,:) = Ft(i,:)/sum(Ft(i,:));\n else\n for j = 1:size(Ft,2)\n Ft(i,j) = 1/(size(Ft,2));\n end\n end\n end\n \n tempM = (Gt*S'*Ft'*Ft*S);\n tempM1 = Xt'*Ft*S;\n for i = 1:size(Gt,1)\n for j = 1:size(Gt,2)\n if tempM(i,j)~=0\n Gt(i,j) = Gt(i,j)*(tempM1(i,j)/tempM(i,j))^(0.5);\n else\n Gt(i,j) = 0;\n end\n end\n end\n for i = 1:size(Gt,1)\n if sum(Gt(i,:))~= 0\n Gt(i,:) = Gt(i,:)/sum(Gt(i,:));\n else\n for j = 1:size(Gt,2)\n Gt(i,j) = 1/(size(Gt,2));\n end\n end\n end\n \n \n tempM = (Fs'*Fs*S*Gs'*Gs+beta*Ft'*Ft*S*Gt'*Gt);\n tempM1 = Fs'*Xs*Gs+beta*Ft'*Xt*Gt;\n for i = 1:size(S,1)\n for j = 1:size(S,2)\n if tempM(i,j)~=0\n S(i,j) = S(i,j)*(tempM1(i,j)/tempM(i,j))^(0.5);\n else\n S(i,j) = 0;\n end\n end\n end\n \n fvalue = trace(Xs'*Xs-2*Xs'*Fs*S*Gs'+Gs*S'*Fs'*Fs*S*Gs')+alpha*b*trace(Gs*Gs'-2*Gs*G0'+G0*G0')+beta*trace(Xt'*Xt-2*Xt'*Ft*S*Gt'+Gt*S'*Ft'*Ft*S*Gt');\n \n pp = [];\n for i = 1:length(TestY)\n if sum(Gt(i,:))~= 0\n pp(1,i) = Gt(i,1)/sum(Gt(i,:));\n else\n pp(1,i) = 0.5;\n end\n end\n Results(circleID) = getResult(pp,TestY);\n fprintf('the %g iteration is %g,the value of objective is %g\\n',circleID,getResult(pp,TestY),fvalue);\n \n if circleID == 1\n tempf = fvalue;\n end\n if circleID > 1\n if abs(tempf - fvalue) < 10^(-11)\n break;\n end\n tempf = fvalue;\n end\nend", "meta": {"author": "FuzhenZhuang", "repo": "Transfer-Learning-Toolkit", "sha": "24b5323b354aee844b8b7df9fcad17fdfb191dc4", "save_path": "github-repos/MATLAB/FuzhenZhuang-Transfer-Learning-Toolkit", "path": "github-repos/MATLAB/FuzhenZhuang-Transfer-Learning-Toolkit/Transfer-Learning-Toolkit-24b5323b354aee844b8b7df9fcad17fdfb191dc4/utilities/TLLibrary64/MTrick/MTrick.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5954414041365214}} {"text": "function [h, compUpAV, compUpVP, compUp] = lfmComputeH3AV(gamma1_p, gamma1_m, sigma2, t1, ...\n t2, preFactor, mode)\n\n% LFMCOMPUTEH3AV Helper function for computing part of the LFMAV kernel.\n% FORMAT\n% DESC computes a portion of the LFMAV kernel.\n% ARG gamma1 : Gamma value for first system.\n% ARG gamma2 : Gamma value for second system.\n% ARG sigma2 : length scale of latent process.\n% ARG t1 : first time input (number of time points x 1).\n% ARG t2 : second time input (number of time points x 1).\n% ARG preFactor : precomputed constants.\n% ARG mode: indicates the correct derivative.\n% RETURN h : result of this subcomponent of the kernel for the given values.\n%\n% COPYRIGHT : Mauricio Alvarez, 2010\n\n% KERN\n\n% Evaluation of h\n\nif nargout>1\n [compUpAV{1}, compUpVP{1}, compUp{1}] = lfmavComputeUpsilonMatrix(gamma1_p,sigma2, t1,t2, mode);\n [compUpAV{2}, compUpVP{2}, compUp{2}] = lfmavComputeUpsilonMatrix(gamma1_m,sigma2, t1,t2, mode);\n h = preFactor(1)*compUpAV{1} + preFactor(2)*compUpAV{2};\nelse\n h = preFactor(1)*lfmavComputeUpsilonMatrix(gamma1_p,sigma2, t1,t2, mode) ...\n + preFactor(2)*lfmavComputeUpsilonMatrix(gamma1_m,sigma2, t1,t2, mode);\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/lfmComputeH3AV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5954391995280209}} {"text": "\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % PULSED SPOTLIGHT SAR SIMULATION AND RECONSTRUCTION %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\ncolormap(gray(256))\ncj=sqrt(-1);\npi2=2*pi;\n%\nc=3e8; % propagation speed\nf0=50e6; % baseband bandwidth is 2*f0\nw0=pi2*f0;\nfc=200e6; % carrier frequency\nwc=pi2*fc;\nlambda_min=c/(fc+f0); % Wavelength at highest frequency\nlambda_max=c/(fc-f0); % Wavelength at lowest frequency\nkc=(pi2*fc)/c; % wavenumber at carrier frequency\nkmin=(pi2*(fc-f0))/c; % wavenumber at lowest frequency\nkmax=(pi2*(fc+f0))/c; % wavenumber at highest frequency\n%\nXc=1000; % Range distance to center of target area\nX0=20; % target area in range is within [Xc-X0,Xc+X0]\nYc=300; % Cross-range distance to center of target area\nY0=60; % target area in cross-range is within\n % [Yc-Y0,Yc+Y0]\n\n% Case 1: L < Y0; requires zero-padding of SAR signal in synthetic\n% aperture domain\n%\n L=100; % synthetic aperture is 2*L\n\n% Case 2: L > Y0; slow-time Doppler subsampling of SAR signal spectrum\n% reduces computation\n%\n% L=400; % synthetic aperture is 2*L\n\ntheta_c=atan(Yc/Xc); % Squint angle\nRc=sqrt(Xc^2+Yc^2); % Squint radial range\nL_min=max(Y0,L); % Zero-padded aperture is 2*L_min\n\n%\nXcc=Xc/(cos(theta_c)^2); % redefine Xc by Xcc for squint processing\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% u domain parameters and arrays for compressed SAR signal %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\nduc=(Xcc*lambda_min)/(4*Y0); % sample spacing in aperture domain\n % for compressed SAR signal\nduc=duc/1.2; % 10 percent guard band; this guard band\n % would not be sufficient for targets\n % outside digital spotlight filter (use\n % a larger guard band, i.e., PRF)\nmc=2*ceil(L_min/duc); % number of samples on aperture\nuc=duc*(-mc/2:mc/2-1); % synthetic aperture array\ndkuc=pi2/(mc*duc); % sample spacing in ku domain\nkuc=dkuc*(-mc/2:mc/2-1); % kuc array\n%\ndku=dkuc; % sample spacing in ku domain\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% u domain parameters and arrays for SAR signal %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\nif Yc-Y0-L < 0, % minimum aspect angle\n theta_min=atan((Yc-Y0-L)/(Xc-X0));\nelse,\n theta_min=atan((Yc-Y0-L)/(Xc+X0));\nend;\ntheta_max=atan((Yc+Y0+L)/(Xc-X0)); % maximum aspect angle\n%\ndu=pi/(kmax*(sin(theta_max)- ...\n sin(theta_min))); % sample spacing in aperture\n % domain for SAR signal\ndu=du/1.4; % 20 percent guard band\nm=2*ceil(pi/(du*dku)); % number of samples on aperture\ndu=pi2/(m*dku); % readjust du\nu=du*(-m/2:m/2-1); % synthetic aperture array\nku=dku*(-m/2:m/2-1); % ku array\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Fast-time domain parmeters and arrays %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\nTp=2.5e-7; % Chirp pulse duration\nalpha=w0/Tp; % Chirp rate\nwcm=wc-alpha*Tp; % Modified chirp carrier\n%\nif Yc-Y0-L < 0,\n Rmin=Xc-X0;\nelse,\n Rmin=sqrt((Xc-X0)^2+(Yc-Y0-L)^2);\nend;\nTs=(2/c)*Rmin; % start time of sampling\nRmax=sqrt((Xc+X0)^2+(Yc+Y0+L)^2);\nTf=(2/c)*Rmax+Tp; % end time of sampling\nT=Tf-Ts; % fast-time interval of measurement\nTs=Ts-.1*T; % start slightly earlier (10% guard band)\nTf=Tf+.1*T; % end slightly later (10% guard band)\nT=Tf-Ts;\nTmin=max(T,(4*X0)/(c*cos(theta_max))); % Minimum required T\n%\ndt=1/(4*f0); % Time domain sampling (guard band factor 2)\nn=2*ceil((.5*Tmin)/dt); % number of time samples\nt=Ts+(0:n-1)*dt; % time array for data acquisition\ndw=pi2/(n*dt); % Frequency domain sampling\nw=wc+dw*(-n/2:n/2-1); % Frequency array (centered at carrier)\nk=w/c; % Wavenumber array\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Resolution for Broadside: (x,y) domain rotated by theta_c %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nDX=c/(4*f0); % range resolution (broadside)\nDY=(Xcc*lambda_max)/(4*L); % cross-range resolution (broadside)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Parameters of Targets %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\nntarget=9; % number of targets\n% Set ntarget=1 to see \"clean\" PSF of target at origin\n% Try this with other targets\n\n% xn: range; yn= cross-range; fn: reflectivity\n xn=zeros(1,ntarget); yn=xn; fn=xn;\n\n% Targets within digital spotlight filter\n%\n xn(1)=0; yn(1)=0; fn(1)=1;\n xn(2)=.7*X0; yn(2)=-.6*Y0; fn(2)=1.4;\n xn(3)=0; yn(3)=-.85*Y0; fn(3)=.8;\n xn(4)=-.5*X0; yn(4)=.75*Y0; fn(4)=1.;\n xn(5)=-.5*X0+DX; yn(5)=.75*Y0+DY; fn(5)=1.;\n\n% Targets outside digital spotlight filter\n% (Run the code with and without these targets)\n% \n xn(6)=-1.2*X0; yn(6)=.75*Y0; fn(6)=1.;\n xn(7)=.5*X0; yn(7)=1.25*Y0; fn(7)=1.;\n xn(8)=1.1*X0; yn(8)=-1.1*Y0; fn(8)=1.;\n xn(9)=-1.2*X0; yn(9)=-1.75*Y0; fn(9)=1.;\n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% SIMULATION %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\ns=zeros(n,mc); % SAR signal array\n%\nfor i=1:ntarget; % Loop for each target\n td=t(:)*ones(1,mc)-2*ones(n,1)*sqrt((Xc+xn(i)).^2+(Yc+yn(i)-uc).^2)/c;\n s=s+fn(i)*exp(cj*wcm*td+cj*alpha*(td.^2)).*(td >= 0 & td <= Tp & ...\n ones(n,1)*abs(uc) <= L & t(:)*ones(1,mc) < Tf);\nend;\n%\ns=s.*exp(-cj*wc*t(:)*ones(1,mc)); % Fast-time baseband conversion\n\n% User may apply a slow-time domain window, e.g., power window, on\n% simulated SAR signal array \"s\" here.\n\nG=abs(s)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage(t,uc,256-cg*(G-ng));\naxis('square');axis('xy')\nxlabel('Fast-time t, sec')\nylabel('Synthetic Aperture (Slow-time) U, meters')\ntitle('Measured Spotlight SAR Signal')\nprint P5.1.ps\npause(1)\n%\n\ntd0=t(:)-2*sqrt(Xc^2+Yc^2)/c;\ns0=exp(cj*wcm*td0+cj*alpha*(td0.^2)).*(td0 >= 0 & td0 <= Tp);\ns0=s0.*exp(-cj*wc*t(:)); % Baseband reference fast-time signal\n\ns=ftx(s).*(conj(ftx(s0))*ones(1,mc)); % Fast-time matched filtering\n%\nG=abs(iftx(s))';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\ntm=(2*Rc/c)+dt*(-n/2:n/2-1); % fast-time array after matched filtering\nimage(tm,uc,256-cg*(G-ng));\naxis('square');axis('xy')\nxlabel('Fast-time t, sec')\nylabel('Synthetic Aperture (Slow-time) U, meters')\ntitle('SAR Signal after Fast-time Matched Filtering')\nprint P5.2.ps\npause(1)\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Slow-time baseband conversion for squint %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\nkus=2*kc*sin(theta_c)*ones(1,n); % Doppler frequency shift in ku\n % domain due to squint\n%\ns=s.*exp(-cj*kus(:)*uc); % slow-time baseband conversion\nfs=fty(s);\n\n% Display aliased SAR spectrum\n%\nG=abs(fs)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage(k*c/pi2,kuc,256-cg*(G-ng));\naxis('square');axis('xy')\nxlabel('Fast-time Frequency, Hertz')\nylabel('Synthetic Aperture (Slow-time) Frequency Ku, rad/m')\ntitle('Aliased Spotlight SAR Signal Spectrum')\nprint P5.3.ps\npause(1)\n\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Digital Spotlighting and Bandwidth Expansion in ku Domain %%\n%% via Slow-time Compression and Decompression %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\ns=s.*exp(cj*kus(:)*uc); % Original signal before baseband\n % conversion for squint\n\ncs=s.*exp(cj*2*(k(:)*ones(1,mc)).* ... \n (ones(n,1)*sqrt(Xc^2+(Yc-uc).^2))-cj*2*k(:)*Rc*ones(1,mc));% compression\nfcs=fty(cs); % F.T. of compressed signal w.r.t. u\n%\nG=abs(fcs)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage(k*c/pi2,kuc,256-cg*(G-ng));\naxis('square');axis('xy')\nxlabel('Fast-time Frequency, Hertz')\nylabel('Synthetic Aperture (Slow-time) Frequency Ku, rad/m')\ntitle('Compressed Spotlight SAR Signal Spectrum')\nprint P5.4.ps\npause(1)\n%\nfp=iftx(fty(cs)); % Narrow-bandwidth Polar Format Processed\n % reconstruction\n%\nPH=asin(kuc/(2*kc)); % angular Doppler domain\nR=(c*tm)/2; % range domain mapped from reference\n % fast-time domain\n%\n% Full Aperture Digital-Spotlight Filter\n%\nW_d=((abs(R(:)*cos(PH+theta_c)-Xc) < X0).* ...\n (abs(R(:)*sin(PH+theta_c)-Yc) < Y0));\n%\nG=(abs(fp)/max(max(abs(fp)))+.1*W_d)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage((Rc/Xc)*(.5*c*tm-Rc),(kuc*Rc)/(2*kc),256-cg*(G-ng));\nxlabel('Range x, m')\nylabel('Cross-range y, m')\ntitle('Polar Format SAR Reconstruction with Digital Spotlight Filter')\naxis image; axis xy;\nprint P5.5.ps\npause(1)\n\nfd=fp.*W_d; % Digital Spotlight Filtering\nfcs=ftx(fd); % Transform to (omega,ku) domain\n\n% Zero-padding in ku domain for slow-time upsampling\n%\nmz=m-mc; % number is zeros\nfcs=(m/mc)*[zeros(n,mz/2),fcs,zeros(n,mz/2)];\n%\ncs=ifty(fcs); % Transform to (omega,u) domain\n\ns=cs.*exp(-cj*2*(k(:)*ones(1,m)).* ... \n (ones(n,1)*sqrt(Xc^2+(Yc-u).^2))+cj*2*k(:)*Rc*ones(1,m));% decompression\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% CAUTION %\n% For TDC or backprojection, do not subsample in Doppler domain %\n% and do not perform slow-time baseband conversion %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\ns_ds=s; % Save s(omega,u) array for TDC and\n % backprojection algorithms\n\n%\ns=s.*exp(-cj*kus(:)*u); % Slow-time baseband conversion for squint\nfs=fty(s); % Digitally-spotlighted SAR signal spectrum\n%\nG=abs(fs)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage(k*c/pi2,ku,256-cg*(G-ng));\naxis('square');axis('xy')\nxlabel('Fast-time Frequency, Hertz')\nylabel('Synthetic Aperture (Slow-time) Frequency Ku, rad/m')\ntitle('Spotlight SAR Signal Spectrum after DS & Upsampling')\nprint P5.6.ps\npause(1)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% SLOW-TIME DOPPLER SUBSAMPLING %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\nif Y0 < L,\n ny=2*ceil(1.2*Y0/du); % Number of samples in y domain\n % 20 percent guard band\n ms=floor(m/ny); % subsampling ratio\n tt=floor(m/(2*ms));\n I=m/2+1-tt*ms:ms:m/2+1+(tt-1)*ms; % subsampled index in ku domain\n [tt,ny]=size(I); % number of subsamples\n fs=fs(:,I); % subsampled SAR signal spectrum\n ky=ku(I); % subsampled ky array\n dky=dku*ms; % ky domain sample spacing\nelse,\n dky=dku;\n ny=m;\n ky=ku;\nend;\n\ndy=pi2/(ny*dky); % y domain sample spacing\ny=dy*(-ny/2:ny/2-1); % cross-range array\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% RECONSTRUCTION %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\nky=ones(n,1)*ky+kus(:)*ones(1,ny); % ky array\nkx=(4*k(:).^2)*ones(1,ny)-ky.^2;\nkx=sqrt(kx.*(kx > 0)); % kx array\n%\nplot(kx(1:20:n*ny),ky(1:20:n*ny),'.')\nxlabel('Spatial Frequency k_x, rad/m')\nylabel('Spatial Frequency k_y, rad/m')\ntitle('Spotlight SAR Spatial Frequency Data Coverage')\naxis image; axis xy\nprint P5.7.ps\npause(1)\n%\nkxmin=min(min(kx));\nkxmax=max(max(kx));\ndkx=pi/X0; % Nyquist sample spacing in kx domain\nnx=2*ceil((.5*(kxmax-kxmin))/dkx); % Required number of\n % samples in kx domain;\n % This value will be increased slightly\n % to avoid negative array index\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% %%%\n%%% FIRST TWO OPTIONS FOR RECONSTRUCTION: %%%\n%%% %%%\n%%% 1. 2D Fourier Matched Filtering and Interpolation %%%\n%%% 2. Range Stacking %%%\n%%% %%%\n%%% Note: For \"Range Stacking,\" make sure that the %%%\n%%% arrays nx, x, and kx are defined. %%%\n%%% %%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% 2D FOURIER MATCHED FILTERING AND INTERPOLATION %%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Matched Filtering\n%\nfs0=(kx > 0).*exp(cj*kx*Xc+cj*ky*Yc+cj*.25*pi ...\n -cj*2*k(:)*ones(1,ny)*Rc); % reference signal complex conjugate\nfsm=fs.*fs0; % 2D Matched filtering\n\n% Interpolation\n%\nis=8; % number of neighbors (sidelobes) used for sinc interpolator\nI=2*is+1;\nkxs=is*dkx; % plus/minus size of interpolation neighborhood in KX domain\n%\nnx=nx+2*is+4; % increase number of samples to avoid negative\n % array index during interpolation in kx domain\nKX=kxmin+(-is-2:nx-is-3)*dkx; % uniformly-spaced kx points where\n % interpolation is done\nkxc=KX(nx/2+1); % carrier frequency in kx domain\nKX=KX(:)*ones(1,ny);\n%\nF=zeros(nx,ny); % initialize F(kx,ky) array for interpolation\n\nfor i=1:n; % for each k loop\n i % print i to show that it is running\n icKX=round((kx(i,:)-KX(1,1))/dkx)+1; % closest grid point in KX domain\n cKX=KX(1,1)+(icKX-1)*dkx; % and its KX value\n ikx=ones(I,1)*icKX+[-is:is]'*ones(1,ny);\n ikx=ikx+nx*ones(I,1)*[0:ny-1];\n nKX=KX(ikx);\n SINC=sinc((nKX-ones(I,1)*kx(i,:))/dkx); % interpolating sinc\n HAM=.54+.46*cos((pi/kxs)*(nKX-ones(I,1)*kx(i,:))); % Hamming window\n %%%%% Sinc Convolution (interpolation) follows %%%%%%%%\n F(ikx)=F(ikx)+(ones(I,1)*fsm(i,:)).*(SINC.*HAM);\nend\n%\n% DISPLAY interpolated spatial frequency domain image F(kx,ky)\n\nKX=KX(:,1).';\nKY=ky(1,:);\n\nG=abs(F)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage(KX,KY+kus(1),256-cg*(G-ng));\naxis image; axis xy\nxlabel('Spatial Frequency k_x, rad/m')\nylabel('Spatial Frequency k_y, rad/m')\ntitle('Wavefront Spotlight SAR Reconstruction Spectrum')\nprint P5.8.ps\npause(1)\n\n%\nf=iftx(ifty(F)); % Inverse 2D FFT for spatial domain image f(x,y)\n%\ndx=pi2/(nx*dkx); % range sample spacing in reconstructed image\nx=dx*(-nx/2:nx/2-1); % range array\n%\n% Display SAR reconstructed image\n\nG=abs(f)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage(Xc+x,Yc+y,256-cg*(G-ng));axis([Xc-X0 Xc+X0 Yc-Y0 Yc+Y0]);\naxis image; axis xy\nxlabel('Range X, meters')\nylabel('Cross-range Y, meters')\ntitle('Wavefront Spotlight SAR Reconstruction')\nprint P5.9.ps\npause(1)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% SAR Image Compression (for Spotlight System) %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%\nFc=ftx(fty(f.* ...\n exp(cj*kxc*x(:)*ones(1,ny)+cj*ones(nx,1)*2*kc*sin(theta_c)*y ...\n -cj*2*kc*sqrt(((Xc+x(:)).^2)*ones(1,ny)+ones(nx,1)*((Yc+y).^2)))));\nG=abs(Fc)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage(KX,KY+kus(1),256-cg*(G-ng));\naxis image; axis xy\nxlabel('Spatial Frequency k_x, rad/m')\nylabel('Spatial Frequency k_y, rad/m')\ntitle('Compressed Spotlight SAR Reconstruction Spectrum')\nprint P5.10.ps\npause(1)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% RANGE STACK WAVEFRONT RECONSTRUCTION %%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\nf_stack=zeros(nx,ny); % Initialize reconstruction array in (x,y) domain\nfor i=1:nx; i % Stack's loop for reconstruction at each range\n f_stack(i,:)=ifty(sum(fs.*exp(cj*kx*(Xc+x(i))+cj*ky*Yc ...\n +cj*.25*pi-cj*2*k(:)*ones(1,ny)*Rc)));\nend;\n\n% Remove carrier in range domain\nf_stack=f_stack.*exp(-cj*x(:)*kxc*ones(1,ny));\n%\nf_stack=f_stack/nx; % Scale it for comparison with Fourier interpolation\n % Use \"f_stack-f\" to display difference of two\n % reconstructions\n \nG=abs(f_stack)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage(Xc+x,Yc+y,256-cg*(G-ng));axis([Xc-X0 Xc+X0 Yc-Y0 Yc+Y0]);\naxis image; axis xy\nxlabel('Range X, meters')\nylabel('Cross-range Y, meters')\ntitle('Range Stack Spotlight SAR Reconstruction')\nprint P5.11.ps\npause(1)\n \nF_stack=ftx(fty(f_stack)); % Reconstruction array in spatial frequency\n % domain; Use \"F_stack-F\" to display\n % difference of two reconstructions\n%\nG=abs(F_stack)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage(KX,KY+kus(1),256-cg*(G-ng));\naxis image; axis xy\nxlabel('Spatial Frequency k_x, rad/m')\nylabel('Spatial Frequency k_y, rad/m')\ntitle('Range Stack Spotlight SAR Reconstruction Spectrum')\nprint P5.12.ps\npause(1)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% TIME DOMAIN CORRELATION RECONSTRUCTION %%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\nf_tdc=zeros(nx,ny); % Initialize reconstruction array in (x,y) domain\n\nfor i=1:nx; i\n for j=1:ny;\n t_ij=(2*sqrt((x(i)+Xc)^2+(y(j)+Yc-u).^2))/c;\n f_tdc(i,j)=sum(sum(s_ds.*exp(cj*w(:)*(t_ij-tm(n/2+1))).* ...\n (ones(n,1)*(t_ij >= Ts & t_ij <= Tf))));\n end;\nend;\n\n% Remove carrier in range domain\nf_tdc=f_tdc.*exp(-cj*x(:)*kxc*ones(1,ny));\n%\n\n% Remove carrier in cross-range domain (squint mode)\nf_tdc=f_tdc.*exp(-cj*ones(nx,1)*2*kc*sin(theta_c)*y);\n \nG=abs(f_tdc)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage(Xc+x,Yc+y,256-cg*(G-ng));axis([Xc-X0 Xc+X0 Yc-Y0 Yc+Y0]);\naxis image; axis xy\nxlabel('Range X, meters')\nylabel('Cross-range Y, meters')\ntitle('TDC Spotlight SAR Reconstruction')\nprint P5.13.ps\npause(1)\n \nF_tdc=ftx(fty(f_tdc)); % Reconstruction array in spatial frequency\n%\nG=abs(F_tdc)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage(KX,KY+kus(1),256-cg*(G-ng));\naxis image; axis xy\nxlabel('Spatial Frequency k_x, rad/m')\nylabel('Spatial Frequency k_y, rad/m')\ntitle('TDC Spotlight SAR Reconstruction Spectrum')\nprint P5.14.ps\npause(1)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% BACKPROJECTION RECONSTRUCTION %%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\nf_back=zeros(nx,ny); % Initialize reconstruction array in (x,y) domain\nn_ratio=100; % Upsampling ratio in fast-time domain\nnu=n_ratio*n; % Size of upsampled s(t,u) array in t domain\nnz=nu-n; % Number of zeros\ndtu=(n/nu)*dt; % Fast-time sample spacing of upsampled array\ntu=dtu*(-nu/2:nu/2-1); % Upsampled reference fast-time array\nX=x(:)*ones(1,ny);\nY=ones(nx,1)*y;\n\nfor j=1:m; j\n t_ij=(2*sqrt((X+Xc).^2+(Y+Yc-u(j)).^2))/c;\n t_ij=round((t_ij-tm(n/2+1))/dtu)+nu/2+1;\n it_ij=(t_ij > 0 & t_ij <= nu);\n t_ij=t_ij.*it_ij+nu*(1-it_ij);\n S=ifty([zeros(1,nz/2),s_ds(:,j).',zeros(1,nz/2)])...\n .*exp(cj*wc*tu);\n S(nu)=0;\n f_back=f_back+S(t_ij);\nend;\n\nclear X Y\n\n% Remove carrier in range domain\nf_back=f_back.*exp(-cj*x(:)*kxc*ones(1,ny));\n%\n\n% Remove carrier in cross-range domain (squint mode)\nf_back=f_back.*exp(-cj*ones(nx,1)*2*kc*sin(theta_c)*y);\n \nG=abs(f_back)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage(Xc+x,Yc+y,256-cg*(G-ng));axis([Xc-X0 Xc+X0 Yc-Y0 Yc+Y0]);\naxis image; axis xy\nxlabel('Range X, meters')\nylabel('Cross-range Y, meters')\ntitle('Backprojection Spotlight SAR Reconstruction')\nprint P5.15.ps\npause(1)\n \nF_back=ftx(fty(f_back)); % Reconstruction array in spatial frequency\n%\nG=abs(F_back)';\nxg=max(max(G)); ng=min(min(G)); cg=255/(xg-ng);\nimage(KX,KY+kus(1),256-cg*(G-ng));\naxis image; axis xy\nxlabel('Spatial Frequency k_x, rad/m')\nylabel('Spatial Frequency k_y, rad/m')\ntitle('Backprojection Spotlight SAR Reconstruction Spectrum')\nprint P5.16.ps\npause(1)\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/2188-synthetic-aperture-radar-signal-processing-with-matlab-algorithms/soumekh/spotlight.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5954328488713935}} {"text": "function [L_t, S_t, iters, frob_err] = ncrpca(M, true_r, EPS, MAX_ITER, EPS_S, incoh, TOL)\n\n% This matlab code implements Non-convex Robust PCA (NcRPCA)\n% Input:\n% M = given low rank+sparse matrix to be decomposed\n% true_r = maximum rank of the low rank rank component\n% EPS (optional) = convergence threshold for ||M-(L_t+S_t)||_F; default is 1e-3\n% MAX_ITER (optional) = maximum iterations for NcRPCA; default is 51\n% EPS_S (optional) = threshold for removing small entries in the sparse component; default is 1e-3\n% incoh (optional) = incoherence of the low rank component; default is 1\n% TOL (optional) = tolerance for relative error in ||M-(L_t+S_t)||_F in consecutive iterations; default is 1e-1\n% Output:\n% M_t = thresholded M at each iteration\n% L_t = rank-k approximation of M_t\n% S_t = sparse component, computed as M-M_t\n% iters = number of iteration of NcRPCA\n% frob_err = ||M-(L_t+S_t)||_F at each iteration\n\nif nargin < 7, TOL = 1e-1; end\nif nargin < 6, incoh = 1; end\nif nargin < 5, EPS_S = 1e-3; end\nif nargin < 4, MAX_ITER = 51; end\nif nargin < 3, EPS = 1e-3; end\n\n%addpath code_ncrpca/PROPACK;\n%addpath PROPACK;\nfrob_err(1) = inf;\n[~, n] = size(M);\nt = 1;\nidx = [];\nthresh_const = incoh; % threshold constant: can be tuned depending on incoherence\nthresh_red = 0.9; % parameter to reduce the threshold constant: can be tuned\nr_hat = 1; % initial rank for stagewise algorithm\nL_t = zeros(size(M));\nSig_t = lansvd(M,1,'L');\nD_t = M-L_t;\nthresh = thresh_const*Sig_t/sqrt(n);\nidx = unique([find(abs(D_t) > thresh); idx]);\nS_t = zeros(size(M));\nS_t(idx) = D_t(idx); % initial thresholding\nif max(idx(:))==0\n idx = [];\nend\nwhile frob_err(t)/norm(M, 'fro')>=EPS && t thresh); idx]);\n S_t(idx) = D_t(idx);\n frob_err(t) = norm(M-(L_t+S_t), 'fro');\n if ((frob_err(t-1)-frob_err(t))/frob_err(t-1) <= TOL) && r_hat= 0) & (ib < nb);\n\tgood = good(:);\n\tval = square_strip_int(dr * (ib - tau), ...\n\t\trepmat(angle, 1, np), 'dx', dx, 'sw', strip_width);\n\tval = val(:);\n\tii = col(ib + repmat([0:na-1]'*nb, 1, np)); % sinogram index\n\tlist.ii = [list.ii; 1+ii(good)];\n\tlist.jj = [list.jj; jj(good)];\n\tlist.ss = [list.ss; val(good)];\nend\nif is_single\n\tlist.ss = double(single(list.ss)); % stupid matlab insists on double\nend\nG = sparse(list.ii, list.jj, list.ss, nb*na, nx*ny, length(list.ss));\n\n\n%\n% = Gtomo2_strip_fan()\n%\nfunction G = Gtomo2_strip_fan(nb, na, ds, offset_s, ...\n\tbeta, strip_width, ...\n\tgam_max, ... % maximum angle gamma accepted by detector [radians]\n\tdsd, dso, dfs, roff, ...\n\tnx, ny, dx, dy, offset_x, offset_y, mask, is_single, chat);\n\n% pixel centers\nwx = (nx-1)/2 + offset_x;\nwy = (ny-1)/2 + offset_y;\nwb = (nb-1)/2 + offset_s;\n\nx = dx * ([0:nx-1] - wx);\ny = dy * ([0:ny-1] - wy); % caution, may not match aspire if offset_y != 0\n[x y] = ndgrid(x, y);\nx = x(mask(:)); % [np,1]\ny = y(mask(:));\nnp = length(x); % sum(mask(:)) - total # of support pixels\nna = length(beta);\n\ncbet = cos(beta);\nsbet = sin(beta);\n\n% s0 is \"s\" value for center of each pixel\ngam0 = atan2(cbet * x' + sbet * y' - roff, ...\n\tdso + sbet * x' - cbet * y'); % [na,np]\nclear cbet sbet\nif dfs == 0 % 3rd gen (arc)\n\ts0 = dsd * gam0;\nelseif isinf(dfs)\n\ts0 = dsd * tan(gam0);\nelse\n\terror 'unsupported dfs'\nend\n\nang0 = repmat(beta, [1 np]) + gam0;\nmag0 = dso * cos(gam0) - roff * sin(gam0) ...\n\t+ repmat(x', [na 1]) .* sin(ang0) - repmat(y', [na 1]) .* cos(ang0);\ngamgood = abs(gam0) < gam_max;\nif chat, printm('gam0: %g %g', rad2deg(minmax(gam0(gamgood)))), end\nclear gam0\nif dfs == 0 % 3rd gen (arc)\n\tmag0 = mag0 / dsd; \nelseif isinf(dfs)\n\tmag0 = mag0 / dsd ./ (1 + (s0 ./ dsd).^2);\nelse\n\terror 'dfs bug'\nend\nmag0min = min(mag0(gamgood));\nif isempty(mag0min)\n\tG = sparse([], [], [], nb*na, nx*ny, 0);\n\treturn\nend\n\ntau = s0 / ds + wb; % [na,np], unitless\n\nM = ceil((dx/mag0min * sqrt(2) + strip_width) / ds); % conservative!\nif chat, printm('M=%d, mag0min=%g', M, mag0min), end\nif M > 100\n\tprintm('Warn: M=%d too large? probably x-ray source is too oblique', M)\n\tprintm('type \"return\" and hope for the best, but it may be *slow*')\n\tprintm('recommend using \"gam_max\" to impose incidence angle constraint')\n\tkeyboard\nend\n\nib_min = 1 + floor(tau - M/2);\njj = find(mask(:))';\t% all-column G\njj = repmat(jj, na, 1); % [na,np]\njj = col(jj); % so that na=1 case works\nlist.ii = [];\nlist.jj = [];\nlist.ss = [];\nfor mm=0:M-1\n\tticker(mfilename, mm+1, M)\n\tib = ib_min + mm;\n\tval = mag0 .* square_strip_int(ds * (ib - tau), ...\n\t\tang0, 'dx', dx ./ mag0, ...\n\t\t'sw', strip_width);\n\tval = val(:); % for na=1 case\n%\tval = square_strip_int(ds * (ib - tau) .* mag0, ...\n%\t\tang0, 'dx', dx, 'sw', strip_width .* mag0); % same!\n\tii = col(ib + repmat([0:na-1]'*nb, 1, np)); % sinogram index\n%\tif chat, printm('%d of %d zeros', sum(val(:)==0), length(val(:))), end\n\tgood = (ib >= 0) & (ib < nb);\n\tgood = good & gamgood;\n\tgood = good(:);\n\tgood = good & (val > 0); % remove extra zeros due to conservative M\n\tlist.ii = [list.ii; 1+ii(good)];\n\tlist.jj = [list.jj; jj(good)];\n\tlist.ss = [list.ss; val(good)];\nend\nif is_single\n\tlist.ss = double(single(list.ss)); % stupid matlab insists on double\nend\nG = sparse(list.ii, list.jj, list.ss, nb*na, nx*ny, length(list.ss));\n\n\n%\n% test demo\n%\nfunction Gtomo2_strip_test\nig = image_geom('nx', 512, 'ny', 480', 'fov', 500, 'down', 8);\nig.mask = ig.circ > 0;\n% todo: 3 cases to test: parallel, arc-fan, flat-fan\nsg = sino_geom('par', 'nb', 600, 'na', 480, 'dr', 1.2, 'down', ig.down);\n% sg = sino_geom('fan', 'nb', 888, 'na', 984, 'ds', 1.0, 'down', ig.down, ...\n% \t'offset_s', 0*0.25, 'source_offset', 0*3.0, ...\n% \t'dsd', 949, 'dod', 408, 'dfs', 0);\n\nell = [20 50 150 150 0 1];\nell = [];\n[x ell] = ellipse_im(ig, ell, 'oversample', 2);\nya = ellipse_sino(sg, ell, 'oversample', 4);\n\nG = Gtomo2_strip(sg, ig, 'chat', 0);\n\nyd = G * x;\nsino = sg.zeros; sino(sg.nb/2, 10) = 1;\nb1 = G' * sino;\nbu = G' * sg.ones;\nmax_percent_diff(min(bu(ig.mask)), max(bu(ig.mask)), 'backproject ones')\n\nif im\n\tclf, im pl 2 2\n\tim(1, x, 'test image')\n\tim(2, ya, 'sinogram ya'), cbar\n\tim(4, yd, 'sinogram yd'), cbar\n\tim(3, yd-ya, 'yd-ya'), cbar\n\tif 0\n\t\tim(1, ig.mask, 'support mask')\n\t\tim(2, b1, 'backproject 1 ray'), cbar\n\t\tim(3, bu, 'backproject ones'), cbar\n\tend\nend\n\n% verify consistency with Gtomo2_wtmex (aspire)\nif 1 & has_aspire %& streq(sg.type, 'par')\nprompt\n\tGw = Gtomo2_wtmex(sg, ig, 'pairs', {'strip_width', sg.d});\n\tyw = Gw * x;\n\tys = G * x;\n\tmax_percent_diff(yw, ys, 'sino Gtomo2_wtmex vs Gtomo2_strip')\n\tif im\n\t\tim pl 2 3, im(1, x), cbar\n\t\tim(1, ya, 'ya'), cbar\n\t\tim(2, ys, 'ys'), cbar\n\t\tim(3, yw, 'yw'), cbar\n\t\tim(4, ys-yw, 'ys-yw'), cbar\n\t\txlabelf('%g%%', 100*nrms(ys(:), yw(:)))\n\t\tim(5, ys-ya, 'ys-ya'), cbar\n\t\txlabelf('%g%%', 100*nrms(ys(:), ya(:)))\n\t\tim(6, yw-ya, 'yw-ya'), cbar\n\t\txlabelf('%g%%', 100*nrms(yw(:), ya(:)))\n\tend\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/contrib/sse_proj/irt/systems/Gtomo2_strip_sse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.6757646140788308, "lm_q1q2_score": 0.5952115017104916}} {"text": "function [h, compUpAP, compUp] = lfmComputeH3AP(gamma1_p, gamma1_m, sigma2, t1, ...\n t2, preFactor, mode)\n\n% LFMCOMPUTEH3AP Helper function for computing part of the LFMAP kernel.\n% FORMAT\n% DESC computes a portion of the LFMAP kernel.\n% ARG gamma1 : Gamma value for first system.\n% ARG gamma2 : Gamma value for second system.\n% ARG sigma2 : length scale of latent process.\n% ARG t1 : first time input (number of time points x 1).\n% ARG t2 : second time input (number of time points x 1).\n% ARG preFactor : precomputed constants.\n% ARG mode: indicates the correct derivative.\n% RETURN h : result of this subcomponent of the kernel for the given values.\n%\n% COPYRIGHT : Mauricio Alvarez, 2010\n\n% KERN\n\n% Evaluation of h\n\nif nargout>1 \n [compUpAP{1}, compUp{1}] = lfmapComputeUpsilonMatrix(gamma1_p,sigma2, t1,t2, mode);\n [compUpAP{2}, compUp{2}] = lfmapComputeUpsilonMatrix(gamma1_m,sigma2, t1,t2, mode);\n h = preFactor(1)*compUpAP{1} + preFactor(2)*compUpAP{2};\nelse\n h = preFactor(1)*lfmapComputeUpsilonMatrix(gamma1_p,sigma2, t1,t2, mode) ...\n + preFactor(2)*lfmapComputeUpsilonMatrix(gamma1_m,sigma2, t1,t2, mode);\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/lfmComputeH3AP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5952114859784666}} {"text": "%% Misorientation Distribution Function\n%\n%% TODO: Please help to extend this section\n% Let us consider the uncorrelated missorientation ODF corresponding to our\n% model ODF.\n\n\nmtexdata titanium\n\nodf = calcDensity(ebsd.orientations)\n\n%%\n\n\n% the uncorrelated \nmdf = calcMDF(odf)\n\n%%\n\nplotSection(mdf,'axisAngle')\n\n\n%% Axis / Angle Distribution\n% Then we can plot the distribution of the rotation axes of this\n% missorientation ODF\n\nplotAxisDistribution(mdf)\n\n%%\n% and the distribution of the missorientation angles and compare them to a\n% uniform ODF\n\nclose all\nplotAngleDistribution(mdf)\nhold all\nplotAngleDistribution(ebsd.CS,ebsd.CS)\nhold off\nlegend('model ODF','uniform ODF')\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/Misorientations/MisorientationDistributionFunction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.5951741527927086}} {"text": "function [X,Y,vals,labI]=mp_conic(optn,varargin)\n% MP_CONIC Conic projections\n% This function should not be used directly; instead it is\n% is accessed by various high-level functions named M_*.\n\n% Rich Pawlowicz (rich@ocgy.ubc.ca) 2/Apr/1997\n%\n% This software is provided \"as is\" without warranty of any kind. But\n% it's mine, so you can't sell it.\n%\n% Mathematical formulas for the projections and their inverses are taken from\n%\n% Snyder, John P., Map Projections used by the US Geological Survey, \n% Geol. Surv. Bull. 1532, 2nd Edition, USGPO, Washington D.C., 1983.\n%\n% These are conic projections with two standard parallels, useful\n% for showing limited areas at mid-latitudes.\n% Albers equal-area - has an equal-area property\n% Lambert conformal - is conformal\n%\n% 7/6/99 - fixed tendency to re-define .ulongs if .clong set by user\n% 3/4/02 - added error if parallels are equidistant from equator (i.e. not conic projection really)\n% 24/10/08 - added ellipsoidal earth computations for lambert conformal conic projection\n% 16/10/09 - added ellipsoidal earth computations for albers conic projection\n% 06/03/17 - changed 'false_origin' to 'origin' as option name, also it\n% didn't work correctly with the 'normal' spheroid so this was\n% fixed, AND changed the default parallels so they were at 25%\n% and 75% limits instead of being a single parallel at the\n% center to prevent blowups with the albers ellipsoidal\n% projection AND made it work with SPHERE ellipsoid.\n\nglobal MAP_PROJECTION MAP_VAR_LIST\n\nMAP_ELLIP=mc_ellips;\n\nname={'Albers Equal-Area Conic','Lambert Conformal Conic'};\n\npi180=pi/180;\n\nswitch optn\n\n case 'name'\n\n X=name;\n\n case {'usage','set'}\n\n m_names=fieldnames(MAP_ELLIP);\n\n X=char({[' ''' varargin{1} ''''],...\n ' <,''lon'',[min max]>',...\n ' <,''lat'',[min max]>',...\n ' <,''clo'',value>',...\n ' <,''par'',[lat1 lat2]>',...\n ' <,''rec'', ( ''on'' | ''off'' )>',...\n ' <,''ell'', one of',...\n reshape(sprintf(' %6s',m_names{:}),15,length(m_names))',...\n ' >',...\n\t ' <,''ori'', [long lat]>'});\n\n case 'get'\n\n X=char([' Projection: ' MAP_PROJECTION.name ' (function: ' MAP_PROJECTION.routine ')'],...\n [' longitudes: ' num2str(MAP_VAR_LIST.ulongs) ' (centered at ' num2str(MAP_VAR_LIST.clong) ')'],...\n [' latitudes: ' num2str(MAP_VAR_LIST.ulats) ],...\n [' standard parallels: ' num2str(MAP_VAR_LIST.parallels) ],...\n [' Rectangular border: ' MAP_VAR_LIST.rectbox ],...\n [' ellipsoid: ' MAP_VAR_LIST.ellipsoid ],...\n [' origin: ' num2str(MAP_VAR_LIST.origin) ]);\n\n case 'initialize'\n\n MAP_VAR_LIST=[];\n MAP_PROJECTION.name=varargin{1};\n MAP_VAR_LIST.ulongs=[-180 -50];\n MAP_VAR_LIST.ulats=[10 85];\n MAP_VAR_LIST.parallels=NaN;\n MAP_VAR_LIST.clong=NaN;\n MAP_VAR_LIST.origin=NaN;\n MAP_VAR_LIST.rectbox='off';\n MAP_VAR_LIST.ellipsoid = 'normal';\n MAP_VAR_LIST.aussiemode=false;\n k=2;longs_def=0;\n while kMAP_VAR_LIST.ulongs(2)\n MAP_VAR_LIST.ulongs=MAP_VAR_LIST.ulongs([2 1]);\n end\n case 'clo'\n MAP_VAR_LIST.clong=varargin{k+1};\n case 'lat'\n MAP_VAR_LIST.ulats=varargin{k+1}(:)';\n case 'par'\n MAP_VAR_LIST.parallels=varargin{k+1};\n case 'rec'\n switch lower(varargin{k+1}(1:2))\n case {'on','bo'}\n MAP_VAR_LIST.rectbox='on';\n case 'of'\n MAP_VAR_LIST.rectbox='on';\n otherwise\n error(['m_proj: Unrecognized box option: ' varargin{k+1}]);\n end\n case 'ell'\n MAP_VAR_LIST.ellipsoid=varargin{k+1};\n case 'ori'\n MAP_VAR_LIST.origin=varargin{k+1};\n case 'fal'\n error(' FALSE_ORIGIN option has been renamed to ORIGIN - Change your m_proj call! ');\n\t case 'aus' % aussiemode - my joke\n\t if strcmp(varargin{k+1},'on')\n\t MAP_VAR_LIST.aussiemode=true;\n\t end \n otherwise\n disp(['Unknown option: ' varargin{k}]);\n end\n k=k+2;\n end\n if isnan(MAP_VAR_LIST.clong)\n if isnan(MAP_VAR_LIST.origin)\n MAP_VAR_LIST.clong=mean(MAP_VAR_LIST.ulongs); \n else\n MAP_VAR_LIST.clong=MAP_VAR_LIST.origin(1);\n end \t \n elseif ~longs_def\n MAP_VAR_LIST.ulongs=MAP_VAR_LIST.clong+[-180 180]; \n end\n if isnan(MAP_VAR_LIST.parallels), MAP_VAR_LIST.parallels=mean(MAP_VAR_LIST.ulats)*[1 1]+diff(MAP_VAR_LIST.ulats)*[-1/6 1/6]; end % change default mar/2017\n if isnan(MAP_VAR_LIST.origin), MAP_VAR_LIST.origin=[MAP_VAR_LIST.clong mean(MAP_VAR_LIST.parallels)]; end\n\n MAP_VAR_LIST.rlongs=MAP_VAR_LIST.ulongs*pi180;\n MAP_VAR_LIST.rlats=MAP_VAR_LIST.ulats*pi180;\n MAP_VAR_LIST.rparallels=MAP_VAR_LIST.parallels*pi180;\n MAP_VAR_LIST.rorigin=MAP_VAR_LIST.origin*pi180;\n\n MAP_VAR_LIST.ellip=getfield(MAP_ELLIP,MAP_VAR_LIST.ellipsoid);\n \n % These are constants used by the projection formulas\n\n switch MAP_PROJECTION.name\n case name(1)\n if MAP_VAR_LIST.ellip(2)==0 % spherical\n MAP_VAR_LIST.n=sum(sin(MAP_VAR_LIST.rparallels))/2;\n if MAP_VAR_LIST.n==0\n error('Your parallels are equidistant from the equator - use a cylindrical projection!'); \n end\n MAP_VAR_LIST.C=cos(MAP_VAR_LIST.rparallels(1)).^2+2*MAP_VAR_LIST.n*sin(MAP_VAR_LIST.rparallels(1));\n MAP_VAR_LIST.rho0=MAP_VAR_LIST.ellip(1)*sqrt(MAP_VAR_LIST.C-2*MAP_VAR_LIST.n*sin( MAP_VAR_LIST.rorigin(2) ))/MAP_VAR_LIST.n;\n else\n \t e=sqrt(2*MAP_VAR_LIST.ellip(2)-MAP_VAR_LIST.ellip(2)^2);\n\t m12=cos(MAP_VAR_LIST.rparallels)./sqrt(1-(e.*sin(MAP_VAR_LIST.rparallels)).^2);\n\t q12=(1-e.^2)*(sin(MAP_VAR_LIST.rparallels)./(1-(e.*sin(MAP_VAR_LIST.rparallels)).^2) - ...\n\t 1./(2*e)*log((1-e.*sin(MAP_VAR_LIST.rparallels))./(1+e.*sin(MAP_VAR_LIST.rparallels))) );\n\t q0= (1-e.^2)*(sin(MAP_VAR_LIST.rorigin(2))./(1-(e.*sin(MAP_VAR_LIST.rorigin(2))).^2) - ...\n\t 1./(2*e)*log((1-e.*sin(MAP_VAR_LIST.rorigin(2)))./(1+e.*sin(MAP_VAR_LIST.rorigin(2)))) );\n if diff( MAP_VAR_LIST.rparallels )==0\n\t MAP_VAR_LIST.n=sin(MAP_VAR_LIST.rparallels(1));\n else\n\t MAP_VAR_LIST.n=-diff(m12.^2)/diff(q12);\n end\n\t MAP_VAR_LIST.C=m12(1).^2 + MAP_VAR_LIST.n.*q12(1);\n\t MAP_VAR_LIST.rho0=MAP_VAR_LIST.ellip(1)*sqrt(MAP_VAR_LIST.C-MAP_VAR_LIST.n*q0)/MAP_VAR_LIST.n;\t\n end\n case name(2)\n if strcmp(MAP_VAR_LIST.ellipsoid,'normal')\n if diff(MAP_VAR_LIST.parallels)==0\n MAP_VAR_LIST.n=sin(MAP_VAR_LIST.rparallels(1));\n else\n MAP_VAR_LIST.n=-diff(log(cos(MAP_VAR_LIST.rparallels)))/diff(log(tan(MAP_VAR_LIST.rparallels/2+pi/4)));\n end\n MAP_VAR_LIST.F=cos(MAP_VAR_LIST.rparallels(1))/MAP_VAR_LIST.n* ...\n \t tan(pi/4+MAP_VAR_LIST.rparallels(1)/2).^MAP_VAR_LIST.n;\n MAP_VAR_LIST.rho0=MAP_VAR_LIST.F/tan(pi/4+ MAP_VAR_LIST.rorigin(2)/2).^MAP_VAR_LIST.n;\n else\n \t e=sqrt(2*MAP_VAR_LIST.ellip(2)-MAP_VAR_LIST.ellip(2)^2);\n\t m12=cos(MAP_VAR_LIST.rparallels)./sqrt(1-(e.*sin(MAP_VAR_LIST.rparallels)).^2);\n\t t12=tan(pi/4-MAP_VAR_LIST.rparallels/2)./( (1-e*sin(MAP_VAR_LIST.rparallels))./(1+e*sin(MAP_VAR_LIST.rparallels)) ).^(e/2);\n\t tF=tan(pi/4-MAP_VAR_LIST.rorigin(2)/2)./( (1-e*sin(MAP_VAR_LIST.rorigin(2)))./(1+e*sin(MAP_VAR_LIST.rorigin(2))) ).^(e/2);\n\t if diff(MAP_VAR_LIST.rparallels)==0\n\t MAP_VAR_LIST.n=sin(MAP_VAR_LIST.rparallels(1));\n else \n MAP_VAR_LIST.n=diff(log(m12))/diff(log(t12));\n end \n\t MAP_VAR_LIST.F=m12(1)/MAP_VAR_LIST.n/t12(1).^MAP_VAR_LIST.n;\n\t MAP_VAR_LIST.rho0=MAP_VAR_LIST.ellip(1)*MAP_VAR_LIST.F*tF.^MAP_VAR_LIST.n;\n end \n end\n\n % check for a valid ellipsoid. if not, use the normalized sphere\n \n if ~isfield(MAP_ELLIP,MAP_VAR_LIST.ellipsoid)\n MAP_VAR_LIST.ellipsoid = 'normal';\n end\n\n % Get X/Y and (if we are in a box) update the lat/long limits.\n\n mu_util('xylimits');\n if strcmp(MAP_VAR_LIST.rectbox,'on'), mu_util('lllimits'); end\n\n\n case 'll2xy'\n\n long=varargin{1};\n lat=varargin{2};\n vals=zeros(size(long));\n \n % Clip out-of-range values (lat/long box)\n \n if ~strcmp(MAP_VAR_LIST.rectbox,'on') && ~strcmp(varargin{4},'off')\n vals=vals | long<=MAP_VAR_LIST.longs(1)+eps*10 | long>=MAP_VAR_LIST.longs(2)-eps*10 | ...\n\t lat<=MAP_VAR_LIST.lats(1)+eps*10 | lat>=MAP_VAR_LIST.lats(2)-eps*10;\n [long,lat]=mu_util('clip',varargin{4},long,MAP_VAR_LIST.longs(1),longMAP_VAR_LIST.longs(2),lat);\n [lat,long]=mu_util('clip',varargin{4},lat,MAP_VAR_LIST.lats(1),latMAP_VAR_LIST.lats(2),long);\n end\n\n switch MAP_PROJECTION.name\n case name(1) \n if MAP_VAR_LIST.ellip(2)==0 % spherical\n rho=MAP_VAR_LIST.ellip(1)*sqrt(MAP_VAR_LIST.C-2*MAP_VAR_LIST.n*sin(lat*pi180))/MAP_VAR_LIST.n;\n else\n\t e=sqrt(2*MAP_VAR_LIST.ellip(2)-MAP_VAR_LIST.ellip(2)^2);\n\t q= (1-e.^2)*(sin(lat*pi180)./(1-(e.*sin(lat*pi180)).^2) - ...\n\t 1./(2*e)*log((1-e.*sin(lat*pi180))./(1+e.*sin(lat*pi180))) );\n\t rho=MAP_VAR_LIST.ellip(1)*sqrt(MAP_VAR_LIST.C-MAP_VAR_LIST.n*q)/MAP_VAR_LIST.n;\n end \n case name(2)\n if strcmp(MAP_VAR_LIST.ellipsoid,'normal')\n lat(lat==-90)=-89.999; % Prevents /0 problems in next line\n rho=MAP_VAR_LIST.F ./ tan(pi/4+lat*pi180/2).^MAP_VAR_LIST.n;\n else\n\t e=sqrt(2*MAP_VAR_LIST.ellip(2)-MAP_VAR_LIST.ellip(2)^2);\n\t t=tan(pi/4-lat*pi180/2)./( (1-e*sin(lat*pi180))./(1+e*sin(lat*pi180)) ).^(e/2);\n\t rho=MAP_VAR_LIST.ellip(1)*MAP_VAR_LIST.F*t.^MAP_VAR_LIST.n;\n end \n end\n theta=MAP_VAR_LIST.n*(long-MAP_VAR_LIST.origin(1))*pi180;\n\n X=real(rho.*sin(theta)); \n Y=real(MAP_VAR_LIST.rho0-rho.*cos(theta));\n\n % Clip out-of-range values (rectangular box)\n\n if strcmp(MAP_VAR_LIST.rectbox,'on') && ~strcmp(varargin{4},'off')\n vals= vals | X<=MAP_VAR_LIST.xlims(1)+eps*10 | X>=MAP_VAR_LIST.xlims(2)-eps*10 | ...\n Y<=MAP_VAR_LIST.ylims(1)+eps*10 | Y>=MAP_VAR_LIST.ylims(2)-eps*10;\n [X,Y]=mu_util('clip',varargin{4},X,MAP_VAR_LIST.xlims(1),XMAP_VAR_LIST.xlims(2),Y);\n [Y,X]=mu_util('clip',varargin{4},Y,MAP_VAR_LIST.ylims(1),YMAP_VAR_LIST.ylims(2),X);\n end\n if MAP_VAR_LIST.aussiemode, Y=-Y; X=-X; end\n\n\n case 'xy2ll'\n\n pi180=pi/180; \n \n if MAP_VAR_LIST.aussiemode, varargin{2}=-varargin{2}; varargin{1}=-varargin{1}; end\n switch MAP_PROJECTION.name\n case name(1) \n rho=sqrt(varargin{1}.^2+(MAP_VAR_LIST.rho0-varargin{2}).^2);\n theta=atan(varargin{1}./(MAP_VAR_LIST.rho0-varargin{2}));\n if MAP_VAR_LIST.ellip(2)==0\n Y=asin((MAP_VAR_LIST.C-(rho*MAP_VAR_LIST.n/MAP_VAR_LIST.ellip(1)).^2)/(2*MAP_VAR_LIST.n))/pi180;\n else\n\t e=sqrt(2*MAP_VAR_LIST.ellip(2)-MAP_VAR_LIST.ellip(2)^2);\n q=(MAP_VAR_LIST.C - (rho.*MAP_VAR_LIST.n/MAP_VAR_LIST.ellip(1)).^2)./MAP_VAR_LIST.n;\t \n\t % Y is computed iteratively\n\t Y=asin(q/2);\n\t for k=1:4\n\t Y=Y+(1-(e.*sin(Y)).^2).^2./(2*cos(Y)).*( q./(1-e.^2) - sin(Y)./(1-(e.*sin(Y)).^2) + ...\n\t 1./(2*e)*log( (1-e*sin(Y))./(1+e*sin(Y)) ) );\n end\n\t Y=Y/pi180; \n end\n % The pole is an arc in this projection, so for points inside that\n % arc there is no inverse. If so, the math above can return complex\n % values - instead set these to NaN\n if ~isreal(Y)\n Y(imag(Y)>1e-7)=NaN;\n Y=real(Y); \n end\n \n case name(2)\n rho=sign(MAP_VAR_LIST.n)*sqrt(varargin{1}.^2+(MAP_VAR_LIST.rho0-varargin{2}).^2);\n theta=atan(varargin{1}./(MAP_VAR_LIST.rho0-varargin{2}));\n\t if strcmp(MAP_VAR_LIST.ellipsoid,'normal')\n Y=(2*atan((MAP_VAR_LIST.F./rho).^(1/MAP_VAR_LIST.n))-pi/2)/pi180;\n else\n\t e=sqrt(2*MAP_VAR_LIST.ellip(2)-MAP_VAR_LIST.ellip(2)^2);\n\t tp=(rho./MAP_VAR_LIST.ellip(1)/MAP_VAR_LIST.F).^(1./MAP_VAR_LIST.n);\n\t % Y is computed iteratively\n\t Y=pi/2 - 2*atan(tp);\n\t for k=1:4\n\t Y=pi/2 - 2*atan(tp.*((1-e*sin(Y))./(1+e*sin(Y))).^(e/2) );\n end \n\t Y=Y/pi180;\n end \n end\n % Clip out-of-range values (lat/long box)\n X=MAP_VAR_LIST.origin(1)+(theta/MAP_VAR_LIST.n)/pi180;\n\n case 'xgrid'\n \n [X,Y,vals,labI]=mu_util('xgrid',MAP_VAR_LIST.longs,MAP_VAR_LIST.lats,varargin{1},3,varargin{2:3});\n\n case 'ygrid'\n \n [X,Y,vals,labI]=mu_util('ygrid',MAP_VAR_LIST.lats,MAP_VAR_LIST.longs,varargin{1},31,varargin{2:3});\n\n case 'box'\n\n [X,Y]=mu_util('box',31);\n \nend\n\n\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/thirdParty/m_map/private/mp_conic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213718636752, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.595148998205782}} {"text": "function GMST=TAI2GAST(Jul1,Jul2,version,deltaT)\n%%TAI2GAST Convert from international atomic time (TAI) to Greenwhich\n% apparent sidereal time (GAST), which is a measure of the\n% rotational direction of the Earth.\n%\n%INPUTS: Jul1,Jul2 Two parts of a pseudo-Julian date given in TAI. The\n% units of the date are days. The full date is the sum of\n% both terms. The date is broken into two parts to\n% provide more bits of precision. It does not matter how\n% the date is split.\n% version An optional integer specifying the theory to use for\n% GMST. The theory chosen should be consistent with other\n% values used in astronomical routines. Possible values\n% are\n% 1982 Compute GAST ion accordance with the International\n% Astronomical Union's (IAU's) 1982 model.\n% 2000 Compute GMST in line with IAU 2000 resolutions\n% related to precession and nutation.\n% 2006 (The default if omitted) Compute GMST in line with\n% IAU 2006 resolutions related to precession and\n% nutation.\n% deltaT An optional parameter specifying the offset between TT\n% and UT1 in seconds. If this parameter is omitted, then\n% the value of the function getEOP will be used.\n%\n%OUTPUTS: GAST The Greenwhich apparent sideral time in radians. \n%\n%The function just calls TAI2TT and then TT2GAST.\n%\n%GAST is defined in Section 5.5.7 of [1].\n%\n%REFERENCES:\n%[1] G. Petit and B. Luzum, IERS Conventions (2010), International Earth\n% Rotation and Reference Systems Service Std. 36, 2010.\n%\n%April 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n[Jul1,Jul2]=TAI2TT(Jul1,Jul2);\n\nif(nargin==2)\n GMST=TT2GAST(Jul1,Jul2);\nelseif(nargin==3)\n GMST=TT2GAST(Jul1,Jul2,version);\nelse\n GMST=TT2GAST(Jul1,Jul2,version,deltaT);\nend\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Coordinate_Systems/Time/TAI2GAST.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5951406710378421}} {"text": "function M = euclideanfactory(m, n)\n% Returns a manifold struct to optimize over m-by-n matrices.\n%\n% function M = euclideanfactory(m, n)\n%\n% Returns M, a structure describing the Euclidean space of m-by-n matrices\n% equipped with the standard Frobenius distance and associated trace inner\n% product as a manifold for Manopt.\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, Dec. 30, 2012.\n% Contributors: \n% Change log: \n% July 5, 2013 (NB): added egred2rgrad, ehess2rhess, mat, vec, tangent.\n\n \n if ~exist('n', 'var') || isempty(n)\n n = 1;\n end\n\n M.name = @() sprintf('Euclidean space R^(%dx%d)', m, n);\n \n M.dim = @() m*n;\n \n M.inner = @(x, d1, d2) d1(:).'*d2(:);\n \n M.norm = @(x, d) norm(d, 'fro');\n \n M.dist = @(x, y) norm(x-y, 'fro');\n \n M.typicaldist = @() sqrt(m*n);\n \n M.proj = @(x, d) d;\n \n M.egrad2rgrad = @(x, g) g;\n \n M.ehess2rhess = @(x, eg, eh, d) eh;\n \n M.tangent = M.proj;\n \n M.exp = @exp;\n function y = exp(x, d, t)\n if nargin == 3\n y = x + t*d;\n else\n y = x + d;\n end\n end\n \n M.retr = M.exp;\n\t\n\tM.log = @(x, y) y-x;\n\n M.hash = @(x) ['z' hashmd5(x(:))];\n \n M.rand = @() randn(m, n);\n \n M.randvec = @randvec;\n function u = randvec(x) %#ok\n u = randn(m, n);\n u = u / norm(u, 'fro');\n end\n \n M.lincomb = @lincomb;\n function v = lincomb(x, a1, d1, a2, d2) %#ok\n if nargin == 3\n v = a1*d1;\n elseif nargin == 5\n v = a1*d1 + a2*d2;\n else\n error('Bad usage of euclidean.lincomb');\n end\n end\n \n M.zerovec = @(x) zeros(m, n);\n \n M.transp = @(x1, x2, d) d;\n \n M.pairmean = @(x1, x2) .5*(x1+x2);\n \n M.vec = @(x, u_mat) u_mat(:);\n M.mat = @(x, u_vec) reshape(u_vec, [m, n]);\n M.vecmatareisometries = @() true;\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/manopt/manopt/manifolds/euclidean/euclideanfactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.5951024223104188}} {"text": "function jed = transition_to_jed_common ( )\n\n%*****************************************************************************80\n%\n%% TRANSITION_TO_JED_COMMON returns the Common calendar transition as a JED.\n%\n% Discussion:\n%\n% In the Common calendar, the last moment of the Julian calendar was\n% 11:59 pm, 4 October 1582 Julian/CE,\n% 11:59 pm, 14 October 1582 Gregorian.\n% The first minute of the Gregorian calendar ended at\n% 12:01 am, 5 October 1582 Julian,\n% 12:01 am, 15 October 1582 Gregorian/CE.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 December 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real JED, the Julian Ephemeris Date of the date.\n%\n jed = 2299160.5;\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/calpak/transition_to_jed_common.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.5951024180147967}} {"text": "function [Yl,Yh,Yscale] = dtwavexfm2(X,nlevels,biort,qshift);\n\n% Function to perform a n-level DTCWT-2D decompostion on a 2D matrix X\n%\n% [Yl,Yh,Yscale] = dtwavexfm2(X,nlevels,biort,qshift);\n%\n% X -> 2D real matrix/Image\n%\n% nlevels -> No. of levels of wavelet decomposition\n%\n% biort -> 'antonini' => Antonini 9,7 tap filters.\n% 'legall' => LeGall 5,3 tap filters.\n% 'near_sym_a' => Near-Symmetric 5,7 tap filters.\n% 'near_sym_b' => Near-Symmetric 13,19 tap filters.\n%\n% qshift -> 'qshift_06' => Quarter Sample Shift Orthogonal (Q-Shift) 10,10 tap filters, \n% (only 6,6 non-zero taps).\n% 'qshift_a' => Q-shift 10,10 tap filters,\n% (with 10,10 non-zero taps, unlike qshift_06).\n% 'qshift_b' => Q-Shift 14,14 tap filters.\n% 'qshift_c' => Q-Shift 16,16 tap filters.\n% 'qshift_d' => Q-Shift 18,18 tap filters.\n% \n%\n% Yl -> The real lowpass image from the final level\n% Yh -> A cell array containing the 6 complex highpass subimages for each level.\n% Yscale -> This is an OPTIONAL output argument, that is a cell array containing \n% real lowpass coefficients for every scale.\n%\n% \n% Example: [Yl,Yh] = dtwavexfm2(X,3,'near_sym_b','qshift_b');\n% performs a 3-level transform on the real image X using the 13,19-tap filters \n% for level 1 and the Q-shift 14-tap filters for levels >= 2.\n%\n% Nick Kingsbury and Cian Shaffrey\n% Cambridge University, Sept 2001\n\n\nif isstr(biort) & isstr(qshift)\t\t%Check if the inputs are strings\n biort_exist = exist([biort '.mat']);\n qshift_exist = exist([qshift '.mat']);\n if biort_exist == 2 & qshift_exist == 2; \t\t%Check to see if the inputs exist as .mat files\n load (biort);\n load (qshift);\n else\n error('Please enter the correct names of the Biorthogonal or Q-Shift Filters, see help DTWAVEXFM2 for details.');\n end\nelse\n error('Please enter the names of the Biorthogonal or Q-Shift Filters as shown in help DTWAVEXFM2.');\nend \n\norginal_size = size(X);\n\nif ndims(X) >= 3;\n error(sprintf('The entered image is %dx%dx%d, please enter each image slice separately.',orginal_size(1),orginal_size(2),orginal_size(3)));\nend\n\n% The next few lines of code check to see if the image is odd in size, if so an extra ...\n% row/column will be added to the bottom/right of the image\ninitial_row_extend = 0; %initialise\ninitial_col_extend = 0;\nif any(rem(orginal_size(1),2)), %if sx(1) is not divisable by 2 then we need to extend X by adding a row at the bottom\n X = [X; X(end,:)]; %Any further extension will be done in due course.\n initial_row_extend = 1;\nend\nif any(rem(orginal_size(2),2)), \t%if sx(2) is not divisable by 2 then we need to extend X by adding a col to the left\n X = [X X(:,end)]; %Any further extension will be done in due course.\n initial_col_extend = 1;\nend\nextended_size = size(X);\n\nif nlevels == 0, return; end\n\n%initialise\nYh=cell(nlevels,1);\nif nargout == 3\n Yscale=cell(nlevels,1); %this is only required if the user specifies a third output component.\nend\n\nS = [];\nsx = size(X);\nif nlevels >= 1,\n \n % Do odd top-level filters on cols.\n Lo = colfilter(X,h0o).';\n Hi = colfilter(X,h1o).';\n \n % Do odd top-level filters on rows.\n LoLo = colfilter(Lo,h0o).';\t\t\t% LoLo\n Yh{1} = zeros([size(LoLo)/2 6]);\n Yh{1}(:,:,[1 6]) = q2c(colfilter(Hi,h0o).');\t\t\t% Horizontal pair\n Yh{1}(:,:,[3 4]) = q2c(colfilter(Lo,h1o).');\t\t\t% Vertical pair\n Yh{1}(:,:,[2 5]) = q2c(colfilter(Hi,h1o).');\t % Diagonal pair\n S = [ size(LoLo) ;S];\n if nargout == 3\n Yscale{1} = LoLo;\n end\nend\n\nif nlevels >= 2;\n for level = 2:nlevels;\n [row_size col_size] = size(LoLo);\n if any(rem(row_size,4)),\t\t% Extend by 2 rows if no. of rows of LoLo are divisable by 4;\n LoLo = [LoLo(1,:); LoLo; LoLo(end,:)];\n end \n if any(rem(col_size,4)),\t\t% Extend by 2 cols if no. of cols of LoLo are divisable by 4;\n LoLo = [LoLo(:,1) LoLo LoLo(:,end)];\n end \n \n % Do even Qshift filters on rows.\n Lo = coldfilt(LoLo,h0b,h0a).';\n Hi = coldfilt(LoLo,h1b,h1a).';\n \n % Do even Qshift filters on columns.\n LoLo = coldfilt(Lo,h0b,h0a).';\t%LoLo\n Yh{level} = zeros([size(LoLo)/2 6]);\n Yh{level}(:,:,[1 6]) = q2c(coldfilt(Hi,h0b,h0a).');\t% Horizontal\n Yh{level}(:,:,[3 4]) = q2c(coldfilt(Lo,h1b,h1a).');\t% Vertical\n Yh{level}(:,:,[2 5]) = q2c(coldfilt(Hi,h1b,h1a).');\t% Diagonal \n S = [ size(LoLo) ;S];\n if nargout == 3\n Yscale{level} = LoLo;\n end\n end\nend\n\nYl = LoLo;\n\nif initial_row_extend == 1 & initial_col_extend == 1;\n warning(sprintf(' \\r\\r The image entered is now a %dx%d NOT a %dx%d \\r The bottom row and rightmost column have been duplicated, prior to decomposition. \\r\\r ',...\n extended_size(1),extended_size(2),orginal_size(1),orginal_size(2)));\nend\n\nif initial_row_extend == 1 ;\n warning(sprintf(' \\r\\r The image entered is now a %dx%d NOT a %dx%d \\r Row number %d has been duplicated, and added to the bottom of the image, prior to decomposition. \\r\\r',...\n extended_size(1),extended_size(2),orginal_size(1),orginal_size(2),orginal_size(1)));\nend\n\nif initial_col_extend == 1;\n warning(sprintf(' \\r\\r The image entered is now a %dx%d NOT a %dx%d \\r Col number %d has been duplicated, and added to the right of the image, prior to decomposition. \\r\\r',...\n extended_size(1),extended_size(2),orginal_size(1),orginal_size(2),orginal_size(2)));\nend\nreturn\n\n%==========================================================================================\n%\t\t\t\t\t\t********** \tINTERNAL FUNCTION **********\n%==========================================================================================\n\nfunction z = q2c(y)\n\n% function z = q2c(y)\n% Convert from quads in y to complex numbers in z.\n\nsy = size(y);\nt1 = 1:2:sy(1); t2 = 1:2:sy(2);\nj2 = sqrt([0.5 -0.5]);\n\n% Arrange pixels from the corners of the quads into\n% 2 subimages of alternate real and imag pixels.\n% a----b\n% | |\n% | |\n% c----d\n\n% Combine (a,b) and (d,c) to form two complex subimages. \np = y(t1,t2)*j2(1) + y(t1,t2+1)*j2(2); % p = (a + jb) / sqrt(2)\nq = y(t1+1,t2+1)*j2(1) - y(t1+1,t2)*j2(2); % q = (d - jc) / sqrt(2)\n\n% Form the 2 subbands in z.\nz = cat(3,p-q,p+q);\n\nreturn\n", "meta": {"author": "xingchenzhang", "repo": "VIFB", "sha": "7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa", "save_path": "github-repos/MATLAB/xingchenzhang-VIFB", "path": "github-repos/MATLAB/xingchenzhang-VIFB/VIFB-7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa/methods/NSCT_SR/dtcwt_toolbox/dtwavexfm2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5950497991478888}} {"text": "function p = cycle_to_perm ( n, ncycle, t, index )\n\n%*****************************************************************************80\n%\n%% CYCLE_TO_PERM converts a permutation from cycle to array form.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 January 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Donald Kreher, Douglas Simpson,\n% Combinatorial Algorithms,\n% CRC Press, 1998,\n% ISBN: 0-8493-3988-X,\n% LC: QA164.K73.\n%\n% Parameters:\n%\n% Input, integer N, the number of items permuted.\n% N must be positive.\n%\n% Input, integer NCYCLE, the number of cycles.\n% 1 <= NCYCLE <= N.\n%\n% Input, integer T(N), INDEX(NCYCLE), describes the permutation\n% as a collection of NCYCLE cycles. The first cycle is\n% T(1) -> T(2) -> ... -> T(INDEX(1)) -> T(1).\n%\n% Output, integer P(N), describes the permutation using a\n% single array. For each index I, I -> P(I).\n%\n\n%\n% Check.\n%\n ierror = cycle_check ( n, ncycle, t, index );\n\n if ( ierror ~= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CYCLE_TO_PERM - Fatal error!\\n' );\n fprintf ( 1, ' The input array is illegal.\\n' );\n fprintf ( 1, ' IERROR = %d\\n', ierror );\n error ( 'CYCLE_TO_PERM - Fatal error!' );\n end\n\n jhi = 0;\n\n for i = 1 : ncycle\n\n jlo = jhi + 1;\n jhi = jhi + index(i);\n\n for j = jlo : jhi\n\n if ( j < jhi )\n p(t(j)) = t(j+1);\n else\n p(t(j)) = t(jlo);\n end\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/combo/cycle_to_perm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.5950497905701199}} {"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%%*************************************************************************\n\nfunction [xx,resnrm,flag] = mybicgstab(A,b,M1,tol,maxit,printlevel)\n\nN = length(b);\nif (nargin < 6); printlevel = 1; end\nif (nargin < 5) || isempty(maxit); maxit = max(30,length(A.mat22)); end;\nif (nargin < 4) || isempty(tol); tol = 1e-10; end;\ntolb = min(1e-4,tol*norm(b));\nflag = 1;\n\nx = zeros(N,1);\nif (norm(x))\n if isstruct(A); r = b-matvec(A,x); else r = b-mexMatvec(A,x); end;\nelse\n r =b;\nend\nerr = norm(r); resnrm(1) = err; minresnrm = err; xx = x;\n%%if (err < 1e-3*tolb); return; end\n\nomega = 1.0;\nr_tld = r;\n%%\n%%\n%%\nbreakyes = 0;\nsmtol = 1e-40;\nfor 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; %#ok\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\nend\nif (~breakyes) && (printlevel >=3); fprintf(' '); end\n%%\n%%*************************************************************************\n%%*************************************************************************\n%% precond:\n%%*************************************************************************\n\nfunction Mx = precond(A,L,x)\n\nm = L.matdim; m2 = length(x)-m;\nMx = zeros(length(x),1);\n\nfor 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:m+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]; %#ok\n end\n Mx = Mx + d;\nend\n%%*************************************************************************\n%%*************************************************************************\n%% matvec: matrix-vector multiply.\n%% matrix = [A.mat11, A.mat12; A.mat12', A.mat22]\n%%*************************************************************************\n\nfunction Ax = matvec(A,x)\n\nm = length(A.mat11); m2 = length(x)-m;\nif issparse(x); x = full(x); end\nif (m2 > 0)\n x1 = x(1:m);\nelse\n x1 = x;\nend\nAx = mexMatvec(A.mat11,x1);\nif (m2 > 0)\n x2 = x(m+1:m+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)];\nend\n%%*************************************************************************\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/sdpt3/Solver/mybicgstab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.5950486736406014}} {"text": "function h = hs71H(x,lambda)\n\nh = [ 2*x(4) x(4) x(4) 2*x(1)+x(2)+x(3);\n x(4) 0 0 x(1);\n x(4) 0 0 x(1);\n 2*x(1)+x(2)+x(3) x(1) x(1) 0 ];\n \nh = h + lambda.ineqnonlin*-[ 0 x(3)*x(4) x(2)*x(4) x(2)*x(3);\n x(3)*x(4) 0 x(1)*x(4) x(1)*x(3);\n x(2)*x(4) x(1)*x(4) 0 x(1)*x(2);\n x(2)*x(3) x(1)*x(3) x(1)*x(2) 0 ];\n \nh = h + lambda.eqnonlin * diag([2 2 2 2]);", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/OptiToolbox/Test Problems/Development/hs71H.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5949898513677414}} {"text": "function variance = normal_01_variance ( )\n\n%*****************************************************************************80\n%\n%% NORMAL_01_VARIANCE returns the variance of the Normal 01 PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real VARIANCE, the variance of the PDF.\n%\n variance = 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/truncated_normal/normal_01_variance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.5948210644519963}} {"text": "function bessel_k0_int_values_test ( )\n\n%*****************************************************************************80\n%\n%% BESSEL_KO_INT_VALUES_TEST demonstrates the use of BESSEL_KO_INT_VALUES.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 February 2009\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BESSEL_KO_INT_VALUES_TEST:\\n' );\n fprintf ( 1, ' BESSEL_K0_INT_VALUES stores values of \\n' );\n fprintf ( 1, ' the integral of the Bessel function K0.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X FX\\n' );\n fprintf ( 1, '\\n' );\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, x, fx ] = bessel_k0_int_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n fprintf ( 1, ' %12f %24.16f\\n', x, fx );\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/test_values/bessel_k0_int_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.5948210644519963}} {"text": "function [E,J]=SynthMeasWatsonSHCylSingleRadIsoV_GPD(x, protocol, fibredir, roots)\n% Substrate: Impermeable cylinders with one radius in a homogeneous background.\n% Orientation distribution: Watson's distribution with SH approximation\n% Signal approximation: Gaussian phase distribution.\n% Notes: This version includes an isotropic diffusion compartment with its own\n% diffusivity.\n%\n% [E,J]=SynthMeasWatsonSHCylSingleRadIsoV_GPD(x, protocol, fibredir, roots)\n% returns the measurements E according to the model and the Jacobian J of the\n% measurements with respect to the parameters. The Jacobian does not\n% include derivates with respect to the fibre direction.\n%\n% x is the list of model parameters in SI units:\n% x(1) is the volume fraction of the intracellular space.\n% x(2) is the free diffusivity of the material inside and outside the cylinders.\n% x(3) is the hindered diffusivity outside the cylinders in perpendicular directions.\n% x(4) is the radius of the cylinders.\n% x(5) is the concentration parameter of the Watson's distribution.\n% x(6) is the volume fraction of the isotropic compartment.\n% x(7) is the diffusivity of the isotropic compartment.\n%\n% protocol is the object containing the acquisition protocol.\n%\n% fibredir is a unit vector along the symmetry axis of the Watson's\n% distribution. It must be in Cartesian coordinates [x y z]' with size [3 1].\n%\n% roots contains solutions to the Bessel function equation from function\n% BesselJ_RootsCyl.\n%\n% author: Gary Hui Zhang (gary.zhang@ucl.ac.uk)\n%\n\nfiso = x(6);\ndIso = x(7);\n\n% Call the model with no isotropic component to get the anisotropic component.\nif(nargout == 1)\n Eaniso=SynthMeasWatsonSHCylSingleRadGPD(x, protocol, fibredir, roots);\n Eiso = SynthMeasIsoGPD(dIso, protocol);\nelse\n [Eaniso,Janiso]=SynthMeasWatsonSHCylSingleRadGPD(x, protocol, fibredir, roots);\n [Eiso, Jiso] = SynthMeasIsoGPD(dIso, protocol);\nend\n\nE = (1-fiso)*Eaniso + fiso*Eiso;\n\nif(nargout>1)\n \n % Update with anisotropic component.\n J = Janiso*(1-fiso);\n \n % Add derivatives wrt isotropic fraction.\n J(:,6) = Eiso - Eaniso;\n \n % Add entry for dIso\n J(:,7) = fiso*Jiso;\nend\n\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/NODDI_toolbox_v1.0/models/watson/SynthMeasWatsonSHCylSingleRadIsoV_GPD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.5948158710255265}} {"text": "function [Mz_z,Mz_xy,F,ref_eff,Mx_xy,My_xy]=simRf(rf,rephase_factor,prephase_factor) \n%simRf Simulate an RF pulse with the given pulse shape.\n% [Mz_z,Mz_xy,F,ref_eff,Mx_xy,My_xy]=simRf(pulse,prephase_factor,rephase_factor) \n% Performs a rapid RF pulse simulation based on the rotation formalism.\n% The algorithm is optimized by using quaternions to represent rotations. \n% The compulsory parameter 'rf' is the Pulseq RF pulse. Optional\n% parameter 'rephase_factor' is needed in several cases e.g. to correclty \n% visualize the phase of the magnetization for slice-selective\n% excitation. Another optional parameter 'prephase_factor' is an \n% experimental parameter useful for simulating refocusing pulses or\n% spoiling needed. \n% Return values: \n% Mz_z,Mz_xy: z and xy comnponents of the magnetisation after the pulse\n% assuming the unit magnetization was aligned with z before\n% the pulse. Useful for assessing excitation RF pulses. \n% F: frequency axis in Hz \n% ref_eff: Refocusing efficiency of the pulse as a complex value.\n% Magnitude of ref_eff seems to closely follow Mz_z. Phase\n% of ref_eff is related to the effective phase of the RF\n% pulse, e.g. the axis of the planar flip.\n% Mx_xy,My_xy: xy magnetizations after the RF pulse assuming the unit\n% magnetization was aligned with x or y axis prior to the\n% pulse, respectively. Useful for detailed analyses of\n% refocusing pulses.\n%\n% The implementation was inspired by the example by Dr. Tony Stoecker\n% (https://github.com/stoeckert/mr-simu-example-ismrm19)\n% The algorithm was rewritten to quaternions and vectorized for \n% performance by MZ \n%\n\nbw_mul=4; % simulation bandwidth (multiplier of the pulse bandwidth)\ndf=1; % spectral resolution [Hz]\ndt=10e-6; % (re-)sampling interval\n\nif nargin < 2\n if isfield(rf,'use') && strcmp(rf.use,'refocusing')\n rephase_factor = 0;\n else\n rephase_factor = -(rf.shape_dur-mr.calcRfCenter(rf))/rf.shape_dur;\n end\nend\n\nif nargin < 3\n prephase_factor = 0;\nend\n \n[bw,f0,spectrum,FF,rfs,tt]=mr.calcRfBandwidth(rf,0.5,df*10,dt);\n\nT = (1:round(rf.shape_dur/dt))*dt-0.5*dt; % timesteps axis [s]\nF = 2*pi*linspace(f0-bw_mul*bw/2,f0+bw_mul*bw/2,bw/df)'; % offset frequencies [rad/s] \n\nshapea = interp1(rf.t, 2*pi*rf.signal.*exp(1i*(rf.phaseOffset+2*pi*rf.freqOffset*rf.t)),T,'linear',0);\n\n% intialize result vectors\nM_ROT=zeros(size(F)); \nZ_ROT=zeros(size(F));\nsf=size(F);\nq=zeros(sf(1),4);\nq(:,1)=1; % init rotation quaternions\n\n% prephaser / left spoiler\nW = -F*dt*length(T)*prephase_factor; % effective field rotation angle\nQ = [cos(W/2) zeros(sf) zeros(sf) sin(W/2)];\nq=quat_multiply(q,Q);\n\n% RF pulse simulation\nfor j=1:length(T)\n W = -dt*sqrt(abs(shapea(j))^2+F.^2); % effective field rotation angles\n n = dt * [real(shapea(j))*ones(sf) imag(shapea(j))*ones(sf) F]./abs(W); % effective field rotation axes\n Q = [cos(W/2) sin(W/2).*n];\n q=quat_multiply(q,Q);\nend\n\n% rephaser / right spoiler / refocusing pulse\nW = -F*dt*length(T)*rephase_factor; % effective field rotation angle\nQ = [cos(W/2) zeros(sf) zeros(sf) sin(W/2)];\nq=quat_multiply(q,Q);\n\n% export results\nF=F/(2*pi);\nm=zeros(sf(1),4);\n\n% excitation: start with M0=M_z\nm(:,4)=1;\nm0rf=quat_multiply(quat_conj(q),quat_multiply(m,q));\nMz_z=m0rf(:,4);\nMz_xy=m0rf(:,2)+1i*m0rf(:,3);\n\n% refocusing: start both with M0=M_x and them M0=M_y\nm=zeros(sf(1),4);\nm(:,2)=1;\nMx_xy=quat_multiply(quat_conj(q),quat_multiply(m,q));\nMx_xy=Mx_xy(:,2)+1i*Mx_xy(:,3);\nm=zeros(sf(1),4);\nm(:,3)=1;\nMy_xy=quat_multiply(quat_conj(q),quat_multiply(m,q));\nMy_xy=My_xy(:,2)+1i*My_xy(:,3);\nref_eff=(Mx_xy+My_xy*1i)/2;\nend \n\nfunction qout = quat_multiply( q, r )\n% quat_multiply: Calculate the product of two quaternions.\n\n% Calculate vector portion of quaternion product\n% vec = s1*v2 + s2*v1 + cross(v1,v2)\nvec = [q(:,1).*r(:,2) q(:,1).*r(:,3) q(:,1).*r(:,4)] + ...\n [r(:,1).*q(:,2) r(:,1).*q(:,3) r(:,1).*q(:,4)]+...\n [ q(:,3).*r(:,4)-q(:,4).*r(:,3) ...\n q(:,4).*r(:,2)-q(:,2).*r(:,4) ...\n q(:,2).*r(:,3)-q(:,3).*r(:,2)];\n\n% Calculate scalar portion of quaternion product\n% scalar = s1*s2 - dot(v1,v2)\nscalar = q(:,1).*r(:,1) - q(:,2).*r(:,2) - ...\n q(:,3).*r(:,3) - q(:,4).*r(:,4);\n\nqout = [scalar vec];\nend\n \nfunction q = quat_conj( q ) \n% quat_conj Calculate the conjugate of a quaternion.\nq(:,2:4) = -q(:,2:4);\nend\n", "meta": {"author": "pulseq", "repo": "pulseq", "sha": "b4c8fee2a1ffa491d53bd6f507cba2029bf32835", "save_path": "github-repos/MATLAB/pulseq-pulseq", "path": "github-repos/MATLAB/pulseq-pulseq/pulseq-b4c8fee2a1ffa491d53bd6f507cba2029bf32835/matlab/+mr/simRf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5947447199042883}} {"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\nfunction [f, df] = CG_MNIST(VV,Dim,XX);\n\nl1 = Dim(1);\nl2 = Dim(2);\nl3 = Dim(3);\nl4= Dim(4);\nl5= Dim(5);\nl6= Dim(6);\nl7= Dim(7);\nl8= Dim(8);\nl9= Dim(9);\nN = size(XX,1);\n\n% Do decomversion.\n w1 = reshape(VV(1:(l1+1)*l2),l1+1,l2);\n xxx = (l1+1)*l2;\n w2 = reshape(VV(xxx+1:xxx+(l2+1)*l3),l2+1,l3);\n xxx = xxx+(l2+1)*l3;\n w3 = reshape(VV(xxx+1:xxx+(l3+1)*l4),l3+1,l4);\n xxx = xxx+(l3+1)*l4;\n w4 = reshape(VV(xxx+1:xxx+(l4+1)*l5),l4+1,l5);\n xxx = xxx+(l4+1)*l5;\n w5 = reshape(VV(xxx+1:xxx+(l5+1)*l6),l5+1,l6);\n xxx = xxx+(l5+1)*l6;\n w6 = reshape(VV(xxx+1:xxx+(l6+1)*l7),l6+1,l7);\n xxx = xxx+(l6+1)*l7;\n w7 = reshape(VV(xxx+1:xxx+(l7+1)*l8),l7+1,l8);\n xxx = xxx+(l7+1)*l8;\n w8 = reshape(VV(xxx+1:xxx+(l8+1)*l9),l8+1,l9);\n\n\n XX = [XX ones(N,1)];\n w1probs = 1./(1 + exp(-XX*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 = w3probs*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(-w6probs*w7)); w7probs = [w7probs ones(N,1)];\n XXout = 1./(1 + exp(-w7probs*w8));\n\nf = -1/N*sum(sum( XX(:,1:end-1).*log(XXout) + (1-XX(:,1:end-1)).*log(1-XXout)));\nIO = 1/N*(XXout-XX(:,1:end-1));\nIx8=IO; \ndw8 = w7probs'*Ix8;\n\nIx7 = (Ix8*w8').*w7probs.*(1-w7probs); \nIx7 = Ix7(:,1:end-1);\ndw7 = w6probs'*Ix7;\n\nIx6 = (Ix7*w7').*w6probs.*(1-w6probs); \nIx6 = Ix6(:,1:end-1);\ndw6 = w5probs'*Ix6;\n\nIx5 = (Ix6*w6').*w5probs.*(1-w5probs); \nIx5 = Ix5(:,1:end-1);\ndw5 = w4probs'*Ix5;\n\nIx4 = (Ix5*w5');\nIx4 = Ix4(:,1:end-1);\ndw4 = w3probs'*Ix4;\n\nIx3 = (Ix4*w4').*w3probs.*(1-w3probs); \nIx3 = Ix3(:,1:end-1);\ndw3 = w2probs'*Ix3;\n\nIx2 = (Ix3*w3').*w2probs.*(1-w2probs); \nIx2 = Ix2(:,1:end-1);\ndw2 = w1probs'*Ix2;\n\nIx1 = (Ix2*w2').*w1probs.*(1-w1probs); \nIx1 = Ix1(:,1:end-1);\ndw1 = XX'*Ix1;\n\ndf = [dw1(:)' dw2(:)' dw3(:)' dw4(:)' dw5(:)' dw6(:)' dw7(:)' dw8(:)' ]'; \n\n\n", "meta": {"author": "qiuwch", "repo": "DeepLearning", "sha": "60508ffd8c39a085375eec82e576f446d1318bc9", "save_path": "github-repos/MATLAB/qiuwch-DeepLearning", "path": "github-repos/MATLAB/qiuwch-DeepLearning/DeepLearning-60508ffd8c39a085375eec82e576f446d1318bc9/CG_MNIST.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5947427116224192}} {"text": "function [E,J]=SynthMeasWatsonSHCylSingleRadTortIsoVIsoDot_GPD_B0(x, protocol, fibredir, roots)\n% Substrate: Impermeable cylinders with one radius in a homogeneous background.\n% Orientation distribution: Watson's distribution with SH approximation\n% Signal approximation: Gaussian phase distribution.\n% Notes: This version estimates the hindered diffusivity from the free diffusivity\n% and packing density using Szafer et al's tortuosity model for randomly\n% packed cylinders.\n% This version includes an isotropic diffusion compartment with its own\n% diffusivity.\n% This version includes a stationary water compartment.\n% Includes a free parameter for the measurement at b=0.\n%\n% [E,J]=SynthMeasWatsonSHCylSingleRadTortIsoVIsoDot_GPD_B0(x, protocol, fibredir, roots)\n% returns the measurements E according to the model and the Jacobian J of the\n% measurements with respect to the parameters. The Jacobian does not\n% include derivates with respect to the fibre direction.\n%\n% x is the list of model parameters in SI units:\n% x(1) is the volume fraction of the intracellular space.\n% x(2) is the free diffusivity of the material inside and outside the cylinders.\n% x(3) is the radius of the cylinders.\n% x(4) is the concentration parameter of the Watson's distribution.\n% x(5) is the volume fraction of the isotropic compartment.\n% x(6) is the diffusivity of the isotropic compartment.\n% x(7) is the volume fraction of the isotropic restriction.\n% x(8) is the measurement at b=0.\n%\n% protocol is the object containing the acquisition protocol.\n%\n% fibredir is a unit vector along the symmetry axis of the Watson's\n% distribution. It must be in Cartesian coordinates [x y z]' with size [3 1].\n%\n% roots contains solutions to the Bessel function equation from function\n% BesselJ_RootsCyl.\n%\n% author: Gary Hui Zhang (gary.zhang@ucl.ac.uk)\n%\n\nS0 = x(8);\n\n% Call the other function to get normalized measurements.\nif(nargout == 1)\n Enorm=SynthMeasWatsonSHCylSingleRadTortIsoVIsoDot_GPD(x, protocol, fibredir, roots);\nelse\n [Enorm,Jnorm]=SynthMeasWatsonSHCylSingleRadTortIsoVIsoDot_GPD(x, protocol, fibredir, roots);\nend\n\nE = Enorm*S0;\n\nif(nargout>1)\n J = Jnorm*S0;\n J(:,8) = Enorm;\nend\n\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/NODDI_toolbox_v1.0/models/watson/SynthMeasWatsonSHCylSingleRadTortIsoVIsoDot_GPD_B0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5947427077618629}} {"text": "function op = prox_l1pos( q )\n%PROX_L1POS L1 norm, restricted to x >= 0\n% OP = PROX_L1( q ) implements the nonsmooth function\n% OP(X) = norm(q.*X,1) + indicator_{ X >= 0 }\n% Q is optional; if omitted, Q=1 is assumed. But if Q is supplied,\n% then it must be a positive real scalar (or must be same size as X).\n\n% New in v1.0d\n\nif nargin == 0,\n\tq = 1;\nelseif ~isnumeric( q ) || ~isreal( q ) || any( q(:) < 0 ) || all(q(:)==0) %|| numel( q ) ~= 1\n\terror( 'Argument must be positive.' );\nend\n\nop = tfocs_prox( @(x)f(x,q), @(x,t)prox_f(x,t,q), 'vector');\nend\n\nfunction v = f(x,q)\n if any( x(:) < 0 )\n v = Inf;\n elseif isscalar(q)\n v = q*sum( x(:) );\n else\n v = sum( q(:).*x(:) );\n end\nend\n\n% The proximity operator is a simplified version of shrinkage:\nfunction x = prox_f(x,t,q) \n x = max( 0, x - t*q );\nend\n\n\n\n% TFOCS v1.3 by Stephen Becker, Emmanuel Candes, and Michael Grant.\n% Copyright 2013 California Institute of Technology and CVX Research.\n% See the file LICENSE for full license information.\n", "meta": {"author": "cvxr", "repo": "TFOCS", "sha": "164ada20401cd445930673e42bb3d2a5489f2030", "save_path": "github-repos/MATLAB/cvxr-TFOCS", "path": "github-repos/MATLAB/cvxr-TFOCS/TFOCS-164ada20401cd445930673e42bb3d2a5489f2030/prox_l1pos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5947427013424571}} {"text": "function [soln,eqn,info] = StokesP2P0(node,elem,bdFlag,pde,option)\n%% STOKESP2P0 Stokes equation: P2-P0 elements.\n%\n% [soln,eqn,info] = STOKESP2P0(node,elem,bdFlag,pde) use quadratic and piceswise\n% constant elements to approximate velocity u and pressure p, repectively.\n% \n% -div(mu*grad u) + grad p = f in \\Omega,\n% - div u = 0 in \\Omega,\n% with \n% Dirichlet boundary condition u = g_D on \\Gamma_D, \n% Neumann boundary condition du/dn - np = g_N on \\Gamma_N.\n%\n% It is a choice of option.fem in Stokes. Please read Stokes for more\n% information on the input and output.\n%\n% See also Stokes, Poisson, StokesP2P1\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\n\nif ~exist('option','var'), option = []; end\n\n%% Construct Data Structure\n[elem2dof,edge,bdDof] = dofP2(elem);\nN = size(node,1); NT = size(elem,1); Nu = N+size(edge,1); Np = NT;\n\nt = cputime;\n%% Compute geometric quantities and gradient of local basis\n[Dlambda,area] = gradbasis(node,elem);\n\n%% Assemble stiffness matrix for Laplace operator\n% generate sparse pattern\nii = zeros(21*NT,1); jj = zeros(21*NT,1); \nindex = 0;\nfor i = 1:6\n for j = i:6\n ii(index+1:index+NT) = double(elem2dof(:,i)); \n jj(index+1:index+NT) = double(elem2dof(:,j)); \n index = index + NT;\n end\nend\n% quadrature points\nif ~isfield(pde,'nu'), pde.nu = []; end\nif ~isfield(option,'quadorder')\n % constant viscosity\n option.quadorder = 2; % default order\n if ~isempty(pde.nu) && isnumeric(pde.nu) % numerical viscosity\n option.quadorder = 3; % exact for linear diffusion coefficient\n end\nend\n[lambda, w] = quadpts(option.quadorder);\nnQuad = size(lambda,1);\n% compute non-zeros\nsA = zeros(21*NT,nQuad);\nfor p = 1:nQuad\n % Dphi at quadrature points\n Dphip(:,:,6) = 4*(lambda(p,1)*Dlambda(:,:,2)+lambda(p,2)*Dlambda(:,:,1));\n Dphip(:,:,5) = 4*(lambda(p,3)*Dlambda(:,:,1)+lambda(p,1)*Dlambda(:,:,3));\n Dphip(:,:,4) = 4*(lambda(p,2)*Dlambda(:,:,3)+lambda(p,3)*Dlambda(:,:,2));\n Dphip(:,:,1) = (4*lambda(p,1)-1).*Dlambda(:,:,1); \n Dphip(:,:,2) = (4*lambda(p,2)-1).*Dlambda(:,:,2); \n Dphip(:,:,3) = (4*lambda(p,3)-1).*Dlambda(:,:,3); \n index = 0;\n for i = 1:6\n for j = i:6\n Aij = 0;\n if isempty(pde.nu) || isnumeric(pde.nu)\n Aij = Aij + w(p)*dot(Dphip(:,:,i),Dphip(:,:,j),2);\n else\n pxy = lambda(p,1)*node(elem(:,1),:) ...\n + lambda(p,2)*node(elem(:,2),:) ...\n + lambda(p,3)*node(elem(:,3),:);\n Aij = Aij + w(p)*dot(Dphip(:,:,i),Dphip(:,:,j),2).*pde.d(pxy);\n end\n if ~isempty(pde.nu) && (pde.nu~=1)\n Aij = pde.nu*Aij;\n end\n Aij = Aij.*area;\n sA(index+1:index+NT,p) = Aij;\n index = index + NT;\n end\n end\nend\nsA = sum(sA,2);\n% assemble the matrix\ndiagIdx = (ii == jj); upperIdx = ~diagIdx;\nA = sparse(ii(diagIdx),jj(diagIdx),sA(diagIdx),Nu,Nu);\nAU = sparse(ii(upperIdx),jj(upperIdx),sA(upperIdx),Nu,Nu);\nA = A + AU + AU';\nA = blkdiag(A,A);\nclear Aij ii jj sA Dphip\n\n%% Assemble matrix for divergence operator\n% Since Dphi is linear, 1-pt quadrature is exact for the integral\n% int(div(phi)). We evaluate each basis at the barycenter.\nDphic(:,:,6) = 4/3*(Dlambda(:,:,1) + Dlambda(:,:,2));\nDphic(:,:,1) = 1/3*Dlambda(:,:,1); % (4*lambda(p,1)-1).*Dlambda(:,:,1);\nDphic(:,:,2) = 1/3*Dlambda(:,:,2);\nDphic(:,:,3) = 1/3*Dlambda(:,:,3);\nDphic(:,:,4) = 4/3*(Dlambda(:,:,2) + Dlambda(:,:,3));\nDphic(:,:,5) = 4/3*(Dlambda(:,:,3) + Dlambda(:,:,1));\nclear Dlambda\n% divergence matrix\nDx = sparse(Np,Nu);\nDy = sparse(Np,Nu);\nfor i = 1:6 \n Dx = Dx + sparse(1:NT,double(elem2dof(:,i)),Dphic(:,1,i).*area,Np,Nu);\n Dy = Dy + sparse(1:NT,double(elem2dof(:,i)),Dphic(:,2,i).*area,Np,Nu);\nend\nB = -[Dx Dy]; %#ok<*NASGU>\nclear Dphi Dx Dy\n\n%% Assemble right hand side\nf1 = zeros(Nu,1);\nf2 = zeros(Nu,1);\nif ~isfield(option,'fquadorder')\n option.fquadorder = 3; % default order\nend\nif ~isfield(pde,'f') || (isreal(pde.f) && (pde.f==0))\n pde.f = [];\nend\nif ~isempty(pde.f) \n % quadrature points in the barycentric coordinate\n [lambda,weight] = quadpts(option.fquadorder);\n % basis values at quadrature points\n phi(:,6) = 4*lambda(:,1).*lambda(:,2);\n phi(:,1) = lambda(:,1).*(2*lambda(:,1)-1);\n phi(:,2) = lambda(:,2).*(2*lambda(:,2)-1);\n phi(:,3) = lambda(:,3).*(2*lambda(:,3)-1);\n phi(:,4) = 4*lambda(:,2).*lambda(:,3);\n phi(:,5) = 4*lambda(:,3).*lambda(:,1);\n nQuad = size(lambda,1);\n ft1 = zeros(NT,6);\n ft2 = zeros(NT,6);\n for p = 1:nQuad\n % quadrature points in the x-y coordinate\n pxy = lambda(p,1)*node(elem(:,1),:) ...\n + lambda(p,2)*node(elem(:,2),:) ...\n + lambda(p,3)*node(elem(:,3),:);\n % function values at quadrature points\n fp = pde.f(pxy);\n for j = 1:6\n ft1(:,j) = ft1(:,j) + fp(:,1).*phi(p,j)*weight(p);\n ft2(:,j) = ft2(:,j) + fp(:,2).*phi(p,j)*weight(p);\n end\n end\n ft1 = ft1.*repmat(area,1,6);\n ft2 = ft2.*repmat(area,1,6);\n f1 = accumarray(elem2dof(:),ft1(:),[Nu 1]);\n f2 = accumarray(elem2dof(:),ft2(:),[Nu 1]);\nend\n\n%% Boundary condition\n[AD,BD,f,g,u,p,ufreeDof,pDof] = getbdStokesP2P0;\n\n%% Record assembeling time\nassembleTime = cputime - t;\nif ~isfield(option,'printlevel'), option.printlevel = 1; end\nif option.printlevel >= 2\n fprintf('Time to assemble matrix equation %4.2g s\\n',assembleTime);\nend\n\n%% Solve the system of linear equations\nif isempty(ufreeDof), return; end\nif isempty(option) || ~isfield(option,'solver') % no option.solver\n if length(f)+length(g) <= 1e3 % Direct solver for small size systems\n option.solver = 'direct';\n else % Multigrid-type solver for large size systems\n option.solver = 'asmg';\n end\nend\nsolver = option.solver;\n\n%% Solver\nswitch solver\n case 'direct'\n t = cputime;\n bigA = [AD, BD'; ...\n BD, sparse(Np,Np)];\n bigF = [f; g];\n bigu = [u; p];\n bigFreeDof = [ufreeDof; 2*Nu+pDof];\n bigu(bigFreeDof) = bigA(bigFreeDof,bigFreeDof)\\bigF(bigFreeDof);\n u = bigu(1:2*Nu);\n p = bigu(2*Nu+1:end);\n residual = norm(bigF - bigA*bigu);\n info = struct('solverTime',cputime - t,'itStep',0,'err',residual,'flag',2,'stopErr',residual); \n case 'mg'\n option.solver = 'WCYCLE';\n [u(ufreeDof),p,info] = mgstokes(A(ufreeDof,ufreeDof),B(:,ufreeDof),f(ufreeDof),g,...\n u(ufreeDof),p,elem,ufreeDof,option); \n case 'asmg'\n [u(ufreeDof),p,info] = asmgstokes(A(ufreeDof,ufreeDof),B(:,ufreeDof),f(ufreeDof),g,...\n u,p,node,elem,bdFlag,ufreeDof,option); \nend\n\n%% Post-process\nif length(pDof) ~= Np % p is unique up to a constant\n % impose the condition int(p)=0\n c = sum(p.*area)/sum(area);\n p = p - c;\nend\n\n%% Output\nsoln = struct('u',u,'p',p);\neqn = struct('A',AD,'B',BD,'Lap',A,'f',f,'g',g,...\n 'edge',edge,'ufreeDof',ufreeDof,'pDof',pDof);\ninfo.assembleTime = assembleTime;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% subfunctions getbdStokesP2P0\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n function [AD,BD,f,g,u,p,ufreeDof,pDof] = getbdStokesP2P0\n %% Boundary condition of Stokes equation: P2-P0 elements\n\n %% Initial set up\n% f = [f1; f2]; % set in Neumann boundary condition\n g = zeros(Np,1);\n u = zeros(2*Nu,1); \n p = zeros(Np,1);\n ufreeDof = (1:Nu)';\n pDof = (1:Np)';\n \n if ~exist('bdFlag','var'), bdFlag = []; end\n if ~isfield(pde,'g_D'), pde.g_D = []; end\n if ~isfield(pde,'g_N'), pde.g_N = []; end\n if ~isfield(pde,'g_R'), pde.g_R = []; end\n\n %% Part 1: Find Dirichlet dof and modify the matrix\n % Find Dirichlet boundary dof: fixedDof and pDof\n isFixedDof = false(Nu,1); \n if ~isempty(bdFlag) % case: bdFlag is not empty \n elem2edge = elem2dof(:,4:6)-N;\n isDirichlet(elem2edge(bdFlag(:)==1)) = true;\n isFixedDof(edge(isDirichlet,:)) = true; % nodes of all D-edges\n isFixedDof(N + find(isDirichlet')) = true;% dof on D-edges\n fixedDof = find(isFixedDof);\n ufreeDof = find(~isFixedDof); \n end\n if isempty(bdFlag) && ~isempty(pde.g_D) && isempty(pde.g_N) && isempty(pde.g_R)\n fixedDof = bdDof; \n isFixedDof(fixedDof) = true;\n ufreeDof = find(~isFixedDof); \n end\n if isempty(fixedDof) % pure Neumann boundary condition\n % pde.g_N could be empty which is homogenous Neumann boundary condition\n fixedDof = 1;\n ufreeDof = 2:Nu; % eliminate the kernel by enforcing u(1) = 0;\n end\n\n % Modify the matrix\n % Build Dirichlet boundary condition into the matrix AD by enforcing\n % AD(fixedDof,fixedDof)=I, AD(fixedDof,ufreeDof)=0, AD(ufreeDof,fixedDof)=0.\n % BD(:,fixedDof) = 0 and thus BD'(fixedDof,:) = 0.\n bdidx = zeros(2*Nu,1); \n bdidx(fixedDof) = 1;\n bdidx(Nu+fixedDof) = 1;\n Tbd = spdiags(bdidx,0,2*Nu,2*Nu);\n T = spdiags(1-bdidx,0,2*Nu,2*Nu);\n AD = T*A*T + Tbd;\n BD = B*T;\n\n %% Part 2: Find boundary edges and modify the right hand side f and g\n % Find boundary edges: Neumann and Robin\n Neumann = []; Robin = []; %#ok<*NASGU>\n if ~isempty(bdFlag)\n isNeumann(elem2edge((bdFlag(:)==2)|(bdFlag(:) == 3))) = true;\n isRobin(elem2edge(bdFlag(:)==3)) = true;\n Neumannidx = find(isNeumann); \n Neumann = edge(isNeumann,:);\n Robin = edge(isRobin,:);\n end\n if isempty(bdFlag) && (~isempty(pde.g_N) || ~isempty(pde.g_R))\n % no bdFlag, only pde.g_N or pde.g_R is given in the input\n Neumann = edge(bdDof>N,:);\n if ~isempty(pde.g_R)\n Robin = Neumann;\n end\n end\n\n % Neumann boundary condition\n if ~isempty(pde.g_N) && ~isempty(Neumann) && ~(isnumeric(pde.g_N) && (pde.g_N == 0))\n [lambda,w] = quadpts1(3);\n nQuad = size(lambda,1);\n % quadratic bases (1---3---2)\n bdphi(:,1) = (2*lambda(:,1)-1).*lambda(:,1);\n bdphi(:,2) = (2*lambda(:,2)-1).*lambda(:,2);\n bdphi(:,3) = 4*lambda(:,1).*lambda(:,2);\n % length of edge\n ve = node(Neumann(:,1),:) - node(Neumann(:,2),:);\n edgeLength = sqrt(sum(ve.^2,2));\n % update RHS\n gex = zeros(size(Neumann,1),2);\n gey = zeros(size(Neumann,1),2);\n for pp = 1:nQuad\n pxy = lambda(pp,1)*node(Neumann(:,1),:)+lambda(pp,2)*node(Neumann(:,2),:);\n gp = pde.g_N(pxy);\n gex(:,1) = gex(:,1) + w(pp)*edgeLength.*gp(:,1)*bdphi(pp,1);\n gex(:,2) = gex(:,2) + w(pp)*edgeLength.*gp(:,1)*bdphi(pp,2);\n gey(:,1) = gey(:,1) + w(pp)*edgeLength.*gp(:,2)*bdphi(pp,1);\n gey(:,2) = gey(:,2) + w(pp)*edgeLength.*gp(:,2)*bdphi(pp,2);\n f1(N+Neumannidx) = f1(N+Neumannidx) + w(pp)*edgeLength.*gp(:,1)*bdphi(pp,3); % interior bubble\n f2(N+Neumannidx) = f2(N+Neumannidx) + w(pp)*edgeLength.*gp(:,2)*bdphi(pp,3); % interior bubble\n end\n f1(1:N) = f1(1:N) + accumarray(Neumann(:), gex(:),[N,1]);\n f2(1:N) = f2(1:N) + accumarray(Neumann(:), gey(:),[N,1]);\n end\n f = [f1; f2];\n % The case non-empty Neumann but g_N=[] corresponds to the zero flux\n % boundary condition on Neumann edges and no modification is needed.\n\n % Dirichlet boundary conditions\n if ~isempty(fixedDof) && ~isempty(pde.g_D) && ~(isnumeric(pde.g_D) && (pde.g_D == 0))\n u1 = zeros(Nu,1);\n u2 = zeros(Nu,1);\n idx = (fixedDof > N); % index of edge dof\n uD = pde.g_D(node(fixedDof(~idx),:)); % bd value at vertex dofs \n u1(fixedDof(~idx)) = uD(:,1);\n u2(fixedDof(~idx)) = uD(:,2);\n bdEdgeIdx = fixedDof(idx)-N;\n bdEdgeMid = (node(edge(bdEdgeIdx,1),:)+node(edge(bdEdgeIdx,2),:))/2;\n uD = pde.g_D(bdEdgeMid); % bd values at middle points of edges\n u1(fixedDof(idx)) = uD(:,1);\n u2(fixedDof(idx)) = uD(:,2);\n u = [u1; u2]; % Dirichlet bd condition is built into u\n f = f - A*u; % bring affect of nonhomgenous Dirichlet bd condition to\n g = g - B*u; % the right hand side\n g = g - mean(g);\n f(fixedDof) = u1(fixedDof);\n f(fixedDof+Nu) = u2(fixedDof);\n end\n % The case non-empty Dirichlet but g_D=[] corresponds to the zero Dirichlet\n % boundary condition and no modification is needed.\n \n % modfiy pressure dof for pure Dirichlet\n if isempty(Neumann)\n pDof = (1:Np-1)';\n end\n \n ufreeDof = [ufreeDof; Nu+ufreeDof]; \n end % end of function getbdStokesP2P0\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nend\n% TODO: impose compatible condition int(pde.g_D*n)=0 numerically.\n% NOTE: the data should be compatible, which is not easy. One\n% special case is the enclose flow i.e. pde.g_D*n=0 everywhere.", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/equation/StokesP2P0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357494949104, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5947426887057414}} {"text": "function lik = lik_qgp(varargin)\n%LIK_QGP Create a Quantile Gaussian Process likelihood (utility) structure\n%\n% Description\n% LIK = LIK_QGP('PARAM1',VALUE1,'PARAM2,VALUE2,...) \n% creates a quantile gp likelihood structure in which the named\n% parameters have the specified values. Any unspecified\n% parameters are set to default values.\n%\n% LIK = LIK_QGP(LIK,'PARAM1',VALUE1,'PARAM2,VALUE2,...) \n% modify a likelihood function structure with the named\n% parameters altered with the specified values.\n%\n% Parameters for QGP likelihood function [default]\n% sigma2 - variance [0.1]\n% sigma2_prior - prior for sigma2 [prior_logunif]\n% quantile - Quantile of interest [0.5]\n%\n% Note! If the prior is 'prior_fixed' then the parameter in\n% question is considered fixed and it is not handled in\n% optimization, grid integration, MCMC etc. \n%\n% The likelihood is defined as follows:\n% __ n\n% p(y|f, sigma2, tau) = || i=1 tau*(1-tau)/sigma*exp(-(y-f)/sigma*\n% (tau - I(t <= f)))\n% \n% where tau is the quantile of interest, sigma is the standard deviation\n% of the distribution and I(t <= f) = 1 if t <= f, 0 otherwise.\n%\n% Note that because the form of the likelihood, second order derivatives\n% with respect to latent values are 0. Because this, EP should be used\n% instead of Laplace approximation. \n%\n% See also\n% GP_SET, PRIOR_*, LIK_*\n%\n% Reference\n% Boukouvalas et al. (2012). Direct Gaussian Process Quantile\n% Regression Using Expectation Propagation. In Proceedings of the\n% 29th International Conference on Machine Learning, Edinburgh,\n% Scotland, UK, 2012.\n% \n%\n% Copyright (c) 2012 Ville Tolvanen\n\n% This software is distributed under the GNU General Public\n% License (version 3 or later); please refer to the file\n% License.txt, included with the software, for details.\n\n ip=inputParser;\n ip.FunctionName = 'LIK_QGP';\n ip.addOptional('lik', [], @isstruct);\n ip.addParamValue('sigma2',0.1, @(x) isscalar(x) && x>0);\n ip.addParamValue('sigma2_prior',prior_logunif(), @(x) isstruct(x) || isempty(x));\n ip.addParamValue('quantile',0.5, @(x) isscalar(x) && x>0 && x<1);\n ip.parse(varargin{:});\n lik=ip.Results.lik;\n\n if isempty(lik)\n init=true;\n lik.type = 'QGP';\n else\n if ~isfield(lik,'type') || ~isequal(lik.type,'QGP')\n error('First argument does not seem to be a valid likelihood function structure')\n end\n init=false;\n end\n \n % Initialize parameters\n if init || ~ismember('sigma2',ip.UsingDefaults)\n lik.sigma2 = ip.Results.sigma2;\n end\n if init || ~ismember('quantile',ip.UsingDefaults)\n lik.quantile = ip.Results.quantile;\n end\n % Initialize prior structure\n if init\n lik.p=[];\n end\n if init || ~ismember('sigma2_prior',ip.UsingDefaults)\n lik.p.sigma2=ip.Results.sigma2_prior;\n end\n if init\n % Set the function handles to the subfunctions\n lik.fh.pak = @lik_qgp_pak;\n lik.fh.unpak = @lik_qgp_unpak;\n lik.fh.lp = @lik_qgp_lp;\n lik.fh.lpg = @lik_qgp_lpg;\n lik.fh.ll = @lik_qgp_ll;\n lik.fh.llg = @lik_qgp_llg; \n lik.fh.llg2 = @lik_qgp_llg2;\n lik.fh.llg3 = @lik_qgp_llg3;\n lik.fh.tiltedMoments = @lik_qgp_tiltedMoments;\n lik.fh.siteDeriv = @lik_qgp_siteDeriv;\n lik.fh.predy = @lik_qgp_predy;\n lik.fh.invlink = @lik_qgp_invlink;\n lik.fh.recappend = @lik_qgp_recappend;\n end\n\nend\n\nfunction [w s h] = lik_qgp_pak(lik)\n%LIK_QGP_PAK Combine likelihood parameters into one vector.\n%\n% Description\n% W = LIK_QGP_PAK(LIK) takes a likelihood structure LIK\n% and combines the parameters into a single row vector W.\n% This is a mandatory subfunction used for example in \n% energy and gradient computations.\n%\n% w = [ log(lik.sigma2)\n% (hyperparameters of lik.magnSigma2)]'\n% \n% See also\n% LIK_QGP_UNPAK\n\n w = []; s = {}; h=[];\n if ~isempty(lik.p.sigma2)\n w = [w log(lik.sigma2)];\n s = [s; 'log(qgp.sigma2)'];\n h = [h 0];\n % Hyperparameters of sigma2\n [wh, sh, hh] = lik.p.sigma2.fh.pak(lik.p.sigma2); \n w = [w wh];\n s = [s; sh];\n h = [h hh];\n end \n\nend\n\nfunction [lik, w] = lik_qgp_unpak(lik, w)\n%LIK_QGP_UNPAK Extract likelihood parameters from the vector.\n%\n% Description\n% W = LIK_QGP_UNPAK(W, LIK) takes a likelihood structure\n% LIK and extracts the parameters from the vector W to the LIK\n% structure. This is a mandatory subfunction used for example \n% in energy and gradient computations.\n%\n% Assignment is inverse of \n% w = [ log(lik.sigma2)\n% (hyperparameters of lik.magnSigma2)]'\n%\n% See also\n% LIK_QGP_PAK\n \n if ~isempty(lik.p.sigma2)\n lik.sigma2 = exp(w(1));\n w = w(2:end);\n \n % Hyperparameters of sigma2\n [p, w] = lik.p.sigma2.fh.unpak(lik.p.sigma2, w);\n lik.p.sigma2 = p;\n end\nend\n\nfunction lp = lik_qgp_lp(lik)\n%LIK_QGP_LP Evaluate the log prior of likelihood parameters\n%\n% Description\n% LP = LIK_QGP_LP(LIK) takes a likelihood structure LIK and\n% returns log(p(th)), where th collects the parameters. This\n% subfunction is needed when there are likelihood parameters.\n%\n% See also\n% LIK_QGP_PAK, LIK_QGP_UNPAK, LIK_QGP_G, GP_E\n\n lp = 0;\n\n if ~isempty(lik.p.sigma2)\n likp=lik.p;\n lp = likp.sigma2.fh.lp(lik.sigma2, likp.sigma2) + log(lik.sigma2);\n end\nend\n\nfunction lpg = lik_qgp_lpg(lik)\n%LIK_QGP_LPG Evaluate gradient of the log prior with respect\n% to the parameters.\n%\n% Description\n% LPG = LIK_QGP_LPG(LIK) takes a QGP likelihood\n% function structure LIK and returns LPG = d log (p(th))/dth,\n% where th is the vector of parameters. This subfunction is \n% needed when there are likelihood parameters.\n%\n% See also\n% LIK_QGP_PAK, LIK_QGP_UNPAK, LIK_QGP_E, GP_G\n\n lpg = [];\n\n if ~isempty(lik.p.sigma2)\n likp=lik.p;\n \n lpgs = likp.sigma2.fh.lpg(lik.sigma2, likp.sigma2);\n lpg = lpgs(1).*lik.sigma2 + 1;\n if length(lpgs) > 1\n lpg = [lpg lpgs(2:end)];\n end \n end\nend\n\nfunction ll = lik_qgp_ll(lik, y, f, z)\n%LIK_QGP_LL Log likelihood\n%\n% Description\n% LL = LIK_QGP_LL(LIK, Y, F, Z) takes a likelihood\n% structure LIK, observations Y and latent values F. \n% Returns the log likelihood, log p(y|f,z). This subfunction \n% is needed when using Laplace approximation or MCMC for \n% inference with non-Gaussian likelihoods. This subfunction \n% is also used in information criteria (DIC, WAIC) computations.\n%\n% See also\n% LIK_QGP_LLG, LIK_QGP_LLG3, LIK_QGP_LLG2, GPLA_E\n \n tau=lik.quantile;\n sigma=sqrt(lik.sigma2);\n ll = sum(log(tau*(1-tau)/sigma) - (y-f)./sigma.*(tau-(y<=f)));\nend\n\nfunction llg = lik_qgp_llg(lik, y, f, param, z)\n%LIK_QGP_LLG Gradient of the log likelihood\n%\n% Description \n% LLG = LIK_QGP_LLG(LIK, Y, F, PARAM) takes a likelihood\n% structure LIK, observations Y and latent values F. Returns \n% the gradient of the log likelihood with respect to PARAM. \n% At the moment PARAM can be 'param' or 'latent'. This subfunction \n% is needed when using Laplace approximation or MCMC for inference \n% with non-Gaussian likelihoods.\n%\n% See also\n% LIK_QGP_LL, LIK_QGP_LLG2, LIK_QGP_LLG3, GPLA_E\n\n \n tau=lik.quantile;\n sigma2=sqrt(lik.sigma2);\n switch param\n case 'param' \n llg = sum(-1/(2.*sigma2) + (y-f)./(2.*sigma2^(3/2)).*(tau-(y<=f)));\n \n % correction for the log transformation\n llg = llg.*lik.sigma2;\n case 'latent'\n llg = (tau-(y<=f))/sqrt(sigma2);\n end\nend\n\nfunction llg2 = lik_qgp_llg2(lik, y, f, param, z)\n%LIK_QGP_LLG2 Second gradients of the log likelihood\n%\n% Description \n% LLG2 = LIK_QGP_LLG2(LIK, Y, F, PARAM) takes a likelihood\n% structure LIK, observations Y and latent values F. Returns \n% the Hessian of the log likelihood with respect to PARAM. \n% At the moment PARAM can be 'param' or 'latent'. LLG2 is \n% a vector with diagonal elements of the Hessian matrix \n% (off diagonals are zero). This subfunction is needed \n% when using Laplace approximation or EP for inference \n% with non-Gaussian likelihoods.\n%\n% See also\n% LIK_QGP_LL, LIK_QGP_LLG, LIK_QGP_LLG3, GPLA_E\n\n \n tau=lik.quantile;\n sigma2=lik.sigma2;\n switch param\n case 'param'\n llg2 = sum(1/(2*sigma2^2) - 3.*(tau-(y<=f)).*(y-f)./(4.*sigma2^(5/2)));\n \n % correction due to the log transformation\n llg2 = llg2.*lik.sigma2;\n case 'latent'\n llg2 = zeros(size(f));\n case 'latent+param'\n llg2 = -(tau-(y<=f))./(2*sigma2^(3/2));\n \n % correction due to the log transformation\n llg2 = llg2.*lik.disper;\n end\nend \n\nfunction llg3 = lik_qgp_llg3(lik, y, f, param, z)\n%LIK_QGP_LLG3 Third gradients of the log likelihood\n%\n% Description\n% LLG3 = LIK_QGP_LLG3(LIK, Y, F, PARAM) takes a likelihood\n% structure LIK, observations Y and latent values F and \n% returns the third gradients of the log likelihood with \n% respect to PARAM. At the moment PARAM can be 'param' or \n% 'latent'. LLG3 is a vector with third gradients. This \n% subfunction is needed when using Laplace approximation for \n% inference with non-Gaussian likelihoods.\n%\n% See also\n% LIK_QGP_LL, LIK_QGP_LLG, LIK_QGP_LLG2, GPLA_E, GPLA_G\n\n tau=lik.quantile;\n sigma2=lik.sigma2;\n switch param\n case 'param'\n llg3 = sum(-1/sigma2^3 + 15.*(tau-(y<=f)).*(y-f)./(8.*sigma2^(7/2)));\n case 'latent'\n llg3 = 0;\n case 'latent2+param'\n llg3 = 0;\n \n % correction due to the log transformation\n llg3 = llg3.*lik.sigma2;\n end\nend\n\nfunction [logM_0, m_1, sigm2hati1] = lik_qgp_tiltedMoments(lik, y, i1, sigma2_i, myy_i, z)\n%LIK_QGP_TILTEDMOMENTS Returns the marginal moments for EP algorithm\n%\n% Description\n% [M_0, M_1, M2] = LIK_QGP_TILTEDMOMENTS(LIK, Y, I, S2,\n% MYY, Z) takes a likelihood structure LIK, observations\n% Y, index I and cavity variance S2 and mean MYY. Returns \n% the zeroth moment M_0, mean M_1 and variance M_2 of the \n% posterior marginal (see Rasmussen and Williams (2006): \n% Gaussian processes for Machine Learning, page 55). This \n% subfunction is needed when using EP for inference with \n% non-Gaussian likelihoods.\n%\n% See also\n% GPEP_E\n \n yy = y(i1);\n sigma2 = lik.sigma2;\n tau=lik.quantile;\n logM_0=zeros(size(yy));\n m_1=zeros(size(yy));\n sigm2hati1=zeros(size(yy));\n \n for i=1:length(i1)\n if isscalar(sigma2_i)\n sigma2_ii = sigma2_i;\n else\n sigma2_ii = sigma2_i(i);\n end\n \n % get a function handle of an unnormalized tilted distribution\n % (likelihood * cavity = Quantile-GP * Gaussian)\n % and useful integration limits\n [tf,minf,maxf]=init_qgp_norm(yy(i),myy_i(i),sigma2_ii,sigma2,tau);\n \n % Integrate with quadrature\n RTOL = 1.e-6;\n ATOL = 1.e-10;\n [m_0, m_1(i), m_2] = quad_moments(tf, minf, maxf, RTOL, ATOL);\n if isnan(m_0)\n logM_0=NaN;\n return\n end\n sigm2hati1(i) = m_2 - m_1(i).^2;\n \n % If the second central moment is less than cavity variance\n % integrate more precisely. Theoretically for log-concave\n % likelihood should be sigm2hati1 < sigm2_i.\n if sigm2hati1(i) >= sigma2_ii\n ATOL = ATOL.^2;\n RTOL = RTOL.^2;\n [m_0, m_1(i), m_2] = quad_moments(tf, minf, maxf, RTOL, ATOL);\n sigm2hati1(i) = m_2 - m_1(i).^2;\n if sigm2hati1(i) >= sigma2_ii\n error('lik_qgp_tilted_moments: sigm2hati1 >= sigm2_i');\n end\n end\n logM_0(i) = log(m_0);\n end\nend\n\nfunction [g_i] = lik_qgp_siteDeriv(lik, y, i1, sigm2_i, myy_i, z)\n%LIK_QGP_SITEDERIV Evaluate the expectation of the gradient\n% of the log likelihood term with respect\n% to the likelihood parameters for EP \n%\n% Description [M_0, M_1, M2] =\n% LIK_QGP_SITEDERIV(LIK, Y, I, S2, MYY, Z) takes a\n% likelihood structure LIK, observations Y, index I \n% and cavity variance S2 and mean MYY. Returns E_f \n% [d log p(y_i|f_i) /d a], where a is the likelihood \n% parameter and the expectation is over the marginal posterior.\n% This term is needed when evaluating the gradients of \n% the marginal likelihood estimate Z_EP with respect to \n% the likelihood parameters (see Seeger (2008):\n% Expectation propagation for exponential families).This \n% subfunction is needed when using EP for inference with \n% non-Gaussian likelihoods and there are likelihood parameters.\n%\n% See also\n% GPEP_G\n\n\n yy = y(i1);\n sigma2=lik.sigma2;\n tau=lik.quantile;\n \n % get a function handle of an unnormalized tilted distribution \n % (likelihood * cavity = Quantile-GP * Gaussian)\n % and useful integration limits\n [tf,minf,maxf]=init_qgp_norm(yy,myy_i,sigm2_i,sigma2,tau);\n % additionally get function handle for the derivative\n td = @deriv;\n \n % Integrate with quadgk\n [m_0, fhncnt] = quadgk(tf, minf, maxf);\n [g_i, fhncnt] = quadgk(@(f) td(f).*tf(f)./m_0, minf, maxf);\n g_i = g_i.*sigma2;\n\n function g = deriv(f)\n\n g = -1/(2.*sigma2) + (yy-f)./(2.*sigma2^(3/2)).*(tau-(yy<=f));\n \n end\nend\n\nfunction [lpy, Ey, Vary] = lik_qgp_predy(lik, Ef, Varf, yt, zt)\n%LIK_QGP_PREDY Returns the predictive mean, variance and density of y\n%\n% Description \n% LPY = LIK_QGP_PREDY(LIK, EF, VARF YT, ZT)\n% Returns logarithm of the predictive density PY of YT, that is \n% p(yt | zt) = \\int p(yt | f, zt) p(f|y) df.\n% This subfunction is needed when computing posterior predictive \n% distributions for future observations.\n%\n% [LPY, EY, VARY] = LIK_QGP_PREDY(LIK, EF, VARF) takes a\n% likelihood structure LIK, posterior mean EF and posterior\n% Variance VARF of the latent variable and returns the\n% posterior predictive mean EY and variance VARY of the\n% observations related to the latent variables. This \n% subfunction is needed when computing posterior predictive \n% distributions for future observations.\n% \n\n%\n% See also\n% GPLA_PRED, GPEP_PRED, GPMC_PRED\n\n\n sigma2=lik.sigma2;\n tau=lik.quantile;\n \n Ey=[];\n Vary=[];\n \n % Evaluate the posterior predictive densities of the given observations\n lpy = zeros(length(yt),1);\n if (size(Ef,2) > 1) && (size(Ef,2) > 1) && size(yt,2) == 1\n % Approximate integral with sum of grid points when using corrected\n % marginal posterior\n for i1=1:length(yt)\n py = arrayfun(@(f) exp(lik.fh.ll(lik, yt(i1), f, [])), Ef(i1,:));\n pf = Varf(i1,:)./sum(Varf(i1,:));\n lpy(i1) = log(sum(py.*pf));\n end\n else\n for i1=1:length(yt)\n % get a function handle of the likelihood times posterior\n % (likelihood * posterior = Quantile-GP * Gaussian)\n % and useful integration limits\n [pdf,minf,maxf]=init_qgp_norm(...\n yt(i1),Ef(i1),Varf(i1),sigma2, tau);\n % integrate over the f to get posterior predictive distribution\n lpy(i1) = log(quadgk(pdf, minf, maxf));\n end\n end\nend\n\n\nfunction [df,minf,maxf] = init_qgp_norm(yy,myy_i,sigm2_i,sigma2,tau)\n%INIT_QGP_NORM\n%\n% Description\n% Return function handle to a function evaluating\n% Quantile-GP * Gaussian which is used for evaluating\n% (likelihood * cavity) or (likelihood * posterior) Return\n% also useful limits for integration. This is private function\n% for lik_qgp. This subfunction is needed by subfunctions\n% tiltedMoments, siteDeriv and predy.\n% \n% See also\n% LIK_QGP_TILTEDMOMENTS, LIK_QGP_SITEDERIV,\n% LIK_QGP_PREDY\n \n sigma=sqrt(sigma2);\n% avoid repetitive evaluation of constant part\n ldconst = log(tau*(1-tau)/sigma) ...\n - log(sigm2_i)/2 - log(2*pi)/2;\n % Create function handle for the function to be integrated\n df = @qgp_norm;\n % use log to avoid underflow, and derivates for faster search\n ld = @log_qgp_norm;\n ldg = @log_qgp_norm_g;\n% ldg2 = @log_qgp_norm_g2;\n\n % Set the limits for integration\n % Quantile-GP likelihood is log-concave so the qgp_norm\n % function is unimodal, which makes things easier\n if yy==0\n % with yy==0, the mode of the likelihood is not defined\n % use the mode of the Gaussian (cavity or posterior) as a first guess\n modef = myy_i;\n else\n % use precision weighted mean of the Gaussian approximation\n % of the Quantile-GP likelihood and Gaussian\n modef = (myy_i/sigm2_i + yy/sigma2)/(1/sigm2_i + 1/sigma2);\n end\n % find the mode of the integrand using Newton iterations\n % few iterations is enough, since the first guess in the right direction\n niter=8; % number of Newton iterations \n \n minf=modef-6*sigm2_i;\n while ldg(minf) < 0\n minf=minf-2*sigm2_i;\n end\n maxf=modef+6*sigm2_i;\n while ldg(maxf) > 0\n maxf=maxf+2*sigm2_i;\n end\n for ni=1:niter\n% h=ldg2(modef);\n modef=0.5*(minf+maxf);\n if ldg(modef) < 0\n maxf=modef;\n else\n minf=modef;\n end\n end\n % integrand limits based on Gaussian approximation at mode\n minf=modef-6*sqrt(sigm2_i);\n maxf=modef+6*sqrt(sigm2_i);\n modeld=ld(modef);\n iter=0;\n % check that density at end points is low enough\n lddiff=20; % min difference in log-density between mode and end-points\n minld=ld(minf);\n step=1;\n while minld>(modeld-lddiff)\n minf=minf-step*sqrt(sigm2_i);\n minld=ld(minf);\n iter=iter+1;\n step=step*2;\n if iter>100\n error(['lik_qgp -> init_qgp_norm: ' ...\n 'integration interval minimun not found ' ...\n 'even after looking hard!'])\n end\n end\n maxld=ld(maxf);\n iter=0;\n step=1;\n while maxld>(modeld-lddiff)\n maxf=maxf+step*sqrt(sigm2_i);\n maxld=ld(maxf);\n iter=iter+1;\n step=step*2;\n if iter>100\n error(['lik_qgp -> init_qgp_norm: ' ...\n 'integration interval maximun not found ' ...\n 'even after looking hard!'])\n end\n end\n \n function integrand = qgp_norm(f)\n % Quantile-GP * Gaussian\n integrand = exp(ldconst ...\n -(yy-f)./sqrt(sigma2).*(tau-(yy<=f)) ...\n -0.5*(f-myy_i).^2./sigm2_i);\n end\n \n function log_int = log_qgp_norm(f)\n % log(Quantile-GP * Gaussian)\n % log_qgp_norm is used to avoid underflow when searching\n % integration interval\n log_int = ldconst...\n -(yy-f)./sqrt(sigma2).*(tau-(yy<=f)) ...\n -0.5*(f-myy_i).^2./sigm2_i;\n end\n \n function g = log_qgp_norm_g(f)\n % d/df log(Quantile-GP * Gaussian)\n % derivative of log_qgp_norm\n g = (tau-(yy<=f))/sqrt(sigma2) ...\n + (myy_i - f)./sigm2_i;\n end\n \n \nend\n\nfunction mu = lik_qgp_invlink(lik, f, z)\n%LIK_QGP_INVLINK Returns values of inverse link function\n% \n% Description \n% MU = LIK_QGP_INVLINK(LIK, F) takes a likelihood structure LIK and\n% latent values F and returns the values MU of inverse link function.\n% This subfunction is needed when using function gp_predprctmu.\n%\n% See also\n% LIK_QGP_LL, LIK_QGP_PREDY\n \n mu = f;\nend\n\nfunction reclik = lik_qgp_recappend(reclik, ri, lik)\n%RECAPPEND Append the parameters to the record\n%\n% Description \n% RECLIK = LIK_QGP_RECAPPEND(RECLIK, RI, LIK) takes a\n% likelihood record structure RECLIK, record index RI and\n% likelihood structure LIK with the current MCMC samples of\n% the parameters. Returns RECLIK which contains all the old\n% samples and the current samples from LIK. This subfunction\n% is needed when using MCMC sampling (gp_mc).\n% \n% See also\n% GP_MC\n\n if nargin == 2\n % Initialize the record\n reclik.type = 'Quantile-GP';\n\n % Initialize parameter\n reclik.sigma2 = []; \n\n % Set the function handles\n reclik.fh.pak = @lik_qgp_pak;\n reclik.fh.unpak = @lik_qgp_unpak;\n reclik.fh.lp = @lik_qgp_lp;\n reclik.fh.lpg = @lik_qgp_lpg;\n reclik.fh.ll = @lik_qgp_ll;\n reclik.fh.llg = @lik_qgp_llg; \n reclik.fh.llg2 = @lik_qgp_llg2;\n reclik.fh.llg3 = @lik_qgp_llg3;\n reclik.fh.tiltedMoments = @lik_qgp_tiltedMoments;\n reclik.fh.predy = @lik_qgp_predy;\n reclik.fh.invlink = @lik_qgp_invlink;\n reclik.fh.recappend = @lik_qgp_recappend;\n reclik.p=[];\n reclik.p.sigma2=[];\n if ~isempty(ri.p.sigma2)\n reclik.p.sigma2 = ri.p.sigma2;\n end\n else\n \n % Append to the record\n reclik.sigma2(ri,:)=lik.sigma2; \n if ~isempty(lik.p.sigma2)\n reclik.p.sigma2 = lik.p.sigma2.fh.recappend(reclik.p.sigma2, ri, lik.p.sigma2);\n end\n reclik.quantile = lik.quantile;\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/lik_qgp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5946196753234667}} {"text": "function [err_p,elerr_p] = diffpost_bc(aez,fez,elerror,xy,ev,ebound);\n%diffpost_bc postprocesses local Poisson error estimator \n% [err_p,elerr_p] = diffpost_bc(aez,fez,elerror,xy,ev,ebound);\n% input\n% aez elementwise Poisson problem matrices\n% fez elementwise rhs vectors\n% elerror elementwise error estimate (without BC imposition) \n% xy vertex coordinate vector \n% ev element mapping matrix\n% ebound element edge boundary matrix \n% output\n% err_p global error estimate \n% elerr_p elementwise error estimate\n% IFISS function: DJS; 4 March 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \n x=xy(:,1); y=xy(:,2);\n nel=length(ev(:,1));\n lev=[ev,ev(:,1)]; elerr_p=elerror;\n%\n% recompute contributions from elements with Dirichlet boundaries\n nbde=length(ebound(:,1));\n ebdy = zeros(nel,1);\n edge = zeros(nel,1);\n% isolate boundary elements\n for el = 1:nbde\n ee = ebound(el,1);\n ebdy(ee) = ebdy(ee)+1; edge(ee)=ebound(el,2);\n end \n%\n% two edge elements\n k2=find(ebdy==2);\n nel2b=length(k2);\n% loop over two edge elements\n for el = 1:nel2b\n el2e=k2(el);\n kk=find(ebound(:,1) == el2e);\n edges=ebound(kk,2);\n% set up original matrix and RHS vector\n\t ae=squeeze(aez(el2e,1:5,1:5)); \n fe=fez(el2e,:)';\n% set up local coordinates and impose interpolated error as Dirichlet bc\n xl=x(lev(el2e,:)); yl=y(lev(el2e,:)); \n [bae,fe] = localbc_p(ae,fe,edges,xl,yl);\n% solve local problem\n err=bae\\fe;\n elerr_p(el2e,1) = err'*fe;\n end\n% end of element loop\n%\n% one edge elements\n k1=find(ebdy==1);\n nel1b=length(k1);\n% loop over one edge elements\n for el = 1:nel1b\n el1e=k1(el);\n kk=find(ebound(:,1) == el1e);\n edges=ebound(kk,2);\n% set up original matrix and RHS vector \n fe=fez(el1e,:)';\n\t ae=squeeze(aez(el1e,1:5,1:5)); \n% set up local coordinates and impose interpolated error as Dirichlet bc\n xl=x(lev(el1e,:)); yl=y(lev(el1e,:));\n [bae,fe] = localbc_p(ae,fe,edges,xl,yl);\n% solve local problem\n err=bae\\fe;\n elerr_p(el1e,1) = err'*fe;\n end\n% end of element loop\n%\n err_p = sqrt(sum(elerr_p));\n elerr_p = sqrt(elerr_p);\n fprintf('done\\n')\n fprintf('estimated global error (in energy): %10.6e\\n',err_p) \n return\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms866/diffusion/diffpost_bc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.5946196642958376}} {"text": "function V = lumScotopic(imgXYZ)\n%\n% V = lumScotopic(imgXYZ)\n%\n% This function calculates the scotopic luminance\n%\n% input:\n% img: an image in the XYZ color space\n%\n% output:\n% V: scotopic luminance approximation by Larson, Rushmeier and Piatko 1997\n%\n% Copyright (C) 2011-14 Francesco Banterle\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n\ncheck3Color(imgXYZ);\n\neps = 1e-6;\nt = (imgXYZ(:,:,2) + imgXYZ(:,:,3)) ./ (imgXYZ(:,:,1) + eps);\nV = imgXYZ(:,:,2) .* (1.33 * (1.0 + t) - 1.68);\n\nend\n", "meta": {"author": "banterle", "repo": "HDR_Toolbox", "sha": "a2b45dc48b7169192fb633097a83879e71a0c0f2", "save_path": "github-repos/MATLAB/banterle-HDR_Toolbox", "path": "github-repos/MATLAB/banterle-HDR_Toolbox/HDR_Toolbox-a2b45dc48b7169192fb633097a83879e71a0c0f2/source_code/ColorSpace/lumScotopic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5944732054072215}} {"text": "function result = cross_entropy(head_embedding, tail_embedding, head, tail, weights, a, b, same_embedding)\n%CROSS_ENTROPY Given a distance for each 1-simplex in low-dimensional space\n% and the original weights of the 1-simplices in high-dimensional space,\n% compute the approximation to the cross-entropy between the two simplicial\n% complexes. This calculation uses the modified smooth formula Phi for\n% low-dimensional weight that is used in the stochastic gradient descent.\n%\n% result = cross_entropy(head_embedding, tail_embedding, head, tail, weights, a, b, same_embedding)\n%\n% Parameters\n% ----------\n% dists: array of size (n_1_simplices, 1)\n% The current distance between the two endpoints of the 1-simplex in\n% low-dimensional Euclidean space.\n%\n% weights: array of size (n_1_simplices, 1)\n% The original weights assigned to the 1-simplices in high-dimensional\n% space.\n%\n% a: double\n% Parameter of differentiable approximation of right adjoint functor.\n% \n% b: double\n% Parameter of differentiable approximation of right adjoint functor.\n% \n% Returns\n% -------\n% result: double\n% The total approximated cross entropy between the two simplicial complexes.\n%\n% See also: NEG_SAMPLING_OBJECTIVE\n%\n% AUTHORSHIP\n% Math Lead & Primary Developer: Connor Meehan \n% Secondary Developer: Stephen Meehan \n% Bioinformatics Lead: Wayne Moore \n% Provided by the Herzenberg Lab at Stanford University \n% License: BSD 3 clause\n%\n n1 = size(head_embedding, 1);\n n2 = size(tail_embedding, 1);\n \n if n1*n2 > 1e8\n error('HALTED: MATLAB usually freezes for embeddings this large.');\n end\n\n full_dists = pdist2(head_embedding, tail_embedding);\n full_weights = full(sparse(head, tail, weights, n1, n2));\n if same_embedding\n full_weights = full_weights + eye(n1);\n end\n Phi = ones(size(full_weights))./(1 + a*(full_dists.^(2*b)));\n fw0 = full_weights == 0;\n fw1 = full_weights == 1;\n other = ~fw0 & ~fw1;\n Phi_summands = zeros(size(full_weights));\n Phi_summands(fw0) = log(1-Phi(fw0));\n Phi_summands(fw1) = log(Phi(fw1));\n Phi_summands(other) = full_weights(other).*log(Phi(other)) + (1-full_weights(other)).*log(1-Phi(other));\n\n result = -sum(sum(Phi_summands));\nend", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/umap/umap/cross_entropy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5943676348496788}} {"text": "% input: rvqs0: r s in s0, v s in s0, q s0 2 s, note s0 is a fixed local\n% world frame, also called w-frame\n% rqs02e: rs0 in e, q s0 2 e, a, acceleration by IMU, w, angular rate by\n% gyro, dt, sample interval from the last measurement to the current\n% measurement.\n% gwomegaw, $g^w$, gravity in local world frame, 3-vector, and $w_{iw}^w$, 3-vector,\n% if all of them set 0, this amount to integration in inertial frame\n\nfunction rvqs0_new=strapdown_local_quat_bias(rvqs0, rqs02e, a, w, dt, gwomegaw)\nrvqs0_new=zeros(size(rvqs0));\ngs0=gwomegaw (1:3); % gravity in s0 frame\nwie2s0=gwomegaw (4:6);\n%Update attitude\n%% method (1) second order integration\nqe=rvec2quat_v000(wie2s0*dt);\nvr_a=quatmult_v000(rvqs0(7:10),qe);\nqb=rvec2quat_v000(-w*dt);\nrvqs0_new(7:10)=quatmult_v000(qb,vr_a);\n%% method (2) Runge-Kutta 4th order integration, empirically, this sometimes\n% gives worse result than second order integration\n% wie2s=quatrot_v000(rvqs0(7:10),wie2s0,0);\n% omega=zeros(4,2);\n% omega(1,2)=dt;\n% omega(2:4,1)=w-wie2s;\n% omega(2:4,2)=lastw-wie2s;\n% qs2s0=rotationRK4( omega, [rvqs0(7); -rvqs0(8:10)]);\n% rvqs0_new(7:10)=[qs2s0(1); -qs2s0(2:4)];\n\n%% better velocity and position integration than first order rectanglar rule\n%Update Velocity\nvel_inc1=(quatrot_v000(rvqs0(7:10),a*dt,1)+quatrot_v000(rvqs0_new(7:10),a*dt,1))/2;\nvel_inc2=(gs0+2*cross(rvqs0(4:6),wie2s0))*dt;\nrvqs0_new(4:6)=rvqs0(4:6)+vel_inc1+vel_inc2;\n%Update_pos\nrvqs0_new(1:3)=rvqs0(1:3)+(rvqs0(4:6)+rvqs0_new(4:6))*dt/2;\n", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/ekfmonoslam/propagation/strapdown_local_quat_bias.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011833, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5943676344916203}} {"text": "function [x, resvec, lsvec] = dense_overdetermined_lsqr(A, b, R, tol, maxit)\n% x = dense_overdetermined_lsqr(A, b, R, tol, maxit)\n% [x, resvec, lsvec] = dense_overdetermined_lsqr(A, b, R, tol, maxit)\n%\n% LSQR on a dense overdetermined matrix with a dense preconditioner R.\n% Solves x = arg min (A*x - b)\n% Inputs:\n% A, b\n% R - Upper triangular preconditioner. kappa(A * inv(R)) governs\n% the convergence.\n% tol - tolerance. Stop when \n% norm(inv(R') * A' * r) / (norm(A * inv(R), 'fro') * norm(r)) < tol\n% maxit - Maximum number of iterations\n% \n% Outputs:\n% x \n% optional: resvec, lsvec - values of norm(A' * r) and norm(r).\n%\n% 6-December 2009, Version 1.3\n% Copyright (C) 2009, Haim Avron and Sivan Toledo.\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/25241-blendenpik/blendenpik/dense_overdetermined_lsqr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5943460970361804}} {"text": "function q=qrdivide(q1,q2)\n%QRDIVIDE divdes two real quaternions q=[q1,q2]\n%\n% Inputs:\n%\n% q1(4,1), q2(4,1) Two real quaternions in the form [r, i, j, k]' where i^2=j^2=k^2=ijk=-1\n%\n% Outputs: \n%\n% q(4,1) Quotient of q1/q2 such that q1=q*q2.\n% Note that q*q2 ~= q2*q since quaternion multiplication does not commute.\n\n% Copyright (C) Mike Brookes 2000-2008\n% Version: $Id: qrdivide.m,v 1.1 2008/12/03 10:07:53 dmb Exp $\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%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\npersistent a b c d\nif isempty(a)\n a=[5 8 9 10 15 13];\n b=[6 7 11 12 14 16];\n c=[1 2 3 4 6 7 11 12 16 14];\n d=[1 2 3 4 5 8 9 10 13 15];\nend\nif nargin<2\n % just take the inverse of the only input argument\n q=q1/(q1'*q1);\n q(2:4)=-q(2:4);\nelse\n % invert q2 and do a multiply\n q=q2/(q2'*q2);\n q(2:4)=-q(2:4);\n t=q1*q.';\n s=zeros(4,4);\n s(a)=-t(b);\n s(c)=t(d);\n q=sum(s,2);\nend\n\n", "meta": {"author": "decouples", "repo": "Matlab_deep_learning", "sha": "1b823b82686080e32b03e1f1a4648896bd6e3c44", "save_path": "github-repos/MATLAB/decouples-Matlab_deep_learning", "path": "github-repos/MATLAB/decouples-Matlab_deep_learning/Matlab_deep_learning-1b823b82686080e32b03e1f1a4648896bd6e3c44/第 19 章 基于语音识别的信号灯图像模拟控制技术/voicebox/qrdivide.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5943163167262845}} {"text": "function diff_vol = dtiSmoothAnisoPM(vol, num_iter, delta_t, kappa, option, voxel_spacing)\n%ANISODIFF2D Conventional anisotropic diffusion\n% DIFF_VOL = ANISODIFF3D(VOL, NUM_ITER, DELTA_T, KAPPA, OPTION, VOXEL_SPACING) perfoms \n% conventional anisotropic diffusion (Perona & Malik) upon a stack of gray scale images.\n% A 3D network structure of 26 neighboring nodes is considered for diffusion conduction.\n% \n% ARGUMENT DESCRIPTION:\n% VOL - gray scale volume data (MxNxP).\n% NUM_ITER - number of iterations. \n% DELTA_T - integration constant (0 <= delta_t <= 3/44).\n% Usually, due to numerical stability this \n% parameter is set to its maximum value.\n% KAPPA - gradient modulus threshold that controls the conduction.\n% OPTION - conduction coefficient functions proposed by Perona & Malik:\n% 1 - c(x,y,z,t) = exp(-(nablaI/kappa).^2),\n% privileges high-contrast edges over low-contrast ones. \n% 2 - c(x,y,z,t) = 1./(1 + (nablaI/kappa).^2),\n% privileges wide regions over smaller ones.\n% VOXEL_SPACING - 3x1 vector column with the x, y and z dimensions of\n% the voxel (milimeters). In particular, only cubic and \n% anisotropic voxels in the z-direction are considered. \n% When dealing with DICOM images, the voxel spacing \n% dimensions can be extracted using MATLAB's dicominfo(.).\n% \n% OUTPUT DESCRIPTION:\n% DIFF_VOL - (diffused) volume with the largest scale-space parameter.\n% \n% Example\n% -------------\n% vol = randn(100,100,100);\n% num_iter = 4;\n% delta_t = 3/44;\n% kappa = 70;\n% option = 2;\n% voxel_spacing = ones(3,1);\n% diff_vol = anisodiff3D(vol, num_iter, delta_t, kappa, option, voxel_spacing);\n% figure, subplot 121, imshow(vol(:,:,50),[]), subplot 122, imshow(diff_vol(:,:,50),[])\n% \n% See also anisodiff1D, anisodiff2D.\n\n% References: \n% P. Perona and J. Malik. \n% Scale-Space and Edge Detection Using Anisotropic Diffusion.\n% IEEE Transactions on Pattern Analysis and Machine Intelligence, \n% 12(7):629-639, July 1990.\n% \n% G. Grieg, O. Kubler, R. Kikinis, and F. A. Jolesz.\n% Nonlinear Anisotropic Filtering of MRI Data.\n% IEEE Transactions on Medical Imaging,\n% 11(2):221-232, June 1992.\n% \n% MATLAB implementation based on Peter Kovesi's anisodiff(.):\n% P. D. Kovesi. MATLAB and Octave Functions for Computer Vision and Image Processing.\n% School of Computer Science & Software Engineering,\n% The University of Western Australia. Available from:\n% .\n% \n% Credits:\n% Daniel Simoes Lopes\n% ICIST\n% Instituto Superior Tecnico - Universidade Tecnica de Lisboa\n% danlopes (at) civil ist utl pt\n% http://www.civil.ist.utl.pt/~danlopes\n%\n% May 2007 original version.\n\n% Convert input volume to double.\nvol = double(vol);\n\n% Useful variables.\n[rows cols pags] = size(vol);\n\n% PDE (partial differential equation) initial condition.\ndiff_vol = vol;\nclear vol\n\n% Center voxel distances.\nx = voxel_spacing(1);\ny = voxel_spacing(2);\nz = voxel_spacing(3);\ndx = 1;\ndy = 1;\ndz = z/x;\ndd = sqrt(dx^2+dy^2);\ndh = sqrt(dx^2+dz^2);\ndc = sqrt(dd^2+dz^2);\n\n% 3D convolution masks - finite differences.\nh1 = zeros(3,3,3); h1(2,2,2) = -1; h1(2,2,1) = 1;\nh2 = zeros(3,3,3); h2(2,2,2) = -1; h2(2,2,3) = 1;\nh3 = zeros(3,3,3); h3(2,2,2) = -1; h3(2,1,2) = 1;\nh4 = zeros(3,3,3); h4(2,2,2) = -1; h4(2,3,2) = 1;\nh5 = zeros(3,3,3); h5(2,2,2) = -1; h5(3,2,2) = 1;\nh6 = zeros(3,3,3); h6(2,2,2) = -1; h6(1,2,2) = 1;\n\nh7 = zeros(3,3,3); h7(2,2,2) = -1; h7(3,1,1) = 1;\nh8 = zeros(3,3,3); h8(2,2,2) = -1; h8(2,1,1) = 1;\nh9 = zeros(3,3,3); h9(2,2,2) = -1; h9(1,1,1) = 1;\nh10 = zeros(3,3,3); h10(2,2,2) = -1; h10(3,2,1) = 1;\nh11 = zeros(3,3,3); h11(2,2,2) = -1; h11(1,2,1) = 1;\nh12 = zeros(3,3,3); h12(2,2,2) = -1; h12(3,3,1) = 1;\nh13 = zeros(3,3,3); h13(2,2,2) = -1; h13(2,3,1) = 1;\nh14 = zeros(3,3,3); h14(2,2,2) = -1; h14(1,3,1) = 1;\n\nh15 = zeros(3,3,3); h15(2,2,2) = -1; h15(3,1,2) = 1;\nh16 = zeros(3,3,3); h16(2,2,2) = -1; h16(1,1,2) = 1;\nh17 = zeros(3,3,3); h17(2,2,2) = -1; h17(3,3,2) = 1;\nh18 = zeros(3,3,3); h18(2,2,2) = -1; h18(1,3,2) = 1;\n\nh19 = zeros(3,3,3); h19(2,2,2) = -1; h19(3,1,3) = 1;\nh20 = zeros(3,3,3); h20(2,2,2) = -1; h20(2,1,3) = 1;\nh21 = zeros(3,3,3); h21(2,2,2) = -1; h21(1,1,3) = 1;\nh22 = zeros(3,3,3); h22(2,2,2) = -1; h22(3,2,3) = 1;\nh23 = zeros(3,3,3); h23(2,2,2) = -1; h23(1,2,3) = 1;\nh24 = zeros(3,3,3); h24(2,2,2) = -1; h24(3,3,3) = 1;\nh25 = zeros(3,3,3); h25(2,2,2) = -1; h25(2,3,3) = 1;\nh26 = zeros(3,3,3); h26(2,2,2) = -1; h26(1,3,3) = 1;\n\n% Anisotropic diffusion.\nfor t = 1:num_iter\n\n % Finite differences. [imfilter(.,.,'conv') can be replaced by convn(.,.,'same')]\n % Due to possible memory limitations, the diffusion\n % will be calculated at each page/slice of the volume.\n for p = 1:pags-2\n diff3pp = diff_vol(:,:,p:p+2);\n aux = imfilter(diff3pp,h1,'conv'); nabla1 = aux(:,:,2);\n aux = imfilter(diff3pp,h2,'conv'); nabla2 = aux(:,:,2);\n aux = imfilter(diff3pp,h3,'conv'); nabla3 = aux(:,:,2);\n aux = imfilter(diff3pp,h4,'conv'); nabla4 = aux(:,:,2);\n aux = imfilter(diff3pp,h5,'conv'); nabla5 = aux(:,:,2);\n aux = imfilter(diff3pp,h6,'conv'); nabla6 = aux(:,:,2);\n aux = imfilter(diff3pp,h7,'conv'); nabla7 = aux(:,:,2);\n aux = imfilter(diff3pp,h8,'conv'); nabla8 = aux(:,:,2);\n aux = imfilter(diff3pp,h9,'conv'); nabla9 = aux(:,:,2);\n aux = imfilter(diff3pp,h10,'conv'); nabla10 = aux(:,:,2);\n aux = imfilter(diff3pp,h11,'conv'); nabla11 = aux(:,:,2);\n aux = imfilter(diff3pp,h12,'conv'); nabla12 = aux(:,:,2);\n aux = imfilter(diff3pp,h13,'conv'); nabla13 = aux(:,:,2);\n aux = imfilter(diff3pp,h14,'conv'); nabla14 = aux(:,:,2);\n aux = imfilter(diff3pp,h15,'conv'); nabla15 = aux(:,:,2);\n aux = imfilter(diff3pp,h16,'conv'); nabla16 = aux(:,:,2);\n aux = imfilter(diff3pp,h17,'conv'); nabla17 = aux(:,:,2);\n aux = imfilter(diff3pp,h18,'conv'); nabla18 = aux(:,:,2);\n aux = imfilter(diff3pp,h19,'conv'); nabla19 = aux(:,:,2);\n aux = imfilter(diff3pp,h20,'conv'); nabla20 = aux(:,:,2);\n aux = imfilter(diff3pp,h21,'conv'); nabla21 = aux(:,:,2);\n aux = imfilter(diff3pp,h22,'conv'); nabla22 = aux(:,:,2);\n aux = imfilter(diff3pp,h23,'conv'); nabla23 = aux(:,:,2);\n aux = imfilter(diff3pp,h24,'conv'); nabla24 = aux(:,:,2);\n aux = imfilter(diff3pp,h25,'conv'); nabla25 = aux(:,:,2);\n aux = imfilter(diff3pp,h26,'conv'); nabla26 = aux(:,:,2);\n \n % Diffusion function.\n if option == 1\n c1 = exp(-(nabla1/kappa).^2);\n c2 = exp(-(nabla2/kappa).^2);\n c3 = exp(-(nabla3/kappa).^2);\n c4 = exp(-(nabla4/kappa).^2);\n c5 = exp(-(nabla5/kappa).^2);\n c6 = exp(-(nabla6/kappa).^2);\n c7 = exp(-(nabla7/kappa).^2);\n c8 = exp(-(nabla8/kappa).^2);\n c9 = exp(-(nabla9/kappa).^2);\n c10 = exp(-(nabla10/kappa).^2);\n c11 = exp(-(nabla11/kappa).^2);\n c12 = exp(-(nabla12/kappa).^2);\n c13 = exp(-(nabla13/kappa).^2);\n c14 = exp(-(nabla14/kappa).^2);\n c15 = exp(-(nabla15/kappa).^2);\n c16 = exp(-(nabla16/kappa).^2);\n c17 = exp(-(nabla17/kappa).^2);\n c18 = exp(-(nabla18/kappa).^2);\n c19 = exp(-(nabla19/kappa).^2);\n c20 = exp(-(nabla20/kappa).^2);\n c21 = exp(-(nabla21/kappa).^2);\n c22 = exp(-(nabla22/kappa).^2);\n c23 = exp(-(nabla23/kappa).^2);\n c24 = exp(-(nabla24/kappa).^2);\n c25 = exp(-(nabla25/kappa).^2);\n c26 = exp(-(nabla26/kappa).^2); \n elseif option == 2\n c1 = 1./(1 + (nabla1/kappa).^2);\n c2 = 1./(1 + (nabla2/kappa).^2);\n c3 = 1./(1 + (nabla3/kappa).^2);\n c4 = 1./(1 + (nabla4/kappa).^2);\n c5 = 1./(1 + (nabla5/kappa).^2);\n c6 = 1./(1 + (nabla6/kappa).^2);\n c7 = 1./(1 + (nabla7/kappa).^2);\n c8 = 1./(1 + (nabla8/kappa).^2);\n c9 = 1./(1 + (nabla9/kappa).^2);\n c10 = 1./(1 + (nabla10/kappa).^2);\n c11 = 1./(1 + (nabla11/kappa).^2);\n c12 = 1./(1 + (nabla12/kappa).^2); \n c13 = 1./(1 + (nabla13/kappa).^2);\n c14 = 1./(1 + (nabla14/kappa).^2);\n c15 = 1./(1 + (nabla15/kappa).^2);\n c16 = 1./(1 + (nabla16/kappa).^2);\n c17 = 1./(1 + (nabla17/kappa).^2);\n c18 = 1./(1 + (nabla18/kappa).^2); \n c19 = 1./(1 + (nabla19/kappa).^2);\n c20 = 1./(1 + (nabla20/kappa).^2);\n c21 = 1./(1 + (nabla21/kappa).^2);\n c22 = 1./(1 + (nabla22/kappa).^2);\n c23 = 1./(1 + (nabla23/kappa).^2);\n c24 = 1./(1 + (nabla24/kappa).^2); \n c25 = 1./(1 + (nabla25/kappa).^2);\n c26 = 1./(1 + (nabla26/kappa).^2); \n end\n\n % Discrete PDE solution.\n diff_vol(:,:,p+1) = diff_vol(:,:,p+1) + ...\n delta_t*(...\n (1/(dz^2))*c1.*nabla1 + (1/(dz^2))*c2.*nabla2 + ...\n (1/(dx^2))*c3.*nabla3 + (1/(dx^2))*c4.*nabla4 + ...\n (1/(dy^2))*c5.*nabla5 + (1/(dy^2))*c6.*nabla6 + ...\n ...\n (1/(dc^2))*c7.*nabla7 + (1/(dh^2))*c8.*nabla8 + ...\n (1/(dc^2))*c9.*nabla9 + (1/(dh^2))*c10.*nabla10 + ...\n (1/(dh^2))*c11.*nabla11 + (1/(dc^2))*c12.*nabla12 + ...\n (1/(dh^2))*c13.*nabla13 + (1/(dc^2))*c14.*nabla14 + ...\n ...\n (1/(dd^2))*c15.*nabla15 + (1/(dd^2))*c16.*nabla16 + ...\n (1/(dd^2))*c17.*nabla17 + (1/(dd^2))*c18.*nabla18 + ...\n ...\n (1/(dc^2))*c19.*nabla19 + (1/(dh^2))*c20.*nabla20 + ...\n (1/(dc^2))*c21.*nabla21 + (1/(dh^2))*c22.*nabla22 + ...\n (1/(dh^2))*c23.*nabla23 + (1/(dc^2))*c24.*nabla24 + ...\n (1/(dh^2))*c25.*nabla25 + (1/(dc^2))*c26.*nabla26);\n end\nend\n\nreturn;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrDiffusion/utils/dtiSmoothAnisoPM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5943163167262845}} {"text": "function [u, s, U_p, U_k, U_d] = pinHole(p,k,d)\n\n% PINHOLE Pin-hole camera model, with optional radial distortion.\n% U = PINHOLE(P) gives the projected pixel U of a point P in a canonical\n% pin-hole camera, that is, with calibration parameters\n% u0 = 0\n% v0 = 0\n% au = 1\n% av = 1\n% It uses reference frames {RDF,RD} (right-down-front for the 3D world\n% points and right-down for the pixel), according to this scheme:\n%\n% / z (forward)\n% /\n% +------- x +------- u\n% | |\n% | 3D : P=[x;y;z] | image : U=[u;v]\n% | y | v\n%\n% U = PINHOLE(P,K) allows the introduction of the camera's calibration\n% parameters:\n% K = [u0 v0 au av]'.\n%\n% U = PINHOLE(P,K,D) allows the introduction of the camera's radial\n% distortion parameters:\n% D = [K2 K4 K6 ...]'\n% so that the new pixel is distorted following the distortion equation:\n% U_D = U * (1 + K2*R^2 + K4*R^4 + ...)\n% with R^2 = sum(U.^2), being U the projected point in the image plane\n% for a camera with unit focal length.\n%\n% [U,S] = PINHOLE(...) returns the depth S from the camera center.\n%\n% If P is a points matrix, PINHOLE(P,...) returns a pixel matrix U and a\n% depths row-vector S. P, U and S are defined as\n% P = [P1 ... Pn]; Pi = [xi;yi;zi]\n% U = [U1 ... Un]; Ui = [ui;vi]\n% S = [S1 ... Sn]\n%\n% [U,S,U_p,U_k,U_d] returns the Jacobians of U wrt P, K and D. It only\n% works for single points P=[x;y;z].\n%\n% See also PERSP_PROJECT, DISTORT, PIXELLISE, INVPINHOLE, PINHOLEIDP, INVDISTORTION.\n\n% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\n% Point's depth\ns = p(3,:);\n\nif nargout <= 2 % only pixel\n\n switch nargin\n case 1\n u = persp_project(p);\n case 2\n u = pixellise(persp_project(p),k);\n case 3\n if ~isempty(d)\n u = pixellise(distort(persp_project(p),d),k);\n else\n u = pixellise(persp_project(p),k);\n end\n end\n\n\nelse % Jacobians\n\n if size(p,2) > 1\n error('Jacobians not available for multiple points')\n else\n\n switch nargin\n case 1\n [u, U_p] = persp_project(p);\n\n case 2\n [u1, U1_p] = persp_project(p);\n [u, U_u1, U_k] = pixellise(u1,k);\n U_p = U_u1*U1_p;\n\n case 3\n if ~isempty(d)\n [u1, U1_p] = persp_project(p);\n [u2, U2_u1, U2_d] = distort(u1,d);\n [u, U_u2, U_k] = pixellise(u2,k);\n U_d = U_u2*U2_d;\n U_p = U_u2*U2_u1*U1_p;\n else\n [u1, U1_p] = persp_project(p);\n [u, U_u1, U_k] = pixellise(u1,k);\n U_p = U_u1*U1_p;\n U_d = zeros(2,0);\n end\n\n end\n\n end\n\nend\n\nreturn\n\n%% jacobians\nsyms x y z u0 v0 au av d2 d4 d6 real\np = [x;y;z];\nk = [u0;v0;au;av];\nd = [d2;d4;d6];\n\n[u, s, U_p, U_k, U_d] = pinHole(p,k,d);\n\nsimplify(U_p - jacobian(u,p))\nsimplify(U_k - jacobian(u,k))\nsimplify(U_d - jacobian(u,d))\n\n\n\n% ========== End of function - Start GPL license ==========\n\n\n% # START GPL LICENSE\n\n%---------------------------------------------------------------------\n%\n% This file is part of SLAMTB, a SLAM toolbox for Matlab.\n%\n% SLAMTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% SLAMTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with SLAMTB. If not, see .\n%\n%---------------------------------------------------------------------\n\n% SLAMTB is Copyright:\n% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,\n% Copyright (c) 2010-2013, Joan Sola,\n% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,\n% SLAMTB is Copyright 2009 \n% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol\n% @ LAAS-CNRS.\n% See on top of this file for its particular copyright.\n\n% # END GPL LICENSE\n\n", "meta": {"author": "joansola", "repo": "slamtb", "sha": "b4767f6bf38bceed205abb85f1aed12422c9a972", "save_path": "github-repos/MATLAB/joansola-slamtb", "path": "github-repos/MATLAB/joansola-slamtb/slamtb-b4767f6bf38bceed205abb85f1aed12422c9a972/Observations/pinHole.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.5943163137122824}} {"text": "classdef Anodal2gausComputer < handle\n\n properties (Access = public)\n A_nodal_2_gauss\n end\n\n properties (Access = private)\n nnode\n nelem\n npnod\n ngaus\n connec\n shape\n end\n\n methods (Access = public)\n function obj = Anodal2gausComputer(cParams)\n obj.init(cParams);\n end\n\n function compute(obj)\n obj.computeA();\n end\n\n function intX = integrateP1FunctionWithShapeFunction(obj,cParams)\n ndof = size(obj.A_nodal_2_gauss{1},2);\n intX = zeros(ndof,1);\n for igaus = 1:obj.ngaus\n dVG = cParams.dV(:,igaus);\n xG = cParams.x(:,igaus);\n A = obj.A_nodal_2_gauss{igaus};\n intX = intX + A'*(xG.*dVG);\n end\n end\n end\n\n methods (Access = private)\n function init(obj,cParams)\n obj.nnode = cParams.nnode;\n obj.nelem = cParams.nelem;\n obj.npnod = cParams.npnod;\n obj.ngaus = cParams.ngaus;\n obj.connec = cParams.connec;\n obj.shape = cParams.shape;\n end\n\n function computeA(obj)\n A0 = sparse(obj.nelem,obj.npnod);\n A2g = cell(obj.ngaus,1);\n nodes = obj.connec;\n for igaus = 1:obj.ngaus\n A2g{igaus} = A0;\n for inode = 1:obj.nnode\n node = nodes(:,inode);\n shapeN = obj.shape(inode,igaus);\n Ni = ones(obj.nelem,1)*shapeN;\n A = sparse(1:obj.nelem,node,Ni,obj.nelem,obj.npnod);\n A2g{igaus} = A2g{igaus} + A;\n end\n end\n obj.A_nodal_2_gauss = A2g;\n end\n end\n\nend", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/Filters/Anodal2gausComputer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5942999999497646}} {"text": "function [model] = BCPF_MP(Y, varargin)\n% Bayesian CP Factorization using Gaussian Mixture Priors for Image Completion\n% Author : Qibin Zhao 2014\n%\n% -----------------------------------------------------------------------\n% [model] = BCPF_MP(Y, 'PARAM1', val1, 'PARAM2', val2, ...)\n%\n% INPUTS\n% Y - Input tensor\n% 'obs' - Binary (0-1) tensor indicating missing entries\n% (0: missing; 1: observed)\n% 'init' - Initialization method\n% - 'ml' : SVD initilization (default)\n% - 'rand': Random matrices\n% 'maxRank' - The initialization of rank (larger than true rank)\n% 'dimRed' - 1: Remove unnecessary components automaticly (default)\n% - 0: Not remove\n% 'maxiters' - max number of iterations (default: 100)\n% 'tol' - lower band change tolerance for convergence dection\n% (default: 1e-5)\n% 'noise' - whether noise is updated\n% - 'on': update noise parameter (default)\n% - 'off': fixed noise parameter (1e-5)\n% 'predVar' - Predictive distribution\n% - 1: compute and output\n% - 0: doesnot compute (default)\n% 'verbose' - visualization of results\n% - 0: no\n% - 1: text (default)\n% - 2: online display image\n% - 3: show factors by image\n% - 4: show factors by hinton plot (very slow)\n% OUTPUTS\n% model - Model parameters and hyperparameters\n% -----------------------------------------------------------------------\n%\n% Example:\n%\n% [model] = BCPF_MP(Y, 'obs', O, 'init', 'rand', 'maxRank', 10, 'dimRed', 1, 'maxiters', 100, ...\n% 'tol', 1e-6, 'verbose', 3);\n%\n% < Bayesian CP Factorization of Incomplete Image using Gaussian Mixture Priors >\n% Copyright (C) 2014 Qibin Zhao\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%%\nwarning off; %#ok\nrandn('state',1); rand('state',1); %#ok\ndimY = size(Y);\nN = ndims(Y);\n\n%% Set parameters from input or by using defaults\nip = inputParser;\nip.addParamValue('obs', ones(dimY), @(x) (isnumeric(x) || islogical(x)) );\nip.addParamValue('init', 'rand', @(x) (ismember(x,{'ml','rand'})));\nip.addParamValue('maxRank', max(dimY), @isscalar);\nip.addParamValue('maxiters', 100, @isscalar);\nip.addParamValue('tol', 1e-5, @isscalar);\nip.addParamValue('verbose', 1, @isscalar);\nip.addParamValue('noise', 'on', @(x)ismember(x,{'on','off'}));\nip.addParamValue('dimRed', 1, @isscalar);\nip.addParamValue('predVar', 0, @isscalar);\nip.addParamValue('nd', 1, @isscalar);\nip.parse(varargin{:});\n\nO = ip.Results.obs;\ninit = ip.Results.init;\nR = ip.Results.maxRank;\nmaxiters = ip.Results.maxiters;\ntol = ip.Results.tol;\nverbose = ip.Results.verbose;\nDIMRED = ip.Results.dimRed;\nnoise = ip.Results.noise;\npredVar = ip.Results.predVar;\nnd = ip.Results.nd;\n\n%% Initialization\nY = tensor(Y.*O);\nO = tensor(O);\nnObs = sum(O(:));\n\na_gamma0 = 1e-6;\nb_gamma0 = 1e-6;\nif strcmp(noise,'on')\n a_beta0 = 1e-6;\n b_beta0 = 1e-6;\nelse\n a_beta0 = 1e-1;\n b_beta0 = 1e-6;\nend\ngammas = ones(R,1);\nbeta = 1e4;\ndscale =1;\n\nW = cell(N,1);\nW1 = cell(N,1);\noR = nObs/prod(dimY);\nfor n=1:N\n W{n} = zeros(dimY(n),dimY(n));\n for i=1:dimY(n)\n for j=1:dimY(n)\n W{n}(i,j) = exp(-2*oR*abs(i-j)^2);\n end\n end\n W1{n} = W{n} - diag(diag(W{n}));\n W1{n} = nd*5*bsxfun(@times, W1{n}, 1./sum(W1{n},2));\nend\n\nswitch init,\n case 'ml' % Maximum likelihood\n Z = cell(N,1);\n ZSigma = cell(N,1);\n if ~isempty(find(O==0))\n % Y(find(O==0)) = sum(Y(:))/nObs;\n Y1 = Y;\n for n=1:N\n Y1 = ttm(Y1, W{n}, n);\n end\n Y(find(O==0)) = Y1(find(O==0));\n end\n for n = 1:N\n ZSigma{n} = (repmat(eye(R), [1 1 dimY(n)]));\n [U, S, V] = svd(double(tenmat(Y,n)), 'econ');\n if R <= size(U,2)\n Z{n} = U(:,1:R)*(S(1:R,1:R)).^(0.5);\n else\n Z{n} = [U*(S.^(0.5)) randn(dimY(n), R-size(U,2))];\n end\n end\n Y = Y.*O;\n case 'rand' % Random initialization\n Z = cell(N,1);\n ZSigma = cell(N,1);\n for n = 1:N\n Z{n} = rand(dimY(n),R);\n ZSigma{n} = (repmat(eye(R), [1 1 dimY(n)]));\n if n<3\n % Z{n} = cholcov(W{n})'*Z{n};\n Z{n} = Z{n} + W1{n}*Z{n};\n end\n end\nend\n\n% --------- E(aa') = cov(a,a) + E(a)E(a')----------------\nEZZT = cell(N,1);\nfor n=1:N\n EZZT{n} = (reshape(ZSigma{n}, [R*R, dimY(n)]))';\nend\n\nFit =0;\nLB = 0;\nX = double(ktensor(Z));\n\n%% Create figures\nif verbose >2,\n scrsz = get(0,'ScreenSize');\n h1 = figure('Position',[scrsz(3)*0.2 scrsz(4)*0.3 scrsz(3)*0.6 scrsz(4)*0.4]);\n figure(h1);\n switch verbose,\n case 4,\n subplot(2,3,1); hintonDiagram(Z{1}); title('Mode-1'); ylabel('Length of #-mode');\n subplot(2,3,2); hintonDiagram(Z{2}); title('Mode-2'); xlabel('Latent dimensions');\n if N>=3, subplot(2,3,3); hintonDiagram(Z{3}); title('Mode-3'); end\n case 3,\n subplot(2,3,1); imagesc(Z{1}); title('Mode-1'); ylabel('Length of #-mode');\n subplot(2,3,2); imagesc(Z{2}); title('Mode-2'); xlabel('Latent dimensions');\n if N>=3, subplot(2,3,3); imagesc(Z{3}); title('Mode-3');end\n end\n subplot(2,3,4); bar(gammas); title('Posterior mean of \\lambda'); xlabel('Latent components'); ylabel(''); axis tight;\n subplot(2,3,5); plot(LB, '-r.','LineWidth',1.5,'MarkerSize',10 ); title('Lower bound'); xlabel('Iteration'); grid on;\n subplot(2,3,6); plotGamma(a_beta0, a_beta0); title('Posterior pdf'); xlabel('Noise precision \\tau');grid on;\n set(findall(h1,'type','text'),'fontSize',12);\n drawnow;\nend\nif verbose ==2;\n h3 = figure;\n temp = 255.*(X-min(X(:)))/(max(X(:))-min(X(:)));\n imshow(uint8(temp));\n title(['Iter.= ' num2str(0),', Rank = ' num2str(R)],'FontSize', 13, 'color','b');\n tic;\n xlabel(['(BCPF-MP) Time: ' num2str(round(toc)), ' seconds'],'FontSize', 13, 'color','b');\n drawnow;\nend\n\n%% Model learning\nfor it=1:maxiters,\n %% Update factor matrices\n Aw = diag(gammas);\n for n=1:N\n % compute E(Z_{\\n}^{T} Z_{\\n})\n ENZZT = reshape(khatrirao_fast(EZZT{[1:n-1, n+1:N]},'r')' * double(tenmat(O,n)'), [R,R,dimY(n)]);\n % compute E(Z_{\\n})\n FslashY = khatrirao_fast(Z{[1:n-1, n+1:N]},'r')' * tenmat(Y.*O, n)';\n for i=1:dimY(n)\n ZSigma{n}(:,:,i) = (beta * ENZZT(:,:,i) + Aw )^(-1);\n Z{n}(i,:) = (beta * ZSigma{n}(:,:,i) * FslashY(:,i))';\n end\n if n<3\n Z{n} = Z{n} + W1{n}*Z{n};\n end\n EZZT{n} = (reshape(ZSigma{n}, [R*R, dimY(n)]) + khatrirao_fast(Z{n}',Z{n}'))';\n end\n \n %% Update latent tensor X\n X = double(ktensor(Z));\n \n %% Update hyperparameters gamma\n a_gammaN = (0.5*sum(dimY) + a_gamma0)*ones(R,1);\n b_gammaN = 0;\n for n=1:N\n b_gammaN = b_gammaN + diag(Z{n}'*Z{n}) + diag(sum(ZSigma{n},3));\n end\n b_gammaN = b_gamma0 + 0.5.* b_gammaN;\n gammas = a_gammaN./b_gammaN;\n \n %% update noise beta\n % The most time and space consuming part\n if 0 % save time but large space needed\n EX2 = O(:)' * khatrirao_fast(EZZT,'r') * ones(R*R,1);\n else % save space but slow\n temp1 = cell(N,1);\n EX2 =0;\n for i =1:R\n for n=1:N\n temp1{n} = EZZT{n}(:,(i-1)*R+1: i*R);\n end\n EX2 = EX2 + O(:)' * khatrirao_fast(temp1,'r')* ones(R,1);\n end\n end\n err = Y(:)'*Y(:) - 2*Y(:)'*X(:) + EX2;\n if strcmp(noise,'on')\n a_betaN = a_beta0 + 0.5*nObs;\n b_betaN = b_beta0 + 0.5*err;\n else\n a_betaN = a_beta0;\n b_betaN = b_beta0;\n end\n beta = a_betaN/b_betaN;\n Fit = 1 - sqrt(sum(err(:)))/norm(Y(:));\n \n %% Lower bound\n temp1 = -0.5*nObs*safelog(2*pi) + 0.5*nObs*(psi(a_betaN)-safelog(b_betaN)) - 0.5*(a_betaN/b_betaN)*err;\n temp22 =0;\n for n=1:N\n temp22= temp22 + Z{n}'*Z{n} + sum(ZSigma{n},3);\n end\n temp2 = -0.5*R*sum(dimY)*safelog(2*pi) + 0.5*sum(dimY)*sum(psi(a_gammaN)-safelog(b_gammaN)) -0.5*trace(diag(gammas)* temp22);\n temp3 = sum(-safelog(gamma(a_gamma0)) + a_gamma0*safelog(b_gamma0) - b_gamma0.*(a_gammaN./b_gammaN) + (a_gamma0-1).*(psi(a_gammaN)-safelog(b_gammaN)));\n temp4 = -safelog(gamma(a_beta0)) + a_beta0*safelog(b_beta0) + (a_beta0-1)*(psi(a_betaN)-safelog(b_betaN)) - b_beta0*(a_betaN/b_betaN);\n temp5=0;\n for n=1:N\n for i=1:size(ZSigma{n},3)\n temp5 = temp5 + 0.5*safelog(det(ZSigma{n}(:,:,i))) + 0.5*R*(1+safelog(2*pi));\n end\n end\n temp6 = sum(safelog(gamma(a_gammaN)) - (a_gammaN-1).*psi(a_gammaN) -safelog(b_gammaN) + a_gammaN);\n temp7 = safelog(gamma(a_betaN)) - (a_betaN-1)*psi(a_betaN) -safelog(b_betaN) + a_betaN;\n LB(it) = temp1 + temp2 + temp3 + temp4 + temp5 + temp6 + temp7;\n \n %% Prune irrelevant dimensions?\n Zall = cell2mat(Z);\n comPower = diag(Zall' * Zall);\n comTol = sum(dimY)*eps(norm(Zall,'fro'));\n rankest = sum(comPower> comTol );\n if max(rankest)==0\n disp('Rank becomes 0 !!!');\n break;\n end\n if DIMRED==1 && it >=2,\n if R~= max(rankest)\n indices = comPower > comTol;\n gammas = gammas(indices);\n temp = ones(R,R);\n temp(indices,indices) = 0;\n temp = temp(:);\n for n=1:N\n Z{n} = Z{n}(:,indices);\n ZSigma{n} = ZSigma{n}(indices,indices,:);\n EZZT{n} = EZZT{n}(:, temp == 0);\n end\n R = max(rankest);\n end\n end\n \n %% Display progress\n if it>2\n LBRelChan = abs(LB(it) - 2*LB(it-1) + LB(it-2))/-LB(2);\n else\n LBRelChan = NaN;\n end\n if verbose,\n fprintf('Iter. %d: RelChan = %g, Fit = %g, R = %d \\n', it, LBRelChan, Fit, rankest);\n end\n \n %% visualize online results\n if verbose >2 ,\n switch verbose,\n case 4,\n set(0,'CurrentFigure',h1);\n subplot(2,3,1); hintonDiagram(Z{1}); title('Mode-1'); ylabel('Length of #-mode');\n subplot(2,3,2); hintonDiagram(Z{2}); title('Mode-2'); xlabel('Latent dimensions');\n if N>=3, subplot(2,3,3); hintonDiagram(Z{3}); title('Mode-3'); end\n case 3,\n set(0,'CurrentFigure',h1);\n subplot(2,3,1); imagesc(Z{1}); title('Mode-1'); ylabel('Length of #-mode');\n subplot(2,3,2); imagesc(Z{2}); title('Mode-2'); xlabel('Latent dimensions');\n if N>=3, subplot(2,3,3); imagesc(Z{3}); title('Mode-3'); end\n end\n subplot(2,3,4); bar(gammas); title('Posterior mean of \\lambda'); xlabel('Latent components'); ylabel(''); axis tight;\n subplot(2,3,5); plot(LB, '-r.','LineWidth',1.5,'MarkerSize',10 ); title('Lower bound'); xlabel('Iteration'); grid on;\n subplot(2,3,6); plotGamma(a_betaN, b_betaN); title('Posterior pdf'); xlabel('Noise precision \\tau');grid on;\n set(findall(h1,'type','text'),'fontSize',12);\n drawnow;\n end\n if verbose==2\n set(0,'CurrentFigure',h3);\n figure(h3);\n % temp = (X-min(X(:)))/(max(X(:))-min(X(:)));\n % image(temp);\n % axis off;\n imshow(uint8(X));\n title(['Iter.= ' num2str(it),', Rank = ' num2str(max(rankest))],'FontSize', 13, 'color','b');\n xlabel(['(BCPF-MP) Time: ' num2str(round(toc)), ' seconds'],'FontSize', 13, 'color','b');\n drawnow;\n end\n \n %% Convergence check\n if it>5 && abs(LBRelChan) < tol\n disp('\\\\\\======= Converged===========\\\\\\');\n break;\n end\nend\n\n%% Predictive distribution\nif predVar==1\n Xvar = tenzeros(size(Y));\n for n=1:N\n Xvar = tenmat(Xvar,n);\n Fslash = khatrirao_fast(Z{[1:n-1, n+1:N]},'r');\n if 1\n temp1 = double(tenmat(tensor(ZSigma{n}),3));\n temp2 = khatrirao_fast(Fslash', Fslash');\n Xvar(:,:) = Xvar(:,:) + temp1*temp2;\n else\n % --- slow computation ------\n for i=1:size(Xvar,1) %#ok\n Xvar(i,:) = Xvar(i,:) + diag(Fslash * ZSigma{n}(:,:,i) *Fslash')';\n end\n % --- slow computation ------\n end\n Xvar = tensor(Xvar);\n end\n Xvar = Xvar + beta^(-1);\n Xvar = Xvar.*(2*a_betaN)/(2*a_betaN-2);\n Xvar = Xvar.*(dscale^2);\nelse\n Xvar =[];\nend\n\n%% Prepare the results\nSNR = 10*log10(var(X(:))*beta);\nX = ktensor(Z)*dscale;\nX = arrange(X);\n\n%% Output\nmodel.X = X;\nmodel.ZSigma = ZSigma;\nmodel.gammas = gammas;\nmodel.Fit = Fit;\nmodel.SNR = SNR;\nmodel.Xvar = double(Xvar);\nmodel.TrueRank = rankest;\nmodel.LowBound = max(LB);\n\n\nfunction y = safelog(x)\nx(x<1e-300)=1e-200;\nx(x>1e300)=1e300;\ny=log(x);\n\n", "meta": {"author": "andrewssobral", "repo": "mctc4bmi", "sha": "fbcbcd25654b818646387c3d6a64304fb60e12dd", "save_path": "github-repos/MATLAB/andrewssobral-mctc4bmi", "path": "github-repos/MATLAB/andrewssobral-mctc4bmi/mctc4bmi-fbcbcd25654b818646387c3d6a64304fb60e12dd/algs_tc/BCPF/Algorithms/BCPF_MP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7025300698514778, "lm_q1q2_score": 0.5942999941154927}} {"text": "function eclipVec=ICRS2Eliptic(vec,TT1,TT2,method)\n%%ICRS2ECLIPTIC Convert a location vector from the International\n% Celestial Reference System (ICRS) to eliptic coordinates\n% either using the IAU 2006 precession model or the Vondrak\n% 400 millennia precession model.\n%\n%INPUTS: x The NXnumVec collection of vectors in the ICRS to convert. N\n% can be 2, or 3. If the vectors are 2D, then they are assumed to\n% be azimuth and elevation in radians. 3D vectors are assumed to\n% be Cartesian position.\n% Jul1, Jul2 Two parts of a Julian date given in terrestrial time (TT).\n% The units of the date are days. The full date is the sum of\n% both terms. The date is broken into two parts to provide more\n% bits of precision. It does not matter how the date is split.\n% method An optional parameter specifying which algorithm is to be used.\n% Possible values are\n% 0 (The default if omitted or an empty matrix is passed) Use the\n% IAU 2006 precession model.\n% 1 Use the long-term (Vondrak) precession model.\n%\n%OUTPUTS: xG The vectors rotated into the ecliptic coordinate system. If\n% the input was 2D azimuth and elevation, the output will be\n% the same. If the input was Cartesian, then the output will be\n% Cartesian.\n%\n%This function is a Matlab interface for the relevant functions in the\n%International Astronomical Union's (IAU) Standard's of Fundamental\n%Astronomy library.\n%\n%The ecliptic is defined in the IERS Conventions [1] to be the \"the\n%plane perpendicular to the mean heliocentric orbital angular momentum\n%vector of the Earth-Moon barycentre in the BCRS\".\n%\n%The algorithm can be compiled for use in Matlab using the\n%CompileCLibraries function.\n%\n%The algorithm is run in Matlab using the command format\n%eclipVec=ICRS2Eliptic(vec,TT1,TT2,method);\n%\n%REFERENCES:\n%[1] G. Petit and B. Luzum, IERS Conventions (2010), International Earth\n% Rotation and Reference Systems Service Std. 36, 2010.\n%\n%July 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nerror('This function is only implemented as a mexed C or C++ function. Please run CompileCLibraries.m to compile the function for use.')\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Coordinate_Systems/Celestial_and_Terrestrial_Systems/ICRS2Eliptic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424334245618, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5942999810381523}} {"text": "function [I1,wl1,rgb1,g,H1,extra,s,G,S] = estimate_PSF_SRF(I,wl,bbl,rgb,s,extra,options)\n%ESTIMATE_PSF_SRF Estimate point spread function (PSF) and spectral \n%response function (SRF)\ndisp('Start estimating PSF and SRF');\nshow_fig = parse_param(options,'show_fig',0);\n\nI1 = I(:,:,bbl);\nwl1 = wl(bbl);\nrgb1 = rgb;\n\nY = reshape_hsi(I1);\nX = reshape(rgb1, [size(rgb1,1)*size(rgb1,2), size(rgb1,3)]);\n[N,B] = size(Y);\nb = size(X,2);\nR2 = s + extra*2;\nR = prod(R2);\n\nconvergence_t = 1e-3;\n\nSRF_range = parse_param(options,'SRF_range','color');\n% construct S\n[I_sel,bands_sel] = select_relevant_bands(I1,wl1,SRF_range);\nwl_sel = wl1(bands_sel)';\nS = zeros(B,length(wl_sel));\nfor i = 1:size(S,2)\n S(bands_sel(i),i) = 1;\nend\n\n% construct C\nCs = construct_C(I1,rgb1,s,extra);\nC = cat(2,Cs{:});\n\nY1 = [ones(N,1),Y*S];\n\n% construct D\nD = zeros(N*b,R);\nfor i = 1:N\n D((i-1)*b+1:i*b,:) = X'*Cs{i}';\nend\n\n% contruct options\noptions = [];\noptions.D = D;\noptions.Y1 = Y1;\noptions.D1D = D'*D;\noptions.D1YI = D'*kron(Y1,eye(b));\n\ng = (1/R) * ones(R,1);\nG = g2G(C,g,N);\n\n\ndelta_t0 = 1e-4;\ndelta_t_g = delta_t0;\n\nerrors = [];\nfor iter = 1:200\n % Update H1\n H1 = solve_for_H1(G*X, Y1, struct('lambda',1e-4));\n options.H1 = H1;\n \n % Update G\n der_g = calc_der_g(g, options);\n options.der_g = der_g;\n delta_t_g = calc_time_step_adaptive(@eval_obj_fun_g, @update_g, ...\n g, options, delta_t_g, delta_t0);\n g = update_g(g, options, delta_t_g);\n options.g = g;\n G = g2G(C,g,N);\n \n % Test convergence\n errors(end+1) = eval_obj_fun(options);\n\n if test_convergence(errors, convergence_t)\n break;\n end\n \n if mod(iter,100) == 0\n disp(['Process iteration ',num2str(iter)]);\n end\nend\n\nif show_fig\n figure('name','PSF'), mesh(reshape(g,R2));\n figure('name','SRF'), plot(H1);\nend\n\nfunction der_g = calc_der_g(g, options)\nvecH1 = (options.H1)';\nvecH1 = vecH1(:);\nder_g = options.D1D * g - options.D1YI * vecH1;\n\nfunction val = eval_obj_fun_g(g, options)\nvecYH = options.Y1 * options.H1;\nvecYH = vecYH';\nvecYH = vecYH(:);\nval = sum((options.D * g - vecYH).^2);\n\nfunction g_new = update_g(g, options, delta_t)\nder_g = options.der_g;\n\ng_new = g - delta_t * der_g;\ng_new = project_to_simplex(g_new');\ng_new = g_new';\n\nfunction val = eval_obj_fun(options)\ng = options.g;\nval = eval_obj_fun_g(g,options);\n\n", "meta": {"author": "zhouyuanzxcv", "repo": "Hyperspectral", "sha": "f32dcca86677f8d37596376f57e9c733058f8cff", "save_path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral", "path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral/Hyperspectral-f32dcca86677f8d37596376f57e9c733058f8cff/Fusion/estimate_PSF_SRF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5942876843044061}} {"text": "%GM_PHD_Construct_Update_Components\n%Last modified 12th September 2013\n%Matlab code by Bryan Clarke b.clarke@acfr.usyd.edu.au \n\n%This file creates the components needed for performing a Kalman filter update on the\n%targets using the measurement.\ns = sprintf('Step 3: Constructing update components for all targets, new and existing.');\ndisp(s);\n\n%We need to clear the data structures each iteration\neta = [];\nS = [];\nK = [];\nP_k_k = [];\n\nfor j = 1:numTargets_Jk_k_minus_1\n m_j = mk_k_minus_1(:,j);\n eta_j = H2 * m_j;%Observation model. Assume we see position AND velocity of the target.\n\n P_range = calculateDataRange4(j); %4x4 array\n\n PHt = Pk_k_minus_1(:,P_range) * H2'; %Taken from Tim Bailey's EKF code. 4x4 array\n\n %Calculate K via Tim Bailey's method.\n S_j = R2 + H2 * PHt;\n %At this point, Tim Bailey's code makes S_j symmetric. In this case, it leads to the matrix being non-positive definite a lot of the time and chol() crashes.\n %So we won't do that. \n SChol= chol(S_j);\n\n SCholInv= SChol \\ eye(size(SChol)); % triangular matrix, invert via left division\n W1 = PHt * SCholInv;\n\n K_j = W1 * SCholInv';\n\n P_j = Pk_k_minus_1(:,P_range) - W1*W1';%4x4 array\n %End Tim Bailey's code.\n \n eta = [eta, eta_j];\n S = [S, S_j];\n K = [K, K_j];\n P_k_k = [P_k_k, P_j]; \nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/42769-gaussian-mixture-probability-hypothesis-density-filter-gm-phd/GM_PHD_Filter_v104/GM_PHD_Filter/GM_PHD_Construct_Update_Components.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5942050553755988}} {"text": "function [kernel, S] = dat2Kernel(data, kSize)\n% kernel = dat2Kernel(data, kSize,thresh)\n%\n% Function to perform k-space calibration step for ESPIRiT and create\n% k-space kernels. Only works for 2D multi-coil images for now. \n% \n% Inputs: \n% data - calibration data [kx,ky,coils]\n% kSize - size of kernel (for example kSize=[6,6])\n%\n% Outputs: \n% kernel - k-space kernels matrix (not cropped), which correspond to\n% the basis vectors of overlapping blocks in k-space\n% S - (Optional parameter) The singular vectors of the\n% calibration matrix\n%\n%\n% See also:\n% kernelEig\n%\n% (c) Michael Lustig 2013\n\n\n\n[sx,sy,nc] = size(data);\nimSize = [sx,sy] ;\n\ntmp = im2row(data,kSize); [tsx,tsy,tsz] = size(tmp);\nA = reshape(tmp,tsx,tsy*tsz);\n\n[U,S,V] = svd(A,'econ');\n \nkernel = reshape(V,kSize(1),kSize(2),nc,size(V,2));\nS = diag(S);S = S(:);\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/utils/utils_ESPIRiT/dat2Kernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355092, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5941939786879332}} {"text": "function r = exp(a)\n%EXP Taylor exponential exp(a)\n%\n\n% written 05/21/09 S.M. Rump\n% modified 08/26/12 S.M. Rump global variables removed\n%\n\n e = 1e-30;\n if 1+e==1-e % fast check for rounding to nearest\n rndold = 0;\n else\n rndold = getround;\n setround(0)\n end\n\n K1 = getappdata(0,'INTLAB_TAYLOR_ORDER') + 1;\n \n r = a;\n N = size(a.t,2);\n r.t(1,:) = exp(a.t(1,:));\n for j=2:K1\n r.t(j,:) = sum( repmat((1:j-1)',1,N).*r.t(j-1:-1:1,:).*a.t(2:j,:) , 1 ) ./ (j-1);\n end\n\n if rndold\n setround(rndold)\n end\n", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/toolboxes/Intlab_V7.1/taylor/@taylor/exp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5941479382712797}} {"text": "% [func, fx] = mcmc_init_hamiltonian(x_init, get_logpdf, get_dlogpdf, ...\n% epsilon, L, func_x)\n%\n% epsilon is the parameter to the exponential distribution for sampling\n% the momentum\n%\n% L is the number of simulation steps\nfunction [func, fx] = mcmc_init_hamiltonian(x_init, get_logpdf, get_dlogpdf, ...\n epsilon, L, func_x)\n\nif nargin < 6\n func_x = @func_x_default;\nend\n\nx_current = x_init;\n[fx_current, dfx_current] = func_x(x_current);\nlogpdf_current = get_logpdf(fx_current);\ndlogpdf_current = get_dlogpdf(dfx_current);\n\nfunc = @hamiltonian;\nfx = fx_current;\n\n function [x, fx] = hamiltonian(varargin)\n \n x = x_current;\n \n p = normrnd(0,1,size(x_current));\n p_current = p;\n \n lp_current = logpdf_current(varargin{:});\n dlp_current = dlogpdf_current(varargin{:});\n \n% $$$ mycheckgrad(@chkgrad, x, 1e-6)\n% $$$ \n% $$$ function [y,dy] = chkgrad(x)\n% $$$ [fx, dfx] = func_x(x);\n% $$$ f = get_logpdf(fx);\n% $$$ df = get_dlogpdf(dfx);\n% $$$ y = f(varargin{:});\n% $$$ dy = df(varargin{:});\n% $$$ end\n\n % Random step size\n e = exprnd(epsilon);\n \n % Make a half step for momentum at the beginning\n p = p + 0.5*e*dlp_current;\n \n for l=1:L\n x = x + e * p;\n \n if any(isnan(x))\n break;\n end\n \n [fx, dfx] = func_x(x);\n dlogpdf = get_dlogpdf(dfx);\n dlp = dlogpdf(varargin{:});\n if l < L\n p = p + e * dlp;\n else\n logpdf = get_logpdf(fx);\n lp = logpdf(varargin{:});\n end\n end\n \n if all(~isnan(x))\n\n % Make a half step for momentum at the end\n p = p + 0.5*e*dlp;\n \n % Negate momentum to make the proposal symmetric\n p = -p;\n \n \n if log(rand()) < ( (lp - 0.5*(p'*p)) - ...\n (lp_current - 0.5*(p_current'*p_current)) )\n % Accept\n disp('Accept hamiltonian')\n x_current = x;\n fx_current = fx;\n dfx_current = dfx;\n logpdf_current = logpdf;\n dlogpdf_current = dlogpdf;\n else\n disp('Reject hamiltonian')\n end\n \n else\n disp('Reject hamiltonian')\n end\n \n x = x_current;\n fx = fx_current;\n end\n \n \nend\n\nfunction [fx, dfx] = func_x_default(x)\nfx = x;\ndfx = x;\nend\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/mcmc/mcmc_init_hamiltonian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438126, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5940962560242194}} {"text": "%Normalizes homogenous coordinates such that the last coordinate is 1\n%You can use any dimension of the vectors\n%\n%Author: Christian Wengert, \n% Institute of Computer Vision\n% Swiss Federale Institute of Technology, Zurich (ETHZ)\n% wengert@vision.ee.ethz.ch\n% www.vision.ee.ethz.ch/~cwengert/\n%\n%Input: x unnormalized homogenous coordinates\n%\n%Output y normalized homogenous coordinates\n%\n%Syntax: y = normalizeHomogenousCoordinates(x)\n\nfunction y = normalizeHomogenousCoordinates(x)\n\n %get dimension of array\n ni = size(x,1);\n nj = size(x,2);\n %go through\n for j=1:1:nj\n y(:,j) = x(:,j)./x(ni,j);\n end\n y(ni,:) = ones(1,nj);\n ", "meta": {"author": "christianwengert", "repo": "calib_toolbox_addon", "sha": "d4220bde1d17acc9ea03c88433f13eaad94ddccd", "save_path": "github-repos/MATLAB/christianwengert-calib_toolbox_addon", "path": "github-repos/MATLAB/christianwengert-calib_toolbox_addon/calib_toolbox_addon-d4220bde1d17acc9ea03c88433f13eaad94ddccd/normalizeHomogenousCoordinates.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5940704717634263}} {"text": "function [L,E,EMAP] = crouzeix_raviart_cotmatrix(V,F)\n % CROUZEIX_RAVIART_COTMATRIX Compute the Crouzeix-Raviart cotangent\n % Laplacian matrix where we use test functions define at edge midpoints.\n %\n % See for example \"Discrete Quadratic Curvature Energies\" [Wardetzky, Bergou,\n % Harmon, Zorin, Grinspun 2007]\n %\n % Inputs:\n % V #V by dim list of vertex positions\n % F #F by element-size list of triangle indices\n % Outputs:\n % L #E by #E edge-based sparse cotangent matrix\n % E #E by 2 list of edges\n %\n % Examples:\n % % mesh in (V,F)\n % [Lcr,E,EMAP] = crouzeix_raviart_cotmatrix(V,F);\n % [Mcr,E,EMAP] = crouzeix_raviart_massmatrix(V,F);\n % [Ucr,~] = eigs(Lcr,Mcr,5,'sm');\n % % Convert between edge values and vertex values\n % E2V = sparse(E(:),repmat(1:size(E,1),1,2)',1,size(V,1),size(E,1));\n % E2V = bsxfun(@rdivide,E2V,sum(E2V,2));\n % V2E = sparse(E(:),repmat(1:size(E,1),1,2)',1,size(V,1),size(E,1))';\n % V2E = bsxfun(@rdivide,V2E,sum(V2E,2));\n % tsurf(F,[V(:,1:2) E2V*Ucr(:,end-1)])\n % \n % % Display discontinous solution\n % FF = reshape(1:numel(F),size(F));\n % VV = V(F,:);\n % EMAP = reshape(EMAP,size(F));\n % A = sparse( ...\n % [FF FF FF], ...\n % EMAP(:,[1 2 3 2 3 1 3 1 2]), ...\n % repmat(-[1 1 1 -1 -1 -1 -1 -1 -1],size(F,1),1), ...\n % size(VV,1), ...\n % size(E,1));\n % tsurf(FF,[VV(:,1:2) A*Ucr(:,end-1)])\n % \n %\n %\n % See also: edge_laplacian, is_boundary_edge, crouzeix_raviart_massmatrix,\n % cotmatrix\n %\n\n %% check for non-manifold edges\n %S = statistics(V,F,'Fast',true);\n %if S.num_nonmanifold_edges > 0\n % error(sprintf('There are %d non-manifold edges',num_nonmanifold_edges));\n %end\n\n % number of vertices\n n = size(V,1);\n % number of elements\n m = size(F,1);\n % simplex size\n ss = size(F,2);\n switch ss\n case 3\n % Compute cotangents: seems to be 0.5*C\n C = 2*cotangent(V,F);\n\n allE = [F(:,[2 3]);F(:,[3 1]);F(:,[1 2])];\n % Map each face-edge to a unique edge\n F2E = reshape(1:3*m,m,3);\n % Lij = -2 cot aij\n %\n % o\n % |\\\n % | \\\n % | \\\n % | \\\n % i \\\n % | \\\n % | \\\n % |αij \\\n % o----j---o\n %\n %\n LI = F2E(:, [1 2 3 2 3 1 1 2 3 2 3 1]);\n LJ = F2E(:, [2 3 1 1 2 3 1 2 3 2 3 1]);\n LV = 2*[-C(:,[3 1 2 3 1 2]) C(:,[3 1 2 3 1 2])];\n\n % Map duplicate edges to first instance\n [E,~,EMAP] = unique(sort(allE,2),'rows');\n\n assert(all(size(LI)==size(LJ)));\n assert(all(size(LI)==size(LV)));\n L = sparse(EMAP(LI),EMAP(LJ),LV,size(E,1),size(E,1));\n case 4\n % tets\n T = F;\n C = -2*cotangent(V,T);\n allF = [ ...\n T(:,2) T(:,4) T(:,3); ...\n T(:,1) T(:,3) T(:,4); ...\n T(:,1) T(:,4) T(:,2); ...\n T(:,1) T(:,2) T(:,3); ...\n ];\n % Map each element-face to a unique face\n T2F = reshape(1:4*m,m,4);\n % Lij = -2 lij cot αij\n LI = T2F(:,[1 4 4 4 2 3 2 1 2 3 3 1 1 4 4 4 2 3 2 1 2 3 3 1]);\n LJ = T2F(:,[2 1 2 3 3 1 1 4 4 4 2 3 1 4 4 4 2 3 2 1 2 3 3 1]); \n LV = [-C(:,[3 4 5 6 1 2 3 4 5 6 1 2]) C(:,[3 4 5 6 1 2 3 4 5 6 1 2])];\n % Map duplicate facets to first instance\n [F,~,FMAP] = unique(sort(allF,2),'rows');\n\n assert(all(size(LI)==size(LJ)));\n assert(all(size(LI)==size(LV)));\n L = sparse(FMAP(LI),FMAP(LJ),LV,size(F,1),size(F,1));\n E = F;\n EMAP = FMAP;\n\n otherwise\n error(['Simplex size ' num2str(ss) ' unsupported']);\n end\n\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/crouzeix_raviart_cotmatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706735, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5940704644735744}} {"text": "function fe2dx_r_fast_test ( )\n\n%*****************************************************************************80\n%\n%% FE2DX_R_FAST_TEST tests the FE2DX_R_FAST code.\n%\n% Discussion:\n%\n% This function sets all parameter values and initial condition information\n% necessary to execute the \"fast\" version of the fe2dx_r algorithm.\n%\n% Licensing:\n%\n% Copyright (C) 2014 Marcus R. Garvie. \n% See 'mycopyright.txt' for details.\n%\n% Modified:\n%\n% 28 April 2014\n%\n% Author:\n%\n% Marcus R. Garvie. \n%\n% Reference:\n%\n% Marcus R Garvie, John Burkardt, Jeff Morgan,\n% Simple Finite Element Methods for Approximating Predator-Prey Dynamics\n% in Two Dimensions using MATLAB,\n% Submitted to Bulletin of Mathematical Biology, 2014.\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FE2DX_R_FAST_TEST:\\n' );\n fprintf ( 1, ' Test the FE2DX_R_FAST function\\n' );\n fprintf ( 1, ' which applies Robin boundary conditions as it\\n' );\n fprintf ( 1, ' approximates a solution to a predator-prey system.\\n' );\n%\n% Set the parameters.\n%\n alpha = 0.4;\n beta = 2.0;\n gamma = 0.6;\n delta = 1.0;\n%\n% Use T=150.0 for normal run.\n% Use T=0.50 for a \"quick\" run that might take 15 minutes of computing.\n%\n% T = 150.0;\n T = 0.50;\n delt = 1.0 / 384.0;\n k1 = 0.01;\n k2 = 0.01;\n\n t = tic;\n fe2dx_r_fast ( alpha, beta, gamma, delta, T, delt, @u0f, @v0f, k1, k2 );\n t = toc ( t );\n\n fprintf ( 1, ' Execution took %10.2g minutes \\n', t / 60.0 );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FE2DX_R_FAST_TEST:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\n\nfunction value = u0f ( x, y )\n\n%*****************************************************************************80\n%\n%% U0F evaluates the initial condition for U.\n%\n% Licensing:\n%\n% Copyright (C) 2014 Marcus R. Garvie. \n% See 'mycopyright.txt' for details.\n%\n% Modified:\n%\n% 26 April 2014\n%\n% Author:\n%\n% Marcus R. Garvie. \n%\n% Parameters:\n%\n% Input, real X, Y, a location in the region.\n%\n% Output, real VALUE, the initial condition for U at (X,Y).\n%\n value = 6.0 / 35.0 - 2.0E-07 * ( x - 0.1 * y - 225.0 ) * ( x - 0.1 * y - 675.0 );\n\n return\nend\n\nfunction value = v0f ( x, y )\n\n%*****************************************************************************80\n%\n%% V0F evaluates the initial condition for V.\n%\n% Licensing:\n%\n% Copyright (C) 2014 Marcus R. Garvie. \n% See 'mycopyright.txt' for details.\n%\n% Modified:\n%\n% 26 April 2014\n%\n% Author:\n%\n% Marcus R. Garvie. \n%\n% Parameters:\n%\n% Input, real X, Y, a location in the region.\n%\n% Output, real VALUE, the initial condition for V at (X,Y).\n%\n value = 116.0 / 245.0 - 3.0E-05 * ( x - 450.0 ) - 1.2E-04 * ( y - 150.0 );\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/fe2d_predator_prey_fast/fe2dx_r_fast_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.5940704556630101}} {"text": "%% Define Feedforward Convolutional Code\nSNR_dB = 3\nLM = 1600 % Mesg Length excluding pre-determined bits for starting & ending trellis at state 0\nTREL_TYPE = 'Feedback' % {'Feedback', 'Feedforward'}\n\n%% Matlab Generator Polynomial convention\n% Build a binary number representation by placing a 1 in each spot where a connection line from the shift register feeds into the adder,\n% and a 0 elsewhere. The leftmost spot in the binary number represents the current input, while the rightmost spot represents the \n% oldest input that still remains in the shift register.\n\nif strcmp(TREL_TYPE, 'Feedback') \n% CL = 2\t\t% Rate 1/2 Feedback encoder with 2 states\n% GenPoly0_1by2 = 3 % in octal\n% GenPoly1_1by2 = 2\n% FeedBackCoef = [1,1]; % For computing i/p bits needed to terminate trellis at state =0.\n% TREL = poly2trellis(CL, [GenPoly0_1by2, GenPoly1_1by2], GenPoly0_1by2)\n\n%% Rate 1/2 Feedback encoder with 8-states used in 3GPP cellular 3G/4G standard\n CL = 4 \n GenPoly0_1by2 = 13 % in octal\n GenPoly1_1by2 = 15\n FeedBackCoef = [1,0,1,1];% For computing i/p bits needed to terminate trellis at state =0.\n TREL = poly2trellis(CL, [GenPoly0_1by2, GenPoly1_1by2], GenPoly0_1by2) \n \nelse\n %% Rate 1/3 Feedforward encoder with 4 states\n% CL = 3; % constraint length\n% GenPoly0_third = 4; % in octal\n% GenPoly1_third = 5;\n% GenPoly2_third = 7;\n% TREL = poly2trellis( CL, [GenPoly0_third, GenPoly1_third, GenPoly2_third]) \n\n% CL = 4 % constraint length\n% GenPoly0_1by4 = 13 % in octal\n% GenPoly1_1by4 = 15\n% GenPoly2_1by4 = 15\n% GenPoly3_1by4 = 17\n% TREL = poly2trellis( CL, [GenPoly0_1by4, GenPoly1_1by4, GenPoly2_1by4, GenPoly3_1by4])\n\nend\nLM = LM + 2*(CL-1); % space for start & tail bits\n\n%% Verify trellis-structure is OK\n[isok, status] = istrellis(TREL) \n\nrandn('state', sum(100*clock)); % initialize to random state\n\n%% The encoder is assumed to have both started and ended at the all-zeros state\n%% Ensure msg is s.t. trellis starts at \"0\" state and ends at \"0\" state. \n%% Generate Random binary stream & encode \nif strcmp(TREL_TYPE, 'Feedback')\n msg1(1 : CL-1) = zeros(1, CL-1); % 1st (CL-1) bits must be 0\n msg1(CL : LM -CL+1) = randint(LM -2*CL +2, 1, 2)' ; % Random data\n% \tmsg1(CL : LM -CL+1) = [0 1];\n\n % Encode first part of msg, recording final state for later use.\n [cenc_o1, final_state1] = convenc(msg1, TREL);\n\n % Rest of msg depends on final_state1; it makes trellis terminate at final_state=0. \n bvec_fs = bitget(final_state1, (CL-1) : -1 : 1); % All possible binary-vectors of length EncoderN\n for idx = 1 : (CL-1)\n msg2(idx) = rem( [0, bvec_fs]*FeedBackCoef', 2);\n bvec_fs = [0, bvec_fs(1: (end-1))];\n end\n% msg2(1 : CL -1) = bvec_fs; % Last (CL-1) bits depend on state at time=(LM-CL+1)\n [cenc_o2, final_state] = convenc(msg2, TREL, final_state1);\n \n msg = [msg1, msg2]; clear msg1 msg2\n [cenc_o] = [cenc_o1, cenc_o2]; clear cenc_o1 cenc_o2\n final_state \nelse % Feedforward\n msg(1 : CL-1) = zeros(1,CL-1); % 1st (CL-1) bits must be 0\n msg(CL : LM -CL+1) = randint(LM -2*CL +2, 1, 2)' ; % Random data \n msg(LM -CL + 2 : LM) = zeros(CL-1, 1) % Last (CL-1) bits must be 0\n [cenc_o, final_state] = convenc(msg, TREL);\nend\n\nif final_state ~= 0\n disp('trellis not terminated properly: check last (CL-1) bits of mesg')\n return\nend\n\n%%\tMap to BPSK constellation: bit0 -> 1, bit1 -> -1\nsignal_power = 1;\nchan_in = (1 - 2*cenc_o)*sqrt(signal_power);\n\n%%\tGenerate and add Gaussian-noise mean=0, variance= noise_power\nnoise_power = signal_power / 10^(SNR_dB/10);\nnoise = randn(size(chan_in))*sqrt(noise_power);\nchan_o = chan_in + noise;\n% chan_o = chan_in;\n\nEs = log2(TREL.numOutputSymbols)*signal_power;\nNo = noise_power;\nLc = 4*Es/No\n\n%%\tSoft-Decision decoding, map to decision values\nsoft_in = chan_o;\n% decodeds = vitdec_htm(TREL, soft_in');\n\n[LLR, Alpha, Beta] = LogMAPdecode_htm(TREL, chan_o, Lc);\n\ndecd_msg = (1 - sign(LLR))/2;\nerr_vec = abs(decd_msg - msg);\n\nsprintf('# of Bit-Errors = %d out of %d info-bits ', sum(abs(err_vec)), LM -CL -2)\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/24848-log-map-decoder/test_LogMAPdec1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5938885699455118}} {"text": "function B=unimodalcrossproducts(XtX,XtY,Bold)\n\n%UNIMODALCROSSPRODUCTS\n% Solves the problem min|Y-XB'| subject to the columns of \n% B are unimodal and nonnegative. The algorithm is iterative and\n% only one iteration is given, hence the solution is only improving \n% the current estimate\n%\n% I/O B=unimodalcrossproducts(XtX,XtY,Bold)\n% Modified from unimodal.m to handle crossproducts in input 1999\n% Reference\n% Bro and Sidiropoulos, \"Journal of Chemometrics\", 1998, 12, 223-247. \n\n\n% Copyright (C) 1995-2006 Rasmus Bro & Claus Andersson\n% Copenhagen University, DK-1958 Frederiksberg, Denmark, rb@life.ku.dk\n%\n% This program is free software; you can redistribute it and/or modify it under \n% the terms of the GNU General Public License as published by the Free Software \n% Foundation; either version 2 of the License, or (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful, but WITHOUT \n% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS \n% FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n% You should have received a copy of the GNU General Public License along with \n% this program; if not, write to the Free Software Foundation, Inc., 51 Franklin \n% Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n\nB=Bold;\nF=size(B,2);\nfor f=1:F\n xty = XtY(f,:)-XtX(f,[1:f-1 f+1:F])*B(:,[1:f-1 f+1:F])';\n beta=pinv(XtX(f,f))*xty;\n B(:,f)=ulsr(beta',1);\nend\n\n\nfunction [b,All,MaxML]=ulsr(x,NonNeg);\n\n% ------INPUT------\n%\n% x is the vector to be approximated\n% NonNeg If NonNeg is one, nonnegativity is imposed\n%\n%\n%\n% ------OUTPUT-----\n%\n% b \t is the best ULSR vector\n% All \t is containing in its i'th column the ULSRFIX solution for mode\n% \t location at the i'th element. The ULSR solution given in All\n% is found disregarding the i'th element and hence NOT optimal\n% MaxML is the optimal (leftmost) mode location (i.e. position of maximum)\n%\n% ___________________________________________________________\n%\n%\n% Copyright 1997\n%\n% Nikos Sidiroupolos\n% University of Maryland\n% Maryland, US\n%\n% &\n%\n% Rasmus Bro\n% Royal Veterinary & Agricultural University\n% Denmark\n%\n% \n% ___________________________________________________________\n\n\n% This file uses MONREG.M\n\nx=x(:);\nI=length(x);\nxmin=min(x);\nif xmin<0\n x=x-xmin;\nend\n\n\n% THE SUBSEQUENT \n% CALCULATES BEST BY TWO MONOTONIC REGRESSIONS\n\n% B1(1:i,i) contains the monontonic increasing regr. on x(1:i)\n[b1,out,B1]=monreg(x);\n\n% BI is the opposite of B1. Hence BI(i:I,i) holds the monotonic\n% decreasing regression on x(i:I)\n[bI,out,BI]=monreg(flipud(x));\nBI=flipud(fliplr(BI));\n\n% Together B1 and BI can be concatenated to give the solution to\n% problem ULSR for any modloc position AS long as we do not pay\n% attention to the element of x at this position\n\n\nAll=zeros(I,I+2);\nAll(1:I,3:I+2)=B1;\nAll(1:I,1:I)=All(1:I,1:I)+BI;\nAll=All(:,2:I+1);\nAllmin=All;\nAllmax=All;\n% All(:,i) holds the ULSR solution for modloc = i, disregarding x(i),\n\n\niii=find(x>=max(All)');\nb=All(:,iii(1));\nb(iii(1))=x(iii(1));\nBestfit=sum((b-x).^2);\nMaxML=iii(1);\nfor ii=2:length(iii)\n this=All(:,iii(ii));\n this(iii(ii))=x(iii(ii));\n thisfit=sum((this-x).^2);\n if thisfitB(min(I,i+1),1)\n summ=B(i,2)+B(i+1,2);\n B=[B(1:i-1,:);[(B(i,1)*B(i,2)+B(i+1,1)*B(i+1,2))/(summ) summ];B(i+2:size(B,1),:)];\n OK=1;\n while OK\n if B(i,1)=0 with an interior point method\n% using I_est as the initial value and eps as the initial barrier weight\n\n\nln = length(H);\nstep_back_frac = 0.5;\niter = 0;\nif nargin == 2\n I_est = 1e-3*ones(ln,1);\n eps = 1;\nend\nZin = I_est(:);\n\nif nargin == 3\n eps = 1;\nend\nwhile eps>1e-5\n n = D*Zin;\n nnd = 10;\n E = norm(Zin-H)^2 - eps*sum(log(D*Zin));\n grad = 2*(Zin-H) - eps*D'*(n.^(-1));\n Hs = 2*speye(ln) + eps*D'*spdiags(n.^(-2),0,ln,ln)*D; \n while nnd/2>1\n iter = iter + 1;\n Z_dir = -Hs\\grad;\n hit = -n./(D*Z_dir);\n if all(hit<0)\n s = 1;\n else\n s = min(1,.9*min(hit(hit>=0)));\n end\n E_new = E; s = s/step_back_frac;\n x_dg = grad'*Z_dir;\n while E_new > E + 0.25*s*x_dg\n s=s*step_back_frac; \n Z_new = Zin + s*Z_dir;\n n = D*Zin;\n E_new = norm(Z_new-H)^2 - eps*sum(log(D*Z_new));\n end\n %E = E_new;\n Zin = Zin + s*Z_dir;\n nnd = -x_dg;\n E = norm(Zin-H)^2 - eps*sum(log(D*Zin));\n n = D*Zin;\n grad = 2*(Zin-H) - eps*D'*(n.^(-1));\n Hs = 2*speye(ln) + eps*D'*spdiags(n.^(-2),0,ln,ln)*D;\n %disp(nnd)\n end\n eps = eps/10;\nend\n%fprintf('Interior point method converged after %i iterations \\n',iter);\nip_it = iter;\n", "meta": {"author": "flatironinstitute", "repo": "CaImAn-MATLAB", "sha": "49b7884e93348d50df7173e1619d7499468bb1f6", "save_path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB", "path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB/CaImAn-MATLAB-49b7884e93348d50df7173e1619d7499468bb1f6/utilities/plain_foopsi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.5938783326517069}} {"text": "function node_boundary = triangulation_order3_boundary_node ( node_num, ...\n triangle_num, triangle_node )\n\n%*****************************************************************************80\n%\n%% TRIANGULATION_ORDER3_BOUNDARY_NODE indicates which nodes are on the boundary.\n%\n% Discussion:\n%\n% This routine is given a triangulation, an abstract list of triples\n% of nodes. It is assumed that the nodes in each triangle are listed\n% in a counterclockwise order, although the routine should work\n% if the nodes are consistently listed in a clockwise order as well.\n%\n% It is assumed that each edge of the triangulation is either\n% * an INTERIOR edge, which is listed twice, once with positive\n% orientation and once with negative orientation, or;\n% * a BOUNDARY edge, which will occur only once.\n%\n% This routine should work even if the region has holes - as long\n% as the boundary of the hole comprises more than 3 edges!\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 June 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NODE_NUM, the number of nodes.\n%\n% Input, integer TRIANGLE_NUM, the number of triangles.\n%\n% Input, integer TRIANGLE_NODE(3,TRIANGLE_NUM), the nodes that make up the\n% triangles. These should be listed in counterclockwise order.\n%\n% Output, logical NODE_BOUNDARY(NODE_NUM), is TRUE if the node\n% is on a boundary edge.\n%\n m = 2;\n n = 3 * triangle_num;\n%\n% Set up the edge array.\n%\n edge(1:2, 1: triangle_num) = triangle_node(1:2,1:triangle_num);\n edge(1:2, triangle_num+1:2*triangle_num) = triangle_node(2:3,1:triangle_num);\n edge(1, 2*triangle_num+1:3*triangle_num) = triangle_node(3, 1:triangle_num);\n edge(2, 2*triangle_num+1:3*triangle_num) = triangle_node(1, 1:triangle_num);\n%\n% In each column, force the smaller entry to appear first.\n%\n e1(1:n) = min ( edge(1:2,1:n) );\n e2(1:n) = max ( edge(1:2,1:n) );\n\n edge(1,1:n) = e1(1:n);\n edge(2,1:n) = e2(1:n);\n%\n% Ascending sort the column array.\n%\n edge = ( sortrows ( edge' ) )';\n%\n% Records which appear twice are internal edges and can be ignored.\n%\n node_boundary(1:node_num) = 0;\n\n j = 0;\n\n while ( j < 3 * triangle_num )\n\n j = j + 1;\n\n if ( j == 3 * triangle_num )\n node_boundary(edge(1:m,j)) = 1;\n elseif ( all ( edge(1:m,j) == edge(1:m,j+1) ) )\n j = j + 1;\n else\n node_boundary(edge(1:m,j)) = 1;\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/triangulation/triangulation_order3_boundary_node.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.5938783297197349}} {"text": "%-fanDTasia ToolBox------------------------------------------------------------------\n% This Matlab script is part of the fanDTasia ToolBox: a Matlab library for Diffusion \n% Weighted MRI (DW-MRI) Processing, Diffusion Tensor (DTI) Estimation, High-order \n% Diffusion Tensor Analysis, Diffusion Kurtosis Imaging (DKI) Estimation,\n% Tensor ODF estimation, Visualization and more.\n%\n% A Matlab Tutorial on DW-MRI can be found in:\n% http://www.cise.ufl.edu/~abarmpou/lab/fanDTasia/tutorial.php\n%\n%-CITATION---------------------------------------------------------------------------\n% If you use this software please cite the following papers on 4th-order tensors:\n% 1) A. Barmpoutis et al. \"Diffusion Kurtosis Imaging: Robust Estimation from DW-MRI \n% using Homogeneous Polynomials\", In the Proceedings of ISBI, 2011, pp. 262-265.\n% 2) A. Barmpoutis and B.C. Vemuri, \"A Unified Framework for Estimating Diffusion \n% Tensors of any order with Symmetric Positive-Definite Constraints\", \n% In the Proceedings of ISBI, 2010, pp. 1385-1388.\n%\n%-DESCRIPTION------------------------------------------------------------------------\n% This demo script shows how to compute the Diffusion Kurtosis Coefficients from a given \n% Diffusion-Weighted MRI dataset. The method guarantees that the estimated diffusivity as\n% well as the Diffusion Tensor are positive semi-definite, using the method\n% in Sec. 4.2 of the ISBI'11 paper. Here the given demo dataset consists of 5 voxels,\n% 30 gradient directions x 2 b-values from the real brain dataset used in the ISBI'11 paper.\n%\n%-USE--------------------------------------------------------------------------------\n% [D,W]=DEMO_DKI_Estimation_Method2_v2;\n%\n% D: is a vector with the computed Unique Coefficients of the 2nd-order Diffusion Tensor\n% W: is a vector with the computed Unique Coefficients of the 4th-order Kurtosis Tensor\n%\n%-DISCLAIMER-------------------------------------------------------------------------\n% You can use this source code for non commercial research and educational purposes \n% only without licensing fees and is provided without guarantee or warrantee expressed\n% or implied. You cannot repost this file without prior written permission from the \n% authors. If you use this software please cite the following papers:\n% 1) A. Barmpoutis et al. \"Diffusion Kurtosis Imaging: Robust Estimation from DW-MRI \n% using Homogeneous Polynomials\", In the Proceedings of ISBI, 2011.\n% 2) A. Barmpoutis and B.C. Vemuri, \"A Unified Framework for Estimating Diffusion \n% Tensors of any order with Symmetric Positive-Definite Constraints\", \n% In the Proceedings of ISBI, 2010, pp. 1385-1388.\n%\n%-AUTHOR-----------------------------------------------------------------------------\n% Angelos Barmpoutis, PhD\n% Digital Worlds Institute\n% University of Florida, Gainesville, FL 32611, USA\n% angelbar at ufl dot edu\n%------------------------------------------------------------------------------------\nfunction [DKI_D,DKI_W]=DEMO_DKI_Estimation_Method2_v2\n\n%%% DATA OPENING %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%open data files\n[S,B]=openFDT('real_data_5voxels.fdt');\n\n%S0 signal, no diffusion weighting\nS0=S(:,:,:,1);\n\n%acquisition shell 1, 30 orientations\nS_1real=S(:,:,:,[2:31]);\nGradientOrientations_1=B([2:31],[1:3]);\nBValue_1=B(2,4);\n\n%acquisition shell 2, 30 orientations\nS_2real=S(:,:,:,[32:61]);\nGradientOrientations_2=B([32:61],[1:3]);\nBValue_2=B(32,4);\n\n\n\n%%% OPTIONAL: ADD RICIAN NOISE TO THE DATA FOR QUANTITATIVE EVALUATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nstdv=input('Do you want to add Rician noise to the data for validation? \\n If yes, then give the Std. Dev. (e.g: 0.1), otherwise type 0.\\n STD.DEV.:');\nS_1=S_1real;\nfor i=1:size(S_1real,4)\n S_1(:,:,:,i)=sqrt((S_1real(:,:,:,i)+stdv*S0.*randn(size(S_1real,1),size(S_1real,2),size(S_1real,3))).^2+(stdv*S0.*randn(size(S_1real,1),size(S_1real,2),size(S_1real,3))).^2);\nend\nS_2=S_2real;\nfor i=1:size(S_2real,4)\n S_2(:,:,:,i)=sqrt((S_2real(:,:,:,i)+stdv*S0.*randn(size(S_2real,1),size(S_2real,2),size(S_2real,3))).^2+(stdv*S0.*randn(size(S_2real,1),size(S_2real,2),size(S_2real,3))).^2);\nend\n%your data can have as many shells and bvalues you want\n\n\n\n%%% INITIALIZATION - COMPUTING AUXILIARY DATA %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%Construct a constant set of polynomial coefficients C\nC_order2=constructSetOf81Polynomials(2)'; %computes C from section 5.1 (ISBI'10)\nC_order4=constructSetOf321Polynomials(4)'; %computes C from section 5.1 (ISBI'10)\nA_1=D4toDKImatrix(BValue_1);A_1=[A_1(:,[1:6])*C_order2 A_1(:,6+[1:15])];%Computes the matrix A from Table 1 (ISBI'11)\nA_2=D4toDKImatrix(BValue_2);A_2=[A_2(:,[1:6])*C_order2 A_2(:,6+[1:15])];%Computes the matrix A from Table 1 (ISBI'11)\n\n%shell 1\nG_1_order2=constructMatrixOfMonomials(GradientOrientations_1, 2); %computes G from section 5.1 (ISBI'10)\nG_1_order4=constructMatrixOfMonomials(GradientOrientations_1, 4); %computes G from section 5.1 (ISBI'10)\nGbig_1=[-BValue_1*G_1_order2 BValue_1*BValue_1/6*G_1_order4]; %all the monomials for orders 2 and 4.\n\n%shell 2\nG_2_order2=constructMatrixOfMonomials(GradientOrientations_2, 2); %computes G from section 5.1 (ISBI'10)\nG_2_order4=constructMatrixOfMonomials(GradientOrientations_2, 4); %computes G from section 5.1 (ISBI'10)\nGbig_2=[-BValue_2*G_2_order2 BValue_2*BValue_2/6*G_2_order4]; %all the monomials for orders 2 and 4.\n\n%your data can have as many shells and bvalues you want\nGbig=[Gbig_1; Gbig_2]; %all the monomials for orders 2 and 4 and bvalues b1 and b2.\n\n\n\n\n%%%%%% MAIN LOOP - METHOD: LINEAR FITTING - NO CONSTRAINTS %%%%%%%%%%%%%%%%%%%%%%%%%\nfor x=1:size(S,1)\n for y=1:size(S,2)\n for z=1:size(S,3)\n \n logS_1=log(squeeze(S_1(x,y,z,:))/S0(x,y,z));\n logS_2=log(squeeze(S_2(x,y,z,:))/S0(x,y,z));\n \n %The following 2 steps implement the method in Sec. 4.2 of the ISBI'11 paper.\n %Step 1: Compute a positive-definite 4th-order tensor for each b-value\n D4_1=C_order4*lsqnonneg(-G_1_order4*C_order4, logS_1);%computes a positive-definite tensor for b1\n D4_2=C_order4*lsqnonneg(-G_2_order4*C_order4, logS_2);%computes a positive-definite tensor for b2\n\n %Step 2: Compute DKI from the positive definite 4th-order tensors.\n x1=zeros(size(C_order2,2),1); %the initialization is the zero vector\n x2=zeros(15,1); %the initialization is the zero vector\n for i=1:100 %we perform a kind of gradient descent for a number of iterations\n x1=lsqnonneg([A_1(:,[1:size(C_order2,2)]);A_2(:,[1:size(C_order2,2)])],[D4_1;D4_2]-[A_1(:,[size(C_order2,2)+1:size(A_1,2)]);A_2(:,[size(C_order2,2)+1:size(A_1,2)])]*x2);\n x2_new=pinv([A_1(:,[size(C_order2,2)+1:size(A_1,2)]);A_2(:,[size(C_order2,2)+1:size(A_1,2)])]) * ([D4_1;D4_2]-[A_1(:,[1:size(C_order2,2)]);A_2(:,[1:size(C_order2,2)])]*x1);\n %sum(abs(x2-x2_new)) %I just put this here for convergence check\n x2=x2_new;\n end\n dki=[C_order2*x1;x2]; \n\n %Optional Validation if user adds noise to the data\n if stdv>0\n logS_1=log(squeeze(S_1real(x,y,z,:))/S0(x,y,z));\n logS_2=log(squeeze(S_2real(x,y,z,:))/S0(x,y,z));\n err(:,x,y,z)=abs(Gbig*dki-[logS_1; logS_2]);\n end\n \n %Store the data\n DKI_D(:,x,y,z)=dki([1:6]); %The 6 unique coefficients of the diffusion tensor D\n %If you want you can put the result in the form of a 3x3 matrix\n %D=[dki(6) dki(5)/2 dki(4)/2\n % dki(5)/2 dki(3) dki(2)/2\n % dki(4)/2 dki(2)/2 dki(1)];\n \n DKI_W(:,x,y,z)=dki([7:21]); %The 15 unique coefficients of the kurtosis tensor W\n %You can see which coefficient is which you can use the function: printTensor(DKI_W(:,x,y,z),4)\n % or if you want to plot a tensor or a tensor field as spherical functions\n % you have to download the plotTensors.m function developed by Angelos Barmpoutis, Ph.D.\n % and then uncomment the following lines.\n % \n % plotTensors(DKI_D(:,1,1,1),1,[321 1]); %3D ellipsoidal plot of D\n % plotTensors(DKI_W(:,1,1,1),1,[321 1]); %3D ellipsoidal plot of W\n \n %Optional Calculation of Dapp and Kapp\n Dapp(:,x,y,z) = G_1_order2*dki(1:6);\n Kapp(:,x,y,z) = (G_1_order4*dki(7:21))./((G_1_order2*dki(1:6)).^2);\n \n end\n end\nend\n\n\n%%%%%% OPTIONAL: PRINT RESULTS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nall_err=[];\nall_Dapp=[];\nall_Kapp=[];\ncounter=0;\nmeanD=zeros(6,1);\nmeanW=zeros(15,1);\nfor x=1:size(S,1)\n for y=1:size(S,2)\n for z=1:size(S,3)\n if stdv>0\n all_err=[all_err; err(:,x,y,z)];\n end\n all_Dapp=[all_Dapp; Dapp(:,x,y,z)];\n all_Kapp=[all_Kapp; Kapp(:,x,y,z)];\n meanD=meanD+DKI_D(:,x,y,z);\n meanW=meanW+DKI_W(:,x,y,z);\n counter=counter+1;\n end\n end\nend\nmeanD=meanD/counter;\nmeanW=meanW/counter;\n\nfprintf(1,'\\n-----RESULTS:-----\\n\\n');\nfprintf('Number of fitted voxels: %d\\n',counter);\nif stdv>0\n fprintf(1,'Fitting Error: %.4f (std. dev. %.4f)\\n',mean(all_err),std(all_err));\nend\nfprintf(1,'Mean Dapp: %.4f (std. dev. %.4f)\\n',mean(all_Dapp),std(all_Dapp));\nfprintf(1,'Mean Kapp: %.4f (std. dev. %.4f)\\n',mean(all_Kapp),std(all_Kapp));\nfprintf(1,'\\nMean Diffusion Tensor D:\\n');\nprintTensor(meanD,2);\nfprintf(1,'\\nMean Kurtosis Tensor W:\\n');\nprintTensor(meanW,4);\n\n% If you want to plot a Diffusion or Kurtosis tensor as spherical functions\n% you have to download the plotTensors.m function developed by Angelos Barmpoutis, Ph.D.\n% and then uncomment the following lines.\n%\n% subplot(1,2,1)\n% plotTensors(meanD,1,[321 1]);\n% title('Mean Diffusion Tensor');\n% subplot(1,2,2);\n% plotTensors(meanW,1,[321 1]);\n% title('Mean Kurtosis Tensor');\n\n\nfprintf(1,'\\nIf you use this software please cite the following papers on DKI and DTI estimation:\\n');\nfprintf(1,'1) A. Barmpoutis et al. \"Diffusion Kurtosis Imaging: Robust Estimation from DW-MRI\\n'); \nfprintf(1,' using Homogeneous Polynomials\", In the Proceedings of ISBI, 2011, pp. 262-265.\\n');\nfprintf(1,'2) A. Barmpoutis and B.C. Vemuri, \"A Unified Framework for Estimating Diffusion Tensors\\n'); \nfprintf(1,' of any order with Symmetric Positive-Definite Constraints\",\\n');\nfprintf(1,' In the Proceedings of ISBI, 2010, pp. 1385-1388.\\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/31838-diffusion-kurtosis-tensor-estimation/DKI_Estimation/DEMO_DKI_Estimation_Method2_v2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5938631158384394}} {"text": "% \n\nfunction [f, df] = sampleEijOpt(x)\n% optimization code\n\n% param\nvert = x(4:7);\nw_res = x(8);\n\n% box case (4 lines), three free parameters\nx0 = x(1); y0 = x(2); % camera center\nyc = x(3); % corner\n\n% assume vertical lines are fixed\na_aob = (vert(2) - vert (1))/w_res*2*pi;\na_boc = (vert(3) - vert (2))/w_res*2*pi;\na_cod = (vert(4) - vert (3))/w_res*2*pi;\na_doa = (vert(1) + w_res - vert (4))/w_res*2*pi;\n\n% energy\nv_ao = [x0 y0]; v_bo = [x0-1 y0]; v_co = [x0-1 y0 - yc]; v_do = [x0 y0-yc];\nn_v_ao = norm(v_ao); n_v_bo = norm(v_bo); n_v_co = norm(v_co); n_v_do = norm(v_do);\nb_aob = acos(dot(v_ao, v_bo)/n_v_ao/n_v_bo);\nif det([v_ao;v_bo]) < 0\n b_aob = 2*pi - b_aob;\nend\nb_boc = acos(dot(v_bo, v_co)/n_v_bo/n_v_co);\nif det([v_bo;v_co]) < 0\n b_boc = 2*pi - b_boc;\nend\nb_cod = acos(dot(v_co, v_do)/n_v_co/n_v_do);\nif det([v_co;v_do]) < 0\n b_cod = 2*pi - b_cod;\nend\nb_doa = acos(dot(v_do, v_ao)/n_v_do/n_v_ao);\nif det([v_do;v_ao]) < 0\n b_doa = 2*pi - b_doa;\nend\n\nf = (b_aob - a_aob)^2 + (b_boc - a_boc)^2 + (b_cod - a_cod)^2 + (b_doa - a_doa)^2;\n\n% gradient\n% x0\nd_aob_x0 = (2*x0-1)*n_v_ao*n_v_bo + dot(v_ao, v_bo) * (x0*n_v_bo/n_v_ao + (x0-1)*n_v_ao/n_v_bo);\nd_aob_x0 = d_aob_x0 * (-1/(sqrt(1-cos(b_aob)*cos(b_aob))+eps))/n_v_ao/n_v_ao/n_v_bo/n_v_bo;\nif det([v_ao;v_bo]) < 0\n d_aob_x0 = -d_aob_x0;\nend\nd_aob_x0 = 2*(b_aob - a_aob) * d_aob_x0;\n\nd_boc_x0 = 2*(x0-1)*n_v_bo*n_v_co + dot(v_bo, v_co) * ((x0-1)*n_v_co/n_v_bo + (x0-1)*n_v_bo/n_v_co);\nd_boc_x0 = d_boc_x0 * (-1/(sqrt(1-cos(b_boc)*cos(b_boc))+eps))/n_v_bo/n_v_bo/n_v_co/n_v_co;\nif det([v_bo;v_co]) < 0\n d_boc_x0 = -d_boc_x0;\nend\nd_boc_x0 = 2*(b_boc - a_boc) * d_boc_x0;\n\nd_cod_x0 = (2*x0-1)*n_v_co*n_v_do + dot(v_co, v_do) * ((x0-1)*n_v_do/n_v_co + x0*n_v_co/n_v_do);\nd_cod_x0 = d_cod_x0 * (-1/(sqrt(1-cos(b_cod)*cos(b_cod))+eps))/n_v_co/n_v_co/n_v_do/n_v_do;\nif det([v_co;v_do]) < 0\n d_cod_x0 = -d_cod_x0;\nend\nd_cod_x0 = 2*(b_cod - a_cod) * d_cod_x0;\n\nd_doa_x0 = 2*x0*n_v_do*n_v_ao +dot(v_do, v_ao) * (x0*n_v_ao/n_v_do + x0*n_v_do/n_v_ao);\nd_doa_x0 = d_doa_x0 * (-1/(sqrt(1-cos(b_doa)*cos(b_doa))+eps))/n_v_do/n_v_do/n_v_ao/n_v_ao;\nif det([v_do;v_ao]) < 0\n d_doa_x0 = -d_doa_x0;\nend\nd_doa_x0 = 2*(b_doa - a_doa) * d_doa_x0;\n\n% y0\nd_aob_y0 = 2*y0*n_v_ao*n_v_bo + dot(v_ao, v_bo) * (y0*n_v_bo/n_v_ao + y0*n_v_ao/n_v_bo);\nd_aob_y0 = d_aob_y0 * (-1/(sqrt(1-cos(b_aob)*cos(b_aob))+eps))/n_v_ao/n_v_ao/n_v_bo/n_v_bo;\nif det([v_ao;v_bo]) < 0\n d_aob_y0 = -d_aob_y0;\nend\nd_aob_y0 = 2*(b_aob - a_aob) * d_aob_y0;\n\nd_boc_y0 = (2*y0-yc)*n_v_bo*n_v_co + dot(v_bo, v_co) * (y0*n_v_co/n_v_bo + (y0-yc)*n_v_bo/n_v_co );\nd_boc_y0 = d_boc_y0/n_v_bo/n_v_bo/n_v_co/n_v_co;\nif det([v_bo;v_co]) < 0\n d_boc_y0 = -d_boc_y0;\nend\nd_boc_y0 = 2*(b_boc - a_boc) * d_boc_y0;\n\nd_cod_y0 = 2*(y0-yc)*n_v_co*n_v_do + dot(v_co, v_do) * ((y0-yc)*n_v_do/n_v_co + (y0-yc)*n_v_co/n_v_do);\nd_cod_y0 = d_cod_y0 * (-1/(sqrt(1-cos(b_cod)*cos(b_cod))+eps))/n_v_co/n_v_co/n_v_do/n_v_do;\nif det([v_co;v_do]) < 0\n d_cod_y0 = -d_cod_y0;\nend\nd_cod_y0 = 2*(b_cod - a_cod) * d_cod_y0;\n\nd_doa_y0 = (2*y0-yc)*n_v_do*n_v_ao + dot(v_do, v_ao) * ((y0-yc)*n_v_ao/n_v_do + y0*n_v_do/n_v_ao);\nd_doa_y0 = d_doa_y0 * (-1/(sqrt(1-cos(b_doa)*cos(b_doa))+eps))/n_v_do/n_v_do/n_v_ao/n_v_ao;\nif det([v_do;v_ao]) < 0\n d_doa_y0 = -d_doa_y0;\nend\nd_doa_y0 = 2*(b_doa - a_doa) * d_doa_y0;\n\n% yc\nd_boc_yc = (-y0)*n_v_bo*n_v_co + dot(v_bo, v_co) * n_v_bo* (yc-y0)/n_v_co;\nd_boc_yc = d_boc_yc/n_v_bo/n_v_bo/n_v_co/n_v_co;\nif det([v_bo;v_co]) < 0\n d_boc_yc = -d_boc_yc;\nend\nd_boc_yc = 2*(b_boc - a_boc) * d_boc_yc;\n\nd_cod_yc = 2*(yc-y0)*n_v_co*n_v_do + dot(v_co, v_do) * ((yc-y0)*n_v_do/n_v_co+(yc-y0)*n_v_co/n_v_do);\nd_cod_yc = d_cod_yc * (-1/(sqrt(1-cos(b_cod)*cos(b_cod))+eps))/n_v_co/n_v_co/n_v_do/n_v_do;\nif det([v_co;v_do]) < 0\n d_cod_yc = -d_cod_yc;\nend\nd_cod_yc = 2*(b_cod - a_cod) * d_cod_yc;\n\nd_doa_yc = (-y0)*n_v_do*n_v_ao + dot(v_do, v_ao) * n_v_ao * (yc-y0)/n_v_do;\nd_doa_yc = d_doa_yc * (-1/(sqrt(1-cos(b_doa)*cos(b_doa))+eps))/n_v_do/n_v_do/n_v_ao/n_v_ao;\nif det([v_do;v_ao]) < 0\n d_doa_yc = -d_doa_yc;\nend\nd_doa_yc = 2*(b_doa - a_doa) * d_doa_yc;\n\nd_x0 = d_aob_x0 + d_boc_x0 + d_cod_x0 + d_doa_x0;\nd_y0 = d_aob_y0 + d_boc_y0 + d_cod_y0 + d_doa_y0;\nd_yc = d_boc_yc + d_cod_yc + d_doa_yc;\n\ndf = [d_x0; d_y0; d_yc; 0; 0; 0; 0; 0];\n\n", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/sampleEijOpt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660976007597, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.593805099101812}} {"text": "function [u,p,info] = mgDarcy(M,B,f,g,elem,option,varargin)\n%% MGDARCY multigrid solvers for Darcy system discretized by RT0-P0 element\n%\n% [u,p,info] = mgDarcy(M,B,f,g,elem) solves saddle point problem\n% discretized from RT0-P0 mixed FEM for Darcy equation.\n%\n% |M B'| |u| = |f|\n% |B 0 | |p| = |g|\n%\n% A V-cycle multigrid using overlapping Schwarz smoother is implemented.\n% In the first step, mgdivDarcy is called to find initial u satisfying Bu\n% = g. Then at each vertex patch, a local problem with prescribed boundary\n% flux is solved. Detailed description and convergence analysis can be\n% found in the reference.\n%\n% It is around 10 times slower than tripremixPoisson since a large for\n% loop is not efficient in MATLAB. In operation count, this is superior.\n% See the complexity analysis in page 18 of the reference.\n%\n% Reference: L. Chen. Multigrid Methods for Constrained Minimization\n% Problems and Application to Saddle Point Problems\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\ntime = cputime;\n%% Size of systems\nNu = length(f); \nNp = length(g);\nN = max(elem(:)); % number of nodes\n% NT = size(elem,1); % number of elements\n\n%% Options\n% Assign default values to unspecified parameters\nif ~exist('option','var'), \n option = []; \nend\noption = mgoptions(option,Nu); % parameters\nu0 = option.x0; \nN0 = option.N0; \ntol = option.tol;\nmaxIt = option.solvermaxit; \nmu = option.smoothingstep; \ncoarsegridsolver = option.coarsegridsolver; \nprintlevel = option.printlevel; \nfreeEdge = option.freeEdge;\n\n%% Hierarchical Structure of Mesh\nHB = zeros(N,3);\nlevel = 20;\nNL(level+1) = N; % now NL(1:level) = 0;\nelemi = cell(level,1);\nelemi{level} = elem;\nfreeEdgei = cell(level,1);\nfreeEdgei{level} = freeEdge;\nPro_u = cell(level,1);\nPro_p = cell(level,1);\nfor k = level: -1 : 2\n switch option.refType \n case 'red'\n [elemi{k-1},newHB] = uniformcoarsenred(elemi{k}); % coasen red refinement\n if ~isempty(newHB)\n [Pro_u{k-1}, freeEdgei{k-1}] = transferedgered(elemi{k-1},elemi{k},freeEdgei{k}); % transfer operator of u\n Pro_p{k-1} = repmat(speye(size(elemi{k-1},1)),4,1); % transfer operator of p\n end\n case 'bisect'\n % merge two coarsen of bisection grids s.t. the ratio is 1/4.\n [tempelem,newHB1,tree] = uniformcoarsen(elemi{k}); % coarse bisection\n if ~isempty(newHB1) \n % first coarsen\n [tempPro_u,tempFreeEdge] = transferedgecoarsen(tempelem,elemi{k},tree,freeEdgei{k});\n tempPro_p = transferelem(tempelem,elemi{k},tree);\n % second coarsen\n [elemi{k-1},newHB2,tree] = uniformcoarsen(tempelem); % coarse bisection\n [Pro_u{k-1}, freeEdgei{k-1}] = transferedgecoarsen(elemi{k-1},tempelem,tree,tempFreeEdge);\n Pro_u{k-1} = tempPro_u*Pro_u{k-1};\n Pro_p{k-1} = transferelem(elemi{k-1},tempelem,tree);\n Pro_p{k-1} = tempPro_p*Pro_p{k-1};\n newHB = [newHB1; newHB2];\n end\n end \n if (isempty(newHB)) || (size(elemi{k},1)< 2*N0) \n % no nodes are removed or it reaches the coarsest level\n NL = NL(k:end); \n break; \n end\n NL(k) = NL(k+1) - size(newHB,1); % update NL(k)\n HB(NL(k)+1:NL(k+1),1:3) = newHB(:,1:3);\nend\nlevel = length(NL)-1; % actual level\nelemi = elemi(end-level+1: end);\nPro_u = Pro_u(end-level+1: end);\nPro_p = Pro_p(end-level+1: end);\nfreeEdgei = freeEdgei(end-level+1: end);\n% generate edge, elem2edge and freeNode etc\nedgei = cell(level,1);\nelem2edgei = cell(level,1);\nfor k = 1:level\n [elem2edgei{k},edgei{k}] = dofedge(elemi{k});\nend\n\n%% Matrices in each level\noldf = f;\nMi = cell(level,1);\nBi = cell(level,1);\nif size(M,1) > length(freeEdge) % truncate to free edge only\n Mi{level} = M(freeEdge,freeEdge); \n Bi{level} = B(:,freeEdge);\n f = f(freeEdge);\n u0 = u0(freeEdge);\nelse\n Mi{level} = M; \n Bi{level} = B; \nend\nRes_u = cell(level,1);\nRes_p = cell(level,1);\nfor k = level:-1:2\n Res_u{k} = transpose(Pro_u{k-1});\n Res_p{k} = transpose(Pro_p{k-1});\n Mi{k-1} = Res_u{k}*Mi{k}*Pro_u{k-1}; \n Bi{k-1} = Res_p{k}*Bi{k}*Pro_u{k-1};\nend\n\n% %% Exact solver: for debug only\n% C = sparse(size(B,1),size(B,1));\n% A = [M B';B C];\n% F = [f; zeros(size(B,1),1)];\n% tempu = A\\F;\n% exactSigma = tempu(1:Ndof);\n\n%% MG cycles\n% initial set up\nk = 1; \nf0 = f - Mi{level}*u0;\ng0 = g - Bi{level}*u0;\n% find u satisfy Bu = g\nu = u0 + mgdivDarcy(f0,g0);\n% temp = abs(g-Bi{level}*u);\n% idx = temp<1e-14;\n% findelem(node,elem,idx,'noindex','FaceColor','c'); \nif printlevel >= 1\n fprintf('Multigrid Vcycle Iteration \\n')\nend\nerr = zeros(maxIt,1);\nerr(1) = 1;\nr0 = f - Mi{level}*u;\nr = r0;\nwhile (max(err(k,:)) > tol) && (k <= maxIt)\n k = k + 1;\n % Step 2: Compute Br by one Vcylce MG\n Br = vcycle(r);\n % Step 3: Correct the solution\n u = u + Br;\n % Step 1: Form residual r\n r = r - Mi{level}*Br;\n err(k) = sqrt(abs(Br'*r/(u'*r0))); % approximate relative error in energy norm\n if printlevel >= 2\n fprintf('#dof: %8.0u, #nnz: %8.0u, MG Vcycle iter: %2.0u, err = %8.4e\\n',...\n Nu+N, nnz(M)+nnz(B), k-1, err(k));\n end \nend\n\nerr = err(1:k,:);\nitStep = k-1;\n\n%% Find pressure\nAp = B*B';\nubar = zeros(Nu,1);\nubar(freeEdge) = u;\nb = B*(oldf-M*ubar);\np = zeros(Np,1);\nif option.isPureNeumannBC\n freep = 1:Np-1;\nelse\n freep = 1:Np;\nend\np(freep) = Ap(freep,freep)\\b(freep);\n\n%% Output\ntime = cputime - time;\nif k > maxIt\n flag = 1;\nelse\n flag = 0;\nend\nif printlevel >= 2\n fprintf('#dof: %8.0u, level: %2.0u, coarse grid %2.0u, #nnz: %8.0u\\n',...\n Nu+N, level, size(Mi{1},1), nnz(Mi{1}))\nend\nif printlevel >= 1\n fprintf('#dof: %8.0u, #nnz: %8.0u, smoothing: %2.0u, iter: %2.0u, err = %8.4e, time = %4.2g s\\n',...\n Nu+Np, nnz(M)+2*nnz(B), mu, 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% subfunctions vcycle\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Vcycle MG\n function Br = vcycle(r,J) % solve equations Ae = r in each level \n if nargin<=1\n J = level;\n end\n ri = cell(J,1); % record residual in each level\n ei = cell(J,1); % record err in each level\n ri{J} = r;\n for i = J:-1:2\n ei{i} = zeros(size(Mi{i},1),1);\n ei{i} = SchwarzsmootherDarcy(Mi{i},Bi{i},ri{i},zeros(size(Bi{i},1),1),...\n ei{i},elemi{i},edgei{i},elem2edgei{i},freeEdgei{i},mu);\n ri{i-1} = Res_u{i}*(ri{i} - Mi{i}*ei{i});\n end\n if strcmp(coarsegridsolver,'direct')\n Ncoarse = size(Bi{1},1);\n C1 = sparse(Ncoarse,Ncoarse);\n A1 = [Mi{1} Bi{1}'; Bi{1} C1];\n F1 = [ri{1}; zeros(Ncoarse,1)];\n if option.isPureNeumannBC\n bigu = A1(1:end-1,1:end-1)\\F1(1:end-1); % pure Neumann\n else\n bigu = A1\\F1;\n end\n ei{1} = bigu(1:size(Mi{1},1));\n end\n for i = 2:J\n ei{i} = ei{i} + Pro_u{i-1}*ei{i-1};\n ei{i} = SchwarzsmootherDarcy(Mi{i},Bi{i},ri{i},zeros(size(Bi{i},1),1),...\n ei{i},elemi{i},edgei{i},elem2edgei{i},freeEdgei{i},-mu);\n end\n Br = ei{J};\n end\n%% div Darcy\n% Use one V-cycle with post-smoothing only to find u s.t. div u = g\n\n function u = mgdivDarcy(rf,rg)\n J = level;\n rfi = cell(J,1);\n rgi = cell(J,1);\n eui = cell(J,1);\n rfi{J} = rf;\n rgi{J} = rg;\n % restrict the residual to the coarse level\n for i = J:-1:2\n rfi{i-1} = Res_u{i}*rfi{i};\n rgi{i-1} = Res_p{i}*rgi{i};\n end\n % exact solve in the coarest mesh\n Ncoarse = size(Bi{1},1);\n C1 = sparse(Ncoarse,Ncoarse);\n A1 = [Mi{1} Bi{1}'; Bi{1} C1];\n F1 = [rfi{1}; rgi{1}];\n if option.isPureNeumannBC\n bigu = A1(1:end-1,1:end-1)\\F1(1:end-1); % pure Neumann\n else\n bigu = A1\\F1;\n end\n eui{1} = bigu(1:size(Mi{1},1));\n % prolongate to the fine level and post-smoothing in each element\n for i = 2:J\n eui{i} = Pro_u{i-1}*eui{i-1};\n eui{i} = SchwarzsmootherelemDarcy(Mi{i},Bi{i},rfi{i},rgi{i},...\n eui{i},elemi{i},edgei{i},elem2edgei{i},freeEdgei{i},1);\n end\n u = eui{J};\n end\nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/solver/mgDarcy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5936546598216703}} {"text": "function [c, d] = lpdec1(x, h, g, extmod)\n% LPDEC1 One-level Laplacian pyramid decomposition\n%\n%\t[c, d] = lpdec1(x, h, g)\n%\n% Input:\n% x: input signal\n% h, g: two biorthogonal 1-D lowpass filters\n% extmod: [optional] extension mode (default is 'per')\n%\n% Output:\n% c: coarse signal at half size\n% d: detail signal at full size\n%\n% See also:\tLPREC1\n\nif ~exist('extmod', 'var')\n extmod = 'per';\nend\n\nnd = ndims(x);\n\n% Computer the coarse signal by filter and downsample\nc = x;\nfor dim = 1:nd\n c = filtdn(c, h, dim, extmod, 0);\nend\n \n% Compute the detail signal by upsample, filter, and subtract\n% Even size filter needs to be adjusted to obtain perfect reconstruction\nadjust = mod(length(g) + 1, 2);\n\np = c;\nfor dim = 1:nd\n p = upfilt(p, g, dim, extmod, adjust);\nend\n\nd = x - p;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/9868-laplacian-pyramid-toolbox/lpdec1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648678, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5936546338820363}} {"text": " function [C, rj] = penalty2_design(type, varargin)\n%|function [C, rj] = penalty2_design(type, ['leak'|'tight'], wang, ang, mask)\n%|\n%| Design the penalty matrix \"C\" (and penalty coefficients \"rj\")\n%| for a quadratic penalty R(x) = 1/2 x' C * C * x with:\n%| 1st-order differences and a 2nd-order neighborhood (8 neighbors).\n%| For 2D parallel-beam tomography with shift-invariant blur.\n%| Design based on Fourier method in fessler:03:aat (IEEE MIC, 2003).\n%|\n%| in\n%|\ttype\t\t\t'test' or 'quad,d1,n2' or 'quad,d1,n1'\n%|\t\t\t\t(n2 for usual 2nd order neighborhood)\n%|\twang\t[na nx ny]\tangular weights for each pixel\n%|\tang\t[na]\t\tangles\n%|\tmask\t[nx ny]\t\t(logical) reconstruction support\n%| out:\n%|\tC\t[4*nx*ny nx*ny] \"modified\" C containing sqrt{r_j} factors\n%|\trj\t[nx ny 4]\thoriz,vert,diag1,diag2 coefficients\n%|\n%| Copyright 2003-5-23, Jeff Fessler, University of Michigan\n\nif nargin < 1, ir_usage, end\n\n% run a self-test to compare my analytical solution\n% to the numerical solution computed using NNLS.\nif nargin == 1 && streq(type, 'test')\n\tpenalty2_design_test\nreturn\nend\n\n% analytical design of 1st-order difference, 2nd-order neighborhood\nif streq(type, 'quad,d1', 7)\n\tif length(varargin) < 1 || length(varargin) > 3, ir_usage, end\n\n\tif ischar(varargin{1})\n\t\tCtype = varargin{1};\n\t\tvarargin = varargin{2:end};\n\telse\n\t\tCtype = 'leak';\n\tend\n\n\twang = varargin{1};\n\t[na nx ny] = size(wang);\n\tnp = nx*ny;\n\twang = reshape(wang, [na np]);\n\n\tif length(varargin) >= 2\n\t\tang = col(varargin{2});\n\t\tif na ~= length(ang), error 'angle dim', end\n\telse\n\t\tang = [0:(na-1)]'/na * pi; % [0,pi)\n\tend\n\n\tif length(varargin) == 3\n\t\tmask = varargin{3};\n\t\tif any(size(mask) ~= [nx ny]), error 'mask dims', end\n\telse\n\t\tmask = true(nx,ny);\n\tend\n\n\t% dot product of each basis with wj\n\t% the \"mean\" takes care of normalization\n\tbasis = [ones(size(ang)) cos(2*ang) sin(2*ang)];\n\tdot_products = zeros(ncol(basis),np);\n\tfor ib=1:ncol(basis)\n\t\tb = basis(:,ib);\n\t\tb = repmat(basis(:,ib), 1, np);\n\t\tdot_products(ib,:) = mean(b .* wang, 1);\n\tend, clear ib b\n\n\tsptmp = @(tmp) spdiag(tmp, 'nowarn'); % for now\n\n\tif streq(type, 'quad,d1,n1') % 1st-order neighborhood\n\t\trj = penalty2_design_d1_n1(dot_products); % [2 np]\n\t\trj = permute(reshape(rj, [2 nx ny]), [2 3 1]); % [nx ny 2]\n\t\tC = C2sparse('leak', mask, 4, 0, 0);\n\t\ti1 = 1:(nx*ny);\n\t\tC = [\tsptmp(sqrt(col(rj(:,:,1)))) * C(0*nx*ny+i1,:);\n\t\t\tsptmp(sqrt(col(rj(:,:,2)))) * C(1*nx*ny+i1,:)];\n\n\telseif streq(type, 'quad,d1,n2') % 2nd-order neighborhood\n\t\trj = penalty2_design_d1_n2(dot_products); % [4 np]\n\t\trj = permute(reshape(rj, [4 nx ny]), [2 3 1]); % [nx ny 4]\n\t\t% fix: this must depend on flip_y !!\n\t\tprintf('Warn: penalty2_design.m may fail if flip_y = -1')\n\t\trj = rj(:,:,[1 2 4 3]); % re-order 45,135 (empirical)\n\n\t\tC = C2sparse('leak', mask, 8, 0, 0);\n\t\ti1 = 1:(nx*ny);\n\t\t% analysis assumes 1/sqrt(2) for diagonal 1st differences!\n\t\tC = [\tsptmp(sqrt(col(rj(:,:,1))))\t* C(0*nx*ny+i1,:);\n\t\t\tsptmp(sqrt(col(rj(:,:,2))))\t* C(1*nx*ny+i1,:);\n\t\t\tsptmp(sqrt(col(rj(:,:,3))/2))\t* C(2*nx*ny+i1,:);\n\t\t\tsptmp(sqrt(col(rj(:,:,4))/2))\t* C(3*nx*ny+i1,:)];\n\telse\n\t\terror 'bad type'\n\tend\n\nelse\n\terror(['unknown type: ' type])\nend\n\n\n%\n% in:\tiprod\t[3 np]\t\tinner products of angular weights with\n%\t\t\t\t\t[1 cos(2a) sin(2a)]\n% out:\trj\t[2 np]\t\thoriz,vert\n%\nfunction rj = penalty2_design_d1_n1(iprod)\n\nd1 = iprod(1,:);\nd2 = iprod(2,:);\n\nif any(d1 < 0), error 'bad inner products: d1<0', end\nif any(abs(d2) > d1), error 'bad inner products: d2>d1', end\n\nrj = [d1+2*d2; d1-2*d2];\n\nii = d2 > d1/2;\nr1 = 4/3 * (d1 + d2);\nrj(1,ii) = r1(ii);\nrj(2,ii) = 0;\n\nii = d2 < -d1/2;\nr2 = 4/3 * (d1 - d2);\nrj(1,ii) = 0;\nrj(2,ii) = r2(ii);\n\n\n\n%\n% in:\n%\tiprod\t[3 np]\t\tinner products of angular weights with\n%\t\t\t\t\t[1 cos(2a) sin(2a)]\n%\t\t\t\t\ttypically np = # of pixels\n% out:\n%\trj\t[4 np]\t\thoriz,vert,diag1,diag2 coefficients\n%\n% caution: diagonals coefficients are designed to be used with\n% diagonal differences that are normalized by 1/\\sqrt{2}.\n%\nfunction rj = penalty2_design_d1_n2(iprod)\n\nd1 = iprod(1,:);\ndp2 = iprod(2,:);\ndp3 = iprod(3,:);\nd2 = max(abs(dp2), abs(dp3)); % d2 >= d3\nd3 = min(abs(dp2), abs(dp3));\nif any(d1 < 0), error 'bad inner products: d1<0', end\nif any(d2 > d1), error 'bad inner products: d2>d1', end\n\nrj = zeros(4,length(d1));\n\nii = (d2 >= d1/2) & (d3 <= 2/3*d2 - d1/3); % case 1\nr1 = 4/3 * (d1 + d2);\nrj(1,ii) = r1(ii);\n\nii = (d3 >= 2/3*d2 - d1/3) & (d3 + d2 >= d1/2); % case 2\nr1 = 8/5 * (d1/2 + 3/2*d2 - d3);\nr3 = 12/5 * (d3 - 2/3*d2 + 1/3*d1);\nrj(1,ii) = r1(ii);\nrj(3,ii) = r3(ii);\n\nii = (d3 + d2 <= d1/2) & (d2 >= d1/4); % case 3\nrj(1,ii) = 4*d2(ii);\nr3 = d1 - 2*d2 + 2*d3;\nr4 = d1 - 2*d2 - 2*d3;\nrj(3,ii) = r3(ii);\nrj(4,ii) = r4(ii);\n\nii = (d2 <= d1/4); % case 4\nr1 = d1/2 + 2*d2;\nr2 = d1/2 - 2*d2;\nr3 = d1/2 + 2*d3;\nr4 = d1/2 - 2*d3;\nrj(1,ii) = r1(ii);\nrj(2,ii) = r2(ii);\nrj(3,ii) = r3(ii);\nrj(4,ii) = r4(ii);\n\n% symmetries\nii = abs(dp3) > abs(dp2);\nrj(:,ii) = rj([3 4 1 2],ii);\n\nii = dp3 < 0;\nrj([3 4],ii) = rj([4 3],ii);\n\nii = dp2 < 0;\nrj([1 2],ii) = rj([2 1],ii);\n\n\n%\n% brute-force NNLS approach\n% dot\t[3 np]\n% rj\t[4 np]\n%\nfunction rj = penalty2_design_nnls(Amat, dot)\n\nww = [dot(1,:); sqrt(2)*dot([2 3],:)];\nopt = optimset('lsqnonneg');\nopt = optimset(opt, 'tolx', 10*eps);\n\nrj = zeros(4, ncol(ww));\nfor jj=1:ncol(ww)\n\trj(:,jj) = lsqnonneg(Amat, ww(:,jj));\n\tif ~rem(jj,100), printf('%d of %d', jj, ncol(ww)), end\nend\n\n\n\n% penalty2_design_test()\nfunction penalty2_design_test\nAmat = 0.5 * [1 1 1 1;\n\t\t1/sqrt(2) -1/sqrt(2) 0 0 ;\n\t\t0 0 1/sqrt(2) -1/sqrt(2)];\nn2 = 41;\nn3 = 43;\nd2 = linspace(-1,1,n2);\nd3 = linspace(-1,1,n3);\ndot = zeros(3,n2*n3);\n[t2, t3] = ndgrid(d2, d3);\ndot(1,:) = 1;\ndot(2,:) = t2(:)';\ndot(3,:) = t3(:)';\n\nrj_anal = penalty2_design_d1_n2(dot);\nrj_nnls = penalty2_design_nnls(Amat, dot); % [4 n2*n3]\n\npenalty2_design_test_figure(Amat, dot, d2, d3, rj_anal, rj_nnls)\n\n\nfunction penalty2_design_test_figure(Amat, dot, d2, d3, ra, rn)\n\nn2 = length(d2);\nn3 = length(d3);\n\nww = [dot(1,:); sqrt(2)*dot([2 3],:)];\nerra = permute(reshape(Amat * ra - ww, [3 n2 n3]), [2 3 1]); % [n2 n3 3]\nerrn = permute(reshape(Amat * rn - ww, [3 n2 n3]), [2 3 1]);\n\nra = permute(reshape(ra, [4 n2 n3]), [2 3 1]); % [n2 n3 4]\nrn = permute(reshape(rn, [4 n2 n3]), [2 3 1]);\n\nif im\n\tclf, pl=440;\n\tfor ib=1:4\n\t\tim(pl+ib+0, d2, d3, ra(:,:,ib)), axis xy, cbar\n\t\ttitle(sprintf('Anal. ib=%d', ib))\n\t\tim(pl+ib+4, d2, d3, rn(:,:,ib)), axis xy, cbar\n\t\ttitle NNLS\n\tend\n\n\tsubplot(4,4,9)\n\tim(d2, d3, sum(ra > 0,3), 'Anal. sum(r > 0)'), axis xy, cbar\n\tsubplot(4,4,10)\n\tim(d2, d3, sum(rn > 0,3), 'NNLS sum(r > 0)'), axis xy, cbar\n\n\t% hold on, plot(d2, 2/3*(d2 - 1/sqrt(2)), 'c-'), hold off\n\t% hold on, plot(d2, sqrt(2)/3 - 2/3*d2, 'r-'), hold off\n\n\ttmp = sqrt(sum(erra.^2, 3));\n\tsubplot(4, 4, 11)\n\tim(d2, d3, tmp, 'Anal. |err|'), axis xy, cbar\n\tsubplot(4, 4, 15)\n\tim(d2, d3, tmp < 10*eps, 'Anal. |err|=0'), axis xy, cbar\n\n\ttmp = sqrt(sum(errn.^2, 3));\n\tsubplot(4, 4, 12)\n\tim(d2, d3, tmp, 'NNLS |err|'), axis xy, cbar\n\tsubplot(4, 4, 16)\n\tim(d2, d3, tmp < 10*eps, 'NNLS |err|=0'), axis xy, cbar\n\n\tsubplot(4, 4, 13)\n\t%im(d2, d3, sum(erra.^2, 3) < sum(errn.^2, 3)+10*eps, 'Anal,\n% \n%\n% If you use this code for your research, please cite the following two papers:\n%\n% (1) B.D. Fulcher and N.S. Jones, \"hctsa: A Computational Framework for Automated\n% Time-Series Phenotyping Using Massive Feature Extraction, Cell Systems 5: 527 (2017).\n% DOI: 10.1016/j.cels.2017.10.001\n%\n% (2) B.D. Fulcher, M.A. Little, N.S. Jones, \"Highly comparative time-series\n% analysis: the empirical structure of time series and their methods\",\n% J. Roy. Soc. Interface 10(83) 20130048 (2013).\n% DOI: 10.1098/rsif.2013.0048\n%\n% This function is free software: you can redistribute it and/or modify it under\n% the terms of the GNU General Public License as published by the Free Software\n% Foundation, either version 3 of the License, or (at your option) any later\n% version.\n%\n% This program is distributed in the hope that it will be useful, but WITHOUT\n% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n% FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n% details.\n%\n% You should have received a copy of the GNU General Public License along with\n% this program. If not, see .\n% ------------------------------------------------------------------------------\n\n% ------------------------------------------------------------------------------\n%% Check Inputs\n% ------------------------------------------------------------------------------\nN = length(y); % length of the input time series\n\n% Number of nearest neighbours, NNR\nif nargin < 2 || isempty(NNR)\n NNR = 5;\nend\nif (NNR > 0) && (NNR < 1) % specify a proportion of time series length\n NNR = floor(NNR*N); if NNR == 0, NNR = 1; end\nend\n\n% Maximum return time, maxT\nif nargin < 3 || isempty(maxT)\n maxT = 0.1;\nend\nif (maxT > 0) && (maxT <= 1) % specify a proportion\n maxT = floor(N*maxT);\n if maxT == 0, maxT = 1; end\nend\n\n% Theiler window, past\nif nargin < 4 || isempty(past)\n past = 10;\nend\nif (past > 0) && (past < 1) % specify a proportion\n past = floor(N*past);\n if past == 0, past = 1; end % round up from 0\nend\n\n% Number of reference points\nif nargin < 5 || isempty(Nref)\n Nref = -1; % use all available points\nend\n\n% embed parameters\nif nargin < 6 || isempty(embedParams)\n embedParams = {'ac','fnnmar'};\n fprintf(1,'Using default embedding using autocorrelation and cao\\n');\nend\n\ndoPlot = false; % plot outputs to figures\n\n% ------------------------------------------------------------------------------\n%% Embed the signal\n% ------------------------------------------------------------------------------\ns = BF_Embed(y,embedParams{1},embedParams{2},1,true);\nif ~isa(s,'signal') && isnan(s); % embedding failed\n warning('Embedding failed');\n out = NaN; return\nend\nnumPoints = size(data(s),1);\nif numPoints < 10\n % Set heuristic minimum (10) on the number of points needed to perform a meaningful analysis\n warning('Time series not long enough for return time analysis')\n out = NaN; return\nend\n\n% ------------------------------------------------------------------------------\n%% Run the code\n% ------------------------------------------------------------------------------\ntry\n rs = return_time(s, NNR, maxT, past, Nref);\ncatch emsg\n if strcmp(emsg.message,'Index exceeds matrix dimensions.')\n fprintf(1,'Error evaluating return_time\\n');\n out = NaN; return\n else\n error(emsg.message);\n end\nend\n\nTrett = data(rs);\nNN = length(Trett);\n\n% ------------------------------------------------------------------------------\n%% Quantify structure in output\n% ------------------------------------------------------------------------------\nout.max = max(Trett);\nout.std = std(Trett);\nout.pzeros = sum(Trett == 0)/NN;\nout.pg05 = sum(Trett>max(Trett)*0.5)/NN;\nout.iqr = iqr(Trett);\n\n% recurrent peaks:\nicross05 = find((Trett(1:end-1)-0.5*max(Trett)).*(Trett(2:end)-0.5*max(Trett)) < 0);\nif ~isempty(icross05) && length(icross05) > 2\n difficross05 = diff(icross05);\n difficross05 = difficross05(difficross05 > 0.4*max(difficross05)); % remove small entries, crossing peaks\n\n out.meanpeaksep = mean(difficross05)/NN;\n out.maxpeaksep = max(difficross05)/NN;\n out.minpeaksep = min(difficross05)/NN;\n out.rangepeaksep = range(difficross05)/NN;\n out.stdpeaksep = std(difficross05)/sqrt(NN);\nelse\n out.meanpeaksep = NaN;\n out.maxpeaksep = NaN;\n out.minpeaksep = NaN;\n out.rangepeaksep = NaN;\n out.stdpeaksep = NaN;\nend\n\nout.statrtys = std(Trett(1:floor(end/2)))/std(Trett(floor(end/2)+1:end));\nout.statrtym = mean(Trett(1:floor(end/2)))/mean(Trett(floor(end/2)+1:end));\n\nout.hhist = -sum(Trett(Trett>0).*log(Trett(Trett>0)));\n\n% ------------------------------------------------------------------------------\n%% Coarse-grain to 20 bins\n% ------------------------------------------------------------------------------\nnumBins = 20;\ncglav = zeros(numBins,1);\ninds = round(linspace(0,NN,numBins+1));\nfor i = 1:numBins\n cglav(i) = sum(Trett(inds(i)+1:inds(i+1)));\nend\nif doPlot\n figure('color','w');\n box('on');\n plot(cglav,'k')\nend\nout.hcgdist = -sum(cglav(cglav > 0).*log(cglav(cglav > 0)));\nout.rangecgdist = range(cglav);\nout.pzeroscgdist = sum(cglav == 0)/numBins;\n\n% ------------------------------------------------------------------------------\n%% Get distribution of distribution of return times\n% ------------------------------------------------------------------------------\n[nhist, binEdges] = histcounts(Trett,'BinMethod','sqrt','Normalization','probability');\nif doPlot\n binCenters = mean([binEdges(1:end-1); binEdges(2:end)]);\n figure('color','w');\n plot(binCenters,nhist,'o-k')\nend\nout.maxhisthist = max(nhist);\nout.phisthistmin = nhist(1); % this is the same as maxhisthist\nout.hhisthist = -sum(nhist(nhist > 0).*log(nhist(nhist > 0)));\n\nend\n", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Operations/NL_TSTL_ReturnTime.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5935205958928333}} {"text": "%data :3*length increment type equally spaced sensor output.\n%alg :Type of the coning algorithm to be used \nfunction [inc corr]=coning_minor(data, alg)\ninlen=size(data,2);\nswitch (alg)\n case(0)\n %ignagni(1990):Algorithm A (no correction - constant approximation) \n inc=data;\n corr=zeros(size(data));\n case(1)\n %ignagni(1990):Algorithm D (quadratic approximation to 3 points) \n outlen=floor((inlen-3)/3)+1;\n inc=zeros(3,outlen);\n corr=zeros(3,outlen);\n \n ind=1;\n for i=3:3:inlen\n inc(:,ind)=sum(data(:,i-2:i),2);\n corr(:,ind)=(33/80)*cross(data(:,i-2), data(:,i))+(57/80)*cross(data(:,i-1),data(:,i)-data(:,i-2));\n ind=ind+1;\n end\n case(2)\n %ignagni(1990):Algorithm E\n outlen=floor((inlen-3)/3)+1;\n inc=zeros(3,outlen);\n corr=zeros(3,outlen);\n \n ind=1;\n for i=3:3:inlen\n inc(:,ind)=sum(data(:,i-2:i),2);\n corr(:,ind)=(9/20)*cross(data(:,i-2), data(:,i))+(27/40)*cross(data(:,i-1),data(:,i)-data(:,i-2));\n ind=ind+1;\n end\n case(3)\n %ignagni(1996):Algorithm 1\n outlen=floor((inlen-4)/2)+1;\n inc=zeros(3,outlen);\n corr=zeros(3,outlen);\n \n ind=1;\n for i=4:2:inlen\n vr_a=sum(data(:,i-1:i),2);\n vr_b=sum(data(:,i-3:i-2),2);\n inc(:,ind)=var_a;\n corr(:,ind)=(32/45)*cross(data(:,i-1), data(:,i))+(-1/180)*cross(vr_b,vr_a);\n ind=ind+1;\n end\n case(4)\n %ignagni(1996):Algorithm 2\n outlen=floor((inlen-3)/2)+1;\n inc=zeros(3,outlen);\n corr=zeros(3,outlen);\n\n ind=1;\n for i=3:2:inlen\n inc(:,ind)=sum(data(:,i-1:i),2);\n corr(:,ind)=cross(((-1/30)*data(:,i-2)+(11/15)*data(:,i-1)), data(:,i));\n ind=ind+1;\n end\n case (5)\n %ignagni(1996):Algorithm 3 - Ignagni (1990):Algorithm F\n outlen=floor((inlen-3)/3)+1;\n inc=zeros(3,outlen);\n corr=zeros(3,outlen);\n\n ind=1;\n for i=3:3:inlen\n inc(:,ind)=sum(data(:,i-2:i),2);\n corr(:,ind)=cross(((9/20)*data(:,i-2)+(27/20)*data(:,i-1)), data(:,i));\n ind=ind+1;\n end\n case (6)\n %ignagni(1996):Algorithm 4\n outlen=floor((inlen-6)/3)+1;\n inc=zeros(3,outlen);\n corr=zeros(3,outlen);\n\n ind=1;\n for i=6:3:inlen\n vr_a=sum(data(:,i-2:i),2);\n vr_b=sum(data(:,i-5:i-3),2);\n inc(:,ind)=vr_a;\n corr(:,ind)=cross(((243/560)*data(:,i-2)+(1539/1120)*data(:,i-1)), data(:,i))+(1/3360)*cross(vr_b,vr_a);\n ind=ind+1;\n end\n case (7)\n %ignagni(1996):Algorithm 5\n outlen=floor((inlen-4)/3)+1;\n inc=zeros(3,outlen);\n corr=zeros(3,outlen);\n\n ind=1;\n for i=4:3:inlen\n inc(:,ind)=sum(data(:,i-2:i),2);\n corr(:,ind)=cross(((3/280)*data(:,i-3)+(57/140)*data(:,i-2)+(393/280)*data(:,i-1)), data(:,i));\n ind=ind+1;\n end\n case (8)\n %ignagni(1996):Algorithm 6\n outlen=floor((inlen-5)/3)+1;\n inc=zeros(3,outlen);\n corr=zeros(3,outlen);\n\n ind=1;\n for i=5:3:inlen\n inc(:,ind)=sum(data(:,i-2:i),2);\n corr(:,ind)=cross(((-1/420)*data(:,i-4)+(1/40)*data(:,i-3)+(157/420)*data(:,i-2)+(1207/840)*data(:,i-1)), data(:,i));\n ind=ind+1;\n end \n case (9)\n %ignagni(1996):Algorithm 7\n outlen=floor((inlen-4)/4)+1;\n inc=zeros(3,outlen);\n corr=zeros(3,outlen);\n\n ind=1;\n for i=4:4:inlen\n inc(:,ind)=sum(data(:,i-3:i),2);\n corr(:,ind)=cross(((54/105)*data(:,i-3)+(92/105)*data(:,i-2)+(214/105)*data(:,i-1)), data(:,i));\n ind=ind+1;\n end\n otherwise\n disp('Undefined Algorithm (Perhaps, someone else adds it later)');\nend", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/instk/conscull/coning_minor_v000.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.593501333676524}} {"text": "function [B,E,S,info] = DECOLOR(D,opt)\n% DEteting Contiguous Outliers in the LOw-rank Representation\n% http://arxiv.org/PS_cache/arxiv/pdf/1109/1109.0882v1.pdf\n% eexwzhou@ust.hk \n% Syntex: [B,S] = DECOLOR(D); or [B,S] = DECOLOR(D,opt);\n% Input:\n% D -- 2D matrix\n% opt -- options. Usually, default setting is good. No need to specify.\n% opt.K: desired rank of the estimated low-rank component. \n% Default: \\sqrt(min(size(D))) is good generally.\n% opt.lambda: a constant controls the strength of smoothness regularize\n% lambda ~ [1 5] is recommended. Default: 1\n% opt.sigma: STD of noise in the image. If not specified, computed online\n% opt.tol: convergence precision. Default: 1e-4\n% Output:\n% B -- Low-rank component\n% S -- Outlier support\n% info -- other information\n\ndisp('^_^^_^^_^^_^^_^^_^ DECOLOR ^_^^_^^_^^_^^_^');\ntic;\n\n%% default parameter setting\nif ~exist('opt','var'); opt = []; end\nif ~isfield(opt,'tol'); opt.tol = 1e-4; end\nif ~isfield(opt,'K'); opt.K = floor(sqrt(min(size(D)))); end\nif ~isfield(opt,'lambda'); opt.lambda = 1; end % gamma = opt.lambda * beta;\nif ~isfield(opt,'sigma'); opt.sigma = []; end % sigma can be estimated online\n\n%% variable initialize\nD = double(D);\nB = D; % the low-rank matrix\nS = false(size(D)); % background support\nalpha = []; % Default setting by soft-impute\nbeta = 0.5*(std(D(:)))^2; % Start from a big value\nminbeta = 0.5*(3*std(D(:))/20)^2; % lower bound: suppose SNR <= 20\nsigma = opt.sigma; % if empty, will be estimated online\ncard = sum(S(:)); % record mumber of outliers\nminCard = numel(D)/1e4; % minimum number of outliers\nmaxOuterIts = 50; % max number of iteration\n\n% graph cuts initialization\n% GCO toolbox is called\nif opt.lambda > 0\n hMRF = GCO_Create(numel(D),2);\n GCO_SetSmoothCost( hMRF, [0 1;1 0] );\n AdjMatrix = getAdj(size(D));\n amplify = 10 * opt.lambda;\n GCO_SetNeighbors( hMRF, amplify * AdjMatrix );\nend\n\n%% outer loop\nenergy_old = inf; % total energy\nfor outerIts = 1:maxOuterIts\n disp(['---------------- Outer Loop: ' num2str(outerIts) ' ----------------']);\n \n %% update B\n disp('*** Estimate Low-rank Matrix *** ');\n [B,Bnorm,alpha] = softImpute(D,B,~S,alpha,opt.K);\n E = D - B;\n \n %% estimate sigma \n if isempty(opt.sigma)\n sigma_old = sigma;\n sigma = std(E(~S(:)));\n if abs(sigma_old-sigma)/abs(sigma_old) < 0.01\n sigma = sigma_old; % if the change is not too large\n end\n end\n % update beta\n if card < minCard\n beta = beta/2;\n else\n beta = min(max([beta/2,0.5*(3*sigma)^2 minbeta]),beta);\n end\n gamma = opt.lambda * beta;\n \n %% estimate S\n disp('*** Estimate Outlier Support *** ');\n disp(['$$$ beta = ' num2str(beta) '; gamma = ' num2str(gamma) '; sigma = ' num2str(sigma)]);\n if opt.lambda > 0\n % call GCO to run graph cuts\n GCO_SetDataCost( hMRF, (amplify/gamma)*[ 0.5*(E(:)).^2, ones(numel(E),1)*beta]' );\n GCO_Expansion(hMRF);\n S = reshape(GCO_GetLabeling(hMRF)==2,size(S));\n card = sum(S(:)==1);\n energy_cut = (gamma/amplify)*double(GCO_ComputeEnergy(hMRF));\n else\n % direct hard thresholding if no smoothness\n S = 0.5*E.^2 > beta;\n card = sum(S(:));\n energy_cut = 0.5*norm(D-B-E,2)^2 + beta*card;\n end\n \n %% display energy\n energy = energy_cut + alpha * Bnorm;\n disp(['>>> the number of outliers is ' num2str(card)]);\n disp(['>>> the objectvive energy is ' num2str(energy)]);\n \n %% check termination condition\n if card > 0 && abs(energy_old-energy)/energy < opt.tol; break; end\n energy_old = energy;\n \nend\n\ninfo.opt = opt;\ninfo.time = toc;\ninfo.outerIts = outerIts;\ninfo.energy = energy;\ninfo.rank = rank(B);\ninfo.alpha = alpha;\ninfo.beta = beta;\ninfo.sigma = sigma;\n\nif opt.lambda > 0\n GCO_Delete(hMRF);\nend\n\nend\n\n\n\n%% function to get the adjcent matirx of the graph\nfunction W = getAdj(sizeData)\nnumSites = prod(sizeData);\nid1 = [1:numSites, 1:numSites, 1:numSites];\nid2 = [ 1+1:numSites+1,...\n 1+sizeData(1):numSites+sizeData(1),...\n 1+sizeData(1)*sizeData(2):numSites+sizeData(1)*sizeData(2)];\nvalue = ones(1,3*numSites);\nW = sparse(id1,id2,value);\nW = W(1:numSites,1:numSites);\nend\n\n\n\n%% function for soft-impute\nfunction [Z,Znorm,alpha] = softImpute(X,Z,Omega,alpha0,maxRank)\n%\n% This program implements the soft-impute algorithm followed by\n% postprocessing in the Matrix completion paper Mazumder'10 IJML\n% min || Z - X ||_Omega + \\alpha || Z ||_Nulear\n% \\alpha is decrease from alpha0 to the minima value that makes rank(Z) <= maxRank\n\n% X is the incomplete matrix\n% maxRank is the desired rank in the constraint\n% Omega is the mask with value 1 for data and 0 for missing part\nif isempty(Z)\n Z = X;\nend\nif isempty(Omega)\n Omega = true(size(X));\nend\nif isempty(alpha0)\n [dummy,D] = svd(X,'econ'); \n alpha0 = D(2,2);\nend\nif isempty(maxRank)\n maxRank = -1;\nend\n% parameters\neta = 0.707;\nepsilon = 1e-4;\nmaxInnerIts = 20;\n%% trivial\n% no rank constraint\nif maxRank >= min(size(X))\n Z = X;\n [dummy,D] = svd(Z,'econ');\n Znorm = sum(diag(D));\n alpha = 0;\n return;\nend\n% no observation\nif sum(Omega(:)) == 0\n % no data\n Z = zeros(size(X));\n Znorm = 0;\n alpha = alpha0;\n return;\nend\n%% soft-impute\n% 1. initialize\noutIts = 0;\nalpha = alpha0;\n% 2. Do for alpha = alpha0 > alpha_1 > alpha_2 > ... > alpha_maxRank\ndisp('begin soft-impute iterations');\nwhile 1\n outIts = outIts + 1;\n energy = inf;\n for innerIts = 1:maxInnerIts\n % (a)i\n C = X.*Omega + Z.*(1-Omega);\n [U,D,V] = svd(C,'econ');\n VT = V';\n % soft impute\n d = diag(D);\n idx = find(d > alpha);\n Z = U(:,idx) * diag( d(idx) - alpha ) * VT(idx,:);\n % (a)ii\n Znorm = sum(d(idx)-alpha);\n energy_old = energy;\n energy = alpha*Znorm + norm(Z(Omega(:))-X(Omega(:)),'fro')/2;\n if abs(energy - energy_old) / energy_old < epsilon\n break\n end\n end\n % check termination condition of alpha\n k = length(idx); % rank of Z\n disp(['alpha = ' num2str(alpha) '; rank = ' num2str(k) '; number of iteration: ' num2str(innerIts)]);\n if k <= maxRank && alpha > 1e-3\n alpha = alpha*eta;\n else\n break; \n end \nend\nend\n\n\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/rpca/DECOLOR/DECOLOR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5934999767940362}} {"text": "function [X, info] = IRmrnsd(A, b, varargin)\n%IRmrnsd Modified Residual Norm Steepest Descent method\n%\n% options = IRmrnsd('defaults')\n% [X,info] = IRmrnsd(A,b)\n% [X,info] = IRmrnsd(A,b,K)\n% [X,info] = IRmrnsd(A,b,options)\n% [X,info] = IRmrnsd(A,b,K,options)\n%\n% This function implements the Modified Residual Norm Steepest Descent\n% method for computing a nonnegatiely constrained least squares solution.\n%\n% With 'defaults' as input returns the default options. Otherwise outputs\n% the iterates specified in K, using max(K) as MaxIter, and using all other\n% default options. With options as input: uses the user-specified options\n% and all the other default options.\n% \n% Inputs:\n% A : either (a) a full or sparse matrix\n% (b) a matrix object that performs the matrix*vector operation\n% (c) user-defined function handle\n% b : right-hand side vector\n% K : (optional) integer vector that specifies which iterates are returned\n% in X; the maximum number of iterations is assumed to be max(K)\n% [ positive integer | vector of positive components ]\n% options : structure with the following fields (optional)\n% x0 - Initial guess for the iterations\n% [ array | {'none'} ]\n% MaxIter - maximum allowed number of cgls iterations\n% [ {100 } | positive integer ]\n% NOTE: K overrules MaxIter if both are assigned\n% x_true - true solution; allows us to returns error norms with\n% respect to x_true at each iteration\n% [ array | {'none'} ]\n% NoiseLevel - norm of noise in rhs divided by norm of rhs \n% [ {'none'} | nonnegative scalar]\n% eta - safety factor for the discrepancy principle\n% [ {1.01} | scalar greater than (and close to) 1 ]\n% NE_Rtol - relative tolerance on the normal equation residual norm\n% [ {1e-12} | positive integer ]\n% NoStop - specifies whether the iterations should proceed\n% after a stopping criterion has been satisfied\n% [ 'on' | {'off'} ]\n% IterBar - shows the progress of the iterations\n% [ {'on'} | 'off' ]\n% Note: the options structure can be created using the function IRset.\n%\n% Outputs:\n% X : computed solutions, stored column-wise (at the iterations listed in K)\n% info: structure with the following fields:\n% its - number of the last computed iteration\n% saved_iterations - iteration numbers of iterates stored in X \n% StopFlag - string that describes the inner stopping condition:\n% * Residual tolerance satisfied (discrepancy principle)\n% * Normal equations residual tolerance satisfied\n% * Reached maximum number of iterations\n% Rnrm - relative residual norms at each iteration\n% NE_Rnrm - normal eqs relative residual norms at each iteration\n% Xnrm - solution norms at each iteration\n% Enrm - relative error norms (requires x_true) at each iteration\n% StopReg - struct containing information about the solution that\n% satisfies the stopping criterion. Fields:\n% It : iteration where the stopping criterion is satisfied\n% X : solution satisfying the stopping criterion\n% Enrm : the corresponding relative error (requires x_true)\n% BestReg - struct containing information about the solution that\n% minimizes Enrm (requires x_true), with the fields:\n% It : iteration where the minimum is attained\n% X : best solution\n% Enrm : best relative error\n%\n% See also: IRconstr_ls, IRfista, IRnnfcgls, IRget, IRset\n\n% Silvia Gazzola, University of Bath\n% Per Christian Hansen, Technical University of Denmark\n% James G. Nagy, Emory University\n% April, 2018.\n\n% This file is part of the IR Tools package and is distributed under the \n% 3-Clause BSD License. A separate license file should be provided as part \n% of the package.\n\n% Set default values for options.\ndefaultopt = struct('x0','none', 'MaxIter',100, 'x_true','none', ...\n 'NoiseLevel','none', 'eta',1.01, 'NE_Rtol',1e-12, 'IterBar','on', ...\n 'NoStop', 'off');\n \n% If input is 'defaults,' return the default options in X.\nif nargin==1 && nargout <= 1 && isequal(A,'defaults')\n X = defaultopt;\n return;\nend\n\ndefaultopt.verbosity = 'on';\n\n% Check for acceptable number of optional input arguments.\nswitch length(varargin)\n case 0\n K = []; options = [];\n case 1\n if isa(varargin{1}, 'double')\n K = varargin{1}; options = [];\n else\n K = []; options = varargin{1};\n end\n case 2\n if isa(varargin{1}, 'double')\n K = varargin{1}; options = varargin{2};\n else\n K = varargin{2}; options = varargin{1};\n end\n if isfield(options, 'MaxIter') && ~isempty(options.MaxIter) && (~isempty(K) && options.MaxIter ~= max(K))\n warning('The value of MaxIter is discarded; the maximum value in K is taken as MaxIter')\n end\n otherwise\n error('Too many input parameters')\nend\n\nif isempty(options)\n options = defaultopt;\nend\n\noptions = IRset(defaultopt, options);\n\nMaxIter = IRget(options, 'MaxIter', [], 'fast');\nx_true = IRget(options, 'x_true', [], 'fast');\nNoiseLevel = IRget(options, 'NoiseLevel', [], 'fast');\neta = IRget(options, 'eta', [], 'fast');\nNE_Rtol = IRget(options, 'NE_Rtol', [], 'fast');\nIterBar = IRget(options, 'IterBar', [], 'fast');\nNoStop = IRget(options, 'NoStop', [], 'fast');\nverbose = IRget(options, 'verbosity', [], 'fast');\n\nverbose = strcmp(verbose, 'on');\n\n% Setting K.\nif isempty(K)\n K = MaxIter;\nend\n% Sorting the iterations (in case they are shuffled in input).\nK = K(:); K = sort(K,'ascend'); K = unique(K);\nif ~((isreal(K) && (all(K > 0)) && all(K == floor(K))))\n error('K must be a vector of positive real integers')\nend\nif K(end) ~= MaxIter\n MaxIter = K(end); \nend\n\nStopIt = MaxIter;\n\nif isempty(NoiseLevel) || strcmp(NoiseLevel,'none')\n Rtol = 0;\nelse\n Rtol = eta*NoiseLevel;\nend\n\n% We need to find the number of columns in matrix A, but if A is not given \n% as a matrix, and no initial guess is given, then we can find it by \n% computing A'*b. Since we need this anyway, it doesn't cost any \n% additional work.\ntrAb = Atransp_times_vec(A, b);\nn = length(trAb);\n\nnrmb = norm(b(:));\nnrmAtb = norm(trAb(:));\n\n% See if an initial guess is given. If not, then use 0 as initial guess. \nx = IRget(options, 'x0', [], 'fast');\n\nif strcmp(x,'none')\n % the default initial guess for the iterations is defined as the\n % minimizer of || b - A*(alpha*ones(n,1)) ||_2\n coeffx0 = A_times_vec(A, ones(n,1)); alpha = (coeffx0'*b)/norm(coeffx0)^2;\n if alpha <= 0\n alpha = sqrt(eps);\n end\n x = alpha*ones(n,1);\nend\n\nif norm(x) == 0\n error(['IRmrnsd cannot handle a zero initial guess. ',...\n 'Please consider assigning a different initial guess, or avoid specifying the initial guess in order to have a default value'])\nend\n\n% If initial guess has negative values, compensate.\nminx = min(x(:));\nif minx < 0\n x = x - min(0,minx) + sqrt(eps);\nend\n\nnoIterBar = strcmp(IterBar,{'off'});\n\n% Declare matrices.\nX = zeros(n,length(K));\nXnrm = zeros(MaxIter,1);\nRnrm = zeros(MaxIter,1);\nNE_Rnrm = zeros(MaxIter,1);\nif strcmp(x_true,'none')\n errornorms = false;\nelse\n errornorms = true;\n Enrm = zeros(MaxIter,1);\n nrmtrue = norm(x_true(:));\n BestReg.It = [];\n BestReg.X = [];\n BestReg.Enrm = [];\n BestEnrm = 1e10;\n BestReg.Xnrm = [];\n BestReg.Rnrm = [];\n BestReg.NE_Rnrm = [];\nend\n\nNoStop = strcmp(NoStop,'on');\nsaved_iterations = zeros(1, length(K));\n\n% Initializing some variables.\nr = b - A_times_vec(A,x);\ng = -Atransp_times_vec(A, r);\nxg = x .* g;\ngamma = g(:)' * xg(:);\n\nif ~noIterBar\n h_wait = waitbar(0, 'Running iterations, please wait ...');\nend\n\nj = 0;\nfor k = 1:MaxIter\n if ~noIterBar\n waitbar(k/MaxIter, h_wait)\n end\n \n s = - x .* g;\n\n u = A_times_vec(A, s);\n \n theta = gamma / (u(:)'*u(:));\n neg_ind = s < 0;\n \n alpha = min( theta, min( -x(neg_ind) ./ s(neg_ind) ) );\n if isempty(alpha)\n alpha = theta;\n end\n \n x = x + alpha*s;\n \n r = r - alpha*u;\n AlreadySaved = 0; \n if any(K == k)\n j = j+1;\n X(:,j) = x;\n saved_iterations(j) = k;\n AlreadySaved = 1; \n end\n \n z = Atransp_times_vec(A, u);\n\n g = g + alpha*z;\n xg = x .* g;\n gamma = g(:)' * xg(:);\n\n % Compute norms.\n Xnrm(k) = norm(x(:));\n Rnrm(k) = norm(r(:))/nrmb;\n NE_Rnrm(k) = sqrt(gamma)/nrmAtb;\n if errornorms\n Enrm(k) = norm(x_true-x)/nrmtrue;\n if Enrm(k)