{"text": "function SO3VF = rdivide(SO3VF1, SO3VF2)\n% overloads |SO3VF1 ./ SO3VF2|\n%\n% Syntax\n% SO3VF = SO3VF1 ./ SO3VF2\n% SO3VF = SO3VF1 ./ a\n% SO3VF = a ./ SO3VF2\n% SO3VF = SO3F .* SO3VF1\n% SO3VF = SO3VF1 .* SO3F\n% \n% Input\n% SO3VF1, SO3VF2 - @SO3VectorFieldHarmonic\n% a - double\n% SO3F - @SO3Fun\n%\n% Output\n% SO3VF - @SO3VectorFieldHarmonic\n%\n\nif isa(SO3VF2,'vector3d')\n SO3VF2 = SO3VF2.xyz.';\nend\n\nif isnumeric(SO3VF1)\n SO3VF = SO3VectorFieldHandle(@(rot) SO3VF1 ./ SO3VF2.eval(rot),SO3VF2.SRight,SO3VF2.SLeft);\n SO3VF = SO3VectorFieldHarmonic(SO3VF, 'bandwidth', min(getMTEXpref('maxSO3Bandwidth'),2*SO3VF2.bandwidth));\n return\nend\nif isnumeric(SO3VF2)\n SO3VF = times(SO3VF1,1./SO3VF2);\n return\nend\n\nensureCompatibleSymmetries(SO3VF1,SO3VF2);\nSO3VF = SO3VectorFieldHandle(@(rot) SO3VF1.eval(rot)./ SO3VF2.eval(rot),SO3VF1.SRight,SO3VF1.SLeft);\nSO3VF = SO3VectorFieldHarmonic(SO3VF, 'bandwidth', min(getMTEXpref('maxSO3Bandwidth'),2*max(SO3VF1.bandwidth, SO3VF2.bandwidth)));\n\nend", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/SO3Fun/@SO3VectorFieldHarmonic/rdivide.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.49999884243807613}} {"text": "function [in3] = mi32in3(mi3)\n% Convert volume from cubic miles to cubic inches. \n% Chad Greene 2012\nin3 = mi3*254358061050000;", "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/mi32in3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718435083355188, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.4999988387412469}} {"text": "%% Multiple comparison correction with Threshold-Free Cluster Enhancement\n%\n% This example demonstrates cosmo_cluster_neighborhood and\n% cosmo_montecarlo_cluster_stat\n%\n% Note: this example shows multiple-comparison for a single subject, but\n% the same logic can be applied to a group of subjects to do a group\n% analysis.\n%\n% # For CoSMoMVPA's copyright information and license terms, #\n% # see the COPYING file distributed with CoSMoMVPA. #\n\n%% Define data\nconfig=cosmo_config();\ndata_path=fullfile(config.tutorial_data_path,'ak6','s01');\n\ntargets=repmat(1:6,1,10);\nchunks=floor(((1:60)-1)/6)+1;\n\nds = cosmo_fmri_dataset(fullfile(data_path,'glm_T_stats_perrun.nii'),...\n 'mask',fullfile(data_path, 'brain_mask.nii'), ...\n 'targets',targets,'chunks',chunks);\n\n% There are 10 chunks, for which the data is assumed to be independent.\n% Construct a dataset with 10 samples corresponding to each chunk, with\n% the average value across all six targets. Each sample is considered to be\n% the same condition, namely the effect of the stimulus-versus-baseline\n% effect; thus all target values must be set to 1.\n%\n% Use either:\n% - cosmo_split and cosmo_stack\n% - cosmo_average_samples\n% - (advanced) cosmo_fx\n%\n% Assign the result to a variable 'ds_stim'\n% >@@>\nds_stim=cosmo_fx(ds,@(x)mean(x,1),{'chunks'});\n\n% % alternative:\n% ds_stim=ds;\n% ds_stim.sa.targets(:)=1;\n% ds_split=cosmo_split(ds_stim,{'chunks'});\n%\n% for k=1:numel(ds_split)\n% ds_avg_k=cosmo_slice(ds_split{k},1);\n% ds_avg_k.samples=mean(ds_split{k}.samples,1);\n% ds_split{k}=ds_avg_k;\n% end\n%\n% ds_stim=cosmo_stack(ds_split);\n%\n% <@@<\n\n%% Define a cluster neighborhood for this dataset and assign the result to\n% a variable 'cl_nh'.\n% hint: use cosmo_cluster_neighborhood\n\n% >@@>\ncl_nh=cosmo_cluster_neighborhood(ds_stim);\n% <@@<\n\n% Show a plot with the sorted number of neighbors\n% for each voxel\n\n% >@@>\nn_neighbors_per_feature=cellfun(@numel,cl_nh.neighbors);\nplot(sort(n_neighbors_per_feature))\n% <@@<\n\n%% Run cosmo_montecarlo_cluster_stat\n\n% There is one condition per chunk; all targets are set to 1.\n% Thus the subsequent anaylsis is a one-sample t-test.\n% Note: if this was a group analysis, then each sample (row in ds.samples)\n% would contain data from one subject; each unique value in .sa.chunks\n% would correspond to one subject; and each unique value in .sa.targets\n% would correspond to a condition of interest.\n\n% Since this is a one-sample t-test against a mean of zero, we set this as\n% a (required) option\n\nopt=struct();\nopt.h0_mean=0;\n\n% set the number of iterations ('niter' option).\n% At least 10000 is adviced for publication-quality analyses; because that\n% takes quite a while to compute, here we use 200\n\n% >@@>\n% Note: for publication-quality analyses, niter=10000 or more is\n% recommended\nopt.niter=200;\n% <@@<\n\n% using cosmo_montecarlo_cluster_stat, compute a map with z-scores\n% against the null hypothesis of a mean of zero, corrected for multiple\n% comparisons. Store the result in a variable named 'tfce_z_ds_stim'\n\n% >@@>\ntfce_z_ds_stim=cosmo_montecarlo_cluster_stat(ds_stim,cl_nh,opt);\n% <@@<\ncosmo_plot_slices(tfce_z_ds_stim);\n\n%% Using the same logic, run a two-sample t-test for primates versus bugs\n\n% >@@>\nprimates_insects_mask=cosmo_match(ds.sa.targets,[1 2 5 6]);\nds_primates_insects=cosmo_slice(ds, primates_insects_mask);\n\n% set primates=1, insects=2\nds_primates_insects.sa.targets(cosmo_match(...\n ds_primates_insects.sa.targets,[1 2]))=1;\nds_primates_insects.sa.targets(cosmo_match(...\n ds_primates_insects.sa.targets,[5 6]))=2;\n\n% compute average for each unique combination of targets and chunks\nds_avg_primate_insects=cosmo_average_samples(ds_primates_insects);\n\ncl_nh=cosmo_cluster_neighborhood(ds_avg_primate_insects);\n\n\nopt=struct();\n\n% set the number of iterations.\n% At least 10000 is adviced for publication-quality analyses; because that\n% takes quite a while to compute, here we use 200\n\n% Note: for publication-quality analyses, niter=10000 or more is\n% recommended\nopt.niter=200;\n\ntfce_z_ds_primate_vs_insects=cosmo_montecarlo_cluster_stat(...\n ds_avg_primate_insects,cl_nh,opt);\n% <@@<\ncosmo_plot_slices(tfce_z_ds_primate_vs_insects);\n", "meta": {"author": "CoSMoMVPA", "repo": "CoSMoMVPA", "sha": "5de75a1b4bef89b082d39d69e2b99d7f894ad717", "save_path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA", "path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA/CoSMoMVPA-5de75a1b4bef89b082d39d69e2b99d7f894ad717/examples/run_multiple_comparison_correction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.49999883563849806}} {"text": "function [spectrum] = specest_nanfft(dat, time, varargin)\n\n% SPECEST_NANFFT computes a fast Fourier transform in the presence of NaNs\n% in the data\n%\n% Use as\n% [spectrum] = specest_nanfft(dat, ...)\n% where\n% dat = matrix of chan*sample\n% time = vector, containing time in seconds for each sample\n% spectrum = matrix of taper*chan*foi*toi of fourier coefficients\n%\n% Optional arguments should be specified in key-value pairs and can include:\n% basis = precomputes set of basis functions (sines/cosines)\n% datataype = 0, 1, 2\n%\n% FIXME: FFT speed not yet optimized, e.g. MATLAB version, transpose or not, ...\n% FIXME: function is recursive, should be avoided in favor of transparancy\n%\n% See also SPECEST_MTMFFT, SPECEST_CONVOL, SPECEST_HILBERT, SPECEST_MTMCONVOL, SPECEST_MVAR, SPECEST_WAVELET\n\n% Copyright (C) 2008, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\n% get the optional arguments\nbasis = ft_getopt(varargin, 'basis');\ndatatype = ft_getopt(varargin, 'datatype');\n\n% datatype = 0, no missing data\n% datatype = 1, the missing data is at the same location for all channels\n% datatype = 2, the missing data is at different timepoints for different channels\n\n% determine the data characteristics\n[nchan, nsample] = size(dat);\nfsample = 1./mean(diff(time));\n\nif mod(nsample,2)==0\n % the number of samples is even\n k = nsample/2+1;\nelse\n % the number of samples is odd\n k = floor(nsample/2+1);\nend\n\n% determine the type of data and thereby the most suitable algorithm to use\nnancount = sum(isnan(dat), 1);\nif isempty(datatype)\n if all(nancount==0)\n % there is no missing data\n datatype = 0;\n elseif all(nancount==0 | nancount==nchan)\n % the missing data is at the same location for all channels\n datatype = 1;\n else\n % the missing data is at different timepoints for different channels\n datatype = 2;\n end\nend\n\nif datatype==0\n % no basis functions are needed, because the standard FFT routine will be used\n\nelseif datatype~=0 && isempty(basis)\n % create a separate set of basis functions for the cosine and sine\n basis_c = zeros(k, nsample);\n basis_s = zeros(k, nsample);\n\n % create the time axis\n t = linspace(0, 2*pi, nsample+1);\n t = t(1:end-1);\n\n for w=1:k\n c = cos((w-1)*t);\n s = sin((w-1)*t);\n if w==1 || (w==(k) && mod(nsample,2)==0)\n % the normalization for the lowest (DC) and the highest frequency component is different\n s = s/(nsample);\n c = c/(nsample);\n else\n s = s/(nsample/2);\n c = c/(nsample/2);\n end\n basis_c(w,:) = c;\n basis_s(w,:) = s;\n end\n % concatenate the sine and cosine basis functions\n % leaving the first and last sine functions out, since those are all zero\n if mod(nsample,2)==0\n % the number of samples is even -> the last sine wave basis function is zero\n basis = cat(1, basis_c, basis_s(2:end-1, :));\n else\n % the number of samples is odd -> also include the last sine wave basis function\n basis = cat(1, basis_c, basis_s(2:end, :));\n end\nend\n\n\nswitch datatype\n case 0\n % there is no missing data\n % use the standard FFT implementation\n y = fft(dat, [], 2);\n\n case 1\n % the missing data is at the same location for all channels\n % remove that piece from the data and from the basis functions and use linear estimation\n\n keep = ~isnan(dat(1,:));\n\n if all(~keep)\n % the data is all NaN, no reason to try to estimate the basis\n % functions\n y = nan(size(dat));\n\n else\n\n basis = basis(:,keep);\n dat = dat(:,keep);\n\n % do the linear estimation based on dat=y*basis\n % y = dat / basis;\n y = dat * pinv(basis);\n\n % disentagle the estimated components\n\n if mod(nsample,2)==0\n % the number of samples is even -> the last sine wave basis function is zero\n sel1 = 1; % lowest cosine, i.e. DC\n sel2 = 2:(k-1); % all cosines in between\n sel3 = k; % highest cosine\n sel4 = (k+1):nsample; % all sines\n\n est1 = y(:,sel1);\n est2 = y(:,sel2);\n est3 = y(:,sel3);\n est4 = y(:,sel4);\n\n % combine the various estimates into a complex representation compatible with standard FFT\n y_real = cat(2, est1, est2, est3, fliplr(est2));\n y_imag = cat(2, zeros(nchan,1), -est4, zeros(nchan,1), fliplr(est4));\n y = y_real + i*y_imag;\n\n else\n % the number of samples is odd -> also include the last sine wave basis function\n sel1 = 1; % lowest cosine, i.e. DC\n sel2 = 2:k; % all other cosines\n sel3 = (k+1):nsample; % all sines\n\n est1 = y(:,sel1);\n est2 = y(:,sel2);\n est3 = y(:,sel3);\n\n % combine the various estimates into a complex representation compatible with standard FFT\n y_real = cat(2, est1, est2, fliplr(est2));\n y_imag = cat(2, zeros(nchan,1), -est3, fliplr(est3));\n y = y_real + i*y_imag;\n end\n \n end % if all(~keep)\n\n case 2\n % the missing data is at different timepoints for different channels\n % use recursion to compute the nanfft for each channel\n y = zeros(size(dat));\n for k=1:nchan\n y(k,:) = specest_nanfft(dat(k,:), time, 'basis', basis);\n end\n\n otherwise\n ft_error('unsupported configuration of NaNs in the data');\nend\n\n% set output\nspectrum = y;\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/contrib/spike/private/specest_nanfft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49998480977099063}} {"text": "function vemPoisson3(cube, pde, option, varargin)\n\nmaxIt = option.maxIt;\n\n%% Initialize err\nerrL2 = zeros(maxIt,1); errH1 = zeros(maxIt,1); \nerruIuh = zeros(maxIt,1); errMax = zeros(maxIt,1);\nerrTime = zeros(maxIt,1); solverTime = zeros(maxIt,1); \nassembleTime = zeros(maxIt,1); meshTime = zeros(maxIt,1); \nitStep = zeros(maxIt,1); stopErr = zeros(maxIt,1); flag = zeros(maxIt,1);\nN = zeros(maxIt,1);\nh = zeros(maxIt,1);\nh(1) = option.h0;\n\n\n% [node,elem, interfaceData] = interfacemesh3(cube, pde.phi, h(1));\n% checkinterfacemesh3(node,elem,interfaceData)\n% [face, face2elem] = getpolymesh(elem,interfaceData);\n% clear elem interfaceData\n\n% [node, elem] = cubehexmesh(cube,h(k+1));\n% idx = (1:size(elem, 1))';\n% face = [elem(:,[1,4,3,2]); elem(:,[6, 7, 8, 5]);...\n% elem(:,[2,3,7,6]); elem(:,[1, 5, 8, 4]);...\n% elem(:,[1,2,6,5]); elem(:,[4, 8, 7, 3])];\n% face2elem = [idx;idx;idx;idx;idx;idx];\n% clear elem;\n\n[node, elem] = cubemesh(cube, h(1));\nelem = fixorder3(node,elem);\nidx = (1:size(elem,1))';\nface = [elem(:,[2, 3, 4]);elem(:,[1, 4,3]);elem(:,[1,2,4]);elem(:,[1,3,2])];\nface(:,4) = 0;\nface2elem = [idx;idx;idx;idx];\nclear elem\n\n%% Vertual Element Method\nfor k = 1:maxIt\n N(k) = size(node,1);\n [u, info] = Poisson3VEM(node, face, face2elem, pde, option);\n errMax(k) = max(abs(u - pde.exactu(node)));\n if k < maxIt\n h(k+1) = h(k)/2;\n \n% [node, elem, interfaceData] = interfacemesh3(cube, pde.phi, h(k+1));\n% h(k+1)\n% checkinterfacemesh3(node,elem,interfaceData)\n% [face, face2elem] = getpolymesh(elem,interfaceData);\n% clear elem interfaceData\n\n% [node, elem] = cubehexmesh(cube,h(k+1));\n% idx = (1:size(elem, 1))';\n% face = [elem(:,[1,4,3,2]); elem(:,[6, 7, 8, 5]);...\n% elem(:,[2,3,7,6]); elem(:,[1, 5, 8, 4]);...\n% elem(:,[1,2,6,5]); elem(:,[4, 8, 7, 3])];\n% face2elem = [idx;idx;idx;idx;idx;idx];\n% clear elem;\n \n [node, elem] = cubemesh(cube, h(k+1));\n elem = fixorder3(node,elem);\n idx = (1:size(elem,1))';\n face = [elem(:,[2, 3, 4]);elem(:,[1, 4, 3]);...\n elem(:,[1, 2, 4]);elem(:,[1, 3, 2])];\n face(:,4) = 0;\n face2elem = [idx;idx;idx;idx];\n clear elem\n end\nend\n\nset(gcf, 'Units', 'normal');\nset(gcf, 'Position', [0.25, 0.25, 0.55, 0.4]);\nshowrate(1./h(1:k), errMax(1:k), 1, 'k-+', '||u-u_h||');\n\n\nend\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/fem/vemPoisson3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.4999430295042682}} {"text": "function [err,time,solver,eqn] = femStokesHdiv(node,elem,pde,bdFlag,option,varargin)\n%% FEMPOISSON solve Poisson equation by various finite element methods\n% Created by Ming Wang, at Nov., 2012.\n%\n\n%% Check input arguments\nif ~exist('node','var') || ~exist('elem','var')\n [node,elem] = squaremesh([0,1,0,1],0.25); % default mesh is a square\nend\nif ~exist('option','var'), option = []; end\nif ~exist('pde','var')\n pde = StokesZulehnerdata; % default data\nend\nif ~exist('bdFlag','var')\n bdFlag = setboundary(node,elem,'Dirichlet'); \nend\n% default elemType\nif ~isfield(option,'elemType')\n option.elemType = 'RT0-P0';\nend\n\n%% Parameters\noption = femoption(option);\nelemType = option.elemType;\nmaxIt = option.maxIt;\nmaxN = option.maxN;\nL0 = option.L0;\nrefType = option.refType;\n\n%% Generate an initial mesh \nfor k = 1:L0\n if strcmp(refType,'red')\n [node,elem,bdFlag] = uniformrefine(node,elem,bdFlag);\n elseif strcmp(refType,'bisect')\n [node,elem,bdFlag] = uniformbisect(node,elem,bdFlag);\n end\nend\n\n%% Initialize err\nerruL2 = zeros(maxIt,1); erruIuhH1 = zeros(maxIt,1); erruInf = zeros(maxIt,1);\nerrpL2 = zeros(maxIt,1); errpIphL2 = zeros(maxIt,1); errpInf = zeros(maxIt,1);\nerrpL2re = zeros(maxIt,1);\nerrwL2 = zeros(maxIt,1); errwIwh = zeros(maxIt,1);\nerrTime = zeros(maxIt,1); solverTime = zeros(maxIt,1); \nassembleTime = zeros(maxIt,1); meshTime = zeros(maxIt,1); \nitStep = zeros(maxIt,1); stopErr = zeros(maxIt,1); flag = zeros(maxIt,1);\nN = zeros(maxIt,1);\n\n%% Finite Element Method \nfor k = 1:maxIt\n % solve the equation\n switch elemType\n case 'RT0-P0' % RT0-P0 mixed FEM \n [u,p,w,edge,eqn,info] = StokesRT0(node,elem,bdFlag,pde,option);\n case 'BDM1B-P0' % (BDM1+bubble)-P0 mixed FEM\n [u,p,w,edge,eqn,info] = StokesBDM1B(node,elem,bdFlag,pde,option);\n end\n % compute error\n tic;\n % ================== error for velocity ==================\n if isfield(pde,'exactu') \n switch elemType\n case 'RT0-P0'\n erruL2(k) = getL2errorRT0(node,elem,pde.exactu,u);\n % interpolation\n uI = faceinterpolate(pde.exactu,node,edge,'RT0');\n ufreeDof = eqn.ufreeDof;\n u0 = u(ufreeDof);\n uI0 = uI(ufreeDof);\n erruIuhH1(k) = sqrt((u0-uI0)'*eqn.A*(u0-uI0));\n erruInf(k) = max(abs(u0-uI0));\n case 'BDM1B-P0'\n erruL2(k) = getL2errorBDM1(node,elem,pde.exactu,u);\n % interpolation\n uI = u;\n uI(1:2*size(edge,1)) = faceinterpolate(pde.exactu,node,edge,'BDM1');\n ufreeDof = eqn.ufreeDof;\n u0 = u(ufreeDof);\n uI0 = uI(ufreeDof);\n erruIuhH1(k) = sqrt((u0-uI0)'*eqn.A*(u0-uI0));\n erruInf(k) = max(abs(u0-uI0));\n end\n end\n % ================== error for pressure ==================\n if isfield(pde,'exactp')\n area = simplexvolume(node,elem);\n errpL2(k) = getL2error(node,elem,pde.exactp,p);\n pI = Lagrangeinterpolate(pde.exactp,node,elem,'P0');\n rp = recoverP02P1(node,elem,p,'LA');\n % --------------------------\n errpL2(k) = getL2error(node,elem,pde.exactp,p);\n errpL2re(k) = getL2error(node,elem,pde.exactp,rp);\n errpIphL2(k) = sqrt(dot((pI-p).^2,area));\n errpInf(k) = max(abs(p-pI));\n end\n % ================== error for vorticity ==================\n if isfield(pde,'exactw')\n switch elemType\n case 'RT0-P0'\n errwL2(k) = getL2error(node,elem,pde.exactw,w);\n wI = Lagrangeinterpolate(pde.exactw,node,elem,'P1');\n errwIwh(k) = sqrt((w-wI)'*eqn.Mv*(w-wI));\n case 'BDM1B-P0'\n errwL2(k) = getL2error(node,elem,pde.exactw,w);\n wI = Lagrangeinterpolate(pde.exactw,node,elem,'P2',edge);\n errwIwh(k) = sqrt((w-wI)'*eqn.Mv*(w-wI));\n end\n end\n % ================== record ==================\n errTime(k) = toc;\n % record time\n solverTime(k) = info.solverTime;\n assembleTime(k) = info.assembleTime;\n % record solver information\n itStep(k) = info.itStep;\n stopErr(k) = info.stopErr;\n flag(k) = info.flag;\n % plot \n N(k) = size(node,1);\n if option.plotflag && N(k) < 3e3 % show mesh and solution for small size\n figure(1); showresult(node,elem,p); pause(0.1);\n figure(2); \n showsolutionRT(node,elem,u); pause(0.1);\n end\n if N(k) > maxN\n break;\n end\n % refine mesh\n tic;\n if strcmp(refType,'red')\n [node,elem,bdFlag] = uniformrefine(node,elem,bdFlag);\n elseif strcmp(refType,'bisect')\n [node,elem,bdFlag] = uniformbisect(node,elem,bdFlag);\n end\n meshTime(k) = toc;\nend\n\n%% Plot convergence rates\nif option.rateflag\n figure;\n set(gcf,'Units','normal'); \n set(gcf,'Position',[0.25,0.25,0.80,0.40]);\n subplot(1,3,1)\n h = 1./sqrt(N(1:k));\n showrateh3(h,erruL2(1:k),2,'k-+','||u-u_h||',...\n h,erruIuhH1(1:k),2,'r-*','||u_I-u_h||_1',...\n h,erruInf(1:k),2,'b-*','||u_I-u_h||_{\\infty}');\n subplot(1,3,2)\n showrateh4(h,errpL2(1:k),2,'k-+', '||p - p_h||',...\n h,errpL2re(1:k),2,'g-+','||p- p_h^r||',...\n h,errpIphL2(1:k),2,'r-+','||p_I - p_h||',...\n h,errpInf(1:k),2,'b-+','||p_I - p_h||_{\\infty}');\n subplot(1,3,3)\n showrateh2(h,errwL2(1:k),2,'k-+','||w - w_h||',...\n h,errwIwh(1:k),2,'r-+','||w_I - w_h||');\nend\n\n% Output\nerr = struct('N',N,'uL2',erruL2(1:k),'uInf',erruInf,'uIuhH1',erruIuhH1(1:k),...\n 'pL2',errpL2(1:k),'pIphL2',errpIphL2(1:k),'pInf',errpInf(1:k),'pL2re',errpL2re(1:k),...\n 'wL2',errwL2(1:k),'wIwhL2',errwIwh(1:k));\ntime = struct('N',N,'err',errTime(1:k),'solver',solverTime(1:k), ...\n 'assmble',assembleTime(1:k),'mesh',meshTime(1:k));\nsolver = struct('N',N(1:k),'itStep',itStep(1:k),'time',solverTime(1:k),...\n 'stopErr',stopErr(1:k),'flag',flag(1:k));\n \n%% Display error on screen\nts = zeros(k,3); ts = char(ts);\n% error of u\nfprintf('===========================================================\\n');\ndisplay(' N ||u_I-u_h||_1 ||u-u_h|| ||u_I-u_h||_{max}');\ndisplay([num2str(err.N) ts num2str(err.uIuhH1,'%0.5e') ts num2str(err.uL2,'%0.5e') ts num2str(err.uInf,'%0.5e')]);\n% error of p\nfprintf('===========================================================\\n');\ndisplay(' N ||p_I-p_h|| ||p-p_h|| ||p_I-p_h||_{max} ||p_I - p^r_h||');\ndisplay([num2str(err.N) ts num2str(err.pIphL2,'%0.5e') ts num2str(err.pL2,'%0.5e') ts num2str(err.pInf,'%0.5e') ts num2str(err.pL2re,'%0.5e')]);\n% error of w\nfprintf('===========================================================\\n');\ndisplay(' N ||w_I-w_h|| ||w-w_h||');\ndisplay([num2str(err.N) ts num2str(err.wIwhL2,'%0.5e') ts num2str(err.wL2,'%0.5e')]);\nfprintf('===========================================================\\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/iFEM/afem/femStokesHdiv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.499764039486731}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Q = INVERSEKINEMATIC_C8(robot, T)\t\n% Solves the inverse kinematic problem for the KUKA KR5 ARC robot\n% where:\n% robot stores the robot parameters.\n% T is an homogeneous transform that specifies the position/orientation\n% of the end effector.\n%\n% A call to Q=INVERSEKINEMATIC__KUKA_KR5_ARCHW returns 8 possible solutions, thus,\n% Q is a 6x8 matrix where each column stores 6 feasible joint values.\n%\n% \n% Example code:\n%\n% robot=load_robot('EPSON', 'x');\n% q = [0 0 0 0 0 0];\t\n% T = directkinematic(robot, q);\n% %Call the inversekinematic for this robot\n% qinv = inversekinematic(robot, T);\n% check that all of them are feasible solutions!\n% and every Ti equals T\n% for i=1:8,\n% Ti = directkinematic(robot, qinv(:,i))\n% end\n%\tSee also DIRECTKINEMATIC.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n% Copyright (C) 2012, by Arturo Gil Aparicio\n%\n% This file is part of ARTE (A Robotics Toolbox for Education).\n% \n% ARTE is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% ARTE is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with ARTE. If not, see .\nfunction q = inversekinematic_C8(robot, T)\n\n%initialize q,\n%eight possible solutions are generally feasible\nq=zeros(6,8);\n\n% %Evaluate the parameters\n% theta = eval(robot.DH.theta);\nd = eval(robot.DH.d);\nL6=abs(d(6));\n\n\n%T= [ nx ox ax Px;\n% ny oy ay Py;\n% nz oz az Pz];\nPx=T(1,4);\nPy=T(2,4);\nPz=T(3,4);\n\n%Compute the position of the wrist, being W the Z component of the end effector's system\nW = T(1:3,3);\n\n% Pm: wrist position\nPm = [-Py Px Pz]' - L6*W; \n\n%first joint, two possible solutions admited: \n% if q(1) is a solution, then q(1) + pi is also a solution\nq1=atan2(Pm(2), Pm(1));\n\n\n%solve for q2\nq2_1=solve_for_theta2(robot, [q1 0 0 0 0 0 0], Pm);\n%the other possible solution is q1 + pi\nq2_2=solve_for_theta2(robot, [q1+pi 0 0 0 0 0 0], Pm);\n\n%solve for q3\nq3_1=solve_for_theta3(robot, [q1 0 0 0 0 0 0], Pm);\n%solver for q3 for both cases\nq3_2=solve_for_theta3(robot, [q1+pi 0 0 0 0 0 0], Pm);\n\n\n\n%the next matrix doubles each column. For each two columns, two different\n%configurations for theta4, theta5 and theta6 will be computed. These\n%configurations are generally referred as wrist up and wrist down solution\nq = [q1 q1 q1 q1 q1+pi q1+pi q1+pi q1+pi; \n q2_1(1) q2_1(1) q2_1(2) q2_1(2) q2_2(1) q2_2(1) q2_2(2) q2_2(2);\n q3_1(1) q3_1(1) q3_1(2) q3_1(2) q3_2(1) q3_2(1) q3_2(2) q3_2(2);\n 0 0 0 0 0 0 0 0;\n 0 0 0 0 0 0 0 0;\n 0 0 0 0 0 0 0 0];\n\n\n%leave only the real part of the solutions\nq=real(q);\n\n%Note that in this robot, the joint q3 has a non-simmetrical range. In this\n%case, the joint ranges from 60 deg to -219 deg, thus, the typical normalizing\n%step is avoided in this angle (the next line is commented). When solving\n%for the orientation, the solutions are normalized to the [-pi, pi] range\n%only for the theta4, theta5 and theta6 joints.\n\n%normalize q to [-pi, pi]\nq(1,:) = normalize(q(1,:));\nq(2,:) = normalize(q(2,:));\n% solve for the last three joints\n% for any of the possible combinations (theta1, theta2, theta3)\nfor i=1:2:size(q,2),\n qtemp = solve_spherical_wrist(robot, q(:,i), T, 1,'geometric'); %wrist up\n qtemp(4:6)=normalize(qtemp(4:6));\n q(:,i)=qtemp;\n \n qtemp = solve_spherical_wrist(robot, q(:,i), T, -1, 'geometric'); %wrist up\n qtemp(4:6)=normalize(qtemp(4:6));\n q(:,i+1)=qtemp;\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% solve for second joint theta2, two different\n% solutions are returned, corresponding\n% to elbow up and down solution\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction q2 = solve_for_theta2(robot, q, Pm)\n\n%Evaluate the parameters\ntheta = eval(robot.DH.theta);\nd = eval(robot.DH.d);\na = eval(robot.DH.a);\nalpha = eval(robot.DH.alpha);\n\n%See geometry\nL2=abs(a(2));\nL3=abs(d(4));\nA2 = abs(a(3));\n\n%See geometry of the robot\n%compute L4\nL4 = sqrt(A2^2 + L3^2);\n\n%The inverse kinematic problem can be solved as in the IRB 140 (for example)\n\n%given q1 is known, compute first DH transformation\nT01=dh(robot, q, 1);\n\n%Express Pm in the reference system 1, for convenience\np1 = inv(T01)*[Pm; 1];\n\nr = sqrt(p1(1)^2 + p1(2)^2);\n\nbeta = atan2(-p1(2), p1(1));\ngamma = real(acos((L2^2+r^2-L4^2)/(2*r*L2)));\n\n%return two possible solutions\n%elbow up and elbow down\n%the order here is important and is coordinated with the function\n%solve_for_theta3\nq2(1) = pi/2 - beta - gamma; %elbow up\nq2(2) = pi/2 - beta + gamma; %elbow down\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% solve for third joint theta3, two different\n% solutions are returned, corresponding\n% to elbow up and down solution\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction q3 = solve_for_theta3(robot, q, Pm)\n\n%Evaluate the parameters\ntheta = eval(robot.DH.theta);\nd = eval(robot.DH.d);\na = eval(robot.DH.a);\nalpha = eval(robot.DH.alpha);\n\n%See geometry\nL2=abs(a(2));\nL3=abs(d(4));\n\nA2 = abs(a(3));\n\n%See geometry of the robot\n%compute L4\nL4 = sqrt(A2^2 + L3^2);\n\n%the angle phi is fixed\nphi=acos((A2^2+L4^2-L3^2)/(2*A2*L4));\n\n%given q1 is known, compute first DH transformation\nT01=dh(robot, q, 1);\n\n%Express Pm in the reference system 1, for convenience\np1 = inv(T01)*[Pm; 1];\n\nr = sqrt(p1(1)^2 + p1(2)^2);\n\nbeta = real(acos((L2^2 + L4^2 - r^2)/(2*L2*L4)));\n\n%return two possible solutions\n%elbow up and elbow down solutions\n%the order here is important\nq3(1) = pi - phi - beta; \nq3(2) = pi - phi + beta; ", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/robots/EPSON/C8/inversekinematic_C8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.4997640283496214}} {"text": "function [esTSNR,esHRNR]=WienerNoiseReduction(ns,fs,IS)\n\n% [esTSNR,esHRNR]=WIENERNOISEREDUCTION(ns,fs,IS)\n%\n% Title : Wiener Noise Suppressor with TSNR & HRNR algorithms\n%\n% Description : Wiener filter based on tracking a priori SNR using Decision-Directed \n% method, proposed by Plapous et al 2006. The two-step noise reduction\n% (TSNR) technique removes the annoying reverberation effect while\n% maintaining the benefits of the decision-directed approach. However,\n% classic short-time noise reduction techniques, including TSNR, introduce\n% harmonic distortion in the enhanced speech. To overcome this problem, a\n% method called harmonic regeneration noise reduction (HRNR)is implemented\n% in order to refine the a priori SNR used to compute a spectral gain able \n% to preserve the speech harmonics.\n% \n% \n% Reference : Plapous, C.; Marro, C.; Scalart, P., \"Improved Signal-to-Noise Ratio\n% Estimation for Speech Enhancement\", IEEE Transactions on Audio, Speech,\n% and Language Processing, Vol. 14, Issue 6, pp. 2098 - 2108, Nov. 2006 \n%\n% Input Parameters : \n% ns Noisy speech \n% fs Sampling frequency (in Hz)\n% IS Initial Silence (or non-speech activity) Period (in number of samples)\n%\n% Output Parameters : enhanced speech \n% esTSNR enhanced speech with the Two-Step Noise Reduction method \n% esHNRN enhanced speech with the Harmonic Regeneration Noise Reduction method\n% \n%Author : LIU Ming, 2008\n%Modified : SCALART Pascal october, 2008\n%\n%\n\n%% ------- input noisy speech --------\n\nl = length(ns);\ns=ns;\n\nwl = fix(0.020*fs) % window length is 20 ms\nNFFT=2*wl % FFT size is twice the window length\nhanwin = hanning(wl);\n\n\nif (nargin<3 | isstruct(IS))\n IS=10*wl; %Initial Silence or Noise Only part in samples (= ten frames)\nend\n%% -------- compute noise statistics ----------\n\n\nnsum = zeros(NFFT,1);\n\ncount = 0; \n for m = 0:IS-wl\n nwin = s(m+1:m+wl).*hanwin;\t\n nsum = nsum + abs(fft(nwin,NFFT)).^2;\n count = count + 1;\n end\n\nd= (nsum)/count;\n\n\n%% --------- main algorithm ---------------\nSP = 0.25; % Shift percentage is 50 % Overlap-Add method works good with this value\nnormFactor=1/SP;\noverlap = fix((1-SP)*wl); % overlap between sucessive frames\noffset = wl - overlap;\nmax_m = fix((l-NFFT)/offset);\n\nzvector = zeros(NFFT,1);\noldmag = zeros(NFFT,1);\nnews = zeros(l,1);\n\nphasea=zeros(NFFT,max_m);\nxmaga=zeros(NFFT,max_m);\ntsnra=zeros(NFFT,max_m);\nnewmags=zeros(NFFT,max_m);\n\nalpha = 0.98;\n\n%Iteration to remove noise\n\n%% --------------- TSNR ---------------------\nfor m = 0:max_m\n begin = m*offset+1; \n iend = m*offset+wl;\n speech = ns(begin:iend); %extract speech segment\n winy = hanwin.*speech; %perform hanning window\n ffty = fft(winy,NFFT); %perform fast fourier transform\n phasey = angle(ffty); %extract phase\n phasea(:,m+1)=phasey; %for HRNR use\n magy = abs(ffty); %extract magnitude\n xmaga(:,m+1)= magy; %for HRNR use\n postsnr = ((magy.^2) ./ d)-1 ; %calculate a posteriori SNR\n postsnr=max(postsnr,0.1); % limitation to prevent distorsion\n \n %calculate a priori SNR using decision directed approach\n eta = alpha * ( (oldmag.^2)./d ) + (1-alpha) * postsnr;\n newmag = (eta./(eta+1)).* magy;\n \n %calculate TSNR\n tsnr = (newmag.^2) ./ d;\n Gtsnr = tsnr ./ (tsnr+1); %gain of TSNR \n tsnra(:,m+1)=Gtsnr; \n %Gtsnr=max(Gtsnr,0.1); \n Gtsnr = gaincontrol(Gtsnr,NFFT/2);\n \n %for HRNR use\n newmag = Gtsnr .* magy;\n newmags(:,m+1) = newmag; %for HRNR use\n ffty = newmag.*exp(i*phasey);\n oldmag = abs(newmag);\n news(begin:begin+NFFT-1) = news(begin:begin+NFFT-1) + real(ifft(ffty,NFFT))/normFactor;\nend\n\nesTSNR=news;\n%% --------------- HRNR -----------------------\n\n%non linearity\nnewharm= max(esTSNR,0);\nnews = zeros(l,1);\n%\nfor m = 0:max_m\n begin = m*offset+1; \n iend = m*offset+wl;\n\n nharm = hanwin.*newharm(begin:iend);\n ffth = abs(fft(nharm,NFFT)); %perform fast fourier transform\n\n snrham= ( (tsnra(:,m+1)).*(abs(newmags(:,m+1)).^2) + (1-(tsnra(:,m+1))) .* (ffth.^2) ) ./d;\n \n newgain= (snrham./(snrham+1));\n %newgain=max(newgain,0.1); \n \n newgain=gaincontrol(newgain,NFFT/2);\n \n newmag = newgain .* xmaga(:,m+1);\n \n ffty = newmag.*exp(i*phasea(:,m+1));\n \n news(begin:begin+NFFT-1) = news(begin:begin+NFFT-1) + real(ifft(ffty,NFFT))/normFactor;\nend;\n%Output\nesHRNR=news;\n\nfigure;\n[B,f,T] = specgram(ns,NFFT,fs,hanning(wl),wl-10);\nimagesc(T,f,20*log10(abs(B)));axis xy;colorbar\ntitle(['Spectrogram - noisy speech'])\nxlabel('Time (sec)');ylabel('Frequency (Hz)');\n\nfigure;\n[B,f,T] = specgram(esTSNR,NFFT,fs,hanning(wl),wl-10);\nimagesc(T,f,20*log10(abs(B)));axis xy;colorbar\ntitle(['Spectrogram - output speech TSNR'])\nxlabel('Time (sec)');ylabel('Frequency (Hz)');\n\nfigure;\n[B,f,T] = specgram(esHRNR,NFFT,fs,hanning(wl),wl-10);\nimagesc(T,f,20*log10(abs(B)));axis xy;colorbar\ntitle(['Spectrogram - output speech HRNR'])\nxlabel('Time (sec)');ylabel('Frequency (Hz)');\n\n\n\n\n\n\nfunction NewGain=gaincontrol(Gain,ConstraintInLength)\n%\n%Title : Additional Constraint on the impulse response \n% to ensure linear convolution property\n%\n%\n%Description : \n%\n% 1- The time-duration of noisy speech frame is equal to L1 samples.\n%\n% 2- This frame is then converted in the frequency domain \n% by applying a short-time Fourier transform of size NFFT leading\n% to X(wk) k=0,...,NFFT-1 when NFFT is the FFT size.\n%\n% 3- The estimated noise reduction filter is G(wk) k=0,1,...,NFFT-1 \n% leading to an equivalent impulse response g(n)=IFFT[G(wk)] \n% of length L2=NFFT\n%\n% 4- When applying the noise reduction filter G(wk) to the noisy \n% speech spectrum X(wk), the multiplication S(wk)=G(wk)X(wk) is\n% equivalent to a convolution in the time domain. So the\n% time-duration of the enhanced speech s(n) should be equal to \n% Ltot=L1+L2-1.\n%\n% 5- If the length Ltot is greater than the time-duration of the IFFT[S(wk)] \n% the a time-aliasing effect will appear.\n%\n% 6- To overcome this phenomenon, the time-duration L2 of the equivalent\n% impulse response g(n) should be chosen such that Ltot = L1 + L2 -1 <= NFFT \n% => L2 <= NFFT+1-Ll\n%\n% here we have NFFT=2*Ll so we should have L2 <= Ll+1. I have made\n% the following choice : the time-duration of g(n) is limited to\n% L2=NFFT/2=L1 (see lines 88 and 192)\n%\n%Author : SCALART Pascal\n%\n%October 2008\n%\n\n\nmeanGain=mean(Gain.^2);\nNFFT=length(Gain);\n\nL2=ConstraintInLength;\n\nwin=hamming(L2);\n\n% Frequency -> Time\n% computation of the non-constrained impulse response\nImpulseR=real(ifft(Gain));\n\n% application of the constraint in the time domain\nImpulseR2=[ImpulseR(1:L2/2).*win(1+L2/2:L2);zeros(NFFT-L2,1);ImpulseR(NFFT-L2/2+1:NFFT).*win(1:L2/2)];\n\n% Time -> Frequency\nNewGain=abs(fft(ImpulseR2,NFFT));\n\nmeanNewGain=mean(NewGain.^2);\n\nNewGain=NewGain*sqrt(meanGain/meanNewGain); % normalisation to keep the same energy (if white r.v.)\n\n\n \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/WienerNoiseReduction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.49972519508629654}} {"text": "%%*******************************************************************\n%% schurmat_qblk: compute schur matrix corresponding to SOCP blocks.\n%%\n%% HKM direction: output = schur + Ax*Ae' + Ae*Ax' - Ad*Ad'\n%% NT direction: output = schur + Ae*Ae' - Ad*Ad'\n%%\n%% where schur = A*D*A', and Ad is the modification to ADA' \n%% so that the latter is positive definite. \n%%\n%% [schur,UU,EE] = schurmat_qblk(blk,At,schur,UU,EE,p,dd,ee,xx);\n%% \n%% UU: stores the dense columns of Ax, Ae, Ad, and possibly \n%% those of A*D^{1/2}. It has the form UU = [Ax Ae Ad]. \n%% EE: stores the assocaited (2,2) block matrix when the\n%% output matrix is expressed as an augmented matrix.\n%% It has the form EE = [0 -lam 0; -lam 0 0; 0 0 I].\n%%\n%% options = 0, HKM\n%% = 1, NT\n%%*****************************************************************\n%% SDPT3: version 4.0\n%% Copyright (c) 1997 by\n%% Kim-Chuan Toh, Michael J. Todd, Reha H. Tutuncu\n%% Last Modified: 16 Sep 2004\n%%*****************************************************************\n\n function [schur,UU,EE] = schurmat_qblk(blk,At,par,schur,UU,EE,p,dd,ee,xx);\n \n global idxdenAq nnzschur_qblk\n\n if (nargin == 10); options = 0; else; options = 1; end; \n iter = par.iter; \n \n if isempty(EE) \n count = 0; \n else \n count = max(max(EE(:,2)),max(EE(:,1))); \n end\n pblk = blk(p,:); n = sum(pblk{2}); numblk = length(pblk{2}); \n%% \n Ae = qprod(pblk,At{p}',ee{p}); \n if (options == 0) \n Ax = qprod(pblk,At{p}',xx{p}); \n end\n idxden = checkdense(Ae);\n ddsch = dd{p}; \n if ~isempty(idxden); \n spcolidx = setdiff([1:numblk],idxden); \n s = 1 + [0, cumsum(pblk{2})];\n idx = s(idxden); \n tmp = zeros(n,1); \n tmp(idx) = sqrt(2*abs(ddsch(idx))); \n Ad = qprod(pblk,At{p}',tmp); \n ddsch(idx) = abs(ddsch(idx)); \n if (options == 0) \n len = length(idxden); \n gamzsub = par.gamz{p}(idxden);\n lam = gamzsub.*gamzsub;\n UU = [UU, Ax(:,idxden), Ae(:,idxden)*spdiags(lam,0,len,len), Ad(:,idxden)]; \n tmp = count+[1:len]'; \n EE = [EE; [tmp, len+tmp, -lam; len+tmp, tmp, -lam; ...\n 2*len+tmp, 2*len+tmp, ones(len,1)] ];\n count = count+3*len; \n Ax = Ax(:,spcolidx); Ae = Ae(:,spcolidx); \n tmp = Ax*Ae'; \n schur = schur + (tmp + tmp');\n else\n len = length(idxden);\n w2 = par.gamz{p}./par.gamx{p}; \n lam = w2(idxden); \n UU = [UU, Ae(:,idxden)*spdiags(sqrt(lam),0,len,len), Ad(:,idxden)]; \n tmp = count+[1:len]'; \n EE = [EE; [tmp, tmp, -lam; len+tmp, len+tmp, ones(len,1)] ]; \n count = count + 2*len; \n Ae = Ae(:,spcolidx); \n schur = schur + Ae*Ae';\n end\n else\n if (options == 0)\n tmp = Ax*Ae'; \n schur = schur + (tmp+tmp');\n else \n tmp = Ae*Ae'; \n schur = schur + tmp; \n end\n end\n if (iter==1)\n idxdenAq{p} = checkdense(At{p}'); \n end\n if ~isempty(idxdenAq{p});\n idxden = idxdenAq{p}; \n len = length(idxden); \n Ad = At{p}(idxden,:)'*spdiags(sqrt(abs(ddsch(idxden))),0,len,len); \n UU = [UU, Ad];\n tmp = count+[1:len]'; \n EE = [EE; [tmp, tmp, -sign(ddsch(idxden))]]; \n count = count + len; \n ddsch(idxden) = zeros(len,1); \n end \n schurtmp = At{p}' *spdiags(ddsch,0,n,n) *At{p}; \n schur = schur + schurtmp;\n%%*******************************************************************\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/SDPT3-4.0/SDPT3-4.0/Solver/schurmat_qblk_old.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4997251909062489}} {"text": "function gencost = modcost(gencost, alpha, modtype)\n%MODCOST Modifies generator costs by shifting or scaling (F or X).\n% NEWGENCOST = MODCOST(GENCOST, ALPHA)\n% NEWGENCOST = MODCOST(GENCOST, ALPHA, MODTYPE)\n%\n% For each generator cost F(X) (for real or reactive power) in\n% GENCOST, this function modifies the cost by scaling or shifting\n% the function by ALPHA, depending on the value of MODTYPE, and\n% and returns the modified GENCOST. Rows of GENCOST can be a mix\n% of polynomial or piecewise linear costs. ALPHA can be a scalar,\n% applied to each row of GENCOST, or an NG x 1 vector, where each\n% element is applied to the corresponding row of GENCOST.\n%\n% MODTYPE takes one of the 4 possible values (let F_alpha(X) denote the\n% the modified function):\n% 'SCALE_F' (default) : F_alpha(X) == F(X) * ALPHA\n% 'SCALE_X' : F_alpha(X * ALPHA) == F(X)\n% 'SHIFT_F' : F_alpha(X) == F(X) + ALPHA\n% 'SHIFT_X' : F_alpha(X + ALPHA) == F(X)\n\n% MATPOWER\n% Copyright (c) 2010-2020, Power Systems Engineering Research Center (PSERC)\n% by Ray Zimmerman, PSERC Cornell\n%\n% This file is part of MATPOWER.\n% Covered by the 3-clause BSD License (see LICENSE file for details).\n% See https://matpower.org for more info.\n\n%% define named indices into data matrices\n[PW_LINEAR, POLYNOMIAL, MODEL, STARTUP, SHUTDOWN, NCOST, COST] = idx_cost;\n\nif nargin < 3\n modtype = 'SCALE_F';\nend\n\n[ng, m] = size(gencost);\n\nif ng ~= 0\n if length(alpha) ~= ng\n if length(alpha) == 1 && ng > 1 %% scalar, make it a col vector\n alpha = alpha * ones(ng, 1);\n else\n error('modcost: ALPHA must be a scalar or col vector with NG rows');\n end\n elseif size(alpha, 2) ~= 1\n alpha = alpha'; %% convert row vector to col vector\n end\n\n ipwl = find(gencost(:, MODEL) == PW_LINEAR);\n ipol = find(gencost(:, MODEL) == POLYNOMIAL);\n npwl = length(ipwl);\n npol = length(ipol);\n c = gencost(ipol, COST:m);\n\n switch modtype\n case 'SCALE_F',\n if npol\n gencost(ipol, COST:m) = spdiags(alpha(ipol), 0, npol, npol) * c;\n end\n if npwl\n gencost(ipwl, COST+1:2:m) = spdiags(alpha(ipwl), 0, npwl, npwl) * ...\n gencost(ipwl, COST+1:2:m);\n end\n case 'SCALE_X',\n for k = 1:length(ipol)\n n = gencost(ipol(k), NCOST);\n for i = 1:n\n gencost(ipol(k), COST+i-1) = c(k, i) / alpha(ipol(k))^(n-i);\n end\n end\n if npwl\n gencost(ipwl, COST:2:m-1) = spdiags(alpha(ipwl), 0, npwl, npwl) * ...\n gencost(ipwl, COST:2:m-1);\n end\n case 'SHIFT_F',\n for k = 1:length(ipol)\n n = gencost(ipol(k), NCOST);\n gencost(ipol(k), COST+n-1) = alpha(ipol(k)) + c(k, n);\n end\n if npwl\n gencost(ipwl, COST+1:2:m) = spdiags(alpha(ipwl), 0, npwl, npwl) * ...\n ones(length(ipwl), (m+1-COST)/2) + gencost(ipwl, COST+1:2:m);\n end\n case 'SHIFT_X',\n for k = 1:length(ipol)\n n = gencost(ipol(k), NCOST);\n gencost(ipol(k), COST:COST+n-1) = polyshift(c(k, 1:n)', alpha(ipol(k)))';\n end\n if npwl\n gencost(ipwl, COST:2:m-1) = spdiags(alpha(ipwl), 0, npwl, npwl) * ...\n ones(length(ipwl), (m+1-COST)/2) + gencost(ipwl, COST:2:m-1);\n end\n otherwise\n error('modcost: ''%s'' is not a valid modtype\\n', modtype);\n end\nend\n\n\n%%----- POLYSHIFT -----\nfunction d = polyshift(c, a)\n%POLYSHIFT Returns the coefficients of a horizontally shifted polynomial.\n%\n% D = POLYSHIFT(C, A) shifts to the right by A, the polynomial whose\n% coefficients are given in the column vector C.\n%\n% Example: For any polynomial with n coefficients in c, and any values\n% for x and shift a, the f - f0 should be zero.\n% x = rand;\n% a = rand;\n% c = rand(n, 1);\n% f0 = polyval(c, x)\n% f = polyval(polyshift(c, a), x+a)\n\nn = length(c);\nd = zeros(size(c));\nA = (-a * ones(n, 1)) .^ ((0:n-1)');\nb = ones(n, 1);\nfor k = 1:n\n d(n-k+1) = b' * ( c(n-k+1:-1:1) .* A(1:n-k+1) );\n b = cumsum(b(1:n-k));\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/modcost.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.49969550416435476}} {"text": "function [medianPrice,medianTime,totalVol,nObs] = realized_compute_median(price,time,volume)\n% Computes the median price at each time stamp for a vector of prices which may have multiple\n% observations with the same time stamp.\n%\n% USAGE:\n% [MEDIANPRICE,MEDIANTIME,TOTALVOL,NOBS] = realized_compute_median(PRICE,TIME,VOLUME)\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), sorted in\n% ascending order\n% VOLUME - [OPTIONAL] m by 1 vector of transaction volumes or bid/ask size. If omitted\n% TOTALVOLUME will be a vector of 0's.\n%\n% OUTPUTS:\n% MEDIANPRICE - n by 1 vector of median prices where n is the number of unique elements of TIME\n% MEDIANTIME - n by 1 vector of time stamps corresponding to MEDIANPRICE\n% TOTALVOLUME - n by 1 vector capturing the total volume at each time stamp\n% NOBS - n by 1 vector indicating number of prices at each element of MEDIANTIME\n%\n% COMMENTS:\n% This is a helper function for most of the Realized toolkit. Most function in the Realized\n% toolkit expect time stamps to be unique. Median price is a reasonable and fairly robust (to\n% noise) method of computing a unique price for each time stamp.\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 2 Date: 6/12/2011\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% InputChecking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif nargin<2 || nargin>3\n error('Six or seven inputs required.')\nend\nif size(price,2)>size(price,1)\n price=price';\nend\nif size(price,2)>1\n error('PRICE must be a m by 1 vector.')\nend\nm = size(price,1);\n\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)~=m\n error('TIME must be a m by 1 vector.')\nend\ntime = double(time);\n\nif nargin == 3\n if size(volume,2)>size(volume,1)\n volume=volume';\n end\n if size(volume,2)>1 || length(volume)~=m\n error('VOLUME must be a m by 1 vector.')\n end\nelse\n volume = zeros(m,1);\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Make sure time and volume are double since I store it was uint32\ntime = double(time);\nvolume = double(volume);\n\n% Quickly find the time change points\npl = find(diff(time));\npl = [1;pl+1;length(time)+1];\n\n% Get the number of observations\nN = length(pl);\n\n% Pre-allocatte\nmedianPrice = zeros(N-1,1);\nmedianTime = time(pl(1:N-1));\ntotalVol = zeros(N-1,1);\nnObs = zeros(N-1,1);\n\n% Loop over unique sizes, with special cases for 1 and 2\n[sizes,~,ind]=unique(diff(pl));\nfor i=1:length(sizes)\n j=find(ind==i);\n loc = bsxfun(@plus,pl(j),0:sizes(i)-1)';\n switch sizes(i)\n case 1\n medianPrice(j) = price(pl(j));\n totalVol(j) = volume(pl(j));\n case 2\n medianPrice(j) = (price(pl(j)) + price(pl(j)+1))/2;\n otherwise\n sortedPrice = sort(price(loc));\n if mod(sizes(i),2)==0\n medianPrice(j) = mean(sortedPrice([sizes(i)/2;sizes(i)/2+1],:))';\n else\n medianPrice(j) = sortedPrice(ceil(sizes(i)/2),:)';\n end\n end\n totalVol(j) = sum(volume(loc))';\n nObs(j) = sizes(i);\nend\n\n% Old, slower method\n% Loop\n% singleton = pldiff==1;\n% medianPrice(singleton) = price(pl(singleton));\n% totalVol(singleton) = volume(pl(singleton));\n% nObs(singleton) = 1;\n% notSingleton = find(~singleton);\n% \n% for i=1:length(notSingleton)\n% j = notSingleton(i);\n% medianPrice(j) = median(price(pl(j):pl(j+1)-1));\n% totalVol(j) = sum(volume(pl(j):pl(j+1)-1));\n% nObs(j) = pl(j+1)-pl(j)+1;\n% end\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_compute_median.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.661922862511608, "lm_q1q2_score": 0.4996954963599876}} {"text": "function [fDeltaBValue, fBValueLearning, fBValueObserved] = kj_calcbvalues(mCatalog, fSplitTime, bLearningPeriod, fLearningPeriod, bObservedPeriod, fObservedPeriod, nMinimumNumber, nCalculateMC)\n% function [fDeltaBValue, fBValueLearning, fBValueObserved]\n% = kj_calcbvalues(mCatalog, fSplitTime, bLearningPeriod, fLearningPeriod,\n% bObservedPeriod, fObservedPeriod, nMinimumNumber, nCalculateMC)\n% ----------------------------------------------------------------------------------\n% Calculation of the b-values in the learning and observation (forecast) period\n%\n% Input parameters:\n% mCatalog Earthquake catalog\n% fSplitTime Time at which the catalog will be split\n% bLearningPeriod Fix duration of the learning period (1 = fix, 0 = use catalog from start)\n% fLearningPeriod Duration of the learning period\n% bObservedPeriod Fix duration of the observation period (1 = fix, 0 = use catalog till end)\n% fObservedPeriod Duration of the observation period\n% nMinimumNumber Minimum number of earthquakes in the catalog for calculating the output values\n% nCalculateMC Method to determine the magnitude of completeness (see also: help calc_Mc)\n%\n% Output parameters:\n% fDeltaBValue Difference of both of the b-values (fBValueObserved - fBValueLearning)\n% fBValueLearning b-value of the learning period\n% fBValueObserved b-value of the observation (forecast) period\n%\n% Danijel Schorlemmer\n% April 23, 2002\n\nglobal bDebug;\nif bDebug\n report_this_filefun(mfilename('fullpath'));\nend\n\n% Init output variables\nfDeltaBValue = nan;\nfBValueLearning = nan;\nfBValueObserved = nan;\n\ntry\n % Create the catalogs for the learning and observation periods\n [mLearningCatalog, mObservedCatalog] = ex_SplitCatalog(mCatalog, fSplitTime, bLearningPeriod, fLearningPeriod, bObservedPeriod, fObservedPeriod);\n\n % Determine magnitude of completeness\n fMc = calc_Mc(mLearningCatalog, nCalculateMC);\n\n % Calculate the b-value of the learning period\n vSelection = mLearningCatalog(:,6) >= fMc;\n mLearningCatalog = mLearningCatalog(vSelection,:);\n if length(mLearningCatalog(:,1)) > nMinimumNumber\n [vDummy, fBValueLearning, vDummy, vDummy] = bmemag(mLearningCatalog);\n end\n\n % Calculate the b-value of the observation period\n vSelection = mObservedCatalog(:,6) >= fMc;\n mObservedCatalog = mObservedCatalog(vSelection,:);\n if length(mObservedCatalog(:,1)) > nMinimumNumber\n [vDummy, fBValueObserved, vDummy, vDummy] = bmemag(mObservedCatalog);\n end\n\n % Calculate the difference\n if (~isnan(fBValueLearning)) && (~isnan(fBValueObserved))\n fDeltaBValue = fBValueObserved - fBValueLearning;\n end\ncatch\nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/danijel/probfore/kj_calcbvalues.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6406358548398979, "lm_q1q2_score": 0.49969141842334097}} {"text": "% SP_EVALUATE_ELEMENT_LIST: compute the basis functions in a given list of elements.\n%\n% sp = sp_evaluate_element_list (space, msh_elems, 'option1', value1, ...)\n%\n% INPUTS:\n% \n% space: object defining the space of discrete functions (see sp_vector)\n% msh_elems: msh structure containing the information of quadrature or\n% visualization points, for a given list of elements \n% (see msh_cartesian/msh_evaluate_element_list)\n% 'option', value: additional optional parameters, currently available options are:\n% \n% Name | Default value | Meaning\n% ------------+-----------------+----------------------------------\n% value | true | compute shape_functions\n% gradient | false | compute shape_function_gradients\n% divergence | false | compute shape_function_divs\n% curl | false | compute shape_function_curls\n%\n% OUTPUT:\n%\n% sp: struct representing the discrete function space, with the following fields:\n% (see the article for a detailed description)\n%\n% FIELD_NAME (SIZE) DESCRIPTION\n% ncomp (scalar) number of components of the functions of the space\n% ndof (scalar) total number of degrees of freedom\n% ndof_dir (ncomp x ndim matrix) for each component, number of degrees of freedom along each direction\n% nsh_max (scalar) maximum number of shape functions per element\n% nsh (1 x msh_col.nel vector) actual number of shape functions per each element\n% connectivity (nsh_max x msh_col.nel vector) indices of basis functions that do not vanish in each element\n% shape_functions (ncomp x msh_col.nqn x nsh_max x msh_col.nel) basis functions evaluated at each quadrature node in each element\n% shape_function_gradients\n% (ncomp x rdim x msh_col.nqn x nsh_max x msh_col.nel) basis function gradients evaluated at each quadrature node in each element\n% shape_function_divs (msh_col.nqn x nsh_max x msh_col.nel) basis function divergence evaluated at each quadrature node in each element\n% shape_function_curls \n% 2D: (msh_col.nqn x nsh_max x msh_col.nel) basis function curl evaluated at each quadrature node in each element\n% 3D: (3 x msh_col.nqn x nsh_max x msh_col.nel) \n%\n% Copyright (C) 2009, 2010, 2011 Carlo de Falco\n% Copyright (C) 2011, 2015, 2019 Rafael Vazquez\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\nfunction sp = sp_evaluate_element_list (space, msh, varargin)\n\nvalue = true;\ngradient = false;\ndivergence = false;\ncurl = false;\nhessian = false;\nif (~isempty (varargin))\n if (~rem (length (varargin), 2) == 0)\n error ('sp_evaluate_element_list: options must be passed in the [option, value] format');\n end\n for ii=1:2:length(varargin)-1\n if (strcmpi (varargin {ii}, 'value'))\n value = varargin {ii+1};\n elseif (strcmpi (varargin {ii}, 'gradient'))\n gradient = varargin {ii+1};\n elseif (strcmpi (varargin {ii}, 'curl'))\n curl = varargin {ii+1};\n elseif (strcmpi (varargin {ii}, 'divergence'))\n divergence = varargin {ii+1};\n elseif (strcmpi (varargin {ii}, 'hessian'))\n hessian = varargin {ii+1};\n else\n warning ('Ignoring unknown option %s', varargin {ii});\n end\n end\nend\n\ngrad_param = gradient || divergence || curl || hessian;\nvalue_param = value || grad_param;\ndiv_param = false; curl_param = false;\nswitch (lower (space.transform))\n case {'curl-preserving'}\n curl_param = curl;\n case {'div-preserving'}\n div_param = divergence;\nend\n\nsp = sp_evaluate_element_list_param (space, msh, 'value', value_param, 'gradient', grad_param, 'divergence', div_param, 'curl', curl_param, 'hessian', hessian);\n\nif (isempty (msh.elem_list))\n return\nend\n\nswitch (lower (space.transform))\n case {'grad-preserving'}\n sp = sp_vector_grad_preserving_transform (sp, msh, value, gradient, curl, divergence, hessian);\n case {'curl-preserving'}\n sp = sp_vector_curl_preserving_transform (sp, msh, value, curl);\n if (gradient || divergence || hessian)\n warning ('Gradient, divergence and hessian not implemented for curl-preserving transformation')\n end\n case {'div-preserving'}\n sp = sp_vector_div_preserving_transform (sp, msh, value, gradient, curl, divergence);\n if (hessian)\n warning ('Hessian not implemented for div-preserving transformation')\n end\nend\n\nend\n", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/space/@sp_vector/sp_evaluate_element_list.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.4996554002475694}} {"text": "function cS = antigorite\n% serpentine\n\ncs_Atg = crystalSymmetry('m',[4.7013 1 0.7844], [90, 91.633, 90]*degree);\nN = Miller({0,0,1},{0,0,-1},{1,0,0},{-1,0,0},{2,1,0},{-2,1,0},cs_Atg);\ndist = [0.15, 0.15, 0.4, 0.4, 2, 2];\ncS = crystalShape(N./dist);", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/geometry/+crystalShape/antigorite.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.85391273808085, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.49962532863994674}} {"text": "function HD = VARhd(VAR)\n% =======================================================================\n% Compute the historical decomposition of the time series in a VAR\n% estimated with VARmodel and identified with VARir/VARfevd\n% =======================================================================\n% HD = VARhd(VAR)\n% -----------------------------------------------------------------------\n% INPUTS \n% - VAR: structure, result of VARmodel -> VARir/VARfevd function\n% -----------------------------------------------------------------------\n% OUTPUT\n% - HD: structure including the historical decomposition\n% =======================================================================\n% Ambrogio Cesa Bianchi, March 2015\n% ambrogio.cesabianchi@gmail.com\n\n% I thank Andrey Zubarev for finding a bug in the contribution of the \n% exogenous variables when nvar_ex~=0 and nlag_ex>0. \n\n\n%% Check inputs\n%===============================================\nif ~exist('VAR','var')\n error('You need to provide VAR structure, result of VARmodel');\nend\n% If there is VAR check that the inverse of the A matrix is not empty\ninvA = VAR.invA;\nif isempty(invA)\n error('You need to identify the VAR before running VARhd. Run VARir/VARfevd first.');\nend\n\n%% Retrieve and initialize variables \n%===============================================\nFcomp = VAR.Fcomp; % Companion matrix\nconst = VAR.const; % constant and/or trends\nF = VAR.Ft'; % make comparable to notes\neps = invA\\transpose(VAR.residuals); % structural errors \nnvar = VAR.nvar; % number of endogenous variables\nnvar_ex = VAR.nvar_ex; % number of exogenous (excluding constant and trend)\nnvarXeq = VAR.nvar * VAR.nlag; % number of lagged endogenous per equation\nnlag = VAR.nlag; % number of lags \nnlag_ex = VAR.nlag_ex; % number of lags of the exogenous \nY = VAR.Y; % left-hand side\nX = VAR.X(:,1+const:nvarXeq+const); % right-hand side (no exogenous)\nnobs = size(Y,1); % number of observations\n\n\n%% Compute historical decompositions\n%===============================================\n\n% Contribution of each shock\n invA_big = zeros(nvarXeq,nvar);\n invA_big(1:nvar,:) = invA;\n Icomp = [eye(nvar) zeros(nvar,(nlag-1)*nvar)];\n HDshock_big = zeros(nlag*nvar,nobs+1,nvar);\n HDshock = zeros(nvar,nobs+1,nvar);\n for j=1:nvar; % for each variable\n eps_big = zeros(nvar,nobs+1); % matrix of shocks conformable with companion\n eps_big(j,2:end) = eps(j,:);\n for i = 2:nobs+1\n HDshock_big(:,i,j) = invA_big*eps_big(:,i) + Fcomp*HDshock_big(:,i-1,j);\n HDshock(:,i,j) = Icomp*HDshock_big(:,i,j);\n end\n end\n \n% Initial value\n HDinit_big = zeros(nlag*nvar,nobs+1);\n HDinit = zeros(nvar, nobs+1);\n HDinit_big(:,1) = X(1,:)';\n HDinit(:,1) = Icomp*HDinit_big(:,1);\n for i = 2:nobs+1\n HDinit_big(:,i) = Fcomp*HDinit_big(:,i-1);\n HDinit(:,i) = Icomp *HDinit_big(:,i);\n end\n \n% Constant\n HDconst_big = zeros(nlag*nvar,nobs+1);\n HDconst = zeros(nvar, nobs+1);\n CC = zeros(nlag*nvar,1);\n if const>0\n CC(1:nvar,:) = F(:,1);\n for i = 2:nobs+1\n HDconst_big(:,i) = CC + Fcomp*HDconst_big(:,i-1);\n HDconst(:,i) = Icomp * HDconst_big(:,i);\n end\n end\n \n% Linear trend\n HDtrend_big = zeros(nlag*nvar,nobs+1);\n HDtrend = zeros(nvar, nobs+1);\n TT = zeros(nlag*nvar,1);\n if const>1;\n TT(1:nvar,:) = F(:,2);\n for i = 2:nobs+1\n HDtrend_big(:,i) = TT*(i-1) + Fcomp*HDtrend_big(:,i-1);\n HDtrend(:,i) = Icomp * HDtrend_big(:,i);\n end\n end\n \n% Quadratic trend\n HDtrend2_big = zeros(nlag*nvar, nobs+1);\n HDtrend2 = zeros(nvar, nobs+1);\n TT2 = zeros(nlag*nvar,1);\n if const>2;\n TT2(1:nvar,:) = F(:,3);\n for i = 2:nobs+1\n HDtrend2_big(:,i) = TT2*((i-1)^2) + Fcomp*HDtrend2_big(:,i-1);\n HDtrend2(:,i) = Icomp * HDtrend2_big(:,i);\n end\n end\n\n% Exogenous\n HDexo_big = zeros(nlag*nvar,nobs+1);\n HDexo = zeros(nvar,nobs+1);\n EXO = zeros(nlag*nvar,nvar_ex*(nlag_ex+1));\n if nvar_ex>0;\n VARexo = VAR.X_EX;\n EXO(1:nvar,:) = F(:,nvar*nlag+const+1:end); % this is c in my notes\n for i = 2:nobs+1\n HDexo_big(:,i) = EXO*VARexo(i-1,:)' + Fcomp*HDexo_big(:,i-1);\n HDexo(:,i) = Icomp * HDexo_big(:,i);\n end\n end\n\n% All decompositions must add up to the original data\nHDendo = HDinit + HDconst + HDtrend + HDtrend2 + HDexo + sum(HDshock,3);\n \n \n \n%% Save and reshape all HDs\n%===============================================\nHD.shock = zeros(nobs+nlag,nvar,nvar); % [nobs x shock x var]\n for i=1:nvar\n for j=1:nvar\n HD.shock(:,j,i) = [nan(nlag,1); HDshock(i,2:end,j)'];\n end\n end\nHD.init = [nan(nlag-1,nvar); HDinit(:,1:end)']; % [nobs x var]\nHD.const = [nan(nlag,nvar); HDconst(:,2:end)']; % [nobs x var]\nHD.trend = [nan(nlag,nvar); HDtrend(:,2:end)']; % [nobs x var]\nHD.trend2 = [nan(nlag,nvar); HDtrend2(:,2:end)']; % [nobs x var]\nHD.exo = [nan(nlag,nvar); HDexo(:,2:end)']; % [nobs x var]\nHD.endo = [nan(nlag,nvar); HDendo(:,2:end)']; % [nobs x var]\n\n", "meta": {"author": "ambropo", "repo": "VAR-Toolbox", "sha": "9fe5d763da307cdded2827851325766b3a7c60e1", "save_path": "github-repos/MATLAB/ambropo-VAR-Toolbox", "path": "github-repos/MATLAB/ambropo-VAR-Toolbox/VAR-Toolbox-9fe5d763da307cdded2827851325766b3a7c60e1/OldVersions/v2dot0/VAR/VARhd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.49961404796003095}} {"text": "%% STUDY_04_wrist_scaffold_multiple_fiber_evaluation\n% Below is a demonstration for:\n% \n% * Finite element analysis of the performance of additively manufactured scaffolds for scapholunate ligament reconstruction\n%___________________________________________________________________________________________________________________________\n% This study presents a patient-specific computational biomechanical evaluation of the effect of scaffold length, \n% and positioning of the bone attachment sites. Through segmentation and image processing of medical image data \n% for natural wrist motion, detailed 3D geometries as well as patient-specific physiological wrist motion could \n% be derived. This data formed the input for detailed finite element analysis, enabling computational of scaffold \n% stress and strain distributions, which are key predictors of scaffold structural integrity.\n%___________________________________________________________________________________________________________________________\n% * febio_spec version 3.0\n% * febio, FEBio\n% * hexahedral elements, hex8\n% * static, solid\n% * hyperelastic, Ogden\n% * displacement logfile\n% * stress logfile\n\nclear; close all; clc;\n\n% Plot settings\nfontSize=40;\nnumSmoothStepsMain=1;\ncParSmoothMain.n=numSmoothStepsMain;\ncParSmoothMain.Method='HC';\n\n%%\n% Path names\ndefaultFolder = fileparts(fileparts(mfilename('fullpath')));\nsavePath=fullfile(defaultFolder,'2021_Nataliya_Perevoshchikova_wrist_project','data','temp');\nloadPathSurface=fullfile(defaultFolder,'2021_Nataliya_Perevoshchikova_wrist_project','data','STL');\nloadPathMotion=fullfile(defaultFolder,'2021_Nataliya_Perevoshchikova_wrist_project','data','motion');\n\n%% Building a quadrilateral circular mesh\nd=0.35;\nh=7;\nxSpacing=0.93;\nySpacing=0.525;\nnCopies_x=4;\nnCopies_y=7;\nr=d/2;\nne=2; %Elements in radius\nf=0.6; %Fraction (with respect to outer radius) where central square appears\n\npointSpacingHeight=0.1;\nnumStepsSweep=ceil(h/pointSpacingHeight);\n\nxc=zeros(numStepsSweep,1);\nyc=zeros(numStepsSweep,1);\nzc=linspace(-h/2,h/2,numStepsSweep)';\nVc=[xc yc zc];\n\n%SweepLoft\n%Create the mesh\n[Fq,Vq]=discQuadMesh(ne,r,f);\n\nVq(:,3)=0;\nVq1=Vq;\nVq1(:,3)=Vq1(:,3)-h/2;\nVq2=Vq;\nVq2(:,3)=Vq2(:,3)+h/2;\n\n% Visualizing mesh\ncFigure; hold on;\ntitle('Single fiber','FontSize',fontSize);\nplotV(Vq1,'k.','lineWidth',5,'MarkerSize',25);\nplotV(Vq2,'r.','lineWidth',5,'MarkerSize',25);\nplotV(Vc,'g.-','lineWidth',5,'MarkerSize',25);\n\naxisGeom;\ncamlight headlight;\ndrawnow;\n\n[~,~,~,S]=sweepLoft(Vq1,Vq2,[0 0 1],[0 0 1],Vc,numStepsSweep,0,0);\n\nX=S.X'; Y=S.Y'; Z=S.Z'; %Coordinate matrices\nV=[X(:) Y(:) Z(:)]; %Create node list\n\nI=size(Vq,1)*((1:1:numStepsSweep)-1);\nI=I(ones(size(Fq,1),1),:);\nI=I(:);\n\nFQ=repmat(Fq,numStepsSweep,1)+I(:,ones(size(Fq,2),1));\nEfib=[FQ(1:end-size(Fq,1),:) FQ(size(Fq,1)+1:end,:)]; %The hexahedral elements\n\n[Efib,V,ind1,ind2]=mergeVertices(Efib,V); %Merge nodes (start and end are not shared yet)\n%%\nnCopies=nCopies_x*nCopies_y;\nVC=repmat({V},nCopies,1);\nEC=repmat({Efib},nCopies,1);\nnumNodesBar=size(V,1);\n[Efib,V]=joinElementSets(EC,VC);\n\nc=1;\n\nfor qx=1:1:nCopies_x\n for qy=1:1:nCopies_y\n if c>1\n ind1=((c-1)*numNodesBar)+1;\n ind2=(c*numNodesBar);\n V(ind1:ind2,1)=V(ind1:ind2,1)+(qx-1)*xSpacing;\n V(ind1:ind2,2)=V(ind1:ind2,2)+(qy-1)*ySpacing;\n end\n c=c+1;\n end\nend\n\n[F]=element2patch(Efib);\n\n%% Get boundary conditions faces\n%Get boundary faces\nind=tesBoundary(F,V);\nFb=F(ind,:);\n%Get tops/bottoms\nNb=patchNormal(Fb,V);\n\nzVec=[0 0 1];\nd=dot(Nb,zVec(ones(size(Nb,1),1),:),2);\nZ=V(:,3);\nZF=mean(Z(Fb),2);\nlogicTop_Fb=(d>0.9) & ZF>=(max(V(:,3))-eps(1));\nlogicBottom_Fb=(d<-0.9) & ZF<=(min(V(:,3))+eps(1));\nF_start=Fb(logicTop_Fb,:);\nF_end=Fb(logicBottom_Fb,:);\n\n\nlogic_Lig=(ZF>-1.5) & ZF<=1.5;\nF_Lig=Fb(logic_Lig,:);\n\n%%\n% Visualizing mesh\ncFigure; hold on;\ntitle('Multiple fibers','FontSize',fontSize);\npatch('faces',Fb,'vertices',V,'FaceColor','g','FaceAlpha',0.3,'EdgeColor','None');\nplotV(V(F_end',:),'k.','lineWidth',5,'MarkerSize',20);\nplotV(V(F_start',:),'r.','lineWidth',5,'MarkerSize',20);\n\ncamlight headlight;\naxisGeom(gca,fontSize);\ndrawnow;\n\nF_L=F_end;\nF_S=F_start;\n\n%% Scaphoid and lunate at first frame from TriPlane, Brown University\nloadName=fullfile(loadPathSurface,['modelGeometry.mat']);\ndataStruct=load(loadName);\n\nFS_triP=dataStruct.FS;\nFL_triP=dataStruct.FL;\nFC_triP=dataStruct.FC;\nFR_triP=dataStruct.FR;\n\nVL_triP=dataStruct.VL;\nVS_triP=dataStruct.VS;\nVC_triP=dataStruct.VC;\nVR_triP=dataStruct.VR;\n\n%%%\nhFig=cFigure; \nhold on; \ntitle('Radiography','FontSize',fontSize);\n\ngpatch(FS_triP,VS_triP,'w','none',0.5);\ngpatch(FL_triP,VL_triP,'w','none',0.5);\ngpatch(FC_triP,VC_triP,'w','none',0.5);\ngpatch(FR_triP,VR_triP,'w','none',0.5);\n\ngrid on; axis equal;\naxisGeom(gca,fontSize);\ncamlight headlight;\ndrawnow; \n\n\n%% Cutting Radius\npointSpacingR=mean(patchEdgeLengths(FR_triP,VR_triP));\n%% Cut Capitate bone\n% The capitate is cut in the x direction. \n\n%Create a logic for cutting away faces\nmax_X1=max(VR_triP(:,1))-70*pointSpacingR; %Max x-level used for cutting\nlogicVertices=VR_triP(:,1) Nodes\nfebio_spec.Mesh.Nodes{1}.ATTR.name='nodeSet_all'; %The node set name\nfebio_spec.Mesh.Nodes{1}.node.ATTR.id=(1:size(V,1))'; %The node id's\nfebio_spec.Mesh.Nodes{1}.node.VAL=V; %The nodel coordinates\n\n% % -> Elements\npartName1='Scaffold';\nfebio_spec.Mesh.Elements{1}.ATTR.name=partName1; %Name of the element set\nfebio_spec.Mesh.Elements{1}.ATTR.mat=1; %material index for this set \nfebio_spec.Mesh.Elements{1}.ATTR.type='hex8'; %Element type of this set\nfebio_spec.Mesh.Elements{1}.elem.ATTR.id=(1:1:size(E,1))'; %Element id's\nfebio_spec.Mesh.Elements{1}.elem.VAL=E;\n\npartName2='Lunate side';\nfebio_spec.Mesh.Elements{2}.ATTR.name=partName2; %Name of the element set\nfebio_spec.Mesh.Elements{2}.ATTR.mat=2; %material index for this set\nfebio_spec.Mesh.Elements{2}.ATTR.type='quad4'; %Element type of this set\nfebio_spec.Mesh.Elements{2}.elem.ATTR.id=size(E,1)+(1:1:size(F_L,1))'; %Element id's\nfebio_spec.Mesh.Elements{2}.elem.VAL=F_L;\n\npartName3='Scaphoid side';\nfebio_spec.Mesh.Elements{3}.ATTR.name=partName3; %Name of the element set\nfebio_spec.Mesh.Elements{3}.ATTR.mat=3; %material index for this set\nfebio_spec.Mesh.Elements{3}.ATTR.type='quad4'; %Element type of this set\nfebio_spec.Mesh.Elements{3}.elem.ATTR.id=size(E,1)+(1:1:size(F_S,1))'; %Element id's\nfebio_spec.Mesh.Elements{3}.elem.VAL=F_S;\n\npartName4='Lunate';\nfebio_spec.Mesh.Elements{4}.ATTR.name=partName4; %Name of the element set\nfebio_spec.Mesh.Elements{4}.ATTR.mat=4; %material index for this set\nfebio_spec.Mesh.Elements{4}.ATTR.type='tri3'; %Element type of this set\nfebio_spec.Mesh.Elements{4}.elem.ATTR.id=size(E,1)+(1:1:size(FL1,1))'; %Element id's\nfebio_spec.Mesh.Elements{4}.elem.VAL=FL1;\n\n\npartName5='Scaphoid';\nfebio_spec.Mesh.Elements{5}.ATTR.name=partName5; %Name of the element set\nfebio_spec.Mesh.Elements{5}.ATTR.mat=5; %material index for this set\nfebio_spec.Mesh.Elements{5}.ATTR.type='tri3'; %Element type of this set\nfebio_spec.Mesh.Elements{5}.elem.ATTR.id=size(E,1)+(1:1:size(FS1,1))'; %Element id's\nfebio_spec.Mesh.Elements{5}.elem.VAL=FS1;\n\n%Capitate\npartName6='Capitate';\nfebio_spec.Mesh.Elements{6}.ATTR.name=partName6; %Name of the element set\nfebio_spec.Mesh.Elements{6}.ATTR.mat=6; %material index for this set\nfebio_spec.Mesh.Elements{6}.ATTR.type='tri3'; %Element type of this set\nfebio_spec.Mesh.Elements{6}.elem.ATTR.id=size(E,1)+(1:1:size(FC1,1))'; %Element id's\nfebio_spec.Mesh.Elements{6}.elem.VAL=FC1;\n\n%Radius\npartName7='Radius';\nfebio_spec.Mesh.Elements{7}.ATTR.name=partName7; %Name of the element set\nfebio_spec.Mesh.Elements{7}.ATTR.mat=7; %material index for this set\nfebio_spec.Mesh.Elements{7}.ATTR.type='tri3'; %Element type of this set\nfebio_spec.Mesh.Elements{7}.elem.ATTR.id=size(E,1)+(1:1:size(FR1,1))'; %Element id's\nfebio_spec.Mesh.Elements{7}.elem.VAL=FR1;\n\n%MeshDomains section\nfebio_spec.MeshDomains.SolidDomain.ATTR.name=partName1;\nfebio_spec.MeshDomains.SolidDomain.ATTR.mat=materialName1;\n\nfebio_spec.MeshDomains.ShellDomain{1}.ATTR.name=partName2;\nfebio_spec.MeshDomains.ShellDomain{1}.ATTR.mat=materialName2;\n\nfebio_spec.MeshDomains.ShellDomain{2}.ATTR.name=partName3;\nfebio_spec.MeshDomains.ShellDomain{2}.ATTR.mat=materialName3;\n\nfebio_spec.MeshDomains.ShellDomain{3}.ATTR.name=partName4;\nfebio_spec.MeshDomains.ShellDomain{3}.ATTR.mat=materialName4;\n\nfebio_spec.MeshDomains.ShellDomain{4}.ATTR.name=partName5;\nfebio_spec.MeshDomains.ShellDomain{4}.ATTR.mat=materialName5;\n\nfebio_spec.MeshDomains.ShellDomain{5}.ATTR.name=partName6;\nfebio_spec.MeshDomains.ShellDomain{5}.ATTR.mat=materialName6;\n\nfebio_spec.MeshDomains.ShellDomain{6}.ATTR.name=partName7;\nfebio_spec.MeshDomains.ShellDomain{6}.ATTR.mat=materialName7;\n\n% Boundary conditions\ni=1;\nfor count=1:numTimeSteps\n\n FileData = load(fullfile(loadPathMotion, sprintf('Flex_Ext_%d_TriPlane_Lunate.mat',count)));\n MatT_Lunate = FileData.Trans_L;\n \n FileData = load(fullfile(loadPathMotion, sprintf('Flex_Ext_%d_TriPlane_Scaphoid.mat',count)));\n MatT_Scaphoid = FileData.Trans_S;\n \n FileData = load(fullfile(loadPathMotion, sprintf('Flex_Ext_%d_TriPlane_Capitate.mat',count)));\n MatT_Capitate = FileData.Trans_C;\n\n \n RLunate = MatT_Lunate(1:3,1:3);%radians\n RScaphoid = MatT_Scaphoid(1:3,1:3); %radians\n RCapitate = MatT_Capitate(1:3,1:3); %radians\n \n Prescribe_Lunate{i} = MatT_Lunate(1:3,end);\n Prescribe_Scaphoid{i} = MatT_Scaphoid(1:3,end);\n Prescribe_Capitate{i} = MatT_Capitate(1:3,end);\n\n axangL = rotm2axang(RLunate);%Axis-Angle {[x, y, z], angle (radians)}\n AngleLunate{i} = axangL(1:3)*axangL(4);%angle *rot_axis; Axis with angle magnitude (radians) [x, y, z]\n axangS = rotm2axang(RScaphoid);\n AngleScaphoid{i} = axangS(1:3)*axangS(4);%angle*rot_axis;\n axangC = rotm2axang(RCapitate);\n AngleCapitate{i} = axangC(1:3)*axangC(4);%angle*rot_axis; \n tStartNow(i)=count*tStep;\n i=i+1;\nend\n\n%Boundary conditions\n%Rigid section \n% %Start and End\nfebio_spec.Rigid.rigid_constraint{1}.ATTR.name='Rigid_Lunate_X';\nfebio_spec.Rigid.rigid_constraint{1}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{1}.rb=2;\nfebio_spec.Rigid.rigid_constraint{1}.dof='Rx';\nfebio_spec.Rigid.rigid_constraint{1}.value.ATTR.lc=1;\nfebio_spec.Rigid.rigid_constraint{1}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{1}.relative=0;\n\nfebio_spec.Rigid.rigid_constraint{2}.ATTR.name='Rigid_Lunate_Y';\nfebio_spec.Rigid.rigid_constraint{2}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{2}.rb=2;\nfebio_spec.Rigid.rigid_constraint{2}.dof='Ry';\nfebio_spec.Rigid.rigid_constraint{2}.value.ATTR.lc=2;\nfebio_spec.Rigid.rigid_constraint{2}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{2}.relative=0;\n\nfebio_spec.Rigid.rigid_constraint{3}.ATTR.name='Rigid_Lunate_Z';\nfebio_spec.Rigid.rigid_constraint{3}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{3}.rb=2;\nfebio_spec.Rigid.rigid_constraint{3}.dof='Rz';\nfebio_spec.Rigid.rigid_constraint{3}.value.ATTR.lc=3;\nfebio_spec.Rigid.rigid_constraint{3}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{3}.relative=0;\n\nfebio_spec.Rigid.rigid_constraint{4}.ATTR.name='Rigid_Lunate_Ru';\nfebio_spec.Rigid.rigid_constraint{4}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{4}.rb=2;\nfebio_spec.Rigid.rigid_constraint{4}.dof='Ru';\nfebio_spec.Rigid.rigid_constraint{4}.value.ATTR.lc=4;\nfebio_spec.Rigid.rigid_constraint{4}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{4}.relative=0;\n\nfebio_spec.Rigid.rigid_constraint{5}.ATTR.name='Rigid_Lunate_Rv';\nfebio_spec.Rigid.rigid_constraint{5}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{5}.rb=2;\nfebio_spec.Rigid.rigid_constraint{5}.dof='Rv';\nfebio_spec.Rigid.rigid_constraint{5}.value.ATTR.lc=5;\nfebio_spec.Rigid.rigid_constraint{5}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{5}.relative=0;\n\nfebio_spec.Rigid.rigid_constraint{6}.ATTR.name='Rigid_Lunate_Rw';\nfebio_spec.Rigid.rigid_constraint{6}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{6}.rb=2;\nfebio_spec.Rigid.rigid_constraint{6}.dof='Rw';\nfebio_spec.Rigid.rigid_constraint{6}.value.ATTR.lc=6;\nfebio_spec.Rigid.rigid_constraint{6}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{6}.relative=0;\n\nfebio_spec.Rigid.rigid_constraint{7}.ATTR.name='Rigid_Scaphoid_X';\nfebio_spec.Rigid.rigid_constraint{7}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{7}.rb=3;\nfebio_spec.Rigid.rigid_constraint{7}.dof='Rx';\nfebio_spec.Rigid.rigid_constraint{7}.value.ATTR.lc=7;\nfebio_spec.Rigid.rigid_constraint{7}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{7}.relative=0;\n\nfebio_spec.Rigid.rigid_constraint{8}.ATTR.name='Rigid_Scaphoid_Y';\nfebio_spec.Rigid.rigid_constraint{8}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{8}.rb=3;\nfebio_spec.Rigid.rigid_constraint{8}.dof='Ry';\nfebio_spec.Rigid.rigid_constraint{8}.value.ATTR.lc=8;\nfebio_spec.Rigid.rigid_constraint{8}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{8}.relative=0;\n\nfebio_spec.Rigid.rigid_constraint{9}.ATTR.name='Rigid_Scaphoid_Z';\nfebio_spec.Rigid.rigid_constraint{9}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{9}.rb=3;\nfebio_spec.Rigid.rigid_constraint{9}.dof='Rz';\nfebio_spec.Rigid.rigid_constraint{9}.value.ATTR.lc=9;\nfebio_spec.Rigid.rigid_constraint{9}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{9}.relative=0;\n\nfebio_spec.Rigid.rigid_constraint{10}.ATTR.name='Rigid_Scaphoid_RX';\nfebio_spec.Rigid.rigid_constraint{10}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{10}.rb=3;\nfebio_spec.Rigid.rigid_constraint{10}.dof='Ru';\nfebio_spec.Rigid.rigid_constraint{10}.value.ATTR.lc=10;\nfebio_spec.Rigid.rigid_constraint{10}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{10}.relative=0;\n\nfebio_spec.Rigid.rigid_constraint{11}.ATTR.name='Rigid_Scaphoid_RY';\nfebio_spec.Rigid.rigid_constraint{11}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{11}.rb=3;\nfebio_spec.Rigid.rigid_constraint{11}.dof='Rv';\nfebio_spec.Rigid.rigid_constraint{11}.value.ATTR.lc=11;\nfebio_spec.Rigid.rigid_constraint{11}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{11}.relative=0;\n\nfebio_spec.Rigid.rigid_constraint{12}.ATTR.name='Rigid_Scaphoid_RZ';\nfebio_spec.Rigid.rigid_constraint{12}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{12}.rb=3;\nfebio_spec.Rigid.rigid_constraint{12}.dof='Rw';\nfebio_spec.Rigid.rigid_constraint{12}.value.ATTR.lc=12;\nfebio_spec.Rigid.rigid_constraint{12}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{12}.relative=0;\n\n% % -> Prescribed boundary conditions on the rigid body bones\nfebio_spec.Rigid.rigid_constraint{13}.ATTR.name='Rigid_Lunate_side_X';\nfebio_spec.Rigid.rigid_constraint{13}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{13}.rb=4;\nfebio_spec.Rigid.rigid_constraint{13}.dof='Rx';\nfebio_spec.Rigid.rigid_constraint{13}.value.ATTR.lc=1;\nfebio_spec.Rigid.rigid_constraint{13}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{13}.relative=0;\n\nfebio_spec.Rigid.rigid_constraint{14}.ATTR.name='Rigid_Lunate_side_Y';\nfebio_spec.Rigid.rigid_constraint{14}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{14}.rb=4;\nfebio_spec.Rigid.rigid_constraint{14}.dof='Ry';\nfebio_spec.Rigid.rigid_constraint{14}.value.ATTR.lc=2;\nfebio_spec.Rigid.rigid_constraint{14}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{14}.relative=0;\n\nfebio_spec.Rigid.rigid_constraint{15}.ATTR.name='Rigid_Lunate_side_Z';\nfebio_spec.Rigid.rigid_constraint{15}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{15}.rb=4;\nfebio_spec.Rigid.rigid_constraint{15}.dof='Rz';\nfebio_spec.Rigid.rigid_constraint{15}.value.ATTR.lc=3;\nfebio_spec.Rigid.rigid_constraint{15}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{15}.relative=0;\n\nfebio_spec.Rigid.rigid_constraint{16}.ATTR.name='Rigid_Lunate_side_RX';\nfebio_spec.Rigid.rigid_constraint{16}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{16}.rb=4;\nfebio_spec.Rigid.rigid_constraint{16}.dof='Ru';\nfebio_spec.Rigid.rigid_constraint{16}.value.ATTR.lc=4;\nfebio_spec.Rigid.rigid_constraint{16}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{16}.relative=0;\n\nfebio_spec.Rigid.rigid_constraint{17}.ATTR.name='Rigid_Lunate_side_RY';\nfebio_spec.Rigid.rigid_constraint{17}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{17}.rb=4;\nfebio_spec.Rigid.rigid_constraint{17}.dof='Rv';\nfebio_spec.Rigid.rigid_constraint{17}.value.ATTR.lc=5;\nfebio_spec.Rigid.rigid_constraint{17}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{17}.relative=0;\n\nfebio_spec.Rigid.rigid_constraint{18}.ATTR.name='Rigid_Lunate_side_RZ';\nfebio_spec.Rigid.rigid_constraint{18}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{18}.rb=4;\nfebio_spec.Rigid.rigid_constraint{18}.dof='Rw';\nfebio_spec.Rigid.rigid_constraint{18}.value.ATTR.lc=6;\nfebio_spec.Rigid.rigid_constraint{18}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{18}.relative=0;\n\n% %Scaphoid\nfebio_spec.Rigid.rigid_constraint{19}.ATTR.name='Rigid_Scaphoid_side_X';\nfebio_spec.Rigid.rigid_constraint{19}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{19}.rb=5;\nfebio_spec.Rigid.rigid_constraint{19}.dof='Rx';\nfebio_spec.Rigid.rigid_constraint{19}.value.ATTR.lc=7;\nfebio_spec.Rigid.rigid_constraint{19}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{19}.relative=0;\n\nfebio_spec.Rigid.rigid_constraint{20}.ATTR.name='Rigid_Scaphoid_side_Y';\nfebio_spec.Rigid.rigid_constraint{20}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{20}.rb=5;\nfebio_spec.Rigid.rigid_constraint{20}.dof='Ry';\nfebio_spec.Rigid.rigid_constraint{20}.value.ATTR.lc=8;\nfebio_spec.Rigid.rigid_constraint{20}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{20}.relative=0;\n\nfebio_spec.Rigid.rigid_constraint{21}.ATTR.name='Rigid_Scaphoid_side_Z';\nfebio_spec.Rigid.rigid_constraint{21}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{21}.rb=5;\nfebio_spec.Rigid.rigid_constraint{21}.dof='Rz';\nfebio_spec.Rigid.rigid_constraint{21}.value.ATTR.lc=9;\nfebio_spec.Rigid.rigid_constraint{21}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{21}.relative=0;\n\nfebio_spec.Rigid.rigid_constraint{22}.ATTR.name='Rigid_Scaphoid_side_RX';\nfebio_spec.Rigid.rigid_constraint{22}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{22}.rb=5;\nfebio_spec.Rigid.rigid_constraint{22}.dof='Ru';\nfebio_spec.Rigid.rigid_constraint{22}.value.ATTR.lc=10;\nfebio_spec.Rigid.rigid_constraint{22}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{22}.relative=0;\n\nfebio_spec.Rigid.rigid_constraint{23}.ATTR.name='Rigid_Scaphoid_side_RY';\nfebio_spec.Rigid.rigid_constraint{23}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{23}.rb=5;\nfebio_spec.Rigid.rigid_constraint{23}.dof='Rv';\nfebio_spec.Rigid.rigid_constraint{23}.value.ATTR.lc=11;\nfebio_spec.Rigid.rigid_constraint{23}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{23}.relative=0;\n\nfebio_spec.Rigid.rigid_constraint{24}.ATTR.name='Rigid_Scaphoid_side_RZ';\nfebio_spec.Rigid.rigid_constraint{24}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{24}.rb=5;\nfebio_spec.Rigid.rigid_constraint{24}.dof='Rw';\nfebio_spec.Rigid.rigid_constraint{24}.value.ATTR.lc=12;\nfebio_spec.Rigid.rigid_constraint{24}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{24}.relative=0;\n\n%%Capitate\nfebio_spec.Rigid.rigid_constraint{25}.ATTR.name='Rigid_Capitate_X';\nfebio_spec.Rigid.rigid_constraint{25}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{25}.rb=6;\nfebio_spec.Rigid.rigid_constraint{25}.dof='Rx';\nfebio_spec.Rigid.rigid_constraint{25}.value.ATTR.lc=13;\nfebio_spec.Rigid.rigid_constraint{25}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{25}.relative=0;\n\nfebio_spec.Rigid.rigid_constraint{26}.ATTR.name='Rigid_Capitate_Y';\nfebio_spec.Rigid.rigid_constraint{26}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{26}.rb=6;\nfebio_spec.Rigid.rigid_constraint{26}.dof='Ry';\nfebio_spec.Rigid.rigid_constraint{26}.value.ATTR.lc=14;\nfebio_spec.Rigid.rigid_constraint{26}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{26}.relative=0;\n\nfebio_spec.Rigid.rigid_constraint{27}.ATTR.name='Rigid_Capitate_Z';\nfebio_spec.Rigid.rigid_constraint{27}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{27}.rb=6;\nfebio_spec.Rigid.rigid_constraint{27}.dof='Rz';\nfebio_spec.Rigid.rigid_constraint{27}.value.ATTR.lc=15;\nfebio_spec.Rigid.rigid_constraint{27}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{27}.relative=0;\n\nfebio_spec.Rigid.rigid_constraint{28}.ATTR.name='Rigid_Capitate_RX';\nfebio_spec.Rigid.rigid_constraint{28}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{28}.rb=6;\nfebio_spec.Rigid.rigid_constraint{28}.dof='Ru';\nfebio_spec.Rigid.rigid_constraint{28}.value.ATTR.lc=16;\nfebio_spec.Rigid.rigid_constraint{28}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{28}.relative=0;\n\nfebio_spec.Rigid.rigid_constraint{29}.ATTR.name='Rigid_Capitate_RY';\nfebio_spec.Rigid.rigid_constraint{29}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{29}.rb=6;\nfebio_spec.Rigid.rigid_constraint{29}.dof='Rv';\nfebio_spec.Rigid.rigid_constraint{29}.value.ATTR.lc=17;\nfebio_spec.Rigid.rigid_constraint{29}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{29}.relative=0;\n\nfebio_spec.Rigid.rigid_constraint{30}.ATTR.name='Rigid_Capitate_RZ';\nfebio_spec.Rigid.rigid_constraint{30}.ATTR.type='prescribe';\nfebio_spec.Rigid.rigid_constraint{30}.rb=6;\nfebio_spec.Rigid.rigid_constraint{30}.dof='Rw';\nfebio_spec.Rigid.rigid_constraint{30}.value.ATTR.lc=18;\nfebio_spec.Rigid.rigid_constraint{30}.value.VAL=Mag_val;\nfebio_spec.Rigid.rigid_constraint{30}.relative=0;\n\n% %Radius\nfebio_spec.Rigid.rigid_constraint{31}.ATTR.name='Rigid_Radiuas';\nfebio_spec.Rigid.rigid_constraint{31}.ATTR.type='fix';\nfebio_spec.Rigid.rigid_constraint{31}.rb=7;\nfebio_spec.Rigid.rigid_constraint{31}.dofs='Rx,Ry,Rz,Ru,Rv,Rw';\n\nk=1;\nfor i=1:numTimeSteps+1\n \n if k==1\n Mat_X_Lunate(k,1)=0;\n Mat_X_Lunate(k,2)=0;\n \n Mat_Y_Lunate(k,1)=0;\n Mat_Y_Lunate(k,2)=0;\n \n Mat_Z_Lunate(k,1)=0;\n Mat_Z_Lunate(k,2)=0;\n \n Mat_RX_Lunate(k,1)=0;\n Mat_RX_Lunate(k,2)=0;\n \n Mat_RY_Lunate(k,1)=0;\n Mat_RY_Lunate(k,2)=0;\n \n Mat_RZ_Lunate(k,1)=0;\n Mat_RZ_Lunate(k,2)=0;\n \n Mat_X_Scaphoid(k,1)=0;\n Mat_X_Scaphoid(k,2)=0;\n \n Mat_Y_Scaphoid(k,1)=0;\n Mat_Y_Scaphoid(k,2)=0;\n \n Mat_Z_Scaphoid(k,1)=0;\n Mat_Z_Scaphoid(k,2)=0;\n \n Mat_RX_Scaphoid(k,1)=0;\n Mat_RX_Scaphoid(k,2)=0;\n \n Mat_RY_Scaphoid(k,1)=0;\n Mat_RY_Scaphoid(k,2)=0;\n \n Mat_RZ_Scaphoid(k,1)=0;\n Mat_RZ_Scaphoid(k,2)=0;\n \n Mat_X_Capitate(k,1)=0;\n Mat_X_Capitate(k,2)=0;\n \n Mat_Y_Capitate(k,1)=0;\n Mat_Y_Capitate(k,2)=0;\n \n Mat_Z_Capitate(k,1)=0;\n Mat_Z_Capitate(k,2)=0;\n \n Mat_RX_Capitate(k,1)=0;\n Mat_RX_Capitate(k,2)=0;\n \n Mat_RY_Capitate(k,1)=0;\n Mat_RY_Capitate(k,2)=0;\n \n Mat_RZ_Capitate(k,1)=0;\n Mat_RZ_Capitate(k,2)=0;\n else\n Mat_X_Lunate(k,1)=tStartNow(k-1);\n Mat_X_Lunate(k,2)=Prescribe_Lunate{k-1}(1);\n \n Mat_Y_Lunate(k,1)=tStartNow(k-1);\n Mat_Y_Lunate(k,2)=Prescribe_Lunate{k-1}(2);\n \n Mat_Z_Lunate(k,1)=tStartNow(k-1);\n Mat_Z_Lunate(k,2)=Prescribe_Lunate{k-1}(3);\n \n Mat_RX_Lunate(k,1)=tStartNow(k-1);\n Mat_RX_Lunate(k,2)=AngleLunate{k-1}(1);\n \n Mat_RY_Lunate(k,1)=tStartNow(k-1);\n Mat_RY_Lunate(k,2)=AngleLunate{k-1}(2);\n \n Mat_RZ_Lunate(k,1)=tStartNow(k-1);\n Mat_RZ_Lunate(k,2)=AngleLunate{k-1}(3);\n \n Mat_X_Scaphoid(k,1)=tStartNow(k-1);\n Mat_X_Scaphoid(k,2)=Prescribe_Scaphoid{k-1}(1);\n \n Mat_Y_Scaphoid(k,1)=tStartNow(k-1);\n Mat_Y_Scaphoid(k,2)=Prescribe_Scaphoid{k-1}(2);\n \n Mat_Z_Scaphoid(k,1)=tStartNow(k-1);\n Mat_Z_Scaphoid(k,2)=Prescribe_Scaphoid{k-1}(3);\n \n Mat_RX_Scaphoid(k,1)=tStartNow(k-1);\n Mat_RX_Scaphoid(k,2)=AngleScaphoid{k-1}(1);\n \n Mat_RY_Scaphoid(k,1)=tStartNow(k-1);\n Mat_RY_Scaphoid(k,2)=AngleScaphoid{k-1}(2);\n \n Mat_RZ_Scaphoid(k,1)=tStartNow(k-1);\n Mat_RZ_Scaphoid(k,2)=AngleScaphoid{k-1}(3);\n \n Mat_X_Capitate(k,1)=tStartNow(k-1);\n Mat_X_Capitate(k,2)=Prescribe_Capitate{k-1}(1);\n \n Mat_Y_Capitate(k,1)=tStartNow(k-1);\n Mat_Y_Capitate(k,2)=Prescribe_Capitate{k-1}(2);\n \n Mat_Z_Capitate(k,1)=tStartNow(k-1);\n Mat_Z_Capitate(k,2)=Prescribe_Capitate{k-1}(3);\n \n Mat_RX_Capitate(k,1)=tStartNow(k-1);\n Mat_RX_Capitate(k,2)=AngleCapitate{k-1}(1);\n \n Mat_RY_Capitate(k,1)=tStartNow(k-1);\n Mat_RY_Capitate(k,2)=AngleCapitate{k-1}(2);\n \n Mat_RZ_Capitate(k,1)=tStartNow(k-1);\n Mat_RZ_Capitate(k,2)=AngleCapitate{k-1}(3);\n \n end\n k=k+1; \nend\n\n%Lunate\nfebio_spec.LoadData.load_controller{1}.ATTR.id=1;\nfebio_spec.LoadData.load_controller{1}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{1}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{1}.points.point.VAL=Mat_X_Lunate;\n\nfebio_spec.LoadData.load_controller{2}.ATTR.id=2;\nfebio_spec.LoadData.load_controller{2}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{2}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{2}.points.point.VAL=Mat_Y_Lunate;\n\nfebio_spec.LoadData.load_controller{3}.ATTR.id=3;\nfebio_spec.LoadData.load_controller{3}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{3}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{3}.points.point.VAL=Mat_Z_Lunate;\n\nfebio_spec.LoadData.load_controller{4}.ATTR.id=4;\nfebio_spec.LoadData.load_controller{4}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{4}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{4}.points.point.VAL=Mat_RX_Lunate;\n\nfebio_spec.LoadData.load_controller{5}.ATTR.id=5;\nfebio_spec.LoadData.load_controller{5}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{5}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{5}.points.point.VAL=Mat_RY_Lunate;\n\nfebio_spec.LoadData.load_controller{6}.ATTR.id=6;\nfebio_spec.LoadData.load_controller{6}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{6}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{6}.points.point.VAL=Mat_RZ_Lunate;\n\n% %Scaphoid \nfebio_spec.LoadData.load_controller{7}.ATTR.id=7;\nfebio_spec.LoadData.load_controller{7}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{7}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{7}.points.point.VAL=Mat_X_Scaphoid;\n\nfebio_spec.LoadData.load_controller{8}.ATTR.id=8;\nfebio_spec.LoadData.load_controller{8}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{8}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{8}.points.point.VAL=Mat_Y_Scaphoid;\n\nfebio_spec.LoadData.load_controller{9}.ATTR.id=9;\nfebio_spec.LoadData.load_controller{9}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{9}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{9}.points.point.VAL=Mat_Z_Scaphoid;\n\nfebio_spec.LoadData.load_controller{10}.ATTR.id=10;\nfebio_spec.LoadData.load_controller{10}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{10}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{10}.points.point.VAL=Mat_RX_Scaphoid;\n\nfebio_spec.LoadData.load_controller{11}.ATTR.id=11;\nfebio_spec.LoadData.load_controller{11}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{11}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{11}.points.point.VAL=Mat_RY_Scaphoid;\n \nfebio_spec.LoadData.load_controller{12}.ATTR.id=12;\nfebio_spec.LoadData.load_controller{12}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{12}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{12}.points.point.VAL=Mat_RZ_Scaphoid;\n\n% %Capitate\nfebio_spec.LoadData.load_controller{13}.ATTR.id=13;\nfebio_spec.LoadData.load_controller{13}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{13}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{13}.points.point.VAL=Mat_X_Capitate;\n\nfebio_spec.LoadData.load_controller{14}.ATTR.id=14;\nfebio_spec.LoadData.load_controller{14}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{14}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{14}.points.point.VAL=Mat_Y_Capitate;\n\nfebio_spec.LoadData.load_controller{15}.ATTR.id=15;\nfebio_spec.LoadData.load_controller{15}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{15}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{15}.points.point.VAL=Mat_Z_Capitate;\n\nfebio_spec.LoadData.load_controller{16}.ATTR.id=16;\nfebio_spec.LoadData.load_controller{16}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{16}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{16}.points.point.VAL=Mat_RX_Capitate;\n\nfebio_spec.LoadData.load_controller{17}.ATTR.id=17;\nfebio_spec.LoadData.load_controller{17}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{17}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{17}.points.point.VAL=Mat_RY_Capitate;\n \nfebio_spec.LoadData.load_controller{18}.ATTR.id=18;\nfebio_spec.LoadData.load_controller{18}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{18}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{18}.points.point.VAL=Mat_RZ_Capitate;\n\nfebio_spec.Output.logfile.ATTR.file=febioLogFileName;\nfebio_spec.Output.logfile.node_data{1}.ATTR.file=febioLogFileName_disp;\nfebio_spec.Output.logfile.node_data{1}.ATTR.data='ux;uy;uz';\nfebio_spec.Output.logfile.node_data{1}.ATTR.delim=',';\nfebio_spec.Output.logfile.node_data{1}.VAL=1:size(V,1);\n\nfebio_spec.Output.logfile.node_data{2}.ATTR.file=febioLogFileName_force;\nfebio_spec.Output.logfile.node_data{2}.ATTR.data='Rx;Ry;Rz';\nfebio_spec.Output.logfile.node_data{2}.ATTR.delim=',';\nfebio_spec.Output.logfile.node_data{2}.VAL=1:size(V,1);\n\nfebio_spec.Output.logfile.element_data{1}.ATTR.file=febioLogFileName_stress;\nfebio_spec.Output.logfile.element_data{1}.ATTR.data='sx;sy;sz';\nfebio_spec.Output.logfile.element_data{1}.ATTR.delim=',';\n%% Quick viewing of the FEBio input file structure\n%The febView function can be used to view the xml structure in a MATLAB figure window.\n% \n%disp('Viewing the febio file');\n%febView(febio_spec); %Viewing the febio file\n\n%% Exporting the FEBio input file\n% Exporting the febio_spec structure to an FEBio input file is done using\n% the |febioStruct2xml| function.\nfebioStruct2xml(febio_spec,febioFebFileName); %Exporting to file and domNode\n\n% % \n% % \n% % %% Running the FEBio analysis\n% % % To run the analysis defined by the created FEBio input file the\n% % % |runMonitorFEBio| function is used. The input for this function is a\n% % % structure defining job settings e.g. the FEBio input file name. The\n% % % optional output runFlag informs the user if the analysis was run\n% % % succesfully. \n\nfebioAnalysis.run_filename=febioFebFileName; %The input file name\nfebioAnalysis.run_logname=febioLogFileName; %The name for the log file\nfebioAnalysis.disp_on=1; %Display information on the command window\nfebioAnalysis.disp_log_on=1; %Display convergence information in the command window\nfebioAnalysis.runMode='internal';%'internal';\nfebioAnalysis.t_check=0.25; %Time for checking log file (dont set too small)\nfebioAnalysis.maxtpi=1e99; %Max analysis time\nfebioAnalysis.maxLogCheckTime=3; %Max log file checking time\n\n[runFlag]=runMonitorFEBio(febioAnalysis);%START FEBio NOW!!!!!!!!\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/studies/2021_Nataliya_Perevoshchikova_wrist_project/STUDY_04_wrist_scaffold_multiple_fiber_evaluation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.49947798903707796}} {"text": "function [p, v, q] = ch_nav_equ_local_tan(p, v, q ,acc, gyr, dt, gN)\n% ęƒÆåÆ¼č§£ē®—ę›“ę–°ļ¼Œå½“åœ°ē›“č§’åę ‡ē³»ļ¼Œäøč€ƒč™‘åœ°ēƒč‡Ŗč½¬\n% p ä½ē½® XYZ 单位 m\n% v é€Ÿåŗ¦ XYZ 单位 m/s\n% q Qb2n姿态,å››å…ƒę•°č”Øē¤ŗ\n% acc ęÆ”åŠ›ļ¼Œ åŠ é€Ÿåŗ¦č®”ęµ‹é‡å€¼ 单位 (m/s^2), \n% gyr č§’é€Ÿåŗ¦ (rad/s)]\n% dt dt (s) ē§Æåˆ†é—“éš”å¦‚ 0.01s\n% gn 当地重力向量\n\nold_v = v;\n\nsf = acc;\n\n% 姿态结算\nq = ch_att_upt(q, gyr, dt);\n\n\n% é€Ÿåŗ¦č§£ē®—\nsf = ch_qmulv(q, sf);\nsf = sf + gN;\nv = old_v + dt *sf;\n\n% ä½ē½®č§£ē®—\np = p + (old_v + v) *dt/2;\n\nend\n\n\n% \n% \n% function x = ch_nav_equ_local_tan(x ,u, dt, gN)\n% \n% persistent a_old;\n% if isempty(a_old)\n% a_old= u(1:3);\n% end\n% \n% old_v = x(4:6);\n% \n% a_new =u(1:3); \n% %sf = sf + 0.5*cross(u(4:6)*dt, sf);\n% \n% % 姿态结算\n% gyr = u(4:6);\n% q_old = x(7:10);\n% x(7:10) = ch_att_upt(x(7:10), gyr, dt);\n% q_new = x(7:10);\n% \n% % é€Ÿåŗ¦č§£ē®—\n% \n% x(4:6) = old_v + ((ch_qmulv(q_new, a_new) + ch_qmulv(q_old, a_old) )/2 + gN) *dt;\n% \n% % ä½ē½®č§£ē®—\n% x(1:3) = x(1:3) + (old_v + x(4:6)) *dt/2;\n% a_old = a_new;\n% end\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/lib/ch_nav_equ_local_tan.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4993590052004749}} {"text": "function value = month_length_islamic ( y, m )\n\n%*****************************************************************************80\n%\n%% MONTH_LENGTH_ISLAMIC returns the number of days in an Islamic month.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 April 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer Y, the year in which the month occurred.\n%\n% Input, integer M, the number of the month.\n%\n% Output, integer MONTH_LENGTH_ISLAMIC, the number of days\n% in the month.\n%\n mdays = [ 30, 29, 30, 29, 30, 29, 30, 29, 30, 29, 30, 29 ];\n%\n% Copy the input.\n%\n m2 = m;\n y2 = y;\n%\n% Check the input.\n%\n [ y2, m2, ierror ] = ym_check_islamic ( y2, m2 );\n\n if ( ierror ~= 0 )\n month_length_islamic = 0;\n return\n end\n%\n% Get the number of days in the month.\n%\n value = mdays(m2);\n%\n% If necessary, add 1 day for a leap year.\n%\n if ( m2 == 12 && year_is_leap_islamic ( y2 ) )\n value = value + 1;\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/calpak/month_length_islamic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.49935434904080195}} {"text": "function [varargout] = xpower(x,varargin)\n% [z80_ind,z80_grp,OUT] = xpower(x,[c],[true],[N],[gsd],[V],[S],[trueX])\n% Calculates individual and group power as a function of design matrix,\n% true effect magnitudes, and contrasts\n% using central limit theorem approximations/theory for estimates\n%\n% tor wager, 2 / 22 / 04\n%\n% Defaults\n% gsd = .28; % group standard deviation, relative to true effect;\n% default from VNL experiment (could be overestimate, bec. btwn + within\n% not separated)\n% N = 10; % number of subjects, for group stats\n% true true effects; 1 is an increase of 1 std. dev. of scanner noise per event\n% default is .47 SNR everywhere the first contrast has positive\n% weights\n% VNL estimates of signal / noise ratio for visual impulse response, 16 Hz\n% flashing checkerboard for .5 s\n% 0.83% signal change response, 1.67% signal change error std. dev., .47 SNR \n% c = [1 1 -1 -1]; % contrast matrix; one row per contrast, one column\n% per condition; default is one contrast for each effect\n% \n% V is noise autocorrelation matrix, \n% symmetric and ones on the diagonal, n x n (n is number of samples)\n% default is white noise; see also\n% canonical_autocorrelation\n%\n% S is filtering (high/low pass) matrix; see getSmoothing\n%\n%\n% see power_map1.m for examples and scripts\n% see xzpower for a simulation-based approach\n%\n% outputs:\n% z80_ind and z80_grp are the power estimates for individual and group\n% designs. These correspond to the z-value that is expected to be reached\n% in 80% of the realizations of the design.\n\n% Another way of creating the matrices:\n%E = inline('inv(x'' * x) * x'' * Vi','x','Vi'); % E is error cov matrix\n% matrix of orthogonal projection onto model space * Vi\n% test: demo to verify that E is constant for constant SNR, regardless of\n% sigma and t (as long as their ratio is equivalent)\n% sigma = 1; t = .5; e = E(S*X,S* sigma * Vi);ee = e * e', t ./ trace(ee).^.5\n\n% -----------------------------------------------------------------\n% Set up input arguments and defaults\n% -----------------------------------------------------------------\n\n% notes: 2/7/07:\n% keep true signal |h| = 1, or input as entered\n% wsd and gsd are error st. deviations, so SNR = true / wsd (individual\n% level) and true / ...\n\nwsd = .47; % within-subjects d, signal / noise == wsd / 1\ngsd = .28; % group standard deviation, relative to true effect; default from VNL\nN = 10; % number of subjects, for group stats\n\nfor i = 1:length(varargin)\n switch i\n case 1\n if isempty(varargin{i})\n c = [eye(size(x,2)-1) zeros(size(x,2)-1,1)]; \n % contrast matrix; one row per contrast, one column per condition\n else\n c = varargin{i};\n end\n case 2\n if isempty(varargin{i})\n true = c(1,:) > 0; % true effects; 1 is an increase of magnitude 1; SNR depends on wsd and gsd\n % % % true = true .* .47; % estimated SNR from visual experiment (VNL), n = 11\n else\n true = varargin{i};\n end\n case 3\n N = varargin{i};\n case 4\n gsd = varargin{i};\n case 5\n V = varargin{i};\n case 6\n S = varargin{i};\n case 7\n trueX = varargin{i};\n end\nend\n\n% defaults, if not entered\n\nif ~(exist('c') == 1) || isempty(c), c = [eye(size(x,2)-1) zeros(size(x,2)-1,1)]; end\nif ~(exist('true') == 1) || isempty(true),true = 1 .* (c(1,:) > 0); end\n\nif ~(exist('V') == 1) || isempty(V), V = eye(size(x,1)); xc = [1 0 0];\n %[xc,V] = canonical_autocorrelation \nend\nif ~(exist('S') == 1), S = []; end\n \nif ~(exist('trueX') == 1) || isempty(trueX), trueX = x; end\n\n% defaults, if empty\n%if isempty(true),true = 0.47 .* (c(1,:) > 0);,end\nif isempty(N),N = 10; end\nif isempty(gsd),gsd = 0.28; end\n%if isempty(V), V = eye(size(x,1)); ,xc = [1 0 0];,end\n\n% -----------------------------------------------------------------\n% Do the power calculation - start with noncentrality parameters\n% -----------------------------------------------------------------\n\nif ~isempty(S), \n if size(S,1) ~= size(S,2), error('S is not square.'), end\n if size(S,1) ~= size(x,1), error('S and X dims do not match.'), end\n if size(S,1) ~= size(V,1), error('S and Vi dims do not match.'), end\n \n %xo = x; % save original x, for true signal estimate\n x = S * x; V = S * V * S'; %V = S * V; \nend\n\nif size(c,2) < size(x,2), c(:,end+1) = 0;, end\nif size(true,2) < size(x,2), true(:,end+1) = 0;, end\n\nc = c';\n\nif ~isempty(S)\n %y = S * x * true'; % S * xorig * true and x * true are equivalent; no need for xo\n % tor modified may 06\n y = S * trueX * true'; % which = S * (xorig*true), filtered orig. data\nelse\n y = trueX * true';\nend\n\nxtxi = inv(x' * x);\npx = xtxi * x'; %pinv(x);\n\n%b = c' * xtxi * x' * y; % REDUCES to input vector true, regardless of filtering; b = true';\nb = c' * px * y;\n\n% i think this one below has V as the sqrt of the V in Friston\n%sx = sqrt(diag(c' * xtxi * x' * V' * V * x * xtxi * c)) % design part -- std of x, sqrt(var(x))\nsx = sqrt(diag(c' * px * V * px' * c));\n\n% %n = b ./ sx; % noncentrality\n% mod 2/07\nn = b ./ (wsd .* sx);\n\n% GETTING THE NONCENTRALITY PARAMETER n\n% noncentrality parameter n = snr * b/se\n% snr = |h| / sigma, where |h| = scaling of impulse response to neural\n% event. see Zarahn 2001, \"Reference Effect for Power Analysis\"\n% We can simplify the computation by always assuming |h| = 1 and varying\n% sigma, in the simplest case setting snr = 1.\n% \n% t-values are directly related to snr and n.\n% t = (|h| * n) / sigma\n% in the simplest case, where snr = 1, t = n.\n%\n% n is contrast weight invariant. contrasts can be normalized by sum of\n% squared contrast weights.\n%\n% FROM n to POWER\n% By the central limit theorem, n = t if snr = 1, and n is normally\n% distributed with std 1. Then we can integrate the normal distribution.\n%\n% but since the noncentrality param is essentially a t-value, as is the 20%\n% level for the 80% power value, we have to do a small additional\n% adjustment: convert t to Z scores based on the df.\n\n% Degrees of freedom: Worsley and Friston (1995) way (effective df), \n% df reduction due to autocorrelation. This will be different if \n% a prewhitening strategy is used.\n\nR = eye(size(x,1)) - x * xtxi * x';\nU = R * V * V';\ndf = (trace(U) .^ 2) ./ (trace(U * U));\n\n%df = size(x,1) - size(x,2); % standard way, but not correct with\n%autocorrelated errors\n\n%t80_ind = norminv(.2,n,1); \n% mod 2/07\nt80_ind = nctinv(.2,df,n); % 20th% of noncentral t distribution\nztmp = spm_t2z(t80_ind,df);\nztmp = min(ztmp,t80_ind); % use min, as conversion fails for high-power\n\n% % tmp = norminv(tcdf(t80_ind,df));\n% % tmp = min(tmp,t80_ind); % use min, as conversion fails for high-power\n% % \nvarargout{1} = ztmp;\n\n% GROUP POWER\n% group power is calculated by considering the contribution of the\n% individual se to the group se, and assuming a fixed intersubject variance (set nominally to 1). with a\n% with group rrue intersubject standard deviation (gsd) of 1, then\n% gse = (gsd + E(indiv_se)) ./ sqrt(2N)\n% by the central limit theorem.\n% we use sqrt(2N) because std dev of n rnd variables = (s1 + s2 ... sn) / sqrt(n)\n% individual se (ise) is the standard deviation of the sampling distribution\n% gse is the standard deviation\n% \n% take as ise the coefficient of variation (cv), sx / b, which is contrast\n% scale independent.\n\nif nargout > 1\n\n %gse = (gsd + (sx ./ b)) ./ sqrt(2 * N);\n\n %ng = 1 ./ gse; % normalized b / gse. this is contrast weight-scaling independent\n\n % group standard error. sqrt of sum of within + between, over\n % sqrt(N-1) to get standard error from standard deviation\n gse = sqrt( (wsd.*sx).^2 + gsd.^2 ) ./ sqrt(N - 1);\n \n ng = true(1:end-1)' ./ gse; % b / gse. this is contrast weight-scaling independent\n \n dfg = N - 1;\n t80_grp = nctinv(.2, dfg, ng); % 20th% of noncentral t distribution\n ztmp = spm_t2z(t80_grp,dfg);\n ztmp = min(ztmp,t80_grp); % use min, as conversion fails for high-power\n\n% % t80_grp = norminv(.2,ng,1); \n% % \n% % tmp = norminv(tcdf(t80_grp,dfg)); % adjust to Z-score based on df\n% % tmp = min(tmp,t80_grp); % use min, as conversion fails for high-power\n varargout{2} = ztmp;\n \n \n if nargout > 2\n \n OUT.x = x;\n OUT.gsd = gsd;\n OUT.N = N;\n OUT.true = true;\n OUT.c = c';\n OUT.y = y;\n OUT.b = b;\n OUT.sx = sx;\n OUT.n = n;\n OUT.df = df;\n OUT.ng = ng;\n \n OUT.t80_ind = t80_ind;\n OUT.t80_grp = t80_grp;\n OUT.expected_t = b ./ (wsd .* sx);\n \n varargout{3} = OUT;\n \n end\n \nend\n\nreturn\n\n\n\n \n\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/OptimizeDesign11/GA3/xpower.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4992775800698365}} {"text": "function [ var_node, var_num ] = ns_t6_var_count ( element_num, ...\n element_node, node_num )\n\n%*****************************************************************************80\n%\n%% NS_T6_VAR_COUNT counts the Navier Stokes variables on a T6 grid.\n%\n% Discussion:\n%\n% We are given a mesh of T6 elements, and asked to count, in advance,\n% the number of Navier-Stokes variables associated with the grid.\n% In particular, every node has two velocity variables associated with\n% it, but only a node that is a vertex of the element will also have\n% an associated pressure variable.\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% Parameters:\n%\n% Input, integer ELEMENT_NUM, the number of elements.\n%\n% Input, integer ELEMENT_NODE(ELEMENT_ORDER,ELEMENT_NUM);\n% ELEMENT_NODE(I,J) is the global index of local node I in element J.\n%\n% Input, integer NODE_NUM, the number of nodes.\n%\n% Output, integer VAR_NODE(NODE_NUM+1), used to find the variables\n% associated with a given node, which are in VAR in locations\n% VAR_NODE(NODE) to VAR_NODE(NODE+1)-1. Note that the last entry of\n% this array points to the location just after the last location in VAR.\n%\n% Output, integer VAR_NUM, the number of variables.\n%\n element_order = 6;\n%\n% Our job is easy once we determine which nodes are vertices.\n% So to begin with, let VAR_NODE count the number of variables\n% associated with each node.\n%\n var_node(1:node_num) = 2;\n\n for element = 1 : element_num\n for order = 1 : 3\n node = element_node(order,element);\n var_node(node) = 3;\n end\n end\n%\n% Count them.\n%\n var_num = sum ( var_node(1:node_num) );\n%\n% Make pointers.\n%\n total = 1;\n\n for node = 1 : node_num\n num = var_node(node);\n var_node(node) = total;\n total = total + num;\n end\n var_node(node_num+1) = total;\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/fem2d_pack/ns_t6_var_count.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.4991290887102827}} {"text": "function result = normalizekm(km)\n% Copyright 2012 Nino Shervashidze, Karsten Borgwardt\n% normalizes kernelmatrix km \n% such that diag(result) = 1, i.e. K(x,y) / sqrt(K(x,x) * K(y,y))\n% @author Karsten Borgwardt\n% @date June 3rd 2005\n% all rights reserved \n\nnv = sqrt(diag(km));\nnm = nv * nv';\nknm = nm .^ -1;\nfor i = 1:size(knm,1)\nfor j = 1:size(knm,2)\nif (knm(i,j) == Inf)\n knm(i,j) = 0;\nend\nend\nend\nresult = km .* knm;\n", "meta": {"author": "muhanzhang", "repo": "DGCNN", "sha": "7d3663b49561e57fe518f37af0023a364285eee1", "save_path": "github-repos/MATLAB/muhanzhang-DGCNN", "path": "github-repos/MATLAB/muhanzhang-DGCNN/DGCNN-7d3663b49561e57fe518f37af0023a364285eee1/software/graphkernels/svm/normalizekm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7662936324115012, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.49912907486151603}} {"text": "function [H, Z, S, psi] = sfactorization_wilson3x3(S,freq,Niterations,tol,cmbindx,fb,init,checkflag,stabilityfix)\n\n% SFACTORIZATION_WILSON3X3 performs triplet-wise non-parametric spectral factorization on\n% cross-spectra, based on Wilson's algorithm.\n%\n% Usage : [H, Z, psi] = sfactorization_wilson(S,freq);\n%\n% Inputs : S (1-sided, 3D-spectral matrix in the form of Channel x Channel x frequency) \n% : freq (a vector of frequencies) at which S is given. \n%\n% Outputs: H (transfer function)\n% : Z (noise covariance)\n% : S (cross-spectral density 1-sided)\n% : psi (left spectral factor)\n%\n% This function is an implemention of Wilson's algorithm (Eq. 3.1)\n% for spectral matrix factorization.\n%\n% Ref: G.T. Wilson,\"The Factorization of Matricial Spectral Densities,\"\n% SIAM J. Appl. Math.23,420-426(1972).\n% Written by M. Dhamala & G. Rangarajan, UF, Aug 3-4, 2006.\n% Email addresses: mdhamala@bme.ufl.edu, rangaraj@math.iisc.ernet.in\n\n% Copyright (C) 2009-2017, 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<9, stabilityfix = false; end\nif nargin<8, checkflag = true; end\nif nargin<7, init = 'chol'; end\nif nargin<6, fb = 'none'; end\nif nargin<5\n ft_error('FieldTrip:connectivity:sfactorization_wilson3x3', 'when requesting multiple triplet-wise spectral decomposition, ''cmbindx'' needs to be specified');\nend\nif nargin<4, tol = 1e-8; end\nif nargin<3, Niterations = 1000; end\n\ndfreq = round(diff(freq)*1e5)./1e5; % allow for some numeric issues\nif ~all(dfreq==dfreq(1))\n ft_error('FieldTrip:connectivity:sfactorization_wilson3x3', 'frequency axis is not evenly spaced');\nend\n\nif freq(1)~=0\n ft_warning('FieldTrip:connectivity:sfactorization_wilson3x3', 'when performing non-parametric spectral factorization, the frequency axis should ideally start at 0, zero padding the spectral density'); \n dfreq = mean(dfreq);\n npad = freq(1)./dfreq;\n \n % update the freq axis and keep track of the frequency bins that are\n % expected in the output\n selfreq = (1:numel(freq)) + npad;\n freq = [(0:(npad-1))./dfreq freq];\n S = cat(3, zeros(size(S,1), size(S,1), npad), S); \nelse\n selfreq = 1:numel(freq);\nend\n\n% ensure input S is double (mex-files don't work with single)\nS = double(S);\n\n% check whether the last frequency bin is strictly real-valued.\n% if that's the case, then it is assumed to be the Nyquist frequency\n% and the two-sided spectral density will have an even number of \n% frequency bins. if not, in order to preserve hermitian symmetry,\n% the number of frequency bins needs to be odd.\nSend = S(:,:,end);\nN = numel(freq);\nm = size(cmbindx,1);\nif all(imag(Send(:)) pi) = ikInitGuess(ikInitGuess > pi) - 2*pi;\nikInitGuess(ikInitGuess < -pi) = ikInitGuess(ikInitGuess < -pi) + 2*pi;\n\n% Set up plot\nplotMode = 1; % 0 = None, 1 = Trajectory, 2 = Coordinate Frames\nshow(gen3,gen3.homeConfiguration,'Frames','off','PreservePlot',false);\nxlim([-1 1]), ylim([-1 1]), zlim([0 1.2])\nhold on\nif plotMode == 1\n hTraj = plot3(waypoints(1,1),waypoints(2,1),waypoints(3,1),'b.-');\nend\nplot3(waypoints(1,:),waypoints(2,:),waypoints(3,:),'ro','LineWidth',2);\n\n%% Solve IK for all waypoints\nincludeOrientation = false; % Set this to use zero vs. nonzero orientations\n\nnumWaypoints = size(waypoints,2);\nnumJoints = numel(gen3.homeConfiguration);\njointWaypoints = zeros(numJoints,numWaypoints);\n\nfor idx = 1:numWaypoints\n if includeOrientation\n tgtPose = trvec2tform(waypoints(:,idx)') * eul2tform(orientations(:,idx)');\n else\n tgtPose = trvec2tform(waypoints(:,idx)');\n end\n [config,info] = ik(eeName,tgtPose,ikWeights,ikInitGuess);\n jointWaypoints(:,idx) = config';\nend\n\n%% Generate trajectory on joint space\ntrajType = 'trap';\nswitch trajType\n case 'trap'\n [q,qd,qdd] = trapveltraj(jointWaypoints,numel(trajTimes), ...\n 'AccelTime',repmat(waypointAccelTimes,[numJoints 1]), ... \n 'EndTime',repmat(diff(waypointTimes),[numJoints 1]));\n \n case 'cubic'\n [q,qd,qdd] = cubicpolytraj(jointWaypoints,waypointTimes,trajTimes, ... \n 'VelocityBoundaryCondition',zeros(numJoints,numWaypoints));\n \n case 'quintic'\n [q,qd,qdd] = quinticpolytraj(jointWaypoints,waypointTimes,trajTimes, ... \n 'VelocityBoundaryCondition',zeros(numJoints,numWaypoints), ...\n 'AccelerationBoundaryCondition',zeros(numJoints,numWaypoints));\n \n case 'bspline'\n ctrlpoints = jointWaypoints; % Can adapt this as needed\n [q,qd,qdd] = bsplinepolytraj(ctrlpoints,waypointTimes([1 end]),trajTimes);\n \n otherwise\n error('Invalid trajectory type! Use ''trap'', ''cubic'', ''quintic'', or ''bspline''');\nend\n\n% To visualize the trajectory, run the following line\n% plotTrajectory(trajTimes,q,qd,qdd,'Names',\"Joint \" + string(1:numJoints),'WaypointTimes',waypointTimes)\n\n%% Trajectory following loop\nfor idx = 1:numel(trajTimes) \n\n config = q(:,idx)';\n \n % Find Cartesian points for visualization\n eeTform = getTransform(gen3,config,eeName);\n if plotMode == 1\n eePos = tform2trvec(eeTform);\n set(hTraj,'xdata',[hTraj.XData eePos(1)], ...\n 'ydata',[hTraj.YData eePos(2)], ...\n 'zdata',[hTraj.ZData eePos(3)]);\n elseif plotMode == 2\n plotTransforms(tform2trvec(eeTform),tform2quat(eeTform),'FrameSize',0.05);\n end\n\n % Show the robot\n show(gen3,config,'Frames','off','PreservePlot',false);\n title(['Trajectory at t = ' num2str(trajTimes(idx))])\n drawnow \n \nend", "meta": {"author": "mathworks-robotics", "repo": "trajectory-planning-robot-manipulators", "sha": "e7ee8775b5ace44b5da5455b6aee9c4d8cbf0b4e", "save_path": "github-repos/MATLAB/mathworks-robotics-trajectory-planning-robot-manipulators", "path": "github-repos/MATLAB/mathworks-robotics-trajectory-planning-robot-manipulators/trajectory-planning-robot-manipulators-e7ee8775b5ace44b5da5455b6aee9c4d8cbf0b4e/matlab/manipTrajJoint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782277, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.49892193470312224}} {"text": "function lik = lik_gaussian(varargin)\n%LIK_GAUSSIAN Create a Gaussian likelihood structure\n%\n% Description\n% LIK = LIK_GAUSSIAN('PARAM1',VALUE1,'PARAM2,VALUE2,...) \n% creates a Gaussian 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_GAUSSIAN(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 Gaussian likelihood function [default]\n% sigma2 - variance [0.1]\n% sigma2_prior - prior for sigma2 [prior_logunif]\n% n - number of observations per input (See using average\n% observations below)\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% Using average observations\n% The lik_gaussian can be used to model data where each input vector is\n% attached to an average of varying number of observations. That is, we\n% have input vectors x_i, average observations y_i and sample sizes n_i.\n% Each observation is distributed \n%\n% y_i ~ N(f(x_i), sigma2/n_i)\n%\n% The model is constructed as lik_gaussian('n', n), where n is the same\n% length as y and collects the sample sizes. \n%\n% See also\n% GP_SET, PRIOR_*, LIK_*\n\n% Internal note: Because Gaussian noise can be combined\n% analytically to the covariance matrix, lik_gaussian is internally\n% little between lik_* and gpcf_* functions.\n%\n% Copyright (c) 2007-2017 Jarno Vanhatalo\n% Copyright (c) 2010 Aki Vehtari\n\n% This software is distributed under the GNU General Public\n% License (version 3 or later); please refer to the file\n% License.txt, included with the software, for details.\n\n ip=inputParser;\n ip.FunctionName = 'LIK_GAUSSIAN';\n ip.addOptional('lik', [], @(x) isstruct(x) || isempty(x));\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('n',[], @(x) isreal(x) && all(x>0));\n ip.parse(varargin{:});\n lik=ip.Results.lik;\n\n if isempty(lik)\n init=true;\n lik.type = 'Gaussian';\n else\n if ~isfield(lik,'type') || ~isequal(lik.type,'Gaussian')\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('n',ip.UsingDefaults)\n lik.n = ip.Results.n;\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_gaussian_pak;\n lik.fh.unpak = @lik_gaussian_unpak;\n lik.fh.ll = @lik_gaussian_ll;\n lik.fh.llg = @lik_gaussian_llg; \n lik.fh.llg2 = @lik_gaussian_llg2;\n lik.fh.llg3 = @lik_gaussian_llg3;\n lik.fh.lp = @lik_gaussian_lp;\n lik.fh.lpg = @lik_gaussian_lpg;\n lik.fh.cfg = @lik_gaussian_cfg;\n lik.fh.tiltedMoments = @lik_gaussian_tiltedMoments;\n lik.fh.trcov = @lik_gaussian_trcov;\n lik.fh.trvar = @lik_gaussian_trvar;\n lik.fh.predy = @lik_gaussian_predy; \n lik.fh.siteDeriv = @lik_gaussian_siteDeriv;\n lik.fh.recappend = @lik_gaussian_recappend;\n end\n\nend\n\nfunction [w, s, h] = lik_gaussian_pak(lik)\n%LIK_GAUSSIAN_PAK Combine likelihood parameters into one vector.\n%\n% Description\n% W = LIK_GAUSSIAN_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 energy \n% and gradient computations.\n%\n% w = [ log(lik.sigma2)\n% (hyperparameters of lik.magnSigma2)]'\n% \n% See also\n% LIK_GAUSSIAN_UNPAK\n\n w = []; s = {}; h=[];\n if ~isempty(lik.p.sigma2)\n w = [w log(lik.sigma2)];\n s = [s; 'log(gaussian.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_gaussian_unpak(lik, w)\n%LIK_GAUSSIAN_UNPAK Extract likelihood parameters from the vector.\n%\n% Description\n% W = LIK_GAUSSIAN_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_GAUSSIAN_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\n\n\n\nfunction logLik = lik_gaussian_ll(lik, y, f, ~)\n%LIK_GAUSSIAN_LL Log likelihood\n%\n% Description\n% E = LIK_GAUSSIAN_LL(LIK, Y, F, Z) takes a likelihood data\n% structure LIK, incedence counts Y, expected counts Z, and\n% latent values F. Returns the log likelihood, log p(y|f,z).\n% This subfunction is needed when using Laplace approximation\n% or MCMC for inference with non-Gaussian likelihoods. This \n% subfunction is also used in information criteria (DIC, WAIC)\n% computations.\n%\n% See also\n% LIK_GAUSSIAN_LLG, LIK_GAUSSIAN_LLG3, LIK_GAUSSIAN_LLG2, GPLA_E\n\n s2 = lik.sigma2;\n r2 = (f-y).^2; \n logLik = sum(-0.5 * r2./s2 - 0.5*log(s2) - 0.5*log(2*pi));\n \nend\n\n\nfunction llg = lik_gaussian_llg(lik, y, f, param, ~)\n%LIK_GAUSSIAN_LLG Gradient of the log likelihood\n%\n% Description \n% G = LIK_GAUSSIAN_LLG(LIK, Y, F, PARAM) takes a likelihood\n% structure LIK, incedence counts Y, expected counts Z\n% and latent values F. Returns the gradient of the log\n% likelihood with respect to PARAM. At the moment PARAM can be\n% 'param' or 'latent'. This subfunction is needed when using \n% Laplace approximation or MCMC for inference with non-Gaussian \n% likelihoods.\n%\n% See also\n% LIK_GAUSSIAN_LL, LIK_GAUSSIAN_LLG2, LIK_GAUSSIAN_LLG3, GPLA_E\n \n \nswitch param\n case 'param'\n % there is also correction due to the log transformation\n s2 = lik.sigma2;\n r2 = (f-y).^2;\n llg = 0.5.* sum( r2./s2 -1 );\n\n case 'latent'\n s2 = lik.sigma2;\n r = f-y;\n llg = - r./s2 ;\nend\nend\n\n\nfunction llg2 = lik_gaussian_llg2(lik, y, f, param, ~)\n%LIK_GAUSSIAN_LLG2 Second gradients of the log likelihood\n%\n% Description \n% G2 = LIK_GAUSSIAN_LLG2(LIK, Y, F, PARAM) takes a likelihood\n% structure LIK, incedence counts Y, expected counts Z,\n% and latent values F. Returns the Hessian of the log\n% likelihood with respect to PARAM. At the moment PARAM can be\n% only 'latent'. G2 is a vector with diagonal elements of the\n% Hessian matrix (off diagonals are zero). This subfunction\n% is needed when using Laplace approximation or EP for inference \n% with non-Gaussian likelihoods.\n\n%\n% See also\n% LIK_GAUSSIAN_LL, LIK_GAUSSIAN_LLG, LIK_GAUSSIAN_LLG3, GPLA_E\n\n \nswitch param\n case 'latent'\n s2 = lik.sigma2;\n llg2 = - ones(size(y))./s2 ;\n case 'latent+param'\n % there is also correction due to the log transformation\n s2 = lik.sigma2;\n r = f-y;\n llg2 = r./s2 ;\n \nend\nend \n\nfunction llg3 = lik_gaussian_llg3(lik, y, f, param, z)\n%LIK_GAUSSIAN_LLG3 Third gradients of the log likelihood\n%\n% Description\n% G3 = LIK_GAUSSIAN_LLG3(LIK, Y, F, PARAM) takes a likelihood\n% structure LIK, incedence counts Y, expected counts Z\n% and latent values F and returns the third gradients of the\n% log likelihood with respect to PARAM. At the moment PARAM\n% can be only 'latent'. G3 is a vector with third gradients.\n% This subfunction is needed when using Laplace approximation \n% for inference with non-Gaussian likelihoods.\n%\n% See also\n% LIK_GAUSSIAN_LL, LIK_GAUSSIAN_LLG, LIK_GAUSSIAN_LLG2, GPLA_E, GPLA_G\n\nswitch param\n case 'latent'\n llg3 = zeros(size(y));\n case 'latent2+param'\n % there is also correction due to the log transformation\n s2 = lik.sigma2;\n llg3 = ones(size(y))./s2 ;\nend\nend\n\n\nfunction lp = lik_gaussian_lp(lik)\n%LIK_GAUSSIAN_LP Evaluate the log prior of likelihood parameters\n%\n% Description\n% LP = LIK_T_LP(LIK) takes a likelihood structure LIK and\n% returns log(p(th)), where th collects the parameters.\n% This subfunctions is needed when there are likelihood\n% parameters.\n%\n% See also\n% LIK_GAUSSIAN_PAK, LIK_GAUSSIAN_UNPAK, LIK_GAUSSIAN_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_gaussian_lpg(lik)\n%LIK_GAUSSIAN_LPG Evaluate gradient of the log prior with respect\n% to the parameters.\n%\n% Description\n% LPG = LIK_GAUSSIAN_LPG(LIK) takes a Gaussian 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_GAUSSIAN_PAK, LIK_GAUSSIAN_UNPAK, LIK_GAUSSIAN_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\n\n\nfunction DKff = lik_gaussian_cfg(lik, x, x2)\n%LIK_GAUSSIAN_CFG Evaluate gradient of covariance with respect to\n% Gaussian noise\n%\n% Description\n% Gaussian likelihood is a special case since it can be\n% analytically combined with covariance functions and thus we\n% compute gradient of covariance instead of gradient of likelihood.\n%\n% DKff = LIK_GAUSSIAN_CFG(LIK, X) takes a Gaussian likelihood\n% function structure LIK, a matrix X of input vectors and\n% returns DKff, the gradients of Gaussian noise covariance\n% matrix Kff = k(X,X) with respect to th (cell array with\n% matrix elements). This subfunction is needed only in Gaussian \n% likelihood.\n%\n% DKff = LIK_GAUSSIAN_CFG(LIK, X, X2) takes a Gaussian\n% likelihood function structure LIK, a matrix X of input\n% vectors and returns DKff, the gradients of Gaussian noise\n% covariance matrix Kff = k(X,X) with respect to th (cell\n% array with matrix elements). This subfunction is needed \n% only in Gaussian likelihood.\n%\n% See also\n% LIK_GAUSSIAN_PAK, LIK_GAUSSIAN_UNPAK, LIK_GAUSSIAN_E, GP_G\n\n DKff = {};\n if ~isempty(lik.p.sigma2)\n if isempty(lik.n)\n DKff{1}=lik.sigma2;\n else\n n=size(x,1);\n DKff{1} = sparse(1:n, 1:n, lik.sigma2./lik.n, n, n);\n end\n end\nend\n\nfunction DKff = lik_gaussian_ginput(lik, x, t, g_ind, gdata_ind, gprior_ind, varargin)\n%LIK_GAUSSIAN_GINPUT Evaluate gradient of likelihood function with \n% respect to x.\n%\n% Description\n% DKff = LIK_GAUSSIAN_GINPUT(LIK, X) takes a likelihood\n% function structure LIK, a matrix X of input vectors and\n% returns DKff, the gradients of likelihood matrix Kff =\n% k(X,X) with respect to X (cell array with matrix elements).\n% This subfunction is needed only in Gaussian likelihood.\n%\n% DKff = LIK_GAUSSIAN_GINPUT(LIK, X, X2) takes a likelihood\n% function structure LIK, a matrix X of input vectors and\n% returns DKff, the gradients of likelihood matrix Kff =\n% k(X,X2) with respect to X (cell array with matrix elements).\n% This subfunction is needed only in Gaussian likelihood.\n%\n% See also\n% LIK_GAUSSIAN_PAK, LIK_GAUSSIAN_UNPAK, LIK_GAUSSIAN_E, GP_G\n\nend\n\nfunction C = lik_gaussian_trcov(lik, x)\n%LIK_GAUSSIAN_TRCOV Evaluate training covariance matrix\n% corresponding to Gaussian noise\n%\n% Description\n% C = LIK_GAUSSIAN_TRCOV(GP, TX) takes in covariance function\n% of a Gaussian process GP and matrix TX that contains\n% training input vectors. Returns covariance matrix C. Every\n% element ij of C contains covariance between inputs i and j\n% in TX. This subfunction is needed only in Gaussian likelihood.\n%\n% See also\n% LIK_GAUSSIAN_COV, LIK_GAUSSIAN_TRVAR, GP_COV, GP_TRCOV\n\n [n, m] =size(x);\n n1=n+1;\n\n if isempty(lik.n)\n C = sparse(1:n,1:n,ones(n,1).*lik.sigma2,n,n);\n else \n C = sparse(1:n, 1:n, lik.sigma2./lik.n, n, n);\n end\n\nend\n\nfunction C = lik_gaussian_trvar(lik, x)\n%LIK_GAUSSIAN_TRVAR Evaluate training variance vector\n% corresponding to Gaussian noise\n%\n% Description\n% C = LIK_GAUSSIAN_TRVAR(LIK, TX) takes in covariance function\n% of a Gaussian process LIK and matrix TX that contains\n% training inputs. Returns variance vector C. Every element i\n% of C contains variance of input i in TX. This subfunction is \n% needed only in Gaussian likelihood.\n%\n%\n% See also\n% LIK_GAUSSIAN_COV, GP_COV, GP_TRCOV\n\n [n, m] =size(x);\n if isempty(lik.n)\n C=repmat(lik.sigma2,n,1);\n else\n C=lik.sigma2./lik.n(:);\n end\n\nend\n\n\nfunction [lpy, Ey, Vary] = lik_gaussian_predy(lik, Ef, Varf, yt, zt)\n%LIK_Gaussian_PREDY Returns the predictive mean, variance and density of y\n%\n% Description \n% LPY = LIK_POISSON_PREDY(LIK, EF, VARF YT, ZT)\n% Returns also the predictive density of YT, that is \n% p(yt | y,zt) = \\int p(yt | f, zt) p(f|y) df.\n% This requires also the incedence counts YT, expected counts ZT.\n% This subfunction is needed when computing posterior predictive \n% distributions for future observations.\n%\n% [LPY, EY, VARY] = LIK_POISSON_PREDY(LIK, EF, VARF, YT, ZT) \n% takes a likelihood structure LIK, posterior mean EF and \n% posterior 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 subfunction\n% is needed when computing posterior predictive distributions for \n% future observations.\n% \n%\n% See also \n% GPLA_PRED, GPEP_PRED, GPMC_PRED\n\n lpy = [];\n Ey = Ef;\n EVary = lik.sigma2;\n VarEy = Varf; \n Vary = EVary + VarEy;\n if numel(yt) ~= 0\n lpy = norm_lpdf(yt,Ey,sqrt(Vary));\n end\nend\n\nfunction [logM_0, m_1, sigm2hati1] = lik_gaussian_tiltedMoments(lik, y, i1, sigm2_i, myy_i, z)\n%LIK_PROBIT_TILTEDMOMENTS Returns the marginal moments for EP algorithm\n%\n% Description\n% [M_0, M_1, M2] = LIK_PROBIT_TILTEDMOMENTS(LIK, Y, I, S2,\n% MYY) takes a likelihood structure LIK, class labels Y, index\n% I and cavity variance S2 and mean MYY. Returns the zeroth\n% moment M_0, mean M_1 and variance M_2 of the posterior\n% marginal (see Rasmussen and Williams (2006): Gaussian\n% processes for Machine Learning, page 55). This subfunction \n% is needed when using EP for inference with non-Gaussian \n% likelihoods.\n%\n% See also\n% GPEP_E\n\n% m_1=myy_i;\n% sigm2hati1=sigm2_i;\n% logM_0=zeros(size(y));\n \ns2 = lik.sigma2;\ntau = 1./s2 + 1./sigm2_i;\nw = (y(i1)./s2 + myy_i./sigm2_i)./tau;\n%Zi = 1 ./( sqrt( 2.*pi.*(s2+sigm2_i) ) ) .* exp( -0.5*(y(i1)-myy_i).^2./(s2+sigm2_i) );\n\nm_1 = w;\nsigm2hati1 = 1./tau;\n%logM_0 = log(Zi)\nlogM_0 = -0.5*log( 2.*pi) - 0.5*log( (s2+sigm2_i) ) + ( -0.5*(y(i1)-myy_i).^2./(s2+sigm2_i) );\n\nend\n\nfunction [g_i] = lik_gaussian_siteDeriv(lik, y, i1, sigm2_i, myy_i, z)\n%LIK_NEGBIN_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_NEGBIN_SITEDERIV(LIK, Y, I, S2, MYY, Z) takes a\n% likelihood structure LIK, incedence counts Y, expected\n% counts Z, index I and cavity variance S2 and mean MYY. \n% Returns E_f [d log p(y_i|f_i) /d a], where a is the\n% likelihood parameter and the expectation is over the\n% marginal posterior. This term is needed when evaluating the\n% gradients of the marginal likelihood estimate Z_EP with\n% respect to 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\ns2 = lik.sigma2;\ntau = 1/s2 + 1/sigm2_i;\nw = (y(i1)/s2 + myy_i/sigm2_i)/tau;\n%Zi = 1/( sqrt(2*pi*(s2+sigm2_i)) )*exp( -0.5*(y(i1)-myy_i)^2/(s2+sigm2_i) );\n\n%g_i = 0.5*( (1/tau + w.^2 -2*w*y(i1) + y(i1).^2 ) /s2 - 1)/s2 * s2;\ng_i = 0.5*( (1/tau + w.^2 -2*w*y(i1) + y(i1).^2 ) /s2 - 1);\n\n\nend\n\n\n\nfunction reclik = lik_gaussian_recappend(reclik, ri, lik)\n%RECAPPEND Record append\n%\n% Description\n% RECLIK = LIK_GAUSSIAN_RECAPPEND(RECLIK, RI, LIK) takes a\n% likelihood function record structure RECLIK, record index RI\n% and likelihood function structure LIK with the current MCMC\n% samples of the parameters. Returns RECLIK which contains all\n% the old samples and the current samples from LIK. This \n% subfunction is needed when using MCMC sampling (gp_mc).\n%\n% See also\n% GP_MC and GP_MC -> RECAPPEND\n\n if nargin == 2\n % Initialize the record\n reclik.type = 'Gaussian';\n \n % Initialize the parameters\n reclik.sigma2 = []; \n reclik.n = []; \n \n % Set the function handles\n reclik.fh.pak = @lik_gaussian_pak;\n reclik.fh.unpak = @lik_gaussian_unpak;\n reclik.fh.lp = @lik_gaussian_lp;\n reclik.fh.lpg = @lik_gaussian_lpg;\n reclik.fh.ll= @lik_gaussian_ll;\n reclik.fh.llg = @lik_gaussian_llg;\n reclik.fh.llg2 = @lik_gaussian_llg2;\n reclik.fh.llg3 = @lik_gaussian_llg3;\n reclik.fh.tiltedMoments = @lik_gaussian_tiltedMoments;\n reclik.fh.siteDeriv = @lik_gaussian_siteDeriv;\n reclik.fh.cfg = @lik_gaussian_cfg;\n reclik.fh.trcov = @lik_gaussian_trcov;\n reclik.fh.trvar = @lik_gaussian_trvar;\n reclik.fh.predy = @lik_gaussian_predy;\n reclik.fh.recappend = @lik_gaussian_recappend; \n \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 % Append to the record\n likp = lik.p;\n\n % record sigma2\n reclik.sigma2(ri,:)=lik.sigma2;\n if isfield(likp,'sigma2') && ~isempty(likp.sigma2)\n reclik.p.sigma2 = likp.sigma2.fh.recappend(reclik.p.sigma2, ri, likp.sigma2);\n end\n % record n if given\n if isfield(lik,'n') && ~isempty(lik.n)\n reclik.n(ri,:)=lik.n(:)';\n end\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_gaussian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.49858009538407283}} {"text": "%--- help for statespace/forecast ---\n%\n% FORECAST Forecast states and observations of state-space models\n% \n% Syntax:\n% \n% [Y,YMSE,X,XMSE] = forecast(Mdl,numPeriods,Y0)\n% [Y,YMSE,X,XMSE] = forecast(Mdl,numPeriods,name,value,...)\n% \n% Description:\n% \n% Generate multiple-period forecasts for observation vector y(t) and state \n% vector x(t) for a general state-space model (SSM) of the form:\n% \n% State equation: x(t) = A(t) * x(t-1) + B(t) * u(t)\n% Observation equation: y(t) = C(t) * x(t) + D(t) * e(t)\n% \n% where u(t) and e(t) are uncorrelated, unit-variance white noise vector\n% processes. The length of x(t), y(t), u(t), and e(t) is m, n, k, and h, \n% respectively.\n% \n% Additionally, forecast uncertainties are also generated.\n% \n% Input Arguments:\n% \n% Mdl - A state-space model, as created by the SSM constructor or \n% SSM/ESTIMATE method.\n% \n% numPeriods - Positive, scalar, integer specifying the forecast horizon.\n% \n% Y0 - Observed response data to be forecasted. For time-invariant models \n% in which the length of each observation vector (n) is the same, Y0 is \n% a T-by-n matrix. For time-varying models in which the length of the \n% observation vector changes, Y0 is a T-by-1 cell array in which each \n% element contains a time-varying n-element vector of observations, y(t), \n% associated with the corresponding period. The last observation is the \n% most recent.\n% \n% Optional Input Name/Value Pairs:\n% \n% 'A' Cell vector of forecasted state transition matrices in which each \n% element is a matrix corresponding to a period in the forecast horizon \n% at time t = 1,2,...,numPeriods. If the length of the state vector \n% x(t) is constant, then each element is a square m-by-m matrix; \n% however, if the length of x(t) changes, then some elements are \n% non-square matrices. The length of the cell array must be at least \n% numPeriods, and any elements beyond the forecast horizon are ignored.\n% By default, the last coefficient of the input SSM model Mdl is used \n% for all future periods.\n% \n% 'B' Cell vector of forecasted state disturbance loading matrices in which \n% each element is a matrix corresponding to a period in the forecast \n% horizon at time t = 1,2,...,numPeriods. If the lengths of the state \n% vector x(t) and disturbance vector u(t) are constant, then each \n% element is an m-by-k matrix; however, if the length of x(t) or u(t) \n% changes, then the elements are matrices of various sizes. The length \n% of the cell array must be at least numPeriods, and any elements \n% beyond the forecast horizon are ignored. By default, the last \n% coefficient of the input SSM model Mdl is used for all future periods.\n% \n% 'C' Cell vector of forecasted measurement sensitivity matrices in which\n% each element is a matrix corresponding to a period in the forecast \n% horizon at time t = 1,2,...,numPeriods. If the lengths of the \n% observation vector y(t) and state vector x(t) are constant, then each \n% element is an n-by-m matrix; however, if the length of y(t) or x(t) \n% changes, then the elements are matrices of various sizes. The length \n% of the cell array must be at least numPeriods, and any elements \n% beyond the forecast horizon are ignored. By default, the last \n% coefficient of the input SSM model Mdl is used for all future periods.\n% \n% 'D' Cell vector of forecasted observation innovation matrices in which \n% each element is a matrix corresponding to a period in the forecast \n% horizon at time t = 1,2,...,numPeriods. If the lengths of the \n% observation vector y(t) and innovation vector e(t) are constant, then \n% each element is an n-by-h matrix; however, if the length of y(t) or \n% e(t) changes, then the elements are matrices of various sizes. The \n% length of the cell array must be at least numPeriods, and any \n% elements beyond the forecast horizon are ignored. By default, the \n% last coefficient of the input SSM model Mdl is used for all future \n% periods.\n% \n% 'Predictors0' T-by-d matrix of common predictor variables used to\n% include a regression component in the observation equation. \n% Observations at time t are deflated such that\n% \n% [y(t) - z(t)*b] = C * x(t) + D * e(t)\n% \n% where z(t) is a vector of predictor variables and b is \n% the regression coefficient vector (see below). The default\n% is an empty matrix (no regression component)\n% \n% 'PredictorsF' numPeriods-by-d matrix of common predictor variables used to\n% include a regression component in the observation equation. \n% \n% 'Beta' d-by-n matrix of regression coefficients associated with\n% predictors (see above). \n% \n% Output Arguments:\n% \n% Y - Point forecasts of observations, E[y(t)|y(t-1),...,y(1)], for\n% t = 1,2,...,numPeriods. For time-invariant models in which the length \n% of each observation vector (n) is the same, this is a numPeriods-by-n \n% matrix. For time-varying models in which the length of the observation \n% vector changes, this is a numPeriods-by-1 cell array in which each \n% element contains a time-varying n-element vector of forecasts associated\n% with the corresponding period. \n% \n% YMSE - Forecast error variances of future observations, \n% Cov[y(t)|y(t-1),...,y(1)], for t = 1,2,...,numPeriods. For \n% time-invariant models in which the length of each observation vector \n% (n) is the same, this is a numPeriods-by-n matrix. For time-varying \n% models in which the length of the observation vector changes, this is \n% a numPeriods-by-1 cell array in which each element contains a \n% time-varying n-element vector of forecast error variances associated \n% with the corresponding period.\n% \n% X - Point forecasts of states, E[x(t)|y(t-1),...,y(1)], for t = 1,2,..., \n% numPeriods. For time-invariant models in which the length of each state \n% vector (m) is the same, this is a numPeriods-by-m matrix. For \n% time-varying models in which the length of the state vector changes, \n% this is a numPeriods-by-1 cell array in which each element contains a \n% time-varying m-element vector of forecasts associated with the \n% corresponding period. \n% \n% XMSE - Forecast error variances of future states, \n% Cov[x(t)|y(t-1),...,y(1)], for t = 1,2,...,numPeriods. For \n% time-invariant models in which the length of each state vector (m) is \n% the same, this is a numPeriods-by-m matrix. For time-varying models \n% in which the length of the state vector changes, this is a \n% numPeriods-by-1 cell array in which each element contains a time-varying \n% m-element vector of forecast error variances associated with the \n% corresponding period.\n% \n% See also SSM, FILTER, SMOOTH, SIMULATE, ESTIMATE.\n%\n% Other functions named forecast\n%\n% abstvar/forecast garch/forecast\n% arima/forecast generic/forecast\n% conjugateblm/forecast gjr/forecast\n% customblm/forecast regARIMA/forecast\n% diffuseblm/forecast semiconjugateblm/forecast\n% egarch/forecast varm/forecast\n% empiricalblm/forecast vecm/forecast\n%", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/classes/models/@generic/forecast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4985157282436285}} {"text": "% Copyright 2013 Oliver Johnson, Srikanth Patala\n% \n% This file is part of MisorientationMaps.\n% \n% MisorientationMaps 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% MisorientationMaps 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 MisorientationMaps. If not, see .\n\nfunction rgb = colormap432(v)\n\n% this is to adjust to the \"correct\" fundamental sector\nsR = sphericalRegion([vector3d(0,1,-1),vector3d(1,-1,0),vector3d.Z]);\ncs = crystalSymmetry('m-3m');\nv = project2FundamentalRegion(v,cs,sR.center);\n\npts = reshape(double(v),[],3);\n\nkmax = sqrt(2)-1;\ntheta = atan2(pts(:,3),pts(:,2));\nt2ind2 = find(pts(:,1) > 1/3 & theta > atan((1-2*pts(:,1))./(pts(:,1))));\n\ntempvar2 = pts(t2ind2,2).*(1-pts(t2ind2,1));\ntempvar3 = pts(t2ind2,1).*(pts(t2ind2,2)+pts(t2ind2,3))./(tempvar2 + 1*(tempvar2 == 0));\npts(t2ind2,:) = [pts(t2ind2,1) tempvar3.*pts(t2ind2,2) tempvar3.*pts(t2ind2,3)];\ng1 = rotvec2mat([1 0 0 -3*pi/8]);\npts = pts*g1;\npts = [pts(:,1) - kmax pts(:,2) pts(:,3)];\n\ntempvar = (1 + pts(:,2).*tan(pi/8)./(pts(:,3) + 1*(pts(:,3)==0)));\npts = [pts(:,1) pts(:,2).*tempvar pts(:,3).*tempvar];\n\n%%%%% Def Step 3 %%%%%\npts = [pts(:,1) pts(:,2)*cos(pi/8)/tan(pi/8) (pts(:,3) - pts(:,1)./cos(pi/8))];\n\n%%%%% Def Step 4 %%%%%%\ntheta = atan2(-pts(:,1),pts(:,2));\npts = [pts(:,1).*(sin(theta) + abs(cos(theta))) ...\n pts(:,2).*(sin(theta) + abs(cos(theta))) pts(:,3)];\n\n%%%% Def Step 5 %%%%%\ntheta = atan2(-pts(:,1),pts(:,2));\nrad = hypot(pts(:,2),pts(:,1));\npts = [-rad.*sin(2*theta) rad.*cos(2*theta) pts(:,3)];\nkmax = (sqrt(2)-1);tempk = cos(pi/8)/tan(pi/8);\npts(:,1) = pts(:,1)/kmax;pts(:,2) = pts(:,2)/kmax;pts(:,3) = pts(:,3)*tempk;\ng1 = rotvec2mat([0 0 1 -pi/6]);\npts = pts*g1;\n\n% S= hsvconereg(pts);\ninitS = hsvconereg(pts);\ng1 = rotvec2mat([0 1 0 pi]);\ninitS = initS*g1;\ninitS = [initS(:,1) + 1 initS(:,2) initS(:,3)+1];\nrgb = [initS(:,2) initS(:,3) initS(:,1)];\nrgb(rgb > 1 & rgb - 1 <= eps) = 1;\nrgb(rgb < 0 & rgb >= -10*eps) = 0;\n\nend\n\n% testing code\n%v = 0.2*equispacedS2Grid('points',1000);\n\n%rgb = colormap432(v);\n%plot(v,rgb)\n\n\n\n\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/plotting/orientationColorKeys/@PatalaColorKey/private/colormap432.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.49847857215706}} {"text": "classdef prtFeatSelLlnn < prtFeatSel\n % prtFeatSelLLnn Local Learning based feature selection\n %\n % FEATSEL = prtFeatSelLlnn returns a local learning based feature selection\n % object.\n %\n % FEATSEL = prtFeatSelLlnn(PROPERTY1, VALUE1, ...) constructs a\n % prttFeatSelExhaustive object FEATSEL with properties as specified by\n % PROPERTY/VALUE pair\n %\n % A prtFeatSelExhaustive object has the following properties:\n %\n % selectedFeatures - The indices of the features selected,\n % a read-only parameter, found by training. \n % verbosePlot - Toggles plotting on/off during training\n % nMaxIterations - The maximum number of iterations\n % normalizedWeightCutOff - The weight threshold for keeping a feature\n %\n % The following features are settable, and are related to the\n % training algorithm. Please see reference for further information.\n %\n % kernelSigma\n % sparsnessLambda\n % vGradNMaxSteps\n % vGradInitStepSize\n % vGradChangeThreshold\n % vGradNMaxStepSizeChanges\n % weightChangeThreshold\n %\n % Reference:\n % http://www.computer.org/portal/web/csdl/doi/10.1109/TPAMI.2009.190\n %\n % A prtFeatSelExhaustive object inherits the TRAIN and RUN methods\n % from prtClass.\n %\n % Example:\n %\n % dataSet = prtDataGenSpiral; % Create a 2 dimensional data set\n % nNoiseFeatures = 100; % Append 100 irrelevant features\n % dataSet = prtDataSetClass(cat(2,dataSet.getObservations,randn([dataSet.nObservations, nNoiseFeatures])), dataSet.getTargets);\n % featSel = prtFeatSelLlnn('verbosePlot',true); % Create the feature\n % % selection object.\n % featSel.nMaxIterations = 10; % Set the max # of\n % % iterations.\n % featSel = featSel.train(dataSet); % Train \n %\n % See Also: prtFeatSelStatic, prtFeatSelSfs, prtFeatSelExhaustive\n\n\n\n\n\n\n\n properties (SetAccess=private)\n % Required by prtAction\n name = 'Local Learning Nearest Neighbor'\n nameAbbreviation = 'LLNN'\n end\n \n properties\n \n kernelSigma = 1;\n sparsnessLambda = 2;\n vGradNMaxSteps = 100;\n vGradInitStepSize = 1;\n vGradChangeThreshold = 1e-4;\n vGradNMaxStepSizeChanges = 12;\n weightChangeThreshold = 0.01;\n nMaxIterations = 25; % The maximum number of iterations\n normalizedWeightCutOff = 0.05; % The weight threshold to include a feature.\n \n % Learned \n weights = [] ; % The weights of each feature\n selectedFeatures = []; % The selected features\n \n verbosePlot = false; % Toggles plotting on/off during training\n end\n \n methods\n \n % Constructor %%\n function Obj = prtFeatSelLlnn(varargin)\n \n % Allow for string, value pairs\n Obj = prtUtilAssignStringValuePairs(Obj,varargin{:});\n end \n end\n \n methods (Access=protected,Hidden=true)\n \n % Train %%\n function Obj = trainAction(Obj,DS)\n \n % Remove stuff from data set, too many calls to getObservations\n X = DS.getObservations();\n Y = DS.getTargetsClassInd();\n \n vExpDistanceFunction = @(v,zBar)exp(-zBar*(v.^2));\n \n vFitnessFunction = @(v,cExpDistance)sum(log(1+cExpDistance)) + Obj.sparsnessLambda*sum(v.^2);\n \n w = ones(DS.nFeatures,1);\n wOld = w;\n wChanges = nan(Obj.nMaxIterations,1);\n for iter = 1:Obj.nMaxIterations\n \n % Find zBar\n % Eq: 3-5\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n cSigma = Obj.kernelSigma*sqrt(sum((w./max(w))>Obj.normalizedWeightCutOff)); % Modify kernel to the \"dimensionality\" imposed by w\n \n zBar = zeros(DS.nObservations, DS.nFeatures);\n for iSamp = 1:DS.nObservations\n \n % L1 Distance from this point in each dim\n cD = abs(bsxfun(@minus,X(iSamp,:),X));\n cD(iSamp,:) = inf;\n \n % Label of this point\n cY = Y(iSamp);\n \n % Kernel mapped distance to this point\n cK = exp(-sum(bsxfun(@times,cD,w(:)'),2)/cSigma); % Hard coded L1 Distance\n \n % Calculate the prob of nearest miss and nearst hit\n % Eqs: 4, 5\n cKMiss = cK;\n cKMiss(Y==cY) = 0; % Cant be a miss if you are the same type\n cKMiss(iSamp) = 0; % Cant be your own miss\n cKMiss = cKMiss./sum(cKMiss);\n \n cKHit = cK;\n cKHit(Y~=cY) = 0; % Cant be a hit if you are a different type\n cKHit(iSamp) = 0; % Cant be your own hit\n cKHit = cKHit./sum(cKHit);\n \n % Eq: 3\n cD(iSamp,:) = 0; % inf*0 = nan\n zBar(iSamp,:) = sum(bsxfun(@times,cD, cKMiss),1) - sum(bsxfun(@times,cD, cKHit),1);\n \n end\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n % Optimize v\n % Eqs: 9, 10\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n v = sqrt(w);\n \n cExpDistance = vExpDistanceFunction(v,zBar);\n vScore = vFitnessFunction(v,cExpDistance); % Eq: 9\n \n vScoreOld = vScore;\n for iStep = 1:Obj.vGradNMaxSteps\n cStepSize = Obj.vGradInitStepSize*2; % we multiply by 2 since we divide by 2 at every iteration (even the first)\n \n % Transform cExpDistance into necessary term for the\n % gradient, we use the same name... just because\n cExpDistance = cExpDistance./(1 + cExpDistance);\n cExpDistance(isnan(cExpDistance)) = 0; % inf/(inf + 1)\n \n % Eq: 10\n cChange = Obj.sparsnessLambda*ones(size(w)) - sum(bsxfun(@times,cExpDistance, zBar),1)';\n \n for iStepSize = 1:Obj.vGradNMaxStepSizeChanges\n cStepSize = cStepSize / 2; % Lower the step size, we get here if 1) first iteration (we multiplied the step size by 2) or 2) step size was too big so we need to shrink it.\n \n vNew = v - cStepSize*cChange.*v; % Eq: 10\n \n cExpDistance = vExpDistanceFunction(vNew,zBar);\n \n vNewScore = vFitnessFunction(vNew,cExpDistance);\n \n if vNewScore < vScore\n vScore = vNewScore;\n v = vNew;\n % Note that cExpDistance will be reused but\n % immediately over written with its alter ego\n % this saves a little mem I guess\n break\n else\n % We increased the fitness (bad) so the step\n % size must be too big.\n % Continue in the loop decrease the step size\n % by 50%.\n end\n end\n \n if abs(vScore-vScoreOld)/mean([vScore vScoreOld]) < Obj.vGradChangeThreshold\n break\n else\n vScoreOld = vScore;\n end\n end \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n w = v.^2;\n \n cWChange = norm(abs(w-wOld));\n \n %%% Other ideas for exit criterion %%%\n % cWChange = norm(abs(w-wOld))/sqrt(length(w));\n % cWChange = mean(abs(w-wOld)./mean(cat(2,w,wOld),2)); % Average percent change\n % wNorm = w ./ max(w);\n % wOldNorm = wOld ./ max(wOld);\n % cWChange = mean(abs(wNorm-wOldNorm)./mean(cat(2,wNorm,wOldNorm),2)); % Normalized Average percent change\n % cWChange = mean(abs(wNorm-wOldNorm)); % Normalized Average change\n \n if Obj.verbosePlot\n subplot(2,1,1)\n stem(w./max(w));\n title('Feature Importance','FontSize',14)\n xlabel('Feature')\n ylabel('Normalized Feature Weight');\n xlim([1 length(w)]);\n \n subplot(2,1,2)\n wChanges(iter) = cWChange;\n plot(1:iter,wChanges(1:iter),'b-',1:iter,wChanges(1:iter),'rx')\n title('Optimization Exit Criterion','FontSize',14)\n xlabel('Iteration')\n ylabel('Weight Change From Last Iteration')\n xlim([0.5 iter+0.5]);\n set(gca,'XTick',1:iter);\n \n drawnow;\n end\n \n if cWChange < Obj.weightChangeThreshold\n break\n end\n wOld =w;\n \n end\n\n Obj.weights = w;\n Obj.selectedFeatures = find(w > Obj.normalizedWeightCutOff);\n end\n \n % Run %\n function DataSet = runAction(Obj,DataSet)\n DataSet = DataSet.retainFeatures(Obj.selectedFeatures);\n end \n end \nend\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/featSel/prtFeatSelLlnn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.498418453522612}} {"text": "function [b,c,d,x,y,z,qfac] = vox2rasToQform(vox2ras)\n% [a,b,c,x,y,z,qfac] = vox2rasToQform(vox2ras)\n% \n% Converts a vox2ras matrix to NIFTI qform parameters.\n% Note: the vox2ras should be 6 DOF. This code mostly just \n% follows CH's mriToNiftiQform() in mriio.c.\n% \n% hdr.pixdim(1) = qfac;\n% hdr.quatern_b = b;\n% hdr.quatern_c = c;\n% hdr.quatern_d = d;\n% hdr.qoffset_x = x;\n% hdr.qoffset_y = y;\n% hdr.qoffset_z = z;\n% hdr.qform_code = NIFTI_XFORM_SCANNER_ANAT=1;\n%\n\n\n%\n% vox2rasToQform.m\n%\n% Original Author: Doug Greve\n% CVS Revision Info:\n% $Author: nicks $\n% $Date: 2011/03/02 00:04:13 $\n% $Revision: 1.3 $\n%\n% Copyright Ā© 2011 The General Hospital Corporation (Boston, MA) \"MGH\"\n%\n% Terms and conditions for use, reproduction, distribution and contribution\n% are found in the 'FreeSurfer Software License Agreement' contained\n% in the file 'LICENSE' found in the FreeSurfer distribution, and here:\n%\n% https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense\n%\n% Reporting: freesurfer@nmr.mgh.harvard.edu\n%\n\n\na = [];\nif(nargin ~= 1)\n fprintf('[a,b,c,x,y,z,qfac] = vox2rasToQform(vox2ras)\\n');\n return;\nend\n\nx = vox2ras(1,4);\ny = vox2ras(2,4);\nz = vox2ras(3,4);\n\nd = sqrt(sum(vox2ras(:,1:3).^2));\nMdc = vox2ras(1:3,1:3) ./ repmat(d,[3 1]);\nif(det(Mdc) == 0.0)\n fprintf('ERROR: vox2ras determinant is 0\\n');\n return;\nend\n\nr11 = Mdc(1,1);\nr21 = Mdc(2,1);\nr31 = Mdc(3,1);\nr12 = Mdc(1,2);\nr22 = Mdc(2,2);\nr32 = Mdc(3,2);\nr13 = Mdc(1,3);\nr23 = Mdc(2,3);\nr33 = Mdc(3,3);\n\nif(det(Mdc) > 0.0) qfac = 1.0;\nelse\n r13 = -r13;\n r23 = -r23;\n r33 = -r33;\n qfac = -1.0;\nend\n\n% /* following mat44_to_quatern() */\n\na = r11 + r22 + r33 + 1.0;\nif(a > 0.5)\n a = 0.5 * sqrt(a);\n b = 0.25 * (r32-r23) / a;\n c = 0.25 * (r13-r31) / a;\n d = 0.25 * (r21-r12) / a;\nelse\n xd = 1.0 + r11 - (r22+r33);\n yd = 1.0 + r22 - (r11+r33);\n zd = 1.0 + r33 - (r11+r22);\n if(xd > 1.0)\n b = 0.5 * sqrt(xd);\n c = 0.25 * (r12+r21) / b;\n d = 0.25 * (r13+r31) / b;\n a = 0.25 * (r32-r23) / b;\n elseif( yd > 1.0 )\n c = 0.5 * sqrt(yd);\n b = 0.25 * (r12+r21) / c;\n d = 0.25 * (r23+r32) / c;\n a = 0.25 * (r13-r31) / c;\n else\n d = 0.5 * sqrt(zd);\n b = 0.25 * (r13+r31) / d;\n c = 0.25 * (r23+r32) / d;\n a = 0.25 * (r21-r12) / d;\n end\n if(a < 0.0)\n a = -a;\n b = -b;\n c = -c;\n d = -d;\n end\nend\n\n\nreturn\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/external/freesurfer/vox2rasToQform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4982189887745603}} {"text": "classdef BCEIBEA < ALGORITHM\n% \n% Bi-criterion evolution based IBEA\n% kappa --- 0.05 --- Fitness scaling factor\n\n%------------------------------- Reference --------------------------------\n% M. Li, S. Yang, and X. Liu, Pareto or non-Pareto: Bi-criterion evolution\n% in multiobjective optimization, IEEE Transactions on Evolutionary\n% Computation, 2016, 20(5): 645-665.\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 methods\n function main(Algorithm,Problem)\n %% Parameter setting\n kappa = Algorithm.ParameterSet(0.05);\n\n %% Generate random population\n NPC = Problem.Initialization();\n [PC,nND] = PCSelection(NPC,Problem.N);\n\n %% Optimization\n while Algorithm.NotTerminated(PC)\n % PC evolving\n NewPC = Exploration(Problem,PC,NPC,nND,Problem.N);\n % NPC selection\n NPC = EnvironmentalSelection([NPC,NewPC],Problem.N,kappa);\n % NPC evolving\n MatingPool = TournamentSelection(2,Problem.N,-CalFitness(NPC.objs,kappa));\n NewNPC = OperatorGA(Problem,NPC(MatingPool));\n NPC = EnvironmentalSelection([NPC,NewNPC],Problem.N,kappa);\n % PC selection\n [PC,nND] = PCSelection([PC,NewNPC,NewPC],Problem.N);\n end\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Algorithms/Multi-objective optimization/BCE-IBEA/BCEIBEA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.49821898342608323}} {"text": "function [val,vec,info] = syevd(jobz,uplo,a)\n%SYEV Computing eigen information.\n% [VAL,VEC,INFO] = SYEVD(JOBZ,UPLO,A) computes eigenvalues and,\n%\toptionally, eigenvectors of a symmetric matrix A.\n%\n%\tJOBZ allows the user to choose if eigenvectors are to be computed.\n%\tJOBZ\n% = 'N': Compute eigenvalues only;\n% = 'V': Compute eigenvalues and eigenvectors.\n%\n%\tUPLO allows the user to choose which part of the matrix will be referenced.\n%\tUPLO\n% = 'U': Upper triangle of A is stored;\n% = 'L': Lower triangle of A is stored.\n%\n% If only eigenvalues are desired, the QR algorithm is used. \n%\n%\tNo input parameter are optional. If you want an easy to use interface,\n%\tsee SYEV_DRIVER.\n\n vec = [];\n\tval = [];\n\tinfo = [];\n\t\n\tif (nargin~=3),\n\t\tdisp('Wrong number of input parameters.');\n\t\treturn;\n\tend;\n\t\n\t %Do all the boring checking\n\tif (~isnumeric(a)),\n\t\tdisp('The matrix is not composed of numeric values.');\n\t\treturn;\n\telseif (isinteger(a)),\n\t\ta=double(a);\n\tend;\n\n if (size(a,1)~=size(a,2)),\n disp('The matrix must be square.');\n return;\n\tend;\n\tn=int32(size(a,1));\n\tlda=int32(n);\n\t\n\tif (isComplex(a)),\n\t\tif (isDouble(a))\n\n\t\t\tw=zeros(double(n),1);\n\t\t\twork=complex(zeros(1));\n\t\t\trwork=zeros(1,1);\n\t\t\tiwork=int32(zeros(1,1));\n\t\t\tlrwork=int32(-1);\n\t\t\tliwork=int32(-1);\n\t\t\tlwork=int32(-1);\n\t\t\tinfo=int32(-1);\n\t\t\t[jobz, uplo, n, vec, lda, val, work, lwork, rwork,lrwork, iwork, liwork, info]=lapack_zheevd(jobz, uplo, n, a, lda, w, work, lwork, rwork,lrwork, iwork, liwork, info);\n\t\t\tlwork=int32(work(1));\n\t\t\tliwork=int32(iwork(1));\n\t\t\tlrwork=int32(rwork(1));\n\n\t\t\twork=complex(zeros(double(lwork),1));\n\t\t\tiwork=int32(zeros(double(lwork),1));\n\t\t\trwork=zeros(double(lwork),1);\n\t\t\t[jobz, uplo, n, vec, lda, val, work, lwork, rwork,lrwork, iwork, liwork, info]=lapack_zheevd(jobz, uplo, n, a, lda, w, work, lwork, rwork,lrwork, iwork, liwork, info);\n\t\telse\n\t\t\tw=single(zeros(double(n),1));\n\t\t\twork=single(complex(zeros(1)));\n\t\t\trwork=single(zeros(1,1));\n\t\t\tiwork=int32(zeros(1,1));\n\t\t\tlrwork=int32(-1);\n\t\t\tliwork=int32(-1);\n\t\t\tlwork=int32(-1);\n\t\t\tinfo=int32(-1);\n\t\t\t[jobz, uplo, n, vec, lda, val, work, lwork, rwork,lrwork, iwork, liwork, info]=lapack_cheevd(jobz, uplo, n, a, lda, w, work, lwork, rwork,lrwork, iwork, liwork, info);\n\t\t\tlwork=int32(work(1));\n\t\t\tliwork=int32(iwork(1));\n\t\t\tlrwork=int32(rwork(1));\n\n\t\t\twork=single(complex(zeros(double(lwork),1))); \n\t\t\tiwork=int32(zeros(double(liwork),1));\n\t\t\trwork=single(zeros(double(lrwork),1));\n\t\t\t[jobz, uplo, n, vec, lda, val, work, lwork, rwork,lrwork, iwork, liwork, info]=lapack_cheevd(jobz, uplo, n, a, lda, w, work, lwork, rwork,lrwork, iwork, liwork, info);\n\n\t\tend;\n\telse\n\t\tif (isDouble(a)),\n\t\t\tw=zeros(double(n),1);\n\t\t\twork=zeros(1);\n\t\t\tiwork=int32(zeros(1));\n\t\t\tlwork=int32(-1);\n\t\t\tliwork=int32(-1);\n\t\t\tinfo=int32(-1);\n\t\t\t[jobz, uplo, n, vec, lda, val, work, lwork, iwork,liwork, info]= lapack_dsyevd(jobz, uplo, n, a, lda, w, work, lwork, iwork,liwork, info);\n\t\t\tlwork=int32(work(1));\n\t\t\tliwork=int32(iwork(1));\n\t\t\twork=zeros(double(lwork),1);\n\t\t\tiwork=int32(zeros(double(liwork),1));\n\t\t\t[jobz, uplo, n, vec, lda, val, work, lwork, iwork,liwork, info]= lapack_dsyevd(jobz, uplo, n, a, lda, w, work, lwork, iwork,liwork, info);\n\t\telse\n\t\t\tw=single(zeros(double(n),1));\n\t\t\twork=single(zeros(1));\n\t\t\tiwork=int32(zeros(1));\n\t\t\tlwork=int32(-1);\n\t\t\tliwork=int32(-1);\n\t\t\tinfo=int32(-1);\n\t\t\t[jobz, uplo, n, vec, lda, val, work, lwork, iwork,liwork, info]= lapack_ssyevd(jobz, uplo, n, a, lda, w, work, lwork, iwork,liwork, info);\n\t\t\tlwork=int32(work(1));\n\t\t\tliwork=int32(iwork(1));\n\t\t\twork=single(zeros(double(lwork),1));\n\t\t\tiwork=int32(zeros(double(liwork),1));\n\t\t\t[jobz, uplo, n, vec, lda, val, work, lwork, iwork,liwork, info]= lapack_ssyevd(jobz, uplo, n, a, lda, w, work, lwork, iwork,liwork, info);\n\t\tend;\n\tend;\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/LapWrap/lib/m_files/syevd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.49820881226601854}} {"text": "function [c, s, b, g, smin, active_set] = thresholded_oasisAR2(y, g, sn, optimize_b,...\n optimize_g, decimate, maxIter, thresh_factor)\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% g: scalar, Parameter of the AR(1) process that models the fluorescence ...\n%impulse response.\n% sn: scalar, standard deviation of the noise distribution\n% optimize_b: bool, optimize baseline if True\n% optimize_g: integer, number of large, isolated events to consider for\n% optimizing g\n% decimate: int, decimation factor for estimating hyper-parameters faster\n% on decimated data\n% maxIter: int, maximum number of iterations\n% active_set: npool x 4 matrix, warm stared active sets\n% thresh_factor: scalar, set the maximum thresh as thresh_factor*sn^2*T\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% b: scalar, fluorescence baseline\n% g: scalar, parameter of the AR(1) process\n% smin: scalar, minimum nonzero spike count\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\n%% input arguments\ny = reshape(y, [], 1);\nT = length(y);\n\nif ~exist('g', 'var') || isempty(g)\n g = estimate_time_constant(y, 2);\nend\nif ~exist('sn', 'var') || isempty(sn)\n sn = GetSn(y);\nend\nif ~exist('optimize_b', 'var') || isempty(optimize_b)\n optimize_b = false;\nend\nif ~exist('optimize_g', 'var') || isempty(optimize_g)\n optimize_g = 0;\nend\nif ~exist('decimate', 'var') || isempty(decimate)\n decimate = 1;\nelse\n decimate = max(1, round(decimate));\nend\nif ~exist('maxIter', 'var') || isempty(maxIter)\n maxIter = 10;\nend\nif ~exist('thresh_factor', 'var') || isempty(thresh_factor)\n thresh_factor = 1.0;\nend\n\nthresh = thresh_factor* sn * sn * T;\nsmin = 0;\n\n% change parameters due to downsampling\nif decimate>1\n decimate = 1; %#ok\n disp('to be done');\n % fluo = y;\n % y = resample(y, 1, decimate);\n % g = g^decimate;\n % thresh = thresh / decimate / decimate;\n % T = length(y);\nend\ng_converged = false;\n\n%% optimize parameters\ntol = 1e-4;\nif ~optimize_b %% don't optimize the baseline b\n %% initialization\n b = 0;\n [solution, spks, active_set] = oasisAR2(y, g, [], smin);\n \n %% iteratively update parameters lambda & g\n for miter=1:maxIter\n len_active_set = size(active_set, 1);\n \n res = y - solution;\n RSS = res' * res;\n \n % update g\n if and(optimize_g, ~g_converged);\n g0 = g;\n [solution, active_set, g, spks] = update_g(y, g, spks,smin);\n if abs(g-g0)/g0 < 1e-3 % g is converged\n g_converged = true;\n end\n end\n% g_converged = true; \n res = y - solution;\n RSS = res' * res;\n if or(RSS>thresh, sum(solution)<1e-9) % constrained form has been found, stop\n break;\n else\n % update lam\n [smin, solution, spks, active_set] = update_smin(y, g, smin,...\n solution, spks, active_set, sqrt(thresh), max(spks));\n \n % no more change of the active set\n if size(active_set,1)==len_active_set\n break;\n end\n end\n end\nelse\n %% initialization\n b = quantile(y, 0.15);\n [solution, spks, active_set] = oasisAR2(y-b, g, [], smin);\n \n %% optimize the baseline b and dependends on the optimized g too\n g_converged = false;\n for miter=1:maxIter\n % update b and g\n \n res = y - solution - b;\n RSS = res' * res;\n len_active_set = size(active_set,1);\n \n if or(abs(RSS-thresh) < tol, sum(solution)<1e-9)\n break;\n else\n % update smin\n [smin, solution, spks, active_set] = update_smin(y-b, g, smin,...\n solution, spks, active_set, sqrt(thresh), max(spks));\n b = mean(y-solution);\n \n % update b and g\n if and(optimize_g, ~g_converged);\n g0 = g;\n [solution, active_set, g, spks] = update_g(y-b, g0, spks, smin);\n if abs(g-g0)/g0 < 1e-4;\n g_converged = true;\n end\n end\n \n end\n end\n \nend\nc = solution;\ns = spks;\n\n%% nested functions\n function [smin, solution, spks, active_set] = update_smin(y, g, smin, solution, ...\n spks, active_set, thresh, s_max)\n %%estimate smin to match the thresholded RSS\n len_active_set = size(active_set, 1);\n sv = linspace(smin, s_max, min(9, len_active_set));\n ind_start = 1;\n ind_end = length(sv);\n \n while (ind_end-ind_start)>1\n ind = floor((ind_start+ind_end)/2);\n tmp_smin = sv(ind);\n [tmp_solution, tmp_spks, tmp_active_set] = oasisAR2(y, g, [], ...\n tmp_smin, [], [], active_set);\n sqRSS = norm(y-tmp_solution,2);\n if sqRSSthresh % decrease smin\n ind_end = ind;\n else\n break;\n end\n end\n end\n\n\nend\n\n%update the AR coefficient: g\nfunction [c, active_set, g, s] = update_g(y, g, spks, smin)\n%% inputs:\n% y: T*1 vector, One dimensional array containing the fluorescence intensities\n%withone entry per time-bin.\n% g: 2x1 vector, AR2 parameters\n% active_set: npools*4 matrix, previous active sets.\n% smin: scalr, minimize size of nonzero spikes\n\n%% outputs\n% c: T*1 vector\n% s: T*1 vector, spike train\n% active_set: npool x 4 matrix, active sets\n% g: scalar\n\n%% Authors: Pengcheng Zhou, Carnegie Mellon University, 2016\n\n%% initialization\ns_th = quantile(spks(spks>1e-3), 0.25); \ntsp = find(spks>=s_th); \ntsp = reshape(tsp, 1, []); \ntime_p = find(conv2(double(spks<=s_th), ones(30,1), 'same')>0); \ntime_p = reshape(time_p,[],1); \ny = reshape(y,[],1); % fluorescence data\nyp = y(time_p); \nT = length(y); \ntau_dr = ar2exp(g);\ntau_d = tau_dr(1);\ntau_r = tau_dr(2);\n\n%% find the optimal g and get the warm started active_set\ntau_d0 = tau_d;\ntau_r0 = tau_r;\nbnd_d = tau_d0 * [1/4, 4];\nbnd_r = tau_r0 * [1/4, 4];\nfor m=1:10\n tau_r = fminbnd(@rss_taur, bnd_r(1), bnd_r(2));\n tau_d = fminbnd(@rss_taud, bnd_d(1), bnd_d(2));\n if and(abs(tau_d-tau_d0)/tau_d0 < 1e-4, abs(tau_r-tau_r0)/tau_r0 < 1e-4)\n break;\n else\n tau_d0 = tau_d;\n tau_r0 = tau_r;\n end\nend\n\n%% copute the optimal solution\ng = exp2ar([tau_d, tau_r]);\n[c,s,active_set] = oasisAR2(y, g, 0, smin);\n\n%% nested functions\n\n function rss = rss_taur(tau_r) \n ht = (exp(-(1:T)/tau_d) - exp(-(1:T)/tau_r))/(tau_d-tau_r);\n ht(T) = 0;\n ind = bsxfun(@minus, time_p, tsp);\n ind(ind<=0) = T;\n V = ht(ind);\n \n % find the best value of st\n s = (V'*V)\\(V'*yp);\n res = yp - V*s;\n rss = res' * res;\n end\n\n function rss = rss_taud(tau_d) \n ht = (exp(-(1:T)/tau_d) - exp(-(1:T)/tau_r))/(tau_d-tau_r);\n ht(T) = 0;\n ind = bsxfun(@minus, time_p, tsp);\n ind(ind<=0) = T;\n V = ht(ind);\n \n % find the best value of st\n s = (V'*V)\\(V'*yp);\n res = yp - V*s;\n rss = res' * res;\n end\nend", "meta": {"author": "flatironinstitute", "repo": "CaImAn-MATLAB", "sha": "49b7884e93348d50df7173e1619d7499468bb1f6", "save_path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB", "path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB/CaImAn-MATLAB-49b7884e93348d50df7173e1619d7499468bb1f6/deconvolution/oasis/thresholded_oasisAR2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6261241702517976, "lm_q1q2_score": 0.49818076770616415}} {"text": "function Output = Bayesian_RPCAmcmc_MarkovDep(X0,Theta0,Row,Col,hyperpara,MCMCpara)\n%Bayesian_RPCAmcmc_withMarkovDep: Bayesian robust principle component analysis \n%implemented by MCMC, considering Markov dependency on the sparse term in time and space.\n%\n% Model: X0 = D*(Delta.*Z)*S + S2.*Z2 + E\n% ----------------------------------------------------\n%\n%USAGE: Output = Bayesian_RPCAmcmc_withMarkovDep(X0,Theta0,Row,Col,hyperpara,MCMCpara)\n%\n%INPUT : \n% X0: P x N, input data matrix. For the video application, every column is a frame of the video.\n% \n% Theta0: struct data including the initial parameters of the model. The parameters of the model are initialized as follows,\n% D = Theta0.D: P x K matrix as a dictionary for lowrank learning\n% S = Theta0.S: K x N coefficient matrix\n% Z = Theta0.Z: K x K diagnal binary matrix for rank learning\n% Delta = Theta0.Delta: K x K diagnal matrix for weighting Z.\n% Tao = Theta0.Tao: precision of Delta. Here we set Tao=1.\n% Pi = Theta0.Pi: K x 1 vector. Pi is the probability of Z=1.\n% \n% gamma_epsi = Theta0.gamma_epsi: scalar, precision of the noise. Here we assumed the noise is stationary.\n% \n% S2 = Theta0.S2: P x N matrix for Sparse Component learning\n% Z2 = Theta0.Z2: P x N binary matrix for Sparse Component learning\n% gamma_s = Theta0.gamma_s: precision of the S2\n% Pi2 = Theta0.Pi2: P x N . Pi2 is the probability of Z2=1. \n% Note that Pi2 here is a matrix, different from the model structure in function Bayesian_RPCAmcmc.\n%\n% Row and Col: Row and column of the video frame.\n%\n% hyperpara: MCMC hyperparameters\n% hyperpara.a0: scalar, hyperparameter 1 for Pi [1/K or 1/150 if K<150]\n% hyperpara.b0: scalar, hyperparameter 2 for Pi [1-hyperpara.a0]\n% hyperpara.c0: scalar, hyperparameter 1 for Tao precision [1e-6] \n% hyperpara.d0: scalar, hyperparameter 2 for Tao precision [1e-6] \n% hyperpara.e0: scalar, hyperparameter 1 for nosie precision [1e-6] \n% hyperpara.f0: scalar, hyperparameter 2 for nosie precision [1e-6] \n% hyperpara.g0: scalar, hyperparameter 1 for S2 precision [1e-6] \n% hyperpara.h0: scalar, hyperparameter 2 for S2 precision [1e-6] \n% hyperpara.alpha0: scalar,hyperparameter 1 for Pi2 [0.01*N]\n% hyperpara.beta0: scalar,hyperparameter 2 for Pi2 [0.99*N]\n% hyperpara.alpha1: scalar,hyperparameter 3 for Pi2 [0.99*N]\n% hyperpara.beta1: scalar,hyperparameter 4 for Pi2 [0.01*N]\n%\n%\n% MCMCpara: MCMC parameters\n% MCMCpara.nBurnin: scalar, number of burnin iterations [2000]\n% MCMCpara.nCollect: scalar, number of collected samples [1000]\n%\n%OUTPUT:\n% Output: struct data.\n% Output.Lowrank_mean: P x N matrix, mean of the Lowrank Component.\n% Output.Lowrank_std: P x N matrix, std of the Lowrank Component.\n% Output.Sparse_mean: P x N matrix, mean of the Sparse Component.\n% Output.Sparse_std: P x N matrix, std of the Sparse Component.\n% Output.Gamma_epsi_mean: scalar, mean of the noise precision.\n% Output.Gamma_epsi_std: scalar, std of the noise precision.\n% Output.rankL_mean: scalar, mean of the estimated rank of the lowrank Component.\n% Output.rankL_std: scalar, std of the estimated rank of the lowrank Component.\n% Output.NumSparse_mean: scalar, mean of the estimated number of the Sparse Component.\n% Output.NumSparse_std: scalar, std of the estimated number of the Sparse Component.\n\n\n%--------------------------------------------------------------------------\n% References:\n% X. Ding, L. He and L. Carin, Bayesian Robust Principal Component Analysis, submitted to IEEE Trans. Image Processing (2010) \n%\n% Xinghao Ding, Lihan He, ECE, Duke University\n% Created: Apr. 12, 2010,\n% Last change: Aug. 2, 2010. \n%--------------------------------------------------------------------------\n\n% ---------------------\n% check input arguments\n% ---------------------\n\n% P -- Dimension of the data vector\n% N -- Number of samples\n[P,N] = size(X0);\n% K -- the largest possible rank\nK = size(Theta0.D,2);\n\nif nargin<6\n MCMCpara.nBurnin=100;\n MCMCpara.nCollect=100;\nend\nif nargin<5\n % Hyperparameters\n if K<150\n hyperpara.a0 = 1/150;\n else\n hyperpara.a0 = 1/K;\n end \n hyperpara.b0 = 1-hyperpara.a0;\n hyperpara.c0 = 1e-6;\n hyperpara.d0 = 1e-6;\n hyperpara.e0 = 1e-6;\n hyperpara.f0 = 1e-6;\n hyperpara.g0 = 1e-6;\n hyperpara.h0 = 1e-6; \n hyperpara.alpha0 = 0.01*N;\n hyperpara.beta0 = 0.99*N;\n hyperpara.alpha1 = 0.99*N;\n hyperpara.beta1 = 0.01*N; \n \nend\n\nif isempty(hyperpara)\n % P -- Dimension of the data vector\n % N -- Number of samples\n [P,N] = size(X0);\n % K -- the largest possible rank\n K = size(Theta0.D,2);\n\n % Hyperparameters\n if K<150\n hyperpara.a0 = 1/150;\n else\n hyperpara.a0 = 1/K;\n end \n hyperpara.b0 = 1-hyperpara.a0;\n hyperpara.c0 = 1e-6;\n hyperpara.d0 = 1e-6;\n hyperpara.e0 = 1e-6;\n hyperpara.f0 = 1e-6;\n hyperpara.g0 = 1e-6;\n hyperpara.h0 = 1e-6;\n hyperpara.alpha0 = 0.01*N;\n hyperpara.beta0 = 0.99*N;\n hyperpara.alpha1 = 0.99*N;\n hyperpara.beta1 = 0.01*N; \nend\n\nif isempty(MCMCpara)\n MCMCpara.nBurnin=100;\n MCMCpara.nCollect=100;\nend\n\na0 = hyperpara.a0;\nb0 = hyperpara.b0;\nc0 = hyperpara.c0;\nd0 = hyperpara.d0;\ne0 = hyperpara.e0;\nf0 = hyperpara.f0;\ng0 = hyperpara.g0;\nh0 = hyperpara.h0;\nalpha0 = hyperpara.alpha0;\nbeta0 = hyperpara.beta0;\nalpha1 = hyperpara.alpha1;\nbeta1 = hyperpara.beta1; \n\n\nD = Theta0.D;\nS = Theta0.S;\nZ = Theta0.Z;\nDelta = Theta0.Delta;\nTao = Theta0.Tao;\nPi = Theta0.Pi;\ngamma_epsi = Theta0.gamma_epsi;\nS2 = Theta0.S2;\nZ2 = Theta0.Z2;\ngamma_s = Theta0.gamma_s;\nPi2 = Theta0.Pi2;\n\n\nLowrank_Comp = zeros(P,N);\nSparse_Comp = zeros(P,N);\n\n\nfor iter=1:(MCMCpara.nBurnin+MCMCpara.nCollect)\n \n X = X0-D*diag(Delta.*Z)*S-S2.*Z2; \n \n %---------------------------------------------------------------\n % Low-rank component sampling\n %---------------------------------------------------------------\n\n for k=1:K\n Tao(k) =1; \n X = X+ Delta(k)*Z(k)*D(:,k)*S(k,:); \n \n %Sample D----------------------------------------------------------\n sigma_Dk = 1/(gamma_epsi*(Delta(k)).^2*Z(k)*(S(k,:)*S(k,:)')+P);\n mu_Dk = gamma_epsi*sigma_Dk* (Delta(k))*Z(k)*X*S(k,:)';\n D(:,k) = mu_Dk + randn(P,1)*sqrt(sigma_Dk);\n %clear sigma_Dk mu_D\n %------------------------------------------------------------------ \n \n %Sample S----------------------------------------------------------\n \n Dk = D(:,k);\n sigS1 = 1/(1 + gamma_epsi*Z(k)*(Dk'*Dk)*(Delta(k)).^2); \n muS1 = gamma_epsi*sigS1*Z(k)*Delta(k)*D(:,k)'*X;\n S(k,:) = randn(1,N)*sqrt(sigS1) + muS1;\n %------------------------------------------------------------------\n \n \n %Sample Delta(k)\n sig_Delta = 1/(Tao(k)+gamma_epsi*(Dk'*Dk)*(S(k,:)*S(k,:)'));\n mu_Delta = gamma_epsi*sig_Delta*D(:,k)'*X*S(k,:)';\n if Z(k) ==1\n %Delta(k) = randn(1)*sqrt(sig_Delta)+mu_Delta;\n Delta(k) = normrnd(mu_Delta,sqrt(sig_Delta));\n else\n %Delta(k) = randn(1);\n Delta(k) = normrnd(0,sqrt(1/Tao(k)));\n end\n %------------------------------------------------------------------\n \n% %Sample Z---------------------------------------------------------\n Sk = S(k,:);\n Dk = D(:,k);\n temp = - 0.5*gamma_epsi*(Delta(k)).^2*(Dk'*Dk)*(Sk*Sk') + gamma_epsi*Delta(k)*Dk'*(X*S(k,:)'); \n p1 = exp(temp)*Pi(k); \n p0 = 1-Pi(k); \n Z(k) = rand > p0/(p0+p1);\n %------------------------------------------------------------------\n \n% %Clappsed Gibbs Sample Z\n% tmpz = log(Pi(k)+eps) - log(1-Pi(k)+eps) + 0.5*log(sig_Delta) + (mu_Delta^2)/(2*sig_Delta) + 0.5*log(Tao(k));\n% if rand < 1/(1+exp(-tmpz))\n% Z(k) = 1; Delta(k) = normrnd(mu_Delta,sqrt(sig_Delta));\n% else\n% Z(k) = 0; Delta(k) = normrnd(0,sqrt(1/Tao(k)));\n% end\n \n \n %sample Pi--------------------------------------------------\n ai = a0 + Z(k);\n bi = b0 + 1 - Z(k);\n Pi(k) =betarnd(ai,bi);\n %------------------------------------------------------------------\n \n %sample Tao\n% if Z(k) ==1\n% c1 =c0+1/2;\n% d1 =d0 + 0.5*(Delta(k)).^2;\n% Tao(k) = gamrnd(c1,1./d1);\n% else\n% Tao(k) = 1;\n% end\n %------------------------------------------------------------------\n \n X = X - Delta(k)*Z(k)*D(:,k)*S(k,:); \n end \n \n \n %---------------------------------------------------------------\n % Sparse component sampling\n %---------------------------------------------------------------\n\n X = X + S2.*Z2; \n \n % Sample S2\n sig_S2 = 1./(gamma_s + gamma_epsi*Z2);\n mu_S2 = gamma_epsi*sig_S2.*Z2.*X;\n S2 = randn(P,N).*sqrt(sig_S2)+mu_S2;\n \n % Sample Z2 \n temp = exp(-0.5*gamma_epsi*(S2.^2-2*S2.*X)); \n% p1 = repmat(Pi2,[1,N]).*temp;\n% p0 = repmat(1- Pi2,[1,N]); \n p1 = Pi2.*temp;\n p0 = 1- Pi2;\n Z2 = rand(P,N)>p0./(p1+p0);\n \n X = X - S2.*Z2; \n \n %sample gamma_s\n g1 = g0 + 0.5*P*N;\n tempS2 = S2.*S2;\n h1 = h0 + 0.5*sum(tempS2(:));\n gamma_s = gamrnd(g1,1/h1);\n \n \n %Sample Pi2\n% sumZ2 = sum(Z2,2);\n% a2 = a1 + sumZ2;\n% b2 = b1 + N -sumZ2;\n% Pi2 = betarnd(a2,b2); \n \n %h = fspecial('average');\n h = [0.1,0.1,0.1;0.1,0.2,0.1;0.1,0.1,0.1];\n for n = 1:N\n temp1 = reshape(Z2(:,n),[Row,Col]);\n temp2 = imfilter(double(temp1),h)>0.6; \n tempZ2(:,n) = reshape(temp2,[Row*Col,1]);\n end\n \n a2 = alpha0 +Z2(:,1);\n b2 = beta0 + 1 - Z2(:,1);\n Pi2(:,1) = betarnd(a2,b2);\n \n for t = 2:N\n% a2 = alpha0*(~Z2(:,t-1))+alpha1*(Z2(:,t-1)) +Z2(:,t);\n% b2 = beta0*(~Z2(:,t-1))+beta1*(Z2(:,t-1)) +1 - Z2(:,t);\n% a2 = alpha0*(~(Z2(:,t-1).*tempZ2(:,t-1)))+alpha1*(Z2(:,t-1).*tempZ2(:,t-1)) +Z2(:,t);\n% b2 = beta0*(~(Z2(:,t-1).*tempZ2(:,t-1)))+beta1*(Z2(:,t-1).*tempZ2(:,t-1)) +1 - Z2(:,t);\n% a2 = alpha0*(~(tempZ2(:,t-1)))+alpha1*(tempZ2(:,t-1)) +Z2(:,t);\n% b2 = beta0*(~(tempZ2(:,t-1)))+beta1*(tempZ2(:,t-1)) +1 - Z2(:,t);\n a2 = alpha0*(~(tempZ2(:,t)))+alpha1*(tempZ2(:,t)) +Z2(:,t);\n b2 = beta0*(~(tempZ2(:,t)))+beta1*(tempZ2(:,t)) +1 - Z2(:,t);\n \n% a2 = alpha0*(~(tempZ2(:,t-1).*tempZ2(:,t)))+alpha1*(tempZ2(:,t-1).*tempZ2(:,t)) +Z2(:,t);\n% b2 = beta0*(~(tempZ2(:,t-1).*tempZ2(:,t)))+beta1*(tempZ2(:,t-1).*tempZ2(:,t)) +1 - Z2(:,t);\n \n% a2 = alpha0*(~(Z2(:,t-1).*tempZ2(:,t)))+alpha1*(Z2(:,t-1).*tempZ2(:,t)) +Z2(:,t);\n% b2 = beta0*(~(Z2(:,t-1).*tempZ2(:,t)))+beta1*(Z2(:,t-1).*tempZ2(:,t)) +1 - Z2(:,t);\n \n Pi2(:,t) = betarnd(a2,b2);\n end\n \n \n %---------------------------------------------------------------\n % noise component sampling\n %---------------------------------------------------------------\n\n %Sample gamma_epsi\n e1 = e0 + 0.5*P*N;\n f1 = f0 + 0.5*sum(sum(X.^2));\n gamma_epsi = gamrnd(e1,1./f1);\n \n \n %------------------------\n \n % Collect samples\n if iter>MCMCpara.nBurnin\n ii = ceil(iter-MCMCpara.nBurnin); \n \n% Lowrank_Comp(:,:,ii) = D*diag(Delta.*Z)*S;\n% Sparse_Comp(:,:,ii) = S2.*Z2;\n Lowrank_Comp = Lowrank_Comp + D*diag(Delta.*Z)*S;\n Sparse_Comp = Sparse_Comp + S2.*Z2;\n\n Gamma_epsi(ii) = gamma_epsi;\n tmpRank(ii) = length(find(Z~=0));\n %tmpNumSparse(ii) = length(find(Sparse_Comp(:,:,ii)~=0));\n %mse_rec(iter) = sum(sum((X0-Lowrank_Comp{ii}-Sparse_Comp{ii}).^2))/(P*N);\n end\n \nend\n\n% Output.Lowrank_mean = mean(Lowrank_Comp,3);\n% Output.Lowrank_std = std(Lowrank_Comp,0,3);\n% Output.Sparse_mean = mean(Sparse_Comp,3);\n% Output.Sparse_std = std(Sparse_Comp,0,3);\nOutput.Lowrank_mean = Lowrank_Comp/MCMCpara.nCollect;\nOutput.Sparse_mean = Sparse_Comp/MCMCpara.nCollect;\nOutput.Gamma_epsi_mean = mean(Gamma_epsi);\nOutput.Gamma_epsi_std = std(Gamma_epsi);\nOutput.rankL_mean = mean(tmpRank);\nOutput.rankL_std = std(tmpRank);\n% Output.NumSparse_mean = mean(tmpNumSparse);\n% Output.NumSparse_std = std(tmpNumSparse);\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/BRPCA-MD/Bayesian_RPCAmcmc_MarkovDep.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.4981807560875451}} {"text": "function [r0,u0,p0] = Euler_IC1d(x,input)\n% Load the IC of a classical 2D Riemann Problem configuration. \n% By Manuel Diaz 2012.10.24.\n% In the notation we take advantage of the matlab array notation as follows\n%\n% prop = [prop_left , prop_right]\n% \n% Notation:\n% u = Velocity in x direction\n% p = Pressure\n% rho = Density\n% r = Fugacity\n% E = Enerty\n% t = temperature\n%\n% Based on:\n% http://wonka.physics.ncsu.edu/pub/VH-1/testpage/ and\n% http://sitemaker.umich.edu/anand/files/riemann_shock-tube.pdf\n% See also my routine CFD/Riemann.m to compute exact solutions.\n%\n%% Initial Physical Properties per case:\nswitch input\n case{1} % Configuration 1, Sod's Problem\n fprintf('Case 1: Sods problem \\n');\n p = [1 0.1 ];\n u = [0.75 0 ];\n rho = [1 0.125];\n \n case{2} % Configuration 2, Left Expansion and right strong shock\n fprintf('Case 2: Left Expansion and right strong shock \\n');\n p = [1000 0.1 ];\n u = [0 0 ];\n rho = [3 2 ];\n \n case{3} % Configuration 3, Right Expansion and left strong shock\n fprintf('Case 3: Right Expansion and left strong shock \\n');\n p = [7 10 ];\n u = [0 0 ];\n rho = [1 1 ];\n \n case{4} % Configuration 4, Double Shock\n fprintf('Case 4: Double Shock \\n');\n p = [450 45 ];\n u = [20 -6 ];\n rho = [6 6 ];\n \n case{5} % Configuration 5, Double Expansion\n fprintf('Case 5: Double Expansion \\n');\n p = [40 40 ];\n u = [-2 2 ];\n rho = [1 2.5 ];\n\n case{6} % Configuration 6, Cavitation\n fprintf('Case 6: Cavitation \\n');\n p = [0.4 0.4 ];\n u = [-20 20 ];\n rho = [1 1 ];\n \n otherwise \n error('Available cases: 1, 2, 3, 4, 5 and 6');\n \nend\n% Print\nfprintf('\\n');\nfprintf('density (L): %1.3f\\n',rho(1));\nfprintf('velocity(L): %1.3f\\n',u(1));\nfprintf('Presure (L): %1.3f\\n',p(1));\nfprintf('\\n');\nfprintf('density (R): %1.3f\\n',rho(2));\nfprintf('velocity(R): %1.3f\\n',u(2));\nfprintf('Presure (R): %1.3f\\n',p(2));\nfprintf('\\n');\n\n%% Load Selected case Initial condition:\n% number of points required\n nx = length(x);\n \n% Parameters of regions dimensions\nx_middle = ceil(nx/2);\nl_1 = 1:x_middle; l_2 = x_middle+1:nx;\n\n% Pre-Allocate variables\nr0 = zeros(1,nx); \nu0 = zeros(1,nx); \np0 = zeros(1,nx);\n\n% Initial Condition for our 2D domain\n% Fugacity\nr0(l_1) = rho(1); % region 1\nr0(l_2) = rho(2); % region 2\n% Velovity in x\nu0(l_1) = u(1); % region 1\nu0(l_2) = u(2); % region 2\n% temperature\np0(l_1) = p(1); % region 1\np0(l_2) = p(2); % region 2", "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/Euler_IC1d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.6757646140788308, "lm_q1q2_score": 0.49814540128383217}} {"text": "function product_rule ( list_filename, quad_filename )\n\n%*****************************************************************************80\n%\n%% MAIN is the main program for PRODUCT_RULE.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 13 May 2007\n%\n% Author:\n%\n% John Burkardt\n%\n timestamp ( );\n fprintf ( 1, '\\n');\n fprintf ( 1, 'PRODUCT_RULE\\n');\n fprintf ( 1, ' MATLAB version\\n');\n fprintf ( 1, '\\n');\n fprintf ( 1, ' Create a multidimensional product rule\\n');\n fprintf ( 1, ' as a product of distinct 1D integration rules.\\n');\n%\n% Get the list filename.\n%\n if ( nargin < 1 )\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PRODUCT_RULE:\\n' );\n list_filename = input ( ' Enter the name of the file listing the factors.' );\n\n end\n%\n% Get the product file prefix.\n%\n if ( nargin < 2 )\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PRODUCT_RULE:\\n' );\n quad_filename = input ( ' Enter the product file prefix to use.' );\n\n end\n%\n% Count the items in the list file.\n%\n list_num = file_row_count ( list_filename );\n%\n% Determine the spatial dimension and number of points in the product.\n%\n dim_num = list_num;\n point_num = product_rule_size ( list_filename, list_num );\n%\n% Allocate the product items.\n%\n x(1:dim_num,1:point_num) = 0.0;\n w(1:point_num) = 1.0;\n r(1:dim_num,1:2) = 0.0;\n\n list_unit = fopen ( list_filename, 'rt' );\n\n if ( list_unit < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PRODUCT_RULE - Fatal error!\\n' );\n fprintf ( 1, ' Nonzero value of IOS while opening list file.\\n' );\n error ( 'PRODUCT_RULE - Fatal error!' );\n end\n%\n% Read the factor information and apply it.\n%\n for dim = 1 : dim_num\n\n quad_1d_filename = fgetl ( list_unit );\n\n quad_x_1d_filename = strcat ( quad_1d_filename, '_x.txt' );\n quad_w_1d_filename = strcat ( quad_1d_filename, '_w.txt' );\n quad_r_1d_filename = strcat ( quad_1d_filename, '_r.txt' );\n%\n% Read the X file.\n%\n [ dim_num_1d, point_num_1d ] = r8mat_header_read ( quad_x_1d_filename );\n\n if ( dim_num_1d ~= 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PRODUCT_RULE - Fatal error!\\n' );\n fprintf ( 1, ' The 1D quadrature abscissa file should have exactly\\n' );\n fprintf ( 1, ' one value on each line.\\n' );\n error ( 'PRODUCT_RULE - Fatal error!' );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of points in 1D rule = %d\\n', point_num_1d );\n\n x_1d = r8mat_data_read ( quad_x_1d_filename, dim_num_1d, point_num_1d );\n%\n% Read the W file.\n%\n [ dim_num_1d, point_num_1d2 ] = r8mat_header_read ( quad_w_1d_filename );\n\n if ( dim_num_1d ~= 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PRODUCT_RULE - Fatal error!\\n' );\n fprintf ( 1, ' The 1D quadrature weight file should have exactly\\n' );\n fprintf ( 1, ' one value on each line.\\n' );\n error ( 'PRODUCT_RULE - Fatal error!' );\n end\n\n if ( point_num_1d2 ~= point_num_1d )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PRODUCT_RULE - Fatal error!\\n' );\n fprintf ( 1, ' The 1D quadrature weight file should have exactly\\n' );\n fprintf ( 1, ' the same number of lines as the abscissa file.\\n' );\n error ( 'PRODUCT_RULE - Fatal error!' );\n end\n\n w_1d = r8mat_data_read ( quad_w_1d_filename, dim_num_1d, point_num_1d );\n%\n% Read the R file.\n%\n [ dim_num_1d, point_num_1d2 ] = r8mat_header_read ( quad_r_1d_filename );\n\n if ( dim_num_1d ~= 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PRODUCT_RULE - Fatal error!\\n' );\n fprintf ( 1, ' The 1D quadrature region file should have exactly\\n' );\n fprintf ( 1, ' one value on each line.\\n' );\n error ( 'PRODUCT_RULE - Fatal error!' );\n end\n\n if ( point_num_1d2 ~= 2 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PRODUCT_RULE - Fatal error!\\n' );\n fprintf ( 1, ' The 1D quadrature region file should have exactly\\n' );\n fprintf ( 1, ' two lines.\\n' );\n error ( 'PRODUCT_RULE - Fatal error!' );\n end\n\n r_1d = r8mat_data_read ( quad_r_1d_filename, 1, 2 );\n%\n% Update the X, W, and R of the product rule.\n%\n x = r8vec_direct_product ( dim, point_num_1d, x_1d, dim_num, point_num, x );\n\n w = r8vec_direct_product2 ( dim, point_num_1d, w_1d, dim_num, point_num, w );\n\n r(dim,1) = r_1d(1);\n r(dim,2) = r_1d(2);\n\n end\n\n fclose ( list_unit );\n%\n% Write the product rule.\n%\n quad_x_filename = strcat ( quad_filename, '_x.txt' );\n quad_w_filename = strcat ( quad_filename, '_w.txt' );\n quad_r_filename = strcat ( quad_filename, '_r.txt' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Creating product quadrature rule X file = \"%s\".\\n', ...\n quad_x_filename );\n\n r8mat_write ( quad_x_filename, dim_num, point_num, x );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Creating product quadrature rule W file = \"%s\".\\n', ...\n quad_w_filename );\n\n r8mat_write ( quad_w_filename, 1, point_num, w );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Creating product quadrature rule R file = \"%s\".\\n', ...\n quad_r_filename );\n\n r8mat_write ( quad_r_filename, dim_num, 2, r );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PRODUCT_RULE:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction column_num = file_column_count ( input_file_name )\n\n%*****************************************************************************80\n%\n%% FILE_COLUMN_COUNT counts the columns in the first line of a file.\n%\n% Discussion:\n%\n% The file is assumed to be a simple text file.\n%\n% Most lines of the file are presumed to consist of COLUMN_NUM words,\n% separated by spaces. There may also be some blank lines, and some \n% comment lines, which have a \"#\" in column 1.\n%\n% The routine tries to find the first non-comment non-blank line and\n% counts the number of words in that line.\n%\n% If all lines are blanks or comments, it goes back and tries to analyze\n% a comment line.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILE_NAME, the name of the file.\n%\n% Output, integer COLUMN_NUM, the number of columns in the file.\n%\n FALSE = 0;\n TRUE = 1;\n%\n% Open the file.\n%\n input_unit = fopen ( input_file_name );\n\n if ( input_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FILE_COLUMN_COUNT - Error!\\n' );\n fprintf ( 1, ' Could not open the file \"%s\".\\n', input_file_name );\n error ( 'FILE_COLUMN_COUNT - Error!' );\n end\n%\n% Read one line, but skip blank lines and comment lines.\n% Use FGETL so we drop the newline character!\n%\n got_one = FALSE;\n\n while ( 1 )\n\n line = fgetl ( input_unit );\n\n if ( line == -1 )\n break;\n end\n\n if ( s_len_trim ( line ) == 0 )\n\n elseif ( line(1) == '#' )\n\n else\n got_one = TRUE;\n break;\n end\n\n end\n\n fclose ( input_unit );\n\n if ( got_one == FALSE ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FILE_COLUMN_COUNT - Warning!\\n' );\n fprintf ( 1, ' The file does not seem to contain any data.\\n' );\n column_num = -1;\n return;\n end\n\n column_num = s_word_count ( line );\n\n return\nend\nfunction row_num = file_row_count ( input_file_name )\n\n%*****************************************************************************80\n%\n%% FILE_ROW_COUNT counts the number of row records in a file.\n%\n% Discussion:\n%\n% Each input line is a \"RECORD\".\n%\n% The records are divided into three groups:\n% \n% * BLANK LINES (nothing but blanks)\n% * COMMENT LINES (begin with a '#')\n% * DATA RECORDS (anything else)\n%\n% The value returned by the function is the number of data records.\n%\n% By the way, if the MATLAB routine FGETS is used, instead of\n% FGETL, then the variable LINE will include line termination \n% characters, which means that a blank line would not actually\n% have zero characters.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 31 December 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILE_NAME, the name of the input file.\n%\n% Output, integer ROW_NUM, the number of rows found. \n%\n input_unit = fopen ( input_file_name );\n\n if ( input_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FILE_ROW_COUNT - Error!\\n' );\n fprintf ( 1, ' Could not open the file \"%s\".\\n', input_file_name );\n error ( 'FILE_ROW_COUNT - Error!' );\n end\n\n blank_num = 0;\n comment_num = 0;\n row_num = 0;\n \n record_num = 0;\n\n while ( 1 )\n\n line = fgetl ( input_unit );\n\n if ( line == -1 )\n break;\n end\n\n record_num = record_num + 1;\n record_length = s_len_trim ( line );\n \n if ( record_length <= 0 )\n blank_num = blank_num + 1;\n elseif ( line(1) == '#' )\n comment_num = comment_num + 1;\n else\n row_num = row_num + 1;\n end\n\n end\n\n fclose ( input_unit );\n\n return\nend\nfunction point_num = product_rule_size ( list_filename, list_num )\n\n%*****************************************************************************80\n%\n%% PRODUCT_RULE_SIZE returns the size of a product rule of distinct factors.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 10 May 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string LIST_FILENAME, a file containing a list\n% of prefixes defining quadrature rules.\n%\n% Input, integer LIST_NUM, the number of prefixes in the file.\n%\n% Output, integer POINT_NUM, the number of points in the product rule.\n%\n point_num = 1;\n\n list_unit = fopen ( list_filename, 'rt' );\n\n if ( list_unit < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PRODUCT_RULE_SIZE - Fatal error!\\n' );\n fprintf ( 1, ' Nonzero value of IOS while opening list file.\\n' );\n error ( 'PRODUCT_RULE_SIZE - Fatal error!' );\n end\n\n for list = 1 : list_num\n\n quad_1d_filename = fgetl ( list_unit );\n\n quad_x_1d_filename = strcat ( quad_1d_filename, '_x.txt' );\n\n [ dim_num_1d, point_num_1d ] = r8mat_header_read ( quad_x_1d_filename );\n\n point_num = point_num * point_num_1d;\n\n end\n\n fclose ( list_unit );\n\n return\nend\nfunction table = r8mat_data_read ( input_filename, m, n )\n\n%*****************************************************************************80\n%\n%% R8MAT_DATA_READ reads data from an R8MAT file.\n%\n% Discussion:\n%\n% An R8MAT is an array of R8's.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 January 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILENAME, the name of the input file.\n%\n% Input, integer M, N, the number of rows and columns of data.\n%\n% Output, real TABLE(M,N), the point coordinates.\n%\n table = zeros ( m, n );\n%\n% Build up the format string for reading M real numbers.\n%\n string = ' ';\n\n for i = 0 : m\n string = strcat ( string, ' %f' );\n end\n\n input_unit = fopen ( input_filename );\n\n if ( input_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_DATA_READ - Error!\\n' );\n fprintf ( 1, ' Could not open the file.\\n' );\n error ( 'R8MAT_DATA_READ - Error!' );\n end\n\n i = 0;\n\n while ( i < n )\n\n line = fgets ( input_unit );\n\n if ( line == -1 )\n break;\n end\n\n if ( line(1) == '#' )\n\n elseif ( s_len_trim ( line ) == 0 )\n \n else\n\n [ x, count ] = sscanf ( line, string );\n\n if ( count == m )\n i = i + 1;\n table(1:m,i) = x(1:m);\n end\n\n end\n\n end\n\n fclose ( input_unit );\n\n return\nend\nfunction [ m, n ] = r8mat_header_read ( input_filename )\n\n%*****************************************************************************80\n%\n%% R8MAT_HEADER_READ reads the header from an R8MAT file.\n%\n% Discussion:\n%\n% An R8MAT is an array of R8's.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 October 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILENAME, the name of the input file.\n%\n% Output, integer M, the spatial dimension.\n%\n% Output, integer N, the number of points.\n%\n m = file_column_count ( input_filename );\n\n if ( m <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_HEADER_READ - Fatal error!\\n' );\n fprintf ( 1, ' There was some kind of I/O problem while trying\\n' );\n fprintf ( 1, ' to count the number of data columns in\\n' );\n fprintf ( 1, ' the file %s.\\n', input_filename );\n end\n\n n = file_row_count ( input_filename );\n\n if ( n <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_HEADER_READ - Fatal error!\\n' );\n fprintf ( 1, ' There was some kind of I/O problem while trying\\n' );\n fprintf ( 1, ' to count the number of data rows in\\n' );\n fprintf ( 1, ' the file %s\\n', input_filename );\n end\n\n return\nend\nfunction r8mat_write ( output_filename, m, n, table )\n\n%*****************************************************************************80\n%\n%% R8MAT_WRITE writes an R8MAT file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 August 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string OUTPUT_FILENAME, the output filename.\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer N, the number of points.\n%\n% Input, real TABLE(M,N), the points.\n%\n\n%\n% Open the file.\n%\n output_unit = fopen ( output_filename, 'wt' );\n\n if ( output_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_WRITE - Error!\\n' );\n fprintf ( 1, ' Could not open the output file.\\n' );\n error ( 'R8MAT_WRITE - Error!' );\n end\n%\n% Write the data.\n%\n% For smaller data files, and less precision, try:\n%\n% fprintf ( output_unit, ' %14.6f', table(i,j) );\n%\n for j = 1 : n\n for i = 1 : m\n fprintf ( output_unit, ' %24.16f', table(i,j) );\n end\n fprintf ( output_unit, '\\n' );\n end\n%\n% Close the file.\n%\n fclose ( output_unit );\n\n return\nend\nfunction x = r8vec_direct_product ( factor_index, factor_order, ...\n factor_value, factor_num, point_num, x )\n\n%*****************************************************************************80\n%\n%% R8VEC_DIRECT_PRODUCT creates a direct product of R8VEC's.\n%\n% Discussion:\n%\n% To explain what is going on here, suppose we had to construct\n% a multidimensional quadrature rule as the product of K rules\n% for 1D quadrature.\n%\n% The product rule will be represented as a list of points and weights.\n%\n% The J-th item in the product rule will be associated with\n% item J1 of 1D rule 1,\n% item J2 of 1D rule 2, \n% ..., \n% item JK of 1D rule K.\n%\n% In particular, \n% X(J) = ( X(1,J1), X(2,J2), ..., X(K,JK))\n% and\n% W(J) = W(1,J1) * W(2,J2) * ... * W(K,JK)\n%\n% So we can construct the quadrature rule if we can properly\n% distribute the information in the 1D quadrature rules.\n%\n% This routine carries out that task.\n%\n% Another way to do this would be to compute, one by one, the\n% set of all possible indices (J1,J2,...,JK), and then index\n% the appropriate information. An advantage of the method shown\n% here is that you can process the K-th set of information and\n% then discard it.\n%\n% Example:\n%\n% Rule 1: \n% Order = 4\n% X(1:4) = ( 1, 2, 3, 4 )\n%\n% Rule 2:\n% Order = 3\n% X(1:3) = ( 10, 20, 30 )\n%\n% Rule 3:\n% Order = 2\n% X(1:2) = ( 100, 200 )\n%\n% Product Rule:\n% Order = 24\n% X(1:24) = \n% ( 1, 10, 100 )\n% ( 2, 10, 100 )\n% ( 3, 10, 100 )\n% ( 4, 10, 100 )\n% ( 1, 20, 100 )\n% ( 2, 20, 100 )\n% ( 3, 20, 100 )\n% ( 4, 20, 100 )\n% ( 1, 30, 100 )\n% ( 2, 30, 100 )\n% ( 3, 30, 100 )\n% ( 4, 30, 100 )\n% ( 1, 10, 200 )\n% ( 2, 10, 200 )\n% ( 3, 10, 200 )\n% ( 4, 10, 200 )\n% ( 1, 20, 200 )\n% ( 2, 20, 200 )\n% ( 3, 20, 200 )\n% ( 4, 20, 200 )\n% ( 1, 30, 200 )\n% ( 2, 30, 200 )\n% ( 3, 30, 200 )\n% ( 4, 30, 200 )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer FACTOR_INDEX, the index of the factor being processed.\n% The first factor processed must be factor 1%\n%\n% Input, integer FACTOR_ORDER, the order of the factor.\n%\n% Input, real FACTOR_VALUE(FACTOR_ORDER), the factor values\n% for factor FACTOR_INDEX.\n%\n% Input, integer FACTOR_NUM, the number of factors.\n%\n% Input, integer POINT_NUM, the number of elements in the direct product.\n%\n% Input, real X(FACTOR_NUM,POINT_NUM), the elements of the\n% direct product, which are built up gradually. \n%\n% Output, real X(FACTOR_NUM,POINT_NUM), the elements of the\n% direct product, updated by the latest factor.\n%\n% Local Parameters:\n%\n% Local, integer START, the first location of a block of values to set.\n%\n% Local, integer CONTIG, the number of consecutive values to set.\n%\n% Local, integer SKIP, the distance from the current value of START\n% to the next location of a block of values to set.\n%\n% Local, integer REP, the number of blocks of values to set.\n%\n persistent contig;\n persistent rep;\n persistent skip;\n\n if ( factor_index == 1 )\n contig = 1;\n skip = 1;\n rep = point_num;\n x(1:factor_num,1:point_num) = 0.0;\n end\n\n rep = rep / factor_order;\n skip = skip * factor_order;\n\n for j = 1 : factor_order\n\n start = 1 + ( j - 1 ) * contig;\n\n for k = 1 : rep\n x(factor_index,start:start+contig-1) = factor_value(j);\n start = start + skip;\n end\n\n end\n\n contig = contig * factor_order;\n\n return\nend\nfunction w = r8vec_direct_product2 ( factor_index, factor_order, ...\n factor_value, factor_num, point_num, w )\n\n%*****************************************************************************80\n%\n%% R8VEC_DIRECT_PRODUCT2 creates a direct product of R8VEC's.\n%\n% Discussion:\n%\n% To explain what is going on here, suppose we had to construct\n% a multidimensional quadrature rule as the product of K rules\n% for 1D quadrature.\n%\n% The product rule will be represented as a list of points and weights.\n%\n% The J-th item in the product rule will be associated with\n% item J1 of 1D rule 1,\n% item J2 of 1D rule 2, \n% ..., \n% item JK of 1D rule K.\n%\n% In particular, \n% X(J) = ( X(1,J1), X(2,J2), ..., X(K,JK))\n% and\n% W(J) = W(1,J1) * W(2,J2) * ... * W(K,JK)\n%\n% So we can construct the quadrature rule if we can properly\n% distribute the information in the 1D quadrature rules.\n%\n% This routine carries out that task for the weights W.\n%\n% Another way to do this would be to compute, one by one, the\n% set of all possible indices (J1,J2,...,JK), and then index\n% the appropriate information. An advantage of the method shown\n% here is that you can process the K-th set of information and\n% then discard it.\n%\n% Example:\n%\n% Rule 1: \n% Order = 4\n% W(1:4) = ( 2, 3, 5, 7 )\n%\n% Rule 2:\n% Order = 3\n% W(1:3) = ( 11, 13, 17 )\n%\n% Rule 3:\n% Order = 2\n% W(1:2) = ( 19, 23 )\n%\n% Product Rule:\n% Order = 24\n% W(1:24) =\n% ( 2 * 11 * 19 )\n% ( 3 * 11 * 19 )\n% ( 4 * 11 * 19 )\n% ( 7 * 11 * 19 )\n% ( 2 * 13 * 19 )\n% ( 3 * 13 * 19 )\n% ( 5 * 13 * 19 )\n% ( 7 * 13 * 19 )\n% ( 2 * 17 * 19 )\n% ( 3 * 17 * 19 )\n% ( 5 * 17 * 19 )\n% ( 7 * 17 * 19 )\n% ( 2 * 11 * 23 )\n% ( 3 * 11 * 23 )\n% ( 5 * 11 * 23 )\n% ( 7 * 11 * 23 )\n% ( 2 * 13 * 23 )\n% ( 3 * 13 * 23 )\n% ( 5 * 13 * 23 )\n% ( 7 * 13 * 23 )\n% ( 2 * 17 * 23 )\n% ( 3 * 17 * 23 )\n% ( 5 * 17 * 23 )\n% ( 7 * 17 * 23 )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer FACTOR_INDEX, the index of the factor being processed.\n% The first factor processed must be factor 1.\n%\n% Input, integer FACTOR_ORDER, the order of the factor.\n%\n% Input, real FACTOR_VALUE(FACTOR_ORDER), the factor values for\n% factor FACTOR_INDEX.\n%\n% Input, integer FACTOR_NUM, the number of factors.\n%\n% Input, integer POINT_NUM, the number of elements in the direct product.\n%\n% Output, real W(POINT_NUM), the elements of the\n% direct product, updated by the latest factor.\n%\n% Local Parameters:\n%\n% Local, integer START, the first location of a block of values to set.\n%\n% Local, integer CONTIG, the number of consecutive values to set.\n%\n% Local, integer SKIP, the distance from the current value of START\n% to the next location of a block of values to set.\n%\n% Local, integer REP, the number of blocks of values to set.\n%\n persistent contig;\n persistent rep;\n persistent skip;\n\n if ( factor_index == 1 )\n contig = 1;\n skip = 1;\n rep = point_num;\n w(1:point_num) = 1.0;\n end\n\n rep = rep / factor_order;\n skip = skip * factor_order;\n\n for j = 1 : factor_order\n\n start = 1 + ( j - 1 ) * contig;\n\n for k = 1 : rep\n w(start:start+contig-1) = w(start:start+contig-1) * factor_value(j);\n start = start + skip;\n end\n\n end\n\n contig = contig * factor_order;\n\n return\nend\nfunction len = s_len_trim ( s )\n\n%*****************************************************************************80\n%\n%% S_LEN_TRIM returns the length of a character string to the last nonblank.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 June 2003\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string S, the string to be measured.\n%\n% Output, integer LEN, the length of the string up to the last nonblank.\n%\n len = length ( s );\n\n while ( 0 < len )\n if ( s(len) ~= ' ' )\n return\n end\n len = len - 1;\n end\n\n return\nend\nfunction word_num = s_word_count ( s )\n\n%*****************************************************************************80\n%\n%% S_WORD_COUNT counts the number of \"words\" in a string.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 January 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string S, the string to be examined.\n%\n% Output, integer WORD_NUM, the number of \"words\" in the string.\n% Words are presumed to be separated by one or more blanks.\n%\n FALSE = 0;\n TRUE = 1;\n\n word_num = 0;\n s_length = length ( s );\n\n if ( s_length <= 0 )\n return;\n end\n\n blank = TRUE;\n\n for i = 1 : s_length\n\n if ( s(i) == ' ' )\n blank = TRUE;\n elseif ( blank == TRUE )\n word_num = word_num + 1;\n blank = FALSE;\n end\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\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/product_rule/product_rule.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.4981453916567064}} {"text": "function r = r(kernel)\n\n% R\n%\n% This method returns an upper bound on\n%\n% R > k(x1, x1) - k(x1, x2)\n%\n% for arbitrary x1 and x2. For a Gaussian radial basis kernel R = 1.\n\n%\n% File : @rbf/r.m\n%\n% Date : Friday 7th July 2000\n%\n% Author : Dr Gavin C. Cawley\n%\n% Description : Part of an object-oriented implementation of Vapnik's Support\n% Vector Machine, as described in [1].\n%\n% References : [1] V.N. Vapnik,\n% \"The Nature of Statistical Learning Theory\",\n% Springer-Verlag, New York, ISBN 0-387-94559-8,\n% 1995.\n%\n% History : 07/07/2000 - v1.00\n% 12/09/2000 - v1.01 minor improvements to comments and help\n% messages \n%\n% Copyright : (c) Dr Gavin C. Cawley, July 2000\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n% \n\nr = 1.0;\n\n% bye bye...\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/RSVista/mrMethods/svm/cawleyTools/@rbf/r.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.49814539165670635}} {"text": "%% Theory of Misorientations\n%\n%%\n% Misorientation describe the relative orientation of two crystal with\n% respect to each other. Those crystal may be of the same phase or of\n% different phases. Misorientation are used to describe \n\n\n\n\n%% Grain Exchange Symmetry\n\n\n\n\n%%\n% Misorientation describes the relative orientation of two grains with\n% respect to each other. Important concepts are twinnings and\n% CSL (coincidence site lattice) misorientations. To illustrate this\n% concept at a practical example let us first import some Magnesium EBSD\n% data.\n\nmtexdata twins silent\n\n% use only proper symmetry operations\nebsd('M').CS = ebsd('M').CS.properGroup;\n\n% compute grains\ngrains = calcGrains(ebsd('indexed'),'threshold',5*degree);\nCS = grains.CS; % extract crystal symmetry\n\n%%\n% Next we plot the grains together with their mean orientation and\n% highlight grain 74 and grain 85\n\nplot(grains,grains.meanOrientation,'micronbar','off')\n\nhold on\nplot(grains([74,85]).boundary,'edgecolor','w','linewidth',2)\nhold off\n\ntext(grains([74,85]),{'1','2'})\n\n%%\n% After extracting the mean orientation of grain 74 and 85\n\nori1 = grains(74).meanOrientation;\nori2 = grains(85).meanOrientation;\n\n%%\n% we may compute the misorientation angle between both orientations by\n\nangle(ori1, ori2) ./ degree\n\n%%\n% Note that the misorientation angle is computed by default modulo crystal\n% symmetry, i.e., the angle is always the smallest angles between all\n% possible pairs of symmetrically equivalent orientations. In our example\n% this means that symmetrisation of one orientation has no impact on the\n% angle\n\nangle(ori1, ori2.symmetrise) ./ degree\n\n%%\n% The misorientation angle neglecting crystal symmetry can be computed by\n\nangle(ori1, ori2.symmetrise,'noSymmetry')./ degree\n\n%%\n% We see that the smallest angle indeed coincides with the angle computed\n% before.\n\n%% Misorientations\n% Remember that both orientations ori1 and ori2 map crystal coordinates\n% onto specimen coordinates. Hence, the product of an inverse orientation\n% with another orientation transfers crystal coordinates from one crystal\n% reference frame into crystal coordinates with respect to another crystal\n% reference frame. This transformation is called misorientation\n\nmori = inv(ori1) * ori2\n\n%%\n% In the present case the misorientation describes the coordinate transform\n% from the reference frame of grain 85 into the reference frame of crystal\n% 74. Take as an example the plane {11-20} with respect to the grain 85.\n% Then the plane in grain 74 which alignes parallel to this plane can be\n% computed by\n\nround(mori * Miller(1,1,-2,0,CS))\n\n\n%%\n% Conversely, the inverse of mori is the coordinate transform from crystal\n% 74 to grain 85.\n\nround(inv(mori) * Miller(2,-1,-1,0,CS))\n\n\n%% Coincident lattice planes\n% The coincidence between major lattice planes may suggest that the\n% misorientation is a twinning misorientation. Lets analyse whether there\n% are some more alignments between major lattice planes.\n\n%m = Miller({1,-1,0,0},{1,1,-2,0},{1,-1,0,1},{0,0,0,1},CS);\nm = Miller({1,-1,0,0},{1,1,-2,0},{-1,0,1,1},{0,0,0,1},CS);\n\n% cycle through all major lattice planes\nclose all\nfor im = 1:length(m)\n % plot the lattice planes of grains 85 with respect to the\n % reference frame of grain 74\n plot(mori * m(im).symmetrise,'MarkerSize',10,...\n 'DisplayName',char(m(im)),'figSize','large','noLabel','upper')\n hold all\nend\nhold off\n\n% mark the corresponding lattice planes in the twin\nmm = round(unique(mori*m.symmetrise,'noSymmetry'),'maxHKL',6);\nannotate(mm,'labeled','MarkerSize',5,'figSize','large','textAboveMarker')\n\n% show legend\nlegend({},'location','SouthEast','FontSize',13);\n\n%%\n% we observe an almost perfect match for the lattice planes {11-20} to\n% {-2110} and {1-101} to {-1101} and good coincidences for the lattice\n% plane {1-100} to {0001} and {0001} to {0-661}. Lets compute the angles\n% explicitly\n\nangle(mori * Miller(1,1,-2,0,CS),Miller(2,-1,-1,0,CS)) / degree\nangle(mori * Miller(1,0,-1,-1,CS),Miller(1,-1,0,1,CS)) / degree\nangle(mori * Miller(0,0,0,1,CS) ,Miller(1,0,-1,0,CS),'noSymmetry') / degree\nangle(mori * Miller(1,1,-2,2,CS),Miller(1,0,-1,0,CS)) / degree\nangle(mori * Miller(1,0,-1,0,CS),Miller(1,1,-2,2,CS)) / degree\n\n%% Twinning misorientations\n% Lets define a misorientation that makes a perfect fit between the {11-20}\n% lattice planes and between the {10-11} lattice planes\n\nmori = orientation.map(Miller(1,1,-2,0,CS),Miller(2,-1,-1,0,CS),...\n Miller(-1,0,1,1,CS),Miller(-1,1,0,1,CS))\n\n\n% the rotational axis\nround(mori.axis)\n\n% the rotational angle\nmori.angle / degree\n\n%%\n% and plot the same figure as before with the exact twinning\n% misorientation.\n\n% cycle through all major lattice planes\nclose all\nfor im = 1:length(m)\n % plot the lattice planes of grains 85 with respect to the\n % reference frame of grain 74\n plot(mori * m(im).symmetrise,'MarkerSize',10,...\n 'DisplayName',char(m(im)),'figSize','large','noLabel','upper')\n hold all\nend\nhold off\n\n% mark the corresponding lattice planes in the twin\nmm = round(unique(mori*m.symmetrise,'noSymmetry'),'maxHKL',6);\nannotate(mm,'labeled','MarkerSize',5,'figSize','large')\n\n% show legend\nlegend({},'location','NorthWest','FontSize',13);\n\n\n%% Highlight twinning boundaries\n% It turns out that in the previous EBSD map many grain boundaries have a\n% misorientation close to the twinning misorientation we just defined. Lets\n% Lets highlight those twinning boundaries\n\n% consider only Magnesium to Magnesium grain boundaries\ngB = grains.boundary('Mag','Mag');\n\n% check for small deviation from the twinning misorientation\nisTwinning = angle(gB.misorientation,mori) < 5*degree;\n\n% plot the grains and highlight the twinning boundaries\nplot(grains,grains.meanOrientation,'micronbar','off')\nhold on\nplot(gB(isTwinning),'edgecolor','w','linewidth',2)\nhold off\n\n%%\n% From this picture we see that large fraction of grain boudaries are\n% twinning boundaries. To make this observation more evident we may plot\n% the boundary misorientation angle distribution function. This is simply\n% the angle distribution of all boundary misorientations and can be\n% displayed with\n\nclose all\nplotAngleDistribution(gB.misorientation)\n\n%%\n% From this we observe that we have about 50 percent twinning boundaries.\n% Analogously we may also plot the axis distribution\n\nplotAxisDistribution(gB.misorientation,'contour')\n\n%%\n% which emphasises a strong portion of rotations about the (-12-10) axis.\n\n%% Phase transitions\n% Misorientations may not only be defined between crystal frames of the\n% same phase. Lets consider the phases Magnetite and Hematite.\n\nCS_Mag = loadCIF('Magnetite')\nCS_Hem = loadCIF('Hematite')\n\n%%\n% The phase transition from Magnetite to Hematite is described in\n% literature by {111}_m parallel {0001}_h and {-101}_m parallel {10-10}_h\n% The corresponding misorientation is defined in MTEX by\n\nMag2Hem = orientation.map(...\n Miller(1,1,1,CS_Mag),Miller(0,0,0,1,CS_Hem),...\n Miller(-1,0,1,CS_Mag),Miller(1,0,-1,0,CS_Hem))\n\n%%\n% Assume a Magnetite grain with orientation\n\nori_Mag = orientation.byEuler(0,0,0,CS_Mag)\n\n%%\n% Then we can compute all variants of the phase transition by\n\nsymmetrise(ori_Mag) * inv(Mag2Hem)\n\n%%\n% and the corresponding pole figures by\n\nplotPDF(symmetrise(ori_Mag) * inv(Mag2Hem),...\n Miller({1,0,-1,0},{1,1,-2,0},{0,0,0,1},CS_Hem))\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/MisorientationTheory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.49810725707187936}} {"text": "\n%\n% JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY\n%\n%\n%\n%\n\nclear;\nclc;\nclear all; \nclose all;\ndisplay(' ');\ndisplay(' ');\n\ndisplay(' ');\ndisplay(' SOME EXPERIMENTS ON IMAGE DENOISING USING WAVELETS ');\n\ndisplay(' ');\ndisplay(' ');\ndisplay(' RAJA RAO ');\n\ndisplay(' ');\ndisplay(' ');\n\ndisplay('select the image');\n\ndisplay(' 1:lena.png');\ndisplay(' 2:barbara.png');\ndisplay(' 3:boat.png');\ndisplay(' 4:house.png');\ndisplay(' 5:peppers256.png');\ndisplay(' 6:cameraman.jpg');\ndisplay(' ');\ndisplay(' 7:hyderabad.png');\ndisplay(' 8:friendgray.jpg');\ndisplay(' ');\n\n\nss1=input('enter your choice: ');\nswitch ss1\n case 1\n f=imread('lena.png');\n %f=imread('babu.jpg');\n case 2\n f=imread('barbara.png');\n case 3\n f=imread('boat.png');\n case 4\n f=imread('house.png');\n case 5\n f=imread('peppers256.png');\n case 6\n f=imread('cameraman.jpg');\n case 7\n f=imread('hyderabad512.png');\n case 8\n f=imread('friendgray.jpg'); \nend\n\nsubplot(2,2,1), imshow(f);title('original image');\n\ndisplay('enter the type of noise:');\ndisplay(' 1 for salt & pepper');\ndisplay(' 2 for gaussian'); \ndisplay(' 3 for poisson');\ndisplay(' 4 for speckle');\n\nud=input('enter the value:');\n\nswitch ud\n case 1\n display('enter the % of noise(Ex:0.2)');\n ud1=input('pls enter: ');\n g=imnoise(f,'salt & pepper',ud1);\n case 2\n \n \n%f=imread('peppers256.png');\n%subplot(2,2,1),imshow(f);\ndisplay('enter the noise varience: ');\nva=input('enter between 0.01 to 0.09: ');\ng=imnoise(f,'gaussian',0,va);\n case 3\n % display('enter the % of noise(Ex:0.2)');\n %ud1=input('pls enter: ');\n g=imnoise(f,'poisson');\n case 4\n display('enter the varience of noise(Ex:0.02)');\n ud1=input('pls enter: ');\n g=imnoise(f,'speckle',ud1);\n \n \nend\n%g=imnoise(f,'salt & pepper',01);\nsubplot(2,2,2),imshow(g);title('noisy image');\n\n\n%[ca,ch,cv,cd] = dwt2(g,'db2');\n%c=[ca ch;cv cd];\n%subplot(2,2,3),imshow(uint8(c));\n\nx=g;\n% Use wdencmp for image de-noising. \n% find default values (see ddencmp). \n[thr,sorh,keepapp] = ddencmp('den','wv',x);\ndisplay('');\ndisplay('select wavelet');\ndisplay('enter 1 for haar wavelet');\ndisplay('enter 2 for db2 wavelet');\ndisplay('enter 3 for db4 wavelet');\ndisplay('enter 4 for sym wavelet');\ndisplay('enter 5 for sym wavelet');\ndisplay('enter 6 for bior wavelet');\ndisplay('enter 7 for bior wavelet');\ndisplay('enter 8 for mexh wavelet');\ndisplay('enter 9 for coif wavelet');\ndisplay('enter 10 for meyr wavelet');\ndisplay('enter 11 for morl wavelet');\ndisplay('enter 12 for rbio wavelet');\ndisplay('press any key to quit');\ndisplay('');\n\nww=input('enter your choice: ');\nswitch ww\n case 1\n wv='haar';\n case 2\n wv='db2';\n case 3\n wv='db4' ; \n case 4\n wv='sym2'\n case 5\n wv='sym4';\n case 6\n wv='bior1.1';\n case 7\n wv='bior6.8'; \n case 8\n wv='mexh';\n case 9\n wv='coif5';\n case 10\n wv='dmey';\n case 11\n wv='mor1';\n case 12 \n wv='jpeg9.7';\n otherwise \n quit;\nend\ndisplay('');\ndisplay('enter 1 for soft thresholding');\ndisplay('enter 2 for hard thresholding');\ndisplay('enter 3 for bayes soft thresholding');\nsorh=input('sorh: ');\n\ndisplay('enter the level of decomposition');\nlevel=input(' enter 1 or 2 : ');\n\nswitch sorh\n case 1\n sorh='s';\n xd = wdencmp('gbl',x,wv,level,thr,sorh,keepapp);\n case 2\n sorh='h';\n xd = wdencmp('gbl',x,wv,level,thr,sorh,keepapp);\n case 3\n %%%%%%%%%%%%%%%%%%%%%\n % clear all;\n%close all;\n%clc;\n\n%Denoising using Bayes soft thresholding\n\n%Note: Figure window 1 displays the original image, fig 2 the noisy img\n%fig 3 denoised img by bayes soft thresholding\n\n\n%Reading the image \n%pic=imread('elaine','png');\npic=f;\n%figure, imagesc(pic);colormap(gray);\n\n%Define the Noise Variance and adding Gaussian noise\n%While using 'imnoise' the pixel values(0 to 255) are converted to double in the range 0 to 1\n%So variance also has to be suitably converted\nsig=15;\nV=(sig/256)^2;\nnpic=g;\n%npic=imnoise(pic,'gaussian',0,V);\n%figure, imagesc(npic);colormap(gray);\n\n%Define the type of wavelet(filterbank) used and the number of scales in the wavelet decomp\nfiltertype=wv;\nlevels=level;\n\n%Doing the wavelet decomposition\n[C,S]=wavedec2(npic,levels,filtertype);\n\nst=(S(1,1)^2)+1;\nbayesC=[C(1:st-1),zeros(1,length(st:1:length(C)))];\nvar=length(C)-S(size(S,1)-1,1)^2+1;\n\n%Calculating sigmahat\nsigmahat=median(abs(C(var:length(C))))/0.6745;\n\nfor jj=2:size(S,1)-1\n %for the H detail coefficients\n coefh=C(st:st+S(jj,1)^2-1);\n thr=bayes(coefh,sigmahat);\n bayesC(st:st+S(jj,1)^2-1)=sthresh(coefh,thr);\n st=st+S(jj,1)^2;\n \n % for the V detail coefficients\n coefv=C(st:st+S(jj,1)^2-1);\n thr=bayes(coefv,sigmahat);\n bayesC(st:st+S(jj,1)^2-1)=sthresh(coefv,thr);\n st=st+S(jj,1)^2;\n \n %for Diag detail coefficients \n coefd=C(st:st+S(jj,1)^2-1);\n thr=bayes(coefd,sigmahat);\n bayesC(st:st+S(jj,1)^2-1)=sthresh(coefd,thr);\n st=st+S(jj,1)^2;\nend\n\n\n%Reconstructing the image from the Bayes-thresholded wavelet coefficients\nbayespic=waverec2(bayesC,S,filtertype);\nxd=bayespic;\n%Displaying the Bayes-denoised image\n%figure, imagesc(uint8(bayespic));colormap(gray);\ndisplay('IEEE TRANSACTIONS ON IMAGE PROCESSING, VOL. 9, NO. 9, SEPTEMBER 2000');\n\ndisplay('IEEE TRANSACTIONS ON IMAGE PROCESSING, VOL. 9, NO. 9, SEPTEMBER 2000');\ndisplay('Adaptive Wavelet Thresholding for Image Denoising and Compression');\ndisplay('S. Grace Chang, Student Member, IEEE, Bin Yu, Senior Member, IEEE, and Martin Vetterli, Fellow, IEEE');\n\n\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%\n \n \nend\n\n\n\n%sorh=sorh;\n% de-noise image using global thresholding option. \n\n\n%f=imread('peppers256.png');\n[c,s]=wavefast(g,level,wv);\nsubplot(2,2,3),wave2gray(c,s,8);title('decomposed structure');\n\n\nsubplot(2,2,4),xd=uint8(xd);\nimshow(xd);title('denoised image');\n%subplot(2,2,4),sub=f-xd;\n%sub=abs(1.2*sub);\n%imshow(im2uint8(sub));title('difference image');\nff=im2double(f);xdd=im2double(xd);\ndisplay(' ');\ndisplay(' ');\ndisplay('reference: To calcullate signal to noise ratio');\ndisplay('Makoto Miyahara');\ndisplay('\"Objective Picture Quality Scale (PQS) for Image Coding\"');\ndisplay('IEEE Trans. on Comm., Vol 46, No.9, 1998.');\ndisplay(' ');\ndisplay(' ');\nsnr=wpsnr(ff,xdd)\n\ndisplay(' ');\ndisplay(' ');\nmse=compare11(ff,xdd)", "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/16386-image-denoising-using-bayes-thresholding-of-wavelet-coefficients/bayesthresholding/raomain.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.49796617169690394}} {"text": "function [ft3] = mi32ft3(mi3)\n% Convert volume from cubic miles to cubic feet. \n% Chad Greene 2012\nft3 = mi3*147197952000;", "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/mi32ft3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.49796616636374313}} {"text": "function c = tapas_hgf_binary_mab_config\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Contains the configuration for the Hierarchical Gaussian Filter (HGF) in a multi-armded bandit\n% situation for binary inputs in the absence of perceptual uncertainty.\n%\n% The HGF is the model introduced in \n%\n% Mathys C, Daunizeau J, Friston, KJ, and Stephan KE. (2011). A Bayesian foundation\n% for individual learning under uncertainty. Frontiers in Human Neuroscience, 5:39.\n%\n% The binary HGF model has since been augmented with a positive factor kappa1 which\n% scales the second level with respect to the first, i.e., the relation between the\n% first and second level is\n%\n% p(x1=1|x2) = s(kappa1*x2), where s(.) is the logistic sigmoid.\n%\n% By default, kappa1 is fixed to 1, leading exactly to the model introduced in\n% Mathys et al. (2011).\n%\n% This file refers to BINARY inputs (Eqs 1-3 in Mathys et al., (2011));\n% for continuous inputs, refer to tapas_hgf_config.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% The HGF configuration consists of the priors of parameters and initial values. All priors are\n% Gaussian in the space where the quantity they refer to is estimated. They are specified by their\n% sufficient statistics: mean and variance (NOT standard deviation).\n% \n% Quantities are estimated in their native space if they are unbounded (e.g., the omegas). They are\n% estimated in log-space if they have a natural lower bound at zero (e.g., the sigmas).\n% \n% Parameters can be fixed (i.e., set to a fixed value) by setting the variance of their prior to\n% zero. Aside from being useful for model comparison, the need for this arises whenever the scale\n% and origin at the j-th level are arbitrary. This is the case if the observation model does not\n% contain the representations mu_j and sigma_j. A choice of scale and origin is then implied by\n% fixing the initial value mu_j_0 of mu_j and either kappa_j-1 or omega_j-1.\n%\n% Fitted trajectories can be plotted by using the command\n%\n% >> tapas_hgf_binary_mab_plotTraj(est)\n% \n% where est is the stucture returned by tapas_fitModel. This structure contains the estimated\n% perceptual parameters in est.p_prc and the estimated trajectories of the agent's\n% representations (cf. Mathys et al., 2011). Their meanings are:\n% \n% est.p_prc.mu_0 row vector of initial values of mu (in ascending order of levels)\n% est.p_prc.sa_0 row vector of initial values of sigma (in ascending order of levels)\n% est.p_prc.rho row vector of rhos (representing drift; in ascending order of levels)\n% est.p_prc.ka row vector of kappas (in ascending order of levels)\n% est.p_prc.om row vector of omegas (in ascending order of levels)\n%\n% Note that the first entry in all of the row vectors will be NaN because, at the first level,\n% these parameters are either determined by the second level (mu_0 and sa_0) or undefined (rho,\n% kappa, and omega).\n%\n% est.traj.mu mu (rows: trials, columns: levels, 3rd dim: bandits)\n% est.traj.sa sigma (rows: trials, columns: levels, 3rd dim: bandits)\n% est.traj.muhat prediction of mu (rows: trials, columns: levels, 3rd dim: bandits)\n% est.traj.sahat precisions of predictions (rows: trials, columns: levels, 3rd dim: bandits)\n% est.traj.v inferred variance of random walk (rows: trials, columns: levels)\n% est.traj.w weighting factors (rows: trials, columns: levels)\n% est.traj.da volatility prediction errors (rows: trials, columns: levels)\n% est.traj.ud updates with respect to prediction (rows: trials, columns: levels)\n% est.traj.psi precision weights on prediction errors (rows: trials, columns: levels)\n% est.traj.epsi precision-weighted prediction errors (rows: trials, columns: levels)\n% est.traj.wt full weights on prediction errors (at the first level,\n% this is the learning rate) (rows: trials, columns: levels)\n%\n% Note that in the absence of sensory uncertainty (which is the assumption here), the first\n% column of mu, corresponding to the first level, will be equal to the inputs. Likewise, the\n% first column of sa will be 0 always.\n%\n% Tips:\n% - When analyzing a new dataset, take your inputs u and use\n%\n% >> est = tapas_fitModel([], u, 'tapas_hgf_binary_mab_config', 'tapas_bayes_optimal_binary_config');\n%\n% to determine the Bayes optimal perceptual parameters (given your current priors as defined in\n% this file here, so choose them wide and loose to let the inputs influence the result). You can\n% then use the optimal parameters as your new prior means for the perceptual parameters.\n%\n% - If you get an error saying that the prior means are in a region where model assumptions are\n% violated, lower the prior means of the omegas, starting with the highest level and proceeding\n% downwards.\n%\n% - Alternatives are lowering the prior means of the kappas, if they are not fixed, or adjusting\n% the values of the kappas or omegas, if any of them are fixed.\n%\n% - If the log-model evidence cannot be calculated because the Hessian poses problems, look at\n% est.optim.H and fix the parameters that lead to NaNs.\n%\n% - Your guide to all these adjustments is the log-model evidence (LME). Whenever the LME increases\n% by at least 3 across datasets, the adjustment was a good idea and can be justified by just this:\n% the LME increased, so you had a better model.\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2013-2017 Christoph Mathys, TNU, UZH & ETHZ\n%\n% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or .\n\n\n% Config structure\nc = struct;\n\n% Model name\nc.model = 'hgf_binary_mab';\n\n% Number of levels (minimum: 3)\nc.n_levels = 3;\n\n% Number of bandits\nc.n_bandits = 3;\n\n% Coupling\n% This may only be set to true if c.n_bandits is set to 2 above. If\n% true, it means that the two bandits' winning probabilities are\n% coupled in the sense that they add to 1 and are both updated on\n% each trial even though only the outcome for one of them is observed.\nc.coupled = false;\n\n% Input intervals\n% If input intervals are irregular, the last column of the input\n% matrix u has to contain the interval between inputs k-1 and k\n% in the k-th row, and this flag has to be set to true\nc.irregular_intervals = false;\n\n% Sufficient statistics of Gaussian parameter priors\n\n% Initial mus and sigmas\n% Format: row vectors of length n_levels\n% For all but the first two levels, this is usually best\n% kept fixed to 1 (determines origin on x_i-scale). The \n% first level is NaN because it is determined by the second,\n% and the second implies neutrality between outcomes when it\n% is centered at 0.\nc.mu_0mu = [NaN, 0, 1];\nc.mu_0sa = [NaN, 0, 0];\n\nc.logsa_0mu = [NaN, log(0.1), log(1)];\nc.logsa_0sa = [NaN, 0, 0];\n\n% Rhos\n% Format: row vector of length n_levels.\n% Undefined (therefore NaN) at the first level.\n% Fix this to zero to turn off drift.\nc.rhomu = [NaN, 0, 0];\nc.rhosa = [NaN, 0, 0];\n\n% Kappas\n% Format: row vector of length n_levels-1.\n% Fixing log(kappa1) to log(1) leads to the original HGF model.\n% Higher log(kappas) should be fixed (preferably to log(1)) if the\n% observation model does not use mu_i+1 (kappa then determines the\n% scaling of x_i+1).\nc.logkamu = [log(1), log(1)];\nc.logkasa = [ 0, 0];\n\n% Omegas\n% Format: row vector of length n_levels.\n% Undefined (therefore NaN) at the first level.\nc.ommu = [NaN, -2, -6];\nc.omsa = [NaN, 4^2, 4^2];\n\n% Gather prior settings in vectors\nc.priormus = [\n c.mu_0mu,...\n c.logsa_0mu,...\n c.rhomu,...\n c.logkamu,...\n c.ommu,...\n ];\n\nc.priorsas = [\n c.mu_0sa,...\n c.logsa_0sa,...\n c.rhosa,...\n c.logkasa,...\n c.omsa,...\n ];\n\n% Check whether we have the right number of priors\nexpectedLength = 3*c.n_levels+2*(c.n_levels-1)+1;\nif length([c.priormus, c.priorsas]) ~= 2*expectedLength;\n error('tapas:hgf:PriorDefNotMatchingLevels', 'Prior definition does not match number of levels.')\nend\n\n% Model function handle\nc.prc_fun = @tapas_hgf_binary_mab;\n\n% Handle to function that transforms perceptual parameters to their native space\n% from the space they are estimated in\nc.transp_prc_fun = @tapas_hgf_binary_mab_transp;\n\nreturn;\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/HGF/tapas_hgf_binary_mab_config.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4978559210814802}} {"text": "function sc = patchCorr(imId,pix,ptch,method)\n\n% PATCHCORR Correlation score of a patch in an image\n% PATCHCORR(IMID,PIX,PATCH,METHOD) computes the correlation score\n% between PATCH and the corresponding patch centered at pixel\n% PIX in the _global_ image Image{IMID}, using METHOD.\n%\n% PATCH is a structure containing:\n% I: Matrix with pixellic values of the patch\n% SI: Sum of all pixellic values\n% SII: Sum of all squared pixellic values\n%\n% METHOD is one of the following strings 'zncc', 'ssd', 'census'\n%\n% See also ZNCC, SSD, CENSUS\n\n% (c) 2005 Joan Sola\n\n% patch size\npSze = size(ptch.I);\n\n% pixel centered image patch\niPatch = pix2patch(imId,pix,pSze(2),pSze(1));\n\nif nargin<4\n method = 'zncc';\nend\n\nswitch lower(method)\n case 'zncc'\n sc = zncc(...\n ptch.I,iPatch.I,...\n ptch.SI,ptch.SII,...\n iPatch.SI,iPatch.SII);\n case 'ssd'\n sc = ssd(ptch,iPatch);\n case 'census'\n sc = census(ptch,iPatch);\n otherwise\n error('Unknown correlation method.')\nend\n\n\n\n% ========== End of function - Start GPL license ==========\n\n\n% # START GPL LICENSE\n\n%---------------------------------------------------------------------\n%\n% This file is part of SLAMTB, a SLAM toolbox for Matlab.\n%\n% SLAMTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% SLAMTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with SLAMTB. If not, see .\n%\n%---------------------------------------------------------------------\n\n% SLAMTB is Copyright:\n% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,\n% Copyright (c) 2010-2013, Joan Sola,\n% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,\n% SLAMTB is Copyright 2009 \n% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol\n% @ LAAS-CNRS.\n% See on top of this file for its particular copyright.\n\n% # END GPL LICENSE\n\n", "meta": {"author": "joansola", "repo": "slamtb", "sha": "b4767f6bf38bceed205abb85f1aed12422c9a972", "save_path": "github-repos/MATLAB/joansola-slamtb", "path": "github-repos/MATLAB/joansola-slamtb/slamtb-b4767f6bf38bceed205abb85f1aed12422c9a972/DetectionMatching/patchCorr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.4977743278408268}} {"text": "%% DEMO_febio_0054_lattice_hydrostatic_01\n% Below is a demonstration for:\n%\n% * Building geometry for a cube with hexahedral elements\n% * Defining the boundary conditions\n% * Coding the febio structure\n% * Running the model\n% * Importing and visualizing the displacement and stress results\n\n%% Keywords\n%\n% * febio_spec version 3.0\n% * febio, FEBio\n% * uniaxial loading\n% * compression, tension, compressive, tensile\n% * displacement control, displacement boundary condition\n% * hexahedral elements, hex8\n% * cube, box, rectangular\n% * static, solid\n% * hyperelastic, Ogden\n% * displacement logfile\n% * stress logfile\n\n%%\n\nclear; close all; clc;\n\n%% Plot settings\n% Plot settings\nfontSize=15;\nfaceAlpha1=0.8;\nfaceAlpha2=1;\nedgeColor=0.25*ones(1,3);\nedgeWidth=1.5;\nmarkerSize=25;\ncMap=gjet(4);\n\n%% Control parameters\n\n% Path names\ndefaultFolder = fileparts(fileparts(mfilename('fullpath')));\nsavePath=fullfile(defaultFolder,'data','temp');\n\n% Defining file names\nfebioFebFileNamePart='tempModel';\nfebioFebFileName=fullfile(savePath,[febioFebFileNamePart,'.feb']); %FEB file name\nfebioLogFileName=fullfile(savePath,[febioFebFileNamePart,'.txt']); %FEBio log file name\nfebioLogFileName_disp=[febioFebFileNamePart,'_disp_out.txt']; %Log file name for exporting displacement\nfebioLogFileName_force=[febioFebFileNamePart,'_force_out.txt']; %Log file name for exporting force\nfebioLogFileName_stress=[febioFebFileNamePart,'_stress_out.txt']; %Log file name for exporting stress\nfebioLogFileName_stiffness=[febioFebFileNamePart,'_stiffness_out.txt']; %Log file name for exporting stiffness\n\n%Specifying dimensions and number of elements\nsampleSize=10;\nlatticeType=1;\n\n%Define applied displacement\nJ_final=0.7; %Final Jacobian or volume ration\nlambdaFinal=J_final^(1/3); %Stretch values in all directions\ndisplacementMagnitude=((lambdaFinal*sampleSize)-sampleSize)/2; %The displacement magnitude\n\n%Material parameter set\nc1=1; %Shear-modulus-like parameter\nm1=2;\nk=50*c1;\n\n% FEA control settings\nnumTimeSteps=50; %Number of time steps desired\nmax_refs=50; %Max reforms\nmax_ups=0; %Set to zero to use full-Newton iterations\nopt_iter=25; %Optimum number of iterations\nmax_retries=5; %Maximum number of retires\ndtmin=(1/numTimeSteps)/100; %Minimum time step size\ndtmax=(1/numTimeSteps); %Maximum time step size\nmin_residual=1e-20;\nsymmetric_stiffness=0;\nrunMode='external';\n\n%%\n\n%Specifying dimensions and number of elements\nr=0.5; %Radii, results in a width of 1\nn=4;\nnCopies=n*ones(1,3); %Number of offset copies\nd=2*r; %Diameter\nw=(n-1)*d; %sampleSize\n\n%% Create lattice\n\nswitch latticeType\n case 1 %Octet truss\n [Er,Vr,Cr,Fr,CFr]=rhombicDodecahedronMesh(r,nCopies);\n Vr=Vr./(n-1);\n Vr=Vr*sampleSize;\n \n [indBoundary]=tesBoundary(Fr,Vr);\n cPar.shrinkFactor=0.15; %Strut sides are formed by shrinking the input mesh faces by this factor\n cPar.meshType='hex'; %desired output mesh type\n cPar.indBoundary=indBoundary; %indices of the boundary faces\n cPar.hexSplit=2;\n cPar.latticeSide=2; %1=side 1 the edge lattice, 2=side 2 the dual lattice to the edge lattice\n [E,V,C]=element2lattice(Er,Vr,cPar); %Get lattice structure\n \n logicKeep1=~(V(:,1)<=-1e-3);\n logicKeep2=~(V(:,2)<=-1e-3);\n logicKeep3=~(V(:,3)<=-1e-3);\n logicKeep4=~(V(:,1)>=sampleSize+1e-3);\n logicKeep5=~(V(:,2)>=sampleSize+1e-3);\n logicKeep6=~(V(:,3)>=sampleSize+1e-3);\n \n logicKeepEs=sum(logicKeep1(E),2)>=4 &...\n sum(logicKeep2(E),2)>=4 &...\n sum(logicKeep3(E),2)>=4 &...\n sum(logicKeep4(E),2)>=4 &...\n sum(logicKeep5(E),2)>=4 &...\n sum(logicKeep6(E),2)>=4;\n \n E=E(logicKeepEs,:);\n C=C(logicKeepEs,:);\n [E,V,indFix]=patchCleanUnused(E,V);\n \n % [Es,Vs,~,~]=subHex(Es,Vs,1,1);\n % Cs=repmat(Cs,8,1);\n \n % Create patch Data for visualization\n [Fs,CsF]=element2patch(E,C); %Patch data for plotting\n \n %Get new boundary set\n indB=tesBoundary(Fs,V);\n Fb=Fs(indB,:);\n case 2 %Rhombic dodecahedron mesh (\"dual\" of octet truss lattice)\n [Er,Vr,Cr,Fr,CFr]=rhombicDodecahedronMesh(r,nCopies);\n Vr=Vr./(n-1);\n Vr=Vr*sampleSize;\n \n [indBoundary]=tesBoundary(Fr,Vr);\n cPar.shrinkFactor=0.15; %Strut sides are formed by shrinking the input mesh faces by this factor\n cPar.meshType='hex'; %desired output mesh type\n cPar.indBoundary=indBoundary; %indices of the boundary faces\n cPar.hexSplit=2;\n cPar.latticeSide=1; %1=side 1 the edge lattice, 2=side 2 the dual lattice to the edge lattice\n [E,V,C]=element2lattice(Er,Vr,cPar); %Get lattice structure\n \n logicKeep1=~(V(:,1)<=-1e-3);\n logicKeep2=~(V(:,2)<=-1e-3);\n logicKeep3=~(V(:,3)<=-1e-3);\n logicKeep4=~(V(:,1)>=sampleSize+1e-3);\n logicKeep5=~(V(:,2)>=sampleSize+1e-3);\n logicKeep6=~(V(:,3)>=sampleSize+1e-3);\n \n logicKeepEs=sum(logicKeep1(E),2)>=4 &...\n sum(logicKeep2(E),2)>=4 &...\n sum(logicKeep3(E),2)>=4 &...\n sum(logicKeep4(E),2)>=4 &...\n sum(logicKeep5(E),2)>=4 &...\n sum(logicKeep6(E),2)>=4;\n \n E=E(logicKeepEs,:);\n C=C(logicKeepEs,:);\n [E,V,indFix]=patchCleanUnused(E,V);\n \n % [Es,Vs,~,~]=subHex(Es,Vs,1,1);\n % Cs=repmat(Cs,8,1);\n \n % Create patch Data for visualization\n [Fs,CsF]=element2patch(E,C); %Patch data for plotting\n \n %Get new boundary set\n indB=tesBoundary(Fs,V);\n Fb=Fs(indB,:);\n case 3\n boxDim=sampleSize*[1 1 1];\n boxEl=[2 2 2];\n [meshStruct]=hexMeshBox(boxDim,boxEl);\n Er=meshStruct.E;\n Vr=meshStruct.V;\n minV=min(Vr,[],1); %Get lower left front corner\n Vr=Vr-minV(ones(size(Vr,1),1),:); %Set corner as origin\n [Er,Vr,~]=hex2tet(Er,Vr,[],1); %Convert to tetrahedral elements\n [Fr,Cr]=element2patch(Er,[]); %Patch data for plotting\n [indBoundary]=tesBoundary(Fr,Vr);\n \n % Create lattice structure\n controlParameter.latticeSide=1;\n controlParameter.numDigitKeep=5; %used for merging nodes\n controlParameter.indBoundary=indBoundary; %indices of the boundary faces\n controlParameter.shrinkFactor=0.15;\n controlParameter.meshType='hex';\n controlParameter.hexSplit=2;\n \n [E,V,C]=element2lattice(Er,Vr,controlParameter); %Get lattice structure\n \n % Create patch Data for visualization\n [Fs,CsF]=element2patch(E,C); %Patch data for plotting\n \n indB=tesBoundary(Fs,V);\n Fb=Fs(indB,:);\nend\n%%\n% Visualizing input mesh and lattic structures\n\ncFigure;\nhs=subplot(1,2,1);\ntitle('The input mesh','fontSize',fontSize)\nhold on;\ngpatch(Fr,Vr,0.5*ones(1,3),'k',0.5);\naxisGeom(gca,fontSize);\ncamlight headlight; lighting flat;\n\nsubplot(1,2,2);\ntitle('Lattice side 1','fontSize',fontSize)\nhold on;\ngpatch(Fb,V,'bw','k',1);\n% patchNormPlot(Fs,Vs);\naxisGeom(gca,fontSize);\ncamlight headlight; lighting flat;\n\ndrawnow;\n\n%% DEFINE BC's\n\n% Define node set logics\nindAll=(1:1:size(V,1))';\nlogicBoundary=ismember(indAll,Fb);\n\nZ=V(:,3);\nlogicTop=Z>=(sampleSize-eps(sampleSize))& logicBoundary;\nlogicBottom=Z<=eps(sampleSize) & logicBoundary;\n\nX=V(:,1);\nlogicSide1=X>=(sampleSize-eps(sampleSize))& logicBoundary;\nlogicSide2=X<=eps(sampleSize)& logicBoundary;\n\nY=V(:,2);\nlogicSide3=Y>=(sampleSize-eps(sampleSize))& logicBoundary;\nlogicSide4=Y<=eps(sampleSize)& logicBoundary;\n\n%Prescribed force nodes\nbcPrescribeListCell{1}=find(logicSide1)';\nbcPrescribeListCell{2}=find(logicSide2)';\nbcPrescribeListCell{3}=find(logicSide3)';\nbcPrescribeListCell{4}=find(logicSide4)';\nbcPrescribeListCell{5}=find(logicTop)';\nbcPrescribeListCell{6}=find(logicBottom)';\n\n%% Smoothing lattice\n\n% indKeep=unique([bcPrescribeListCell{:}]);\n% [Fb_clean,Vb_clean,indFix]=patchCleanUnused(Fb,Vs);\n%\n% cPar.Method='HC';\n% cPar.n=6;\n%\n% cPar.RigidConstraints=indFix(indKeep);\n% % cPar.RigidConstraints=cPar.RigidConstraints(cPar.RigidConstraints>0);\n%\n% [Vb_clean]=tesSmooth(Fb_clean,Vb_clean,[],cPar);\n% ind=Fb(:);\n% ind=unique(ind(:));\n% Vs(ind,:)=Vb_clean;\n\n% cFigure; hold on;\n% gpatch(Fb,Vs,'bw','k',1);\n% % patchNormPlot(Fs,Vs);\n% % plotV(Vs(indKeep,:),'k.','MarkerSize',25)\n% axisGeom(gca,fontSize);\n% camlight headlight; lighting flat;\n% drawnow;\n\n%%\n% Visualizing input mesh and lattic structures\n\ncFigure;\nhs=subplot(1,2,1);\ntitle('The input mesh','fontSize',fontSize)\nhold on;\ngpatch(Fr,Vr,0.5*ones(1,3),'k',0.5);\naxisGeom(gca,fontSize);\ncamlight headlight; lighting flat;\n\nsubplot(1,2,2);\ntitle('Lattice side 1','fontSize',fontSize)\nhold on;\ngpatch(Fb,V,'bw');\n% patchNormPlot(Fs,Vs);\naxisGeom(gca,fontSize);\ncamlight headlight; lighting flat;\n\ndrawnow;\n\n%%\n% Visualize BC's\n\ncFigure; hold on;\ntitle('Boundary conditions','FontSize',fontSize);\ngpatch(Fb,V,'kw','none',0.4);\nhl=gobjects(1,6);\nplotColors=gjet(6);\nfor q=1:1:numel(bcPrescribeListCell)\n hl(q)=plotV(V(bcPrescribeListCell{q},:),'k.','MarkerSize',markerSize);\n hl(q).Color=plotColors(q,:);\nend\n\nlegend(hl,{'BC 1','BC 2','BC 3','BC 4','BC 5','BC 6'});\naxisGeom;\ncamlight headlight;\nset(gca,'FontSize',fontSize);\ndrawnow;\n\n%% Defining the FEBio input structure\n% See also |febioStructTemplate| and |febioStruct2xml| and the FEBio user\n% manual.\n\n%Get a template with default settings \n[febio_spec]=febioStructTemplate;\n\n%febio_spec version \nfebio_spec.ATTR.version='3.0'; \n\n%Module section\nfebio_spec.Module.ATTR.type='solid'; \n\n%Control section\nfebio_spec.Control.analysis='STATIC';\nfebio_spec.Control.time_steps=numTimeSteps;\nfebio_spec.Control.step_size=1/numTimeSteps;\nfebio_spec.Control.solver.max_refs=max_refs;\nfebio_spec.Control.solver.max_ups=max_ups;\nfebio_spec.Control.solver.symmetric_stiffness=symmetric_stiffness;\nfebio_spec.Control.time_stepper.dtmin=dtmin;\nfebio_spec.Control.time_stepper.dtmax=dtmax; \nfebio_spec.Control.time_stepper.max_retries=max_retries;\nfebio_spec.Control.time_stepper.opt_iter=opt_iter;\n\n%Material section\nmaterialName1='Material1';\nfebio_spec.Material.material{1}.ATTR.name=materialName1;\nfebio_spec.Material.material{1}.ATTR.type='Ogden';\nfebio_spec.Material.material{1}.ATTR.id=1;\nfebio_spec.Material.material{1}.c1=c1;\nfebio_spec.Material.material{1}.m1=m1;\n% febio_spec.Material.material{1}.c2=c1;\n% febio_spec.Material.material{1}.m2=-m1;\nfebio_spec.Material.material{1}.k=k;\n\n\n% Mesh section\n% -> Nodes\nfebio_spec.Mesh.Nodes{1}.ATTR.name='Object1_lattice'; %The node set name\nfebio_spec.Mesh.Nodes{1}.node.ATTR.id=(1:size(V,1))'; %The node id's\nfebio_spec.Mesh.Nodes{1}.node.VAL=V; %The nodel coordinates\n\n% -> Elements\npartName1='Part1_lattice';\nfebio_spec.Mesh.Elements{1}.ATTR.name=partName1; %Name of this part\nfebio_spec.Mesh.Elements{1}.ATTR.type='hex8'; %Element type\nfebio_spec.Mesh.Elements{1}.elem.ATTR.id=(1:1:size(E,1))'; %Element id's\nfebio_spec.Mesh.Elements{1}.elem.VAL=E; %The element matrix\n\n% -> NodeSets\nfor q=1:1:numel(bcPrescribeListCell) \n febio_spec.Mesh.NodeSet{q}.ATTR.name=['bcPrescribeList_',num2str(q)];\n febio_spec.Mesh.NodeSet{q}.node.ATTR.id=bcPrescribeListCell{q}';\nend\n\n%MeshDomains section\nfebio_spec.MeshDomains.SolidDomain.ATTR.name=partName1;\nfebio_spec.MeshDomains.SolidDomain.ATTR.mat=materialName1;\n\n%Boundary condition section\n\n% -> Prescribe boundary conditions\ndirectionStringSet={'x','x','y','y','z','z'};\ndisplacementMagnitudeDir=[1 -1 1 -1 1 -1];\nfor q=1:1:numel(bcPrescribeListCell) \n nodeSetName=febio_spec.Mesh.NodeSet{q}.ATTR.name;\n febio_spec.Boundary.bc{q}.ATTR.type='prescribe';\n febio_spec.Boundary.bc{q}.ATTR.node_set=nodeSetName;\n febio_spec.Boundary.bc{q}.dof=directionStringSet{q};\n febio_spec.Boundary.bc{q}.scale.ATTR.lc=1;\n febio_spec.Boundary.bc{q}.scale.VAL=displacementMagnitudeDir(q).*displacementMagnitude;\n febio_spec.Boundary.bc{q}.relative=0;\nend\n\n%LoadData section\n% -> load_controller\nfebio_spec.LoadData.load_controller{1}.ATTR.id=1;\nfebio_spec.LoadData.load_controller{1}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{1}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{1}.points.point.VAL=[0 0; 1 1];\n\n%Output section\n% -> log file\nfebio_spec.Output.logfile.ATTR.file=febioLogFileName;\n\nfebio_spec.Output.logfile.node_data{1}.ATTR.file=febioLogFileName_disp;\nfebio_spec.Output.logfile.node_data{1}.ATTR.data='ux;uy;uz';\nfebio_spec.Output.logfile.node_data{1}.ATTR.delim=',';\n\nfebio_spec.Output.logfile.node_data{2}.ATTR.file=febioLogFileName_force;\nfebio_spec.Output.logfile.node_data{2}.ATTR.data='Rx;Ry;Rz';\nfebio_spec.Output.logfile.node_data{2}.ATTR.delim=',';\n\nfebio_spec.Output.logfile.element_data{1}.ATTR.file=febioLogFileName_stress;\nfebio_spec.Output.logfile.element_data{1}.ATTR.data='sz';\nfebio_spec.Output.logfile.element_data{1}.ATTR.delim=',';\n\n%% Quick viewing of the FEBio input file structure\n% The |febView| function can be used to view the xml structure in a MATLAB\n% figure window. \n\n%%\n% |febView(febio_spec); %Viewing the febio file|\n\n%% Exporting the FEBio input file\n% Exporting the febio_spec structure to an FEBio input file is done using\n% the |febioStruct2xml| function. \n\nfebioStruct2xml(febio_spec,febioFebFileName); %Exporting to file and domNode\n%system(['gedit ',febioFebFileName,' &']);\n\n%% Running the FEBio analysis\n% To run the analysis defined by the created FEBio input file the\n% |runMonitorFEBio| function is used. The input for this function is a\n% structure defining job settings e.g. the FEBio input file name. The\n% optional output runFlag informs the user if the analysis was run\n% succesfully. \n\nfebioAnalysis.run_filename=febioFebFileName; %The input file name\nfebioAnalysis.run_logname=febioLogFileName; %The name for the log file\nfebioAnalysis.disp_on=1; %Display information on the command window\nfebioAnalysis.runMode=runMode;\nfebioAnalysis.maxLogCheckTime=10; %Max log file checking time\n\n[runFlag]=runMonitorFEBio(febioAnalysis);%START FEBio NOW!!!!!!!!\n\n%% Import FEBio results\n\nif runFlag==1 %i.e. a succesful run\n \n %%\n \n % Importing nodal displacements from a log file\n dataStruct=importFEBio_logfile(fullfile(savePath,febioLogFileName_disp),1,1);\n \n %Access data\n N_disp_mat=dataStruct.data; %Displacement\n timeVec=dataStruct.time; %Time\n \n %Create deformed coordinate set\n V_DEF=N_disp_mat+repmat(V,[1 1 size(N_disp_mat,3)]);\n \n %%\n \n % Importing nodal forces\n dataStruct=importFEBio_logfile(fullfile(savePath,febioLogFileName_force),1,1);\n N_force_mat=dataStruct.data;\n \n indicesSide=bcPrescribeListCell{1};\n areaSide=sampleSize.^2;\n \n stressVal=mean(squeeze(N_force_mat(indicesSide,1,:))./areaSide,1);\n J_Val=1-((1-J_final).*timeVec(:));\n \n %% \n \n cFigure; hold on;\n xlabel('$J$','Interpreter','Latex'); ylabel('$\\sigma^*$','Interpreter','Latex');\n plot(J_Val(:),stressVal(:),'r.-','LineWidth',3,'MarkerSize',15);\n axis square; axis tight; grid on; box on;\n set(gca,'FontSize',fontSize);\n drawnow;\n \n %%\n % Plotting the simulated results using |anim8| to visualize and animate\n % deformations\n \n DN_magnitude=sqrt(sum(N_disp_mat(:,:,end).^2,2)); %Current displacement magnitude\n \n % Create basic view and store graphics handle to initiate animation\n hf=cFigure; %Open figure\n gtitle([febioFebFileNamePart,': Press play to animate']);\n hp=gpatch(Fb,V_DEF(:,:,end),DN_magnitude,'k',1); %Add graphics object to animate\n % gpatch(Fb,Vs,'kw','none',0.25); %A static graphics object\n hp.FaceColor='interp';\n \n axisGeom(gca,fontSize);\n colormap(gjet(250)); colorbar;\n caxis([0 max(DN_magnitude)]);\n axis(axisLim(V_DEF)); %Set axis limits statically\n % view(130,25); %Set view direction\n camlight headlight;\n \n % Set up animation features\n animStruct.Time=timeVec; %The time vector\n for qt=1:1:size(N_disp_mat,3) %Loop over time increments\n DN=N_disp_mat(:,:,qt); %Current displacement\n DN_magnitude=sqrt(sum(DN.^2,2)); %Current displacement magnitude\n \n %Set entries in animation structure\n animStruct.Handles{qt}=[hp hp]; %Handles of objects to animate\n animStruct.Props{qt}={'Vertices','CData'}; %Properties of objects to animate\n animStruct.Set{qt}={V_DEF(:,:,qt),DN_magnitude}; %Property values for to set in order to animate\n end\n anim8(hf,animStruct); %Initiate animation feature\n drawnow;\n\nend\n\n%%\n%\n% <>\n%\n% _*GIBBON*_\n% \n%\n% _Kevin Mattheus Moerman_, \n\n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/docs/DEMO_febio_0054_lattice_hydrostatic_01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.4977743228255097}} {"text": "function [c1, lmin1, lmax1, as, pm, sig8] = cmbaccur(van, omt, bmark, one_percent, lmax, stfname)\n% cmbaccur.m :\n% this program calculates the radiation and matter spectra to an accuracy of 1% or 0.1% for the open, flat and\n% closed Friedman-Robertson-Walker universe.\n% The radiation spectra include the temperature- polarisation and cross-polarisation spectra.\n% We follow the method of Uros Seljak amd Matias Zaldarriaga in 'A line-of-sight integration approach\n% to Cosmic microwave background anisotropies', ApJ, nr 469, 437-444 (1996), see also :\n% Ma and Bertschinger, ApJ nr 455, 7-25 (1995) and Zaldarriaga, Seljak, Bertschinger\n% ApJ nr 494, 491 (1998) and Zaldarriaga and Seljak, ApJ nr129, 431 (2000) and W Hu e.a, 'A complete treatment\n% of CMB anisotropies in a FRW universe', Phys Rev D57, 3290-3301 (1998), for reionisation see N Sugiyama, \n% ApJ nr 419 L1-L4 (1993) and ApjS nr 100, 281 (1995)\n%\n% input : the \"vanilla-set\" of Cosmological parameters, omt, the curvature of the universe, \n% bmark : a benchmark (file) to compare with (see remarks), one_percent: the accuracy \n% is 1% resp 0.1% for ~one_percent==0 resp one_percent==0, the default is 1%, lmax, the maximum \n% multipoint number, the default lmax value is lmax=1500 (lmax must be <= 1500. otherwise a special\n% la-vector has to be defined), name of the startfile for the ultra-spherical function. \n% no inputs : if no inputs are given the functions takes the default values (see remarks),\n% if 5th argument (lmax) is missing, the default value lmax=1500 is taken\n%\n% output :the normalisation constant (asc), the positions of the peaks (minima and maxima)\n% in the temperature anisotropy spectrum (lmin & lmax), as: the temperature anisotropy spectrum, as.ctt \n% the E-polarisation spectrum, as.cee and the cross-correlation spectrum, as.cte, pm: the matter spectrum\n\n% D Vangheluwe 29 jun 2005 finished 4 july 2005\n% remark 1: the vanilla-set is (As, omega_lambda, omega_d, omega_b, ns, tau), which are : the amplitude correction\n% at l=10, dark energy density, dark matter density, baryon density, scalar spectral index, optical depth.\n% The vanilla-set is converted internally to the parameters (c1, om, omt, omb, h, nprimtilt, zri), which are: \n% the amplitude correction at l=10, dark matter omega, total omega, baryon omega, Hubble factor, scalar spectral index, \n% reionisation redshift, see below for the default values. For example: omt = omega_lambda + omega_b + omega_d\n% remark 1 this is a compilation of the programs cmbacc1.m and ambacc2.m for resp open (K<=0) and closed space (K>0)\n% remark 2 the discrete values of la for closed space are chosen different from the ones for open space : reason that\n% for closed space the peaks in the spectrum shift to lower la and we need more points there : therefore the\n% step change in la is chosen at la =100 resp la = 250 for open/flat resp closed space.\n% remark 3 :the lamda content of the universe is automatically : omt - omr -om, for example with omt = 1.1,\n% om = 0.27, h = 0.72 and omr = omp/(1 - fv)= 8.01e-5, we have oml = 0.83, we have chosen here not to\n% specify the lamda energy content of primordial space. For the Vanilla parameters see ambaccur(.)\n% remark 4: the different path taken for closed resp open/flat space can be seen at the if (K>0) statements.\n% for K>0 we take a different set of k1 values to solve the Bolzamn equations and a different set of k2\n% (also 'beta' in the literature) values for the calculation of the anistropy spectrum\n% remark 6: the connections with the input of cmbfast and our input is a bit difficult : we give the connection\n% for resp omega of the vacuum (omegav), cold dark matter (omegac) and baryons (omegab) :\n% omegav = omt - om, omegac = om - omb, omegab = omb (om is the omega for all matter, baryons+dark matter and omt\n% is the total omega)\n% remark 7: try the vanilla-lite model from Tegmark et al. astro-ph/0310723, 15jan 2004:\n% van = [0.89, 0.72, 0.12, 0.024, 1, 0.17] and omt =1, it is the best fit to WMAP2003 +SDSS assuming ns==1 and tensor field zero.\n% or the old cdm model, a universe without dark energy : van = [1, 0.954, 0.0, 0.0115, 1, 0] and omt =1.\n% remark 5 (4 aug 2005): if the spectrum needs only to be calculated for a multipole range smaller than the \n% default lmax0=1500, specify this value <1500 as the last argument, the accuracy is\n% kept in line with this choice (several changes are necessary such as : smaller nkst, extended k1max etc.)\n% The calculation time is proportional to sqrt(lmax), not with lmax!\n\n\nglobal GL_dt_table GL_pp_dtau;\nglobal GL_cmb_c GL_cmb_h0 GL_cmb_t0 GL_cmb_T0 GL_cmb_rv GL_cmb_fv GL_cmb_kg1 GL_cmb_ka1 ...\n GL_cmb_yp GL_cmb_ncr GL_cmb_cr GL_cmb_pcm GL_cmb_dha;\n% give the global physical constants a value\ncmbglobl;\n\n% tolerance\ntol = 1e-6;\ntrace = [];\n\n%cosmological parameters : (As, omega_lambda, omega_d, omega_b, ns, zri) and omt for spacial curvature\nif nargin == 0 %take the default vanilla-set (which gives the best fit to wmap2003)\n% the default set is : c10=1, om=0.27, omb=0.046, h=0.72, ns=0.99, zri= 17.28\n van = [1, 0.73, 0.1161216, 0.0238464, 0.99, 0.17295];\n omt = 1;\n lmax = 1500;\n% the default accuracy is : one_percent == 1, for an of accuracy 1%, the accuracy = 0.1% only for one_percent == 0.\n one_percent = 1\n% benchmark calculations to compare : available are cmbfast for h=0.72: 'h72', 'h72i' for reionisation with zri = 17.3\n% 'h72o1' for h = 0.72 open universe with omt=1.1, 'h72c1' for h = 0.72 closed universe with omt=0.9, \n% 'cdm', for the CDM model (flat space) (see for more info cmbdata3.m)\n bmark = 'h72i';\nelse \n if nargin == 1, error('the benchmark must be defined'), return; end\n if nargin == 2, error('the accuracy must be defined'), return; end\n if nargin == 4, lmax = 1500; end\nend\nif ~(one_percent == 0), one_percent = 1; end;\n\n% the hubble factor h\n%h = 0.71\n%h = 0.72\nif (omt - van(2) > 0)\n h = sqrt((van(3) + van(4))/(omt - van(2)))\nelse\n error('omt < van(2) not allowed');\n return\nend\n\n% baryon content of the universe\n%omb = 0.0444\n%omb = 0.046\nomb = van(4)/h^2\n\n% matter content of the universe\n%om = 0.27\n%om = 0.27\nom = (van(3) + van(4))/h^2\n\n% redshift for reionisation\n%zri = 0\n%zri = 17.28 % tauri = 0.170\n%zri = 0\nzri = 92*(0.03 * h * van(6)/van(4))^(2/3) * om^(1/3)\n\n% primordial tilt : the exponent of the power spectrum of matter\n%nprimtilt = 0.99;\n%nprimtilt = 0.99;\nnprimtilt = van(5)\n\n% normalisation of the anisotropy spectrum\n%c10 = 1.00;\nc10 = van(1);\n\n% the cmb temperature\n%cmbtemp = 2.725;\ncmbtemp = GL_cmb_t0;\n% velocity of light in m/s\n%c = 2.998e8;\nc = GL_cmb_c;\n% the hubble constant at present in h Mpc^-1, see my notes p71\n%h0 = 1e5/c;\nh0 = GL_cmb_h0;\n% the ratio of neutrino to total radiation density fv, assuming three massless neutrinos\n%rv = (21/8) * (4/11)^(4/3);\n%fv = rv/(1 + rv);\nfv = GL_cmb_fv;\n% amplitude of the primordial density perturbation at the horizon, see Dodelson (8.76)\n%dha = 4.6e-5;\ndha = GL_cmb_dha;\ndha2 = dha^2;\n% the ratio of the radiation density and the critical density, see Dodelson (omega_gamma) \n%kg1 = 2.47e-5;\nkg1 = GL_cmb_kg1;\n%ka1 = kg1/(1 - fv);\nka1 = GL_cmb_ka1;\n\naeq = ka1/(om * h^2);\nkeq = h0 * h * sqrt(om*2/aeq);\n% omega of radiation and neutrinos separately\nomp = kg1/h^2;\nomr = omp/(1 - fv);\nomn = omp * fv/(1 - fv);\n% the constant K for curvature energy content from the Friedman equation\nK = (omt - 1) * (h0 * h)^2;\n\nif nargin < 6\n if K > 0, stfname = 'stfile1';\n else, stfname = 'stfile';\n end\nend\n\ntol_ode23 = 1e-5;\nif one_percent == 1\n tol_ode23 = 2e-4; % default 2e-4\nend\n\n% find the recombination curve and the inverse optical depth, dtau in Mpc^-1, \n% tau and the visibility function (vsb1) :\ndt = recomb(om, omb, omt, h, zri);\n%sdata = load('cmbxe');\n%dt = sdata.dt;\nGL_dt_table = dt.dt_table;\n%tauri = dt.tauri;\ntauri = van(6);\n\nzdec = dt.zdec;\nsizetable = size(GL_dt_table, 2)\nat1 = GL_dt_table(1,:);\ndtau1 = GL_dt_table(3,:);\n%tau1 = GL_dt_table(4,:);\n%vsb1 = GL_dt_table(5,:);\n% make a spline of dtau\nGL_pp_dtau = spline(GL_dt_table(1,:), GL_dt_table(3,:));\n\n% calculate the current conformal time :ctc0 and ctime at reionisation and at decoupling\nctc0 = quadl(@conftim1, 0, 1, tol, trace, om, omr, omt, h);\nctad = quadl(@conftim1, 0, 1/(zdec + 1), tol, trace, om, omr, omt, h);\nctri = quadl(@conftim1, 0, 1/(zri + 1), tol, trace, om, omr, omt, h);\n\n% if the spectrum has become isotropic for K > 0 (all photons are coming from one point) break off:\nif (K > 0)\n ct4sym = 0.5 * pi/sqrt(K);\n if (2*ct4sym < ctc0), message('the spectrum is isotropic, return'); return; end\n if sqrt(K) * ctc0 > 2, message('curvature K * ctc0 > 2'); end\nend\n\n% define the range of l (angle number)\n%lmax = 1500;\nlmin = 2;\n\n% the wavenumber kw in Mpc^1 (range : 0.2 < kw < 2e-4)\n% define the k-range\nif one_percent == 1\n% nkst = 44\n nkst = 30 + 10*(lmax - 900)/600; % adapt the k1step for lmax~1500\nelse\n nkst = 88\nend\n\n% find the maximum multipole number in the startfile for K>0 (lmax0 =default 1500)\nstv1 = load(stfname);\nlmax0 = stv1.ust.la(end);\nif (K > 0)\n k1min = 3*sqrt(K);\n% k1int = 4e-3;\n k1int = 8e-3;\n% if K*ctc0 > 2, it is necessary to increase k1max : important change for K>0!!\n% and extend the range of k1 in case lmax < maximum of the startfile (lmax0 is default 1500)\n k1max = max(2*sqrt(lmax*lmax0)/ctc0, 1.5*sqrt(lmax*lmax0)*sqrt(K));\n k1step = (k1int - k1min)/8;\n k1step2 = (k1max - k1int)/nkst;\n k1 = [[k1min : k1step : (k1int - k1step)], [k1int : k1step2 : k1max]];\nelse\n k1min = 1e-5;\n k1int = 8e-3;\n% extend the range of k1 in case lmax < maximum of the startfile (lmax0 is default 1500)\n k1max = 2*sqrt(lmax*lmax0)/ctc0;\n k1step = 0.0012;\n k1step2 = (k1max - k1int)/nkst;\n k1 = [k1min, 4e-5, 8e-5, 2e-4, 4e-4, 6e-4, 8e-4 : k1step : k1int, k1int+k1step2 : k1step2 : k1max];\nend %define k1 range\nlk1 = size(k1, 2)\n\n% take smaller steps in the same range of the conformal time now ct2:\nstep0 = ctc0/7000;\nif one_percent == 1\n ct2step = step0;\nelse\n ct2step = step0/2;\nend\nct2min = 0.5;\nct2max = ctc0;\nct2 = ct2min : ct2step : ct2max;\nlct2 = size(ct2, 2);\n\n%555555555555555555\n% solve the Bolzman equations :\n[table_srt, table_srp, deltam, a2] = ...\n bolzmslv(ct2, k1, tol_ode23, om, omb, omt, h, ctc0, ctad, zri, ctri, K, one_percent);\n\n% find the conformal time at recombination :\nvsb2 = spline(GL_dt_table(1,:), GL_dt_table(5,:), a2);\n[vsbm irm] = max(vsb2);\netar = ct2(irm);\n% calculate the thickness of the recombination surface in conformal time\nids = find(vsb2 >= 0.5* vsbm);\n% half width ct2 points are:\nhw1 = ct2(ids(1));\nhw2 = ct2(ids(end));\ntrs = hw2 - hw1;\n% number of points over the half width of the visibility function :\nnphw = length(ids)\n% find an accurate value for the decoupling time (recombination)\nct3 = hw1:0.01:hw2;\nvsb3 = spline(ct2, vsb2, ct3);\n[vsbm irm] = max(vsb3);\nctad1 = ct3(irm);\n\n% define a k2 range:\nif (K > 0)\n% define a k-range with more points ->k2 :where kb = 1/3..\n logstep = 0;\n nn2min = fix(k1min/sqrt(K));\n nn2max = fix(k1max/sqrt(K));\n nksteps = 1.5* sqrt(lmax * lmax0);\n nn2step = max(1, round((nn2max - nn2min)/nksteps));\n nn2step = min(2, nn2step); % limit to nn2step==2\n nn2 = nn2min : nn2step : nn2max;\n k2 = nn2 * sqrt(K);\nelse\n\n logstep = 1;\n k2min = k1min;\n k2max = k1max;\n if one_percent == 1\n ek2step = 0.002;\n else\n ek2step = 0.0015;\n end\n ek2 = log(k2min)/log(10) : ek2step : log(k2max)/log(10);\n k2 = 10 .^ ek2;\nend % define k2 range\nlk2 = size(k2, 2);\nik2 = floor(lk2/2);\nik4 = floor(lk2/4);\n\n% calculate the anisotropy- and polariation spectrum for l > 2 in 2 steps: step1 :l<100 and step2 :l>100\n% for l > 100 :select the interval in the conformal time range ct2 where the source is none zero\n% for l < 100 :the source extends over a rather large cf time range of 200-ctc0 and we found that\n% the ctime integration range must be extended in order to achieve 0.1% accuracy for l < 100\n% With reionisation (zri > 0) for 1% accuracy, integration should be extended over the total ct time range.\n\n%##anisotropy spectrum, step1 : l < 100 (2 and lct2-1 to stay within interpolation limits)\nict4min = 2;\n%ict4max = lct2 - 1;\nict4max = lct2;\nif one_percent == 1\n ict4step = 2;\nelse\n ict4step = 1;\nend \nict4 = ict4min : ict4step : ict4max;\nct4 = ct2(ict4);\nlct4 = size(ict4, 2);\n\n% take as much splines ready for k2 interpolations as there are cftime points in ct4 :\n% for each time we have one spline (the splines are in a column vector)\n% this steps needs a lot of memory : if short of memory use srcpint.m with pp4, pp5 as argument : this\n% is the case for one_percent ~= 1\npp4 = spline(k1, table_srt(:, ict4)');\npp5 = spline(k1, table_srp(:, ict4)');\nif one_percent == 1\n src4 = [ppval(pp4, k2(1:ik2)), ppval(pp4, k2(ik2+1:end))];\n src5 = [ppval(pp5, k2(1:ik2)), ppval(pp5, k2(ik2+1:end))];\nend\n\n% calculate the anisotropy spectrum for l <= 100\nif (one_percent == 1) & (K > 0 )\n lstep = 20;\nelse\n lstep = 10;\nend\n%la1 = 2;\nif (K > 0)\n la1 = [2,6,10, 20:lstep:220];\n lla1 = size(la1,2);\n if one_percent == 1\n [cct1, ta1, te1] = srcintf1(la1, nn2, ct4, src4, src5, ctc0, ctad, nprimtilt, lmax, K, stfname);\n else\n [cct1, ta1, ta2] = srcint1(la1, nn2, ct4, pp4, pp5, ctc0, ctad, nprimtilt, lmax, K, stfname);\n end\n\nelse\n la1 = [2,6,10,20:lstep:90];\n lla1 = size(la1,2);\n if one_percent == 1\n [cct1, ta1, te1] = srcintf(la1, k2, ct4, src4, src5, ctc0, nprimtilt, lmax, K, stfname, logstep);\n else\n [cct1, ta1, ta2] = srcint(la1, k2, ct4, pp4, pp5, ctc0, nprimtilt, lmax, K, stfname, logstep);\n end\n\nend\n\n% change the stepsize in the k2 vector\nif (K > 0)\n nksteps = 0.75* sqrt(lmax * lmax0);\n% take care that in case the peak in the source region is splitup by the symmetry point, we take all\n% modes (even and uneven nn2(i)) in the summation for the anistropy spectrum and nn2min==3\n if ( (ctc0 - ct4sym) > 0 & (ctc0 - ct4sym) < (ctad + 100) )\n nn2step = 1;\n else\n nn2step = max(1, round((nn2max - nn2min)/nksteps));\n nn2step = min(2, nn2step); % limit to nn2step==2\n end\n nn2 = nn2min : nn2step : nn2max;\n k2 = nn2 * sqrt(K);\nelse\n\n clear('k2')\n logstep = 0;\n if one_percent == 1\n nksteps = 1.5*sqrt(lmax *lmax0);\n else\n nksteps = 2*sqrt(lmax *lmax0);\n end\n k2step = (k2max - k2min)/nksteps;\n k2 = k2min : k2step : k2max;\nend % define k2 range\nlk2 = size(k2, 2);\nik2 = floor(lk2/2);\nik4 = floor(lk2/4);\n\n%##anisotropy spectrum, step 2 :l > 100, note that the cftime extends to the full range, ict4max= lt2-1\nif one_percent == 1\n ict4step = 2;\nelse\n ict4step = 1;\nend\nict4 = ict4min : ict4step : ict4max;\nct4 = ct2(ict4);\nlct4 = size(ict4, 2);\n\n% take the splines for all k2 interpolations within the conformal time interval ict4\n% for each time we have one spline (the splines are in a column vector)\n% this steps needs a lot of memory : if short of memory use srcpint.m with pp4, pp5 as argument\npp4 = spline(k1, table_srt(:, ict4)');\npp5 = spline(k1, table_srp(:, ict4)');\nif one_percent == 1\n src4 = [ppval(pp4, k2(1:ik2)), ppval(pp4, k2(ik2+1:end))];\n src5 = [ppval(pp5, k2(1:ik2)), ppval(pp5, k2(ik2+1:end))];\nend\n\n% calculate the anisotropy spectrum for l > 100\nif one_percent == 1\n lstep = 50;\nelse\n lstep = 25;\nend\n%la2 = 500\nif (K > 0)\n la2 = 250:lstep:lmax;\n lla2 = size(la2,2);\n if one_percent == 1\n [cct2, ta1] = srcintf1(la2, nn2, ct4, src4, src5, ctc0, ctad, nprimtilt, lmax, K,stfname);\n else\n [cct2, ta1] = srcint1(la2, nn2, ct4, pp4, pp5, ctc0, ctad, nprimtilt, lmax, K,stfname);\n end\nelse\n la2 = 100:lstep:lmax;\n lla2 = size(la2,2);\n if one_percent == 1\n [cct2, ta1] = srcintf(la2, k2, ct4, src4, src5, ctc0, nprimtilt, lmax, K, stfname, logstep);\n else\n [cct2, ta1] = srcint(la2, k2, ct4, pp4, pp5, ctc0, nprimtilt, lmax, K, stfname, logstep);\n end\nend\n\n% collect the results and go to the final step\nla = [la1, la2];\nctth = [cct1.ctt, cct2.ctt];\nceeh = [cct1.cee, cct2.cee];\ncteh = [cct1.cte, cct2.cte];\n\n% calculate the amplitude of the anistropy spectrum in terms of the cmb temperature cmbtemp as\n% cmbtemp^2*l*(l+1)*C1/(2*pi) in units of Kelvin^2 (including the effect of primordial tilt of the\n% power spectrum)\n% calculate the present (a==1) grow factor D1 by integration (see Dodelson 7.77)\nD1 = 2.5 * om * quadl(@cmd3, 0, 1.0, tol, trace, om, omt);\n% calculate the proportionality factor of the temperature spectrum, see Sachs and Wolfe and\n% Dodelson (8.74) :\ncswl1 = (50/9) * cmbtemp^2* (h*h0)^(1-nprimtilt) * (om/D1)^2;\n\n% calculate the power spectrum of matter psm in units (Mpc/h)^3 as a function of kh = k1/h in h/Mpc.\nkh = k1/h;\n% use deltam(k) = delta(k)/psi, see Dodelson formulas (6.100) and (7.9) and delta is the mass overdensity.\npsm1 =(50 *pi^2/9) .* (h./k1) .^3 .* (k1/(h*h0)) .^ (nprimtilt-1) .* (deltam .^2) * (om/D1)^2;\ndeltam(1)\n\n% find psm at k1=0.05/Mpc and normalise the spectra with the density fluctuation at horizon crossing (dha)\n% the c10 normalisation for the temperature spectrum is taken at l=10 :\n% the best fit value for wmap2003 is 727 microKelvin^2, which gives C10 = 5.59e-12 and sqrt(C10) = 2.36e-6.\n% the density fluctuation at the horizon for the best fit (dha) is in the global file of constants (cmbglobl.m)\n% we use it to normalise both temperature and matter spectra. \nkfid = 0.05\n% normalise the temperature and matter spectra:\npsm = psm1 * dha2;\ncswl = cswl1 * dha2;\n\n% calculate sigma8, the extended rms mass overdensity, sampled with a sphere of radius of radius 8 Mpc/h\n% extend the matter power spectrum from k1 into small scales with k3 > 0.2 Mpc^-1, \nk3step = 0.01;\nk3max = 1.0;\nk3 = (k1max+k3step) : k3step : k3max;\n%for the extension use the asymptotic expansion of delta, see Dodelson formula (7.9) with the transfer function of (7.69)\n% as psm is in units (Mpc/h)^3, we have to include the Hubble factor^3 in the Bolzman part of psm\npsm2 = psm/h^3;\npsm3 = psm2(end) * (k1(end) ./ k3) .^(4-nprimtilt) .* (log(k3/(8*keq))/log(k1(end)/(8*keq))) .^2;\nk4 = [k1, k3];\npsm4 = [psm2, psm3];\nsig8h = (0.5/pi^2) * quadl(@sigma_8, k4(1), k4(end), tol, trace, k4, psm4, h);\nsig8 = sqrt(sig8h);\n% plot both psm from Bolzman calculation and the extension from formula (7.69)\nfigure(1)\nloglog(k4, psm4)\n%semilogy(k4, psm4)\ntitle(['full range mass power spectrum: omt=', num2str(omt), ' h=', num2str(h), ',om=', num2str(om), ...\n ',omb=', num2str(omb), ',ns=', num2str(nprimtilt), ',tauri=', num2str(tauri)])\nylabel('P(k) in (Mpc/h)^3')\nxlabel('log of the wavenumber in h/Mpc')\n\n% compare with wmap results and find the normalisation constant c10\nfn = 'cmbansp';\npm.k = kh;\npm.psm = psm;\nas.la = la; \nas.ctt = ctth * cswl;\nas.cee = ceeh * cswl;\nas.cte = cteh * cswl;\n% c1==1 gives a model with a perfect fit\n\n[c1, lmin1, lmax1] = cmbdata1(as, pm, h, omt, om, omb, nprimtilt, tauri, bmark);\n% sigma* has to be corrected with sqrt of the amplitude correction ,sqrt(c1) :standard case sig8 =0.915\nsig8 = sig8 * sqrt(c1);\n\n% save the anisotropy spectra (as/pm) and matter spectrum (pm) and make plots\n%save cmbansp as pm\n% bring the cosmological parameters and other data that have been used in the routine to the output:\nfid = 1;\nfprintf(fid, '\\n');\nfprintf(fid, 'the redshift at decoupling (maximum of the visibility function) = %g\\n', dt.zdec);\nfprintf(fid, 'the thickness of the decoupling surface (half width of vsb in redshift) = %g\\n', dt.tds);\nfprintf(fid, 'the age of the universe at decoupling = %g kyear\\n', dt.tdec);\nfprintf(fid, 'the age of the universe at reionisation = %g kyear\\n', dt.tri);\nfprintf(fid, 'the current age of the universe = %g Gyear\\n', dt.trc);\nfprintf(fid, '\\n');\nfprintf(fid, 'the conformal distance at decoupling = %g Mpc\\n', dt.etadec);\nfprintf(fid, 'the thickness of the decoupling surface (half width of vsb in redshift) = %g Mpc\\n', trs);\nfprintf(fid, 'the number of time integration points over the thickness of the decoupling surface = %g\\n', 2*nphw);\nfprintf(fid, '\\n');\nfprintf(fid, 'the cosmological parameter values used in the routine are :\\n');\nfprintf(fid, 'the density fluctuation at the horizon = %g\\n', dha);\nfprintf(fid, 'the amplitude correction (at l=10) = %g\\n', c1);\nfprintf(fid, 'total omega (omt) = %g\\n', omt);\nfprintf(fid, 'dark matter omega = %g\\n', om);\nfprintf(fid, 'baryon omega = %g\\n', omb);\nfprintf(fid, 'Hubble factor = %g\\n', h);\nfprintf(fid, 'spectral density index = %g\\n', nprimtilt);\nfprintf(fid, 'optical depth at reionisation = %g\\n', tauri);\nfprintf(fid, 'sigma8, rms mass overdensity sampled with a sphere of 8 Mpc/h = %g\\n', sig8);\nfprintf(fid, ['in the figures we compare the results with ', bmark, '\\n'])\nfprintf(fid, 'the minima in the temperature spectrum are at: ')\nfprintf(fid, '%g, ', lmin1)\nfprintf(fid, '\\n')\nfprintf(fid, 'the maxima in the temperature spectrum are at: ')\nfprintf(fid, '%g, ', lmax1)\nfprintf(fid, '\\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/8491-cmbaccur/cmbaccur.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49751942329354}} {"text": "classdef MLSSolver < pf2odfSolver\n% \n% The class MLSSolver implements the modified least squares solver for\n% reconstructing an ODF from arbitrarily scattered pole figure intensities.\n% The resulting ODF is represented as a weighted sum of unimodal\n% components. The shape and the number of component centers can be\n% specified. The algorithm is explained in detail in *A novel pole figure\n% inversion method: specification of the MTEX algorithm*, Hielscher,\n% Schaeben: J. of Appl. Cryst., 41(6), 2008.\n%\n% Syntax\n%\n% solver = MLSSolver(pf,'resolution',5*degree,'halfwidth',7.5*degree);\n% [odf,alpha] = solver.calcODF;\n%\n% Class Properties\n% psi - @SO3Kernel describing the shape of the unimodal components\n% S3G - the centers of the unimodal components as @SO3Grid in orientation space\n% c - weighting coefficients to the unimodal components\n% weights - \n% zrm - @zeroRangeMethod\n% ghostCorrection - whether to use ghost correction\n% iterMax - max number of iterations\n% iterMin - min number of iterations\n%\n% Dependent Class Properties\n% odf - @SO3Fun the reconstructed ODF\n%\n% See also\n% PoleFigureTutorial PoleFigure2ODFAmbiguity PoleFigure2ODFGhostCorrection\n\n properties\n psi % SO3Kernel function\n S3G % SO3Grid\n c % current coefficients\n c0 % constant portion\n weights % cell\n zrm % zero range method\n ghostCorrection = 1\n iterMax = 10; % max number of iterations\n iterMin = 5; % max number of iterations\n lambda = 0; % regularisation parameter\n RM = []; % regularization matrix\n end\n \n properties (Access = private)\n nfft_gh % list of nfft plans\n nfft_r % list of nfft plans\n A % legendre coefficients of the kernel function\n refl % cell\n u\n a\n alpha\n end\n \n properties (Dependent = true)\n odf % the reconstructed @SO3Fun\n end\n \n methods\n function solver = MLSSolver(pf,varargin)\n % constructor\n \n if nargin == 0, return; end\n \n % ensure intensities are non negative\n %solver.pf = unique(max(pf,0));\n solver.pf = max(pf,0);\n\n % normalize very different polefigures\n mm = max(pf.intensities(:));\n\n for i = 1:pf.numPF\n if mm > 5*max(pf.allI{i}(:))\n pf.allI{i} = pf.allI{i} * mm/5/max(pf.allI{i}(:));\n end\n end\n \n % generate discretization of orientation space\n solver.S3G = getClass(varargin,'SO3Grid');\n if isempty(solver.S3G)\n if pf.allR{1}.isOption('resolution')\n res = pf.allR{1}.resolution;\n else\n res = 5*degree;\n end\n res = get_option(varargin,'resolution',res);\n solver.S3G = equispacedSO3Grid(solver.pf.CS,solver.pf.SS,'resolution',res);\n end\n \n % zero range method\n if check_option(varargin,{'ZR','zero_range','zeroRange'})\n solver.zrm = zeroRangeMethod(solver.pf);\n end\n \n % get kernel\n psi = SO3DeLaValleePoussinKernel('halfwidth',...\n get_option(varargin,{'HALFWIDTH','KERNELWIDTH'},solver.S3G.resolution,'double'));\n solver.psi = getClass(varargin,'SO3Kernel',psi);\n \n % get other options\n solver.iterMin = get_option(varargin,'iterMin',solver.iterMin);\n solver.iterMax = get_option(varargin,'iterMax',solver.iterMax);\n \n % start vector\n solver.c = get_option(varargin,'C0',[]);\n \n % ghost correction\n solver.ghostCorrection = ~check_option(varargin,'noGhostCorrection');\n\n % compute quadrature weights\n if numProper(solver.SS) == 1\n solver.weights = cellfun(@(r) calcQuadratureWeights(r),solver.pf.allR,'UniformOutput',false);\n else\n solver.weights = num2cell(1./length(pf,[]));\n end\n \n % regularisation\n solver.lambda = get_option(varargin,'regularisation',0);\n \n end\n\n function delete(solver)\n % destructor\n\n % free all nfft plans\n for i = 1:length(solver.nfft_gh)\n nfsftmex('finalize',solver.nfft_gh(i));\n end\n\n for i = 1:length(solver.nfft_r)\n nfsftmex('finalize',solver.nfft_r(i));\n end\n\n end\n \n function odf = get.odf(solver)\n if solver.c0 > 0.99\n odf = SO3FunHarmonic(1,solver.CS, solver.SS);\n else\n odf = SO3FunRBF(solver.S3G,solver.psi,...\n (1-solver.c0)*solver.c./sum(solver.c), solver.c0);\n end \n end\n \n end\n \n methods (Static = true)\n \n function check\n \n cs = crystalSymmetry('222');\n odf = unimodalODF(orientation.id(cs));\n r = equispacedS2Grid('upper','antipodal','resolution',5*degree);\n h = Miller({1,0,0},{1,1,1},{1,1,0},cs);\n pf = calcPoleFigure(odf,h,r);\n odf = calcODF(pf)\n \n plotPDF(odf,h)\n plotFibre(odf,fibre.alpha(cs))\n \n mtexdata dubna\n tic\n solver = MLSSolver;\n solver.pf = pf;\n solver.S3G = equispacedSO3Grid(pf.CS,'resolution',2.5*degree);\n solver.psi = SO3DeLaValleePoussinKernel('halfwidth',2.5*degree);\n solver.weights = repcell(1,numPF(pf),1);\n solver.c = ones(length(solver.S3G),1) ./ length(solver.S3G);\n \n solver.init\n odf = solver.calcODF;\n delete(solver);\n toc\n \n end\n \n end\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/PoleFigureAnalysis/@MLSSolver/MLSSolver.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49751942329354}} {"text": "function bvalfit() \n % bvalfit Calculates Freq-Mag functions (b-value) for two time-segments\n %\n % Calculates Freq-Mag functions (b-value) for two time-segments\n % finds best fit to the foreground for a modified background\n % assuming a change in time of the following types:\n % Mnew = Mold + d , i.e. Simple magnitude shift\n % Mnew = c*Mold + d , i.e. Mag stretch plus shift\n % Nnew = fac*Nold , i.e. Rate change (N = number of events)\n % R. Zuniga IGF-UNAM/GI-UAF 6/94\n % Rev. 4/2001\n \n ZG=ZmapGlobal.Data; % used by get_zmap_globals\n \n %TODO DELETE THIS -> Z TOOL REMOVE COMPARE TWO RATES(FIT)\n \n \n global p\n \n report_this_filefun();\n \n % This is the info window text\n %\n ttlStr='Comparing Seismicity rates ';\n hlpStr1map= ...\n [' '\n ' To be Implemented '\n ' '];\n \n \n if ic == 0\n format short;\n fac = 1.0;\n \n bvfig = figure;\n set(bvfig,'Units','normalized','NumberTitle','off','Name','b-value curves');\n set(bvfig,'pos',[ 0.435 0.3 0.5 0.5])\n \n if isempty(ZG.newcat)\n ZG.newcat = a;\n end\n maxmag = max(ZG.newcat.Magnitude);\n mima = min(ZG.newcat.Magnitude);\n if mima > 0\n mima = 0 ;\n end\n [t0b, teb] = bounds(ZG.newcat.Date) ;\n n = ZG.newcat.Count;\n tdiff = round(teb - t0b);\n \n % number of mag units\n nmagu = (maxmag-mima*10)+1;\n \n td12 = t2p(1) - t1p(1);\n td34 = t4p(1) - t3p(1);\n \n l = ZG.newcat.Date > t1p(1) & ZG.newcat.Date < t2p(1) ;\n backg = ZG.newcat.subset(l);\n [bval,xt2] = hist(backg(:,6),(mima:0.1:maxmag));\n bval = bval/td12; % normalization\n bvalsum = cumsum(bval); % N for M <=\n bvalsum3 = cumsum(bval(end:-1:1)); % N for M >= (counted backwards)\n magsteps_desc = (maxmag:-0.1:mima);\n [cumux, xt] = hist(ZG.newcat.Date(l),t1p(1):days(ZG.bin_dur):t2p(1));\n \n l = ZG.newcat.Date > t3p(1) & ZG.newcat.Date < t4p(1) ;\n foreg = ZG.newcat.subset(l);\n bval2 = histogram(foreg(:,6),(mima:0.1:maxmag));\n bval2 = bval2/td34; % normallization\n bvalsum2 = cumsum(bval2);\n bvalsum4 = cumsum(bval2(end:-1:1));\n [cumux2, xt] = hist(ZG.newcat.Date(l),t3p(1):days(ZG.bin_dur):t4p(1));\n mean1 = mean(cumux);\n mean2 = mean(cumux2);\n var1 = cov(cumux);\n var2 = cov(cumux2);\n zscore = (mean1 - mean2)/(sqrt(var1/length(cumux)+var2/length(cumux2)));\n \n backg_be = log10(bvalsum);\n backg_ab = log10(bvalsum3);\n foreg_be = log10(bvalsum2);\n foreg_ab = log10(bvalsum4);\n \n orient landscape\n rect = [0.2, 0.2, 0.70, 0.70]; % plot Freq-Mag curves\n axes('position',rect)\n semilogy(magsteps_desc,bvalsum3,'om')\n set(gca,'NextPlot','add')\n semilogy(magsteps_desc,bvalsum4,'xb')\n \n te1 = max([bvalsum bvalsum2 bvalsum4 bvalsum3]);\n te1 = te1 - 0.2*te1;\n title([file1 ' o: ' num2str(t1p(1)) ' - ' num2str(t2p(1)) ' x: ' num2str(t3p(1)) ' - ' num2str(t4p(1)) ],'FontSize',ZmapGlobal.Data.fontsz.s,'FontWeight','bold')\n \n xlabel('Magnitude','FontSize',ZmapGlobal.Data.fontsz.s,'FontWeight','bold')\n ylabel('Cum. Number -normalized','FontSize',ZmapGlobal.Data.fontsz.s,'FontWeight','bold')\n % find b-values;\n set(gca,'box','on',...\n 'SortMethod','childorder','TickDir','out','FontWeight',...\n 'bold','FontSize',ZmapGlobal.Data.fontsz.s,'Linewidth',1.2)\n \n figure(mess);\n clf;\n cla;\n set(gcf,'Name','Magnitude selection ');\n set(gca,'visible','off');\n txt5 = text('Position',[.01 0.99 0 ],...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String','Please select two magnitudes to be used');\n txt1 = text('Position',[.01 0.84 0 ],...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String','in the calculation of straight line fit i.e.');\n txt2 = text('Position',[.01 0.66 0 ],...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String','b value of BACKGROUND (o)');\n \n figure(bvfig);\n seti = uicontrol(...\n 'Units','normal','Position',[.4 .01 .2 .05],...\n 'String','Select Mag1 ');\n \n pause(1)\n \n M1b = ginput(1);\n tx1 = text( M1b(1),M1b(2),['M1'] );\n set(seti,'String','Select Mag2');\n \n pause(0.1)\n \n M2b = ginput(1);\n tx2 = text( M2b(1),M2b(2),['M2'] );\n \n pause(0.1)\n delete(seti)\n \n ll = magsteps_desc > M1b(1) & magsteps_desc < M2b(1);\n x = magsteps_desc(ll);\n y = backg_ab(ll);\n p = polyfit(x,y,1); % fit a line to background\n f = polyval(p,x);\n f = 10.^f;\n set(gca,'NextPlot','add')\n semilogy(x,f,'r') % plot linear fit to backg\n r = corrcoef(x,y);\n r = r(1,2);\n std_backg = std(y - polyval(p,x)); % standard deviation of fit\n \n figure(mess);\n clf;\n cla;\n set(gcf,'Name','Magnitude selection ');\n set(gca,'visible','off');\n txt5 = text(...\n 'Position',[.01 0.99 0 ],...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String','Please select two magnitudes to be used');\n txt1 = text('Position',[.01 0.84 0 ],...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String','in the calculation of straight line fit i.e.');\n txt2 = text(...\n 'Position',[.01 0.66 0 ],...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String','b value of FOREGROUND (x)');\n \n figure(bvfig);\n seti = uicontrol('Units','normal',...\n 'Position',[.4 .01 .2 .05],'String','Select Mag1 ');\n \n pause(1)\n\n M1f = [];\n M1f = ginput(1);\n tx3 = text( M1f(1),M1f(2),['M1'] )\n set(seti','String','Select Mag2');\n \n pause(0.1)\n \n M2f = [];\n M2f = ginput(1);\n tx4 = text( M2f(1),M2f(2),['M2'] )\n \n pause(0.1)\n delete(seti)\n \n l = magsteps_desc > M1f(1) & magsteps_desc < M2f(1);\n x = magsteps_desc(l);\n y = foreg_ab(l);\n pp = polyfit(x,y,1);\n % fit a line to foreground\n f = polyval(pp,x);\n f = 10.^f;\n semilogy(x,f,'r') % plot fit to foreg\n rr = corrcoef(x,y);\n rr = rr(1,2);\n std_foreg = std(y - polyval(pp,x)); % standard deviation of fit\n \n figure(mess);\n clf\n set(gca,'visible','off')\n set(gcf,'Units','normalized','pos',[ 0.03 0.1 0.4 0.7])\n set(gcf,'Name','Compare Results');\n orient tall\n te = text(0.,0.99, [' Catalogue : ' file1]) ;\n set(te,'FontSize',ZmapGlobal.Data.fontsz.s);\n stri = [ 'Background (o): ' num2str(t1p(1)) ' to ' num2str(t2p(1)) ];\n te = text(0.01,0.93, stri) ;\n set(te,'FontSize',ZmapGlobal.Data.fontsz.s);\n aa_ = p(2) *1000.0;\n aa_ = round(aa_);\n aa_ = aa_/1000.0;\n bb = p(1) *1000.0;\n bb = round(bb);\n bb = bb/1000.0; % round to 0.001\n stri = [' Log N = ' num2str(aa_) num2str(bb) '*M ' ];\n te = text(0.01,0.88, stri) ;\n set(te,'FontSize',ZmapGlobal.Data.fontsz.s);\n stri = [ 'Foreground (x): ' num2str(t3p(1)) ' to ' num2str(t4p(1)) ];\n te = text(0.01,0.83, stri) ;\n set(te,'FontSize',ZmapGlobal.Data.fontsz.s);\n aa_ = pp(2) *1000.0;\n aa_ = round(aa_);\n aa_ = aa_/1000.0;\n bb = pp(1) *1000.0;\n bb = round(bb);\n bb = bb/1000.0; % round to 0.001\n stri = [' Log N = ' num2str(aa_) num2str(bb) '*M '];\n te = text(0.01,0.78, stri) ;\n set(te,'FontSize',ZmapGlobal.Data.fontsz.s);\n disp([' Correlation coefficient for background = ', num2str(r) ]); \n disp([' Correlation coefficient for foreground = ', num2str(rr) ]);\n % find simple shift\n % first find Mmin ( M for which the background relation\n % departs from straight line by more than std )\n ld = abs(backg_ab - polyval(p,magsteps_desc)) <= std_backg;\n [min_backg, ldb] = min(magsteps_desc(ld)); % Mmin of background\n n1 = backg_ab(ld);\n n1 = n1(ldb); % Cum number for Mmin background\n magi = (n1 - pp(2))/pp(1) % magi is intercept of n1 with foreground linear fit\n dM = magi - min_backg; % magnitude shift\n ld = abs(foreg_ab - polyval(pp,magsteps_desc)) <= std_foreg;\n [min_foreg, ldf] = min(magsteps_desc(ld)); % min_foreg is Mmin of foreground\n disp([' Mmin for background = ', num2str(min_backg) ]); \n disp([' Mmin for foreground = ', num2str(min_foreg) ]);\n stri = [ 'Minimum magnitude for Background = ' num2str(min_backg) ];\n te = text(0.01,0.73, stri) ;\n set(te,'FontSize',ZmapGlobal.Data.fontsz.s);\n stri = [ 'Minimum magnitude for Foreground = ' num2str(min_foreg) ];\n te = text(0.01,0.68, stri) ;\n set(te,'FontSize',ZmapGlobal.Data.fontsz.s);\n stri = ['Z score between both rates: '];\n te = text(0.01,0.63, stri) ;\n set(te,'FontSize',ZmapGlobal.Data.fontsz.s);\n stri = [' Z = ' num2str(zscore) ];\n te = text(0.01,0.58, stri) ;\n set(te,'FontSize',ZmapGlobal.Data.fontsz.s);\n dM = (round(dM *10.0))/10; % round to 0.1\n backg_new = [backg(:,1:5), backg(:,6)+dM, backg(:,7)]; % add shift\n \n [bvalN,xt2] = hist(backg_new(:,6),(mima:0.1:maxmag));\n bvalN = bvalN/td12; % normalize\n bvalsumN = cumsum(bvalN);\n bvalsum3N = cumsum(bvalN(end:-1:1));\n backg_beN = log10(bvalsumN);\n backg_abN = log10(bvalsum3N);\n \n res = (sum((bvalN - bval2).^2)/length(bval2))^0.5 ; % residual in histograms\n %%disp(['Average residual of simple shift = ', num2str(res)]);\n \n figure(mess);\n stri = [ 'Suggested single magnitude shift (d):']\n te = text(0.01,0.50, stri) ;\n set(te,'FontSize',ZmapGlobal.Data.fontsz.s,'FontWeight','bold');\n stri = ['Mx = Mo + (', num2str(dM),')']\n te = text(0.01,0.45, stri) ;\n set(te,'FontSize',ZmapGlobal.Data.fontsz.s,'FontWeight','bold');\n % compute magnitude stretch and shift\n pause(0.1)\n \n mf = p(1)/pp(1); % factor is calculated from ratio of b values\n mf = (round(mf *100.0))/100.0; % round to 0.01\n dM = -mf*(pp(2) - p(2))/p(1); % find shift by diff of zero ordinates\n dM = (round(dM *100.0))/100.0; % round to 0.01\n stri = [ 'Linear Mag correction (stretch, c, and shift, d):' ];\n te = text(0.01,0.38, stri) ;\n set(te,'FontSize',ZmapGlobal.Data.fontsz.s,'FontWeight','bold');\n stri = [ 'Mx = ',num2str(mf), '* Mo + (', num2str(dM),')' ];\n te = text(0.01,0.33, stri) ;\n set(te,'FontSize',ZmapGlobal.Data.fontsz.s,'FontWeight','bold');\n set(gca,'NextPlot','add')\n end % if ic\n \n if ic == 0 | ic == 2\n \n figure(bvfig);\n if ic == 2, clf, end\n bvalsumN = [ ];\n bvalsum3N = [ ];\n % Modify Magnitudes\n backg_new = [backg(:,1:5), (mf*backg(:,6))+dM, backg(:,7)];\n \n [bvalN,xt2] = hist(backg_new(:,6),(mima:0.1:maxmag));\n bvalN = bvalN/td12; % normalize\n bvalsumN = cumsum(bvalN);\n bvalsum3N = cumsum(bvalN(end:-1:1));\n backg_beN = log10(bvalsumN);\n backg_abN = log10(bvalsum3N);\n \n % residual in histograms\n res = (sum((bvalN - bval2).^2)/length(bval2))^0.5 ;\n \n % find rate increase_decrease\n if ic ==0 |ic ==1\n rat = [ ];\n rat = bval2/bvalN; % by mean of ratios\n l = 1 - (isnan(rat) + isinf(rat));\n fac1 = mean(rat(l));\n fac1 = fac1 *100.0;\n fac1 = round(fac1);\n fac1 = fac1/100.0; % round to 0.01\n fac = fac1;\n end % if ic\n \n ind = 0; % find minimum magnitude for the rate change\n resm = [ ];\n if ic ==0\n fac = 1.0 ;\n end\n bvalN = bvalN*fac ; % apply rate to all data\n \n bvalsumN = cumsum(bvalN);\n bvalsum3N = cumsum(bvalN(end:-1:1));\n backg_beN = log10(bvalsumN);\n backg_abN = log10(bvalsum3N);\n \n magi = magi *10.0;\n magi = round(magi);\n magi = magi/10.0; % round to 0.1\n % residual in histograms\n res = (sum((bvalN - bval2).^2)/length(bval2))^0.5 ;\n \n figure(mess);\n if ic == 0 | ic == 1\n stri = [ 'Suggested rate change (Nx = fac*No): \\newline fac = ' num2str(fac1) ];\n te = text(0.01,0.27, stri) ;\n set(te,'FontSize',ZmapGlobal.Data.fontsz.s,'Visible','on');\n end % if ic\n magis = maxmag;\n \n uicontrol('Units','normal','Position',[.88 .9 .11 .06],'String','Print ', 'callback',@callbackfun_001)\n uicontrol('Units','normal','Position',[.88 .80 .11 .06],'String','Close ', 'callback',@callbackfun_002)\n \n freq_field1=uicontrol('Style','edit',...\n 'Position',[.30 .16 .13 .07],...\n 'Units','normalized','String',num2str(dM),...\n 'callback',@callbackfun_003);\n \n freq_field2=uicontrol('Style','edit',...\n 'Position',[.75 .16 .13 .07],...\n 'Units','normalized','String',num2str(mf),...\n 'callback',@callbackfun_004);\n \n freq_field3=uicontrol('Style','edit',...\n 'Position',[.30 .05 .13 .07],...\n 'Units','normalized','String',num2str(fac),...\n 'callback',@callbackfun_005);\n \n txt1 = text(...\n 'Color',[0 0 0 ],...\n 'Position',[.01 0.11 0 ],...\n 'FontSize',ZmapGlobal.Data.fontsz.s ,...\n 'String','Shift (d)');\n \n txt2 = text(...\n 'Color',[0 0 0 ],...\n 'Position',[.44 0.11 0 ],...\n 'FontSize',ZmapGlobal.Data.fontsz.s ,...\n 'String',' Stretch factor (c)');\n \n txt3 = text(...\n 'Color',[0 0 0 ],...\n 'Position',[.01 0.0 0 ],...\n 'FontSize',ZmapGlobal.Data.fontsz.s ,...\n 'String','Rate factor');\n \n go_button=uicontrol('Style','Pushbutton',...\n 'Position',[.52 .01 .10 .07 ],...\n 'Units','normalized',...\n 'callback',@callbackfun_006,...\n 'String','Go');\n res = bval2 - bvalN ;\n \n close(bvfig)\n % Find out if figure already exists and plot results of fit\n %\n bvfig=findobj('Type','Figure','-and','Name','Compare and fit two rates');\n \n ms3 = 5;\n \n %if isempty(bvfig)\n bvfig= figure_w_normalized_uicontrolunits( ...\n 'Name','Compare and fit two rates',...\n 'NumberTitle','off', ...\n 'backingstore','on',...\n 'Visible','on', ...\n 'Position',position_in_current_monitor(ZG.map_len(1), ZG.map_len(2)+200));\n \n \n uicontrol('Units','normal',...\n 'Position',[.0 .93 .08 .06],'String','Print ',...\n 'callback',@callbackfun_007)\n \n uicontrol('Units','normal',...\n 'Position',[.0 .75 .08 .06],'String','Close ',...\n 'callback',@callbackfun_008)\n \n uicontrol('Units','normal',...\n 'Position',[.0 .85 .08 .06],'String','Info ',...\n 'callback',@callbackfun_009)\n axis off\n %end % if figure exits\n \n %%figure(bvfig);\n delete(findobj(bvfig,'Type','axes'));\n % plot b-value plot\n %\n orient tall\n set(gcf,'PaperPosition',[2 1 5.5 7.5])\n rect = [0.20, 0.7, 0.70, 0.25]; % plot Freq-Mag curves\n axes('position',rect)\n set(gca,'NextPlot','add')\n figure(bvfig);\n set(gca,'NextPlot','add')\n pl = semilogy(magsteps_desc,bvalsum4,'xb');\n set(gca,'Yscale','log')\n set(gca,'NextPlot','add')\n set(pl,'MarkerSize',ms3)\n semilogy(magsteps_desc,bvalsum4,'-.b')\n pl = semilogy(magsteps_desc,bvalsum3N,'om');\n set(pl,'MarkerSize',ms3)\n semilogy(magsteps_desc,bvalsum3N,'m')\n te1 = max([bvalsum bvalsum2 bvalsum4 bvalsum3]);\n te1 = te1 - 0.2*te1;\n \n ylabel('Cum. rate/year','FontSize',ZmapGlobal.Data.fontsz.s,'FontWeight','bold')\n str = [ ' o: ' num2str(t1p(1),6) ' - ' num2str(t2p(1),4) ' x: ' num2str(t3p(1),6) ' - ' num2str(t4p(1),6) ];\n \n title(str,'FontSize',ZmapGlobal.Data.fontsz.s,'FontWeight','bold')\n % find b-values;\n set(gca,'box','on',...\n 'SortMethod','childorder','TickDir','out','FontWeight',...\n 'bold','FontSize',ZmapGlobal.Data.fontsz.s,'Linewidth',1.0)\n p1 = gca;\n \n \n % Plot histogram\n %\n \n rect = [0.20, 0.40 0.70, 0.25];\n axes('position',rect)\n pl = plot(xt2,bvalN,'om');\n set(pl,'MarkerSize',ms3,'LineWidth',1.0)\n set(gca,'NextPlot','add')\n pl = plot(xt2,bval2,'xb');\n set(pl,'MarkerSize',ms3,'LineWidth',1.0)\n pl = plot(xt2,bval2,'-.b');\n set(pl,'MarkerSize',ms3,'LineWidth',1.0)\n pl = plot(xt2,bvalN,'m');\n set(pl,'MarkerSize',ms3,'LineWidth',1.0)\n disp([' Summation: ' num2str(sum(bval-bval2))])\n v = axis;\n xlabel('Magnitude ','FontSize',ZmapGlobal.Data.fontsz.s,'FontWeight','bold')\n ylabel('rate/year','FontSize',ZmapGlobal.Data.fontsz.s,'FontWeight','bold')\n set(gca,'box','on',...\n 'SortMethod','childorder','TickDir','out','FontWeight',...\n 'bold','FontSize',ZmapGlobal.Data.fontsz.s,'Linewidth',1.0)\n \n uic = uicontrol('Units','normal','Position',[.35 .15 .30 .07],'String','Magnitude Signature? ', 'callback',@callbackfun_010);\n \n end % if ic\n \n clear rat bvalNN mean1 mean2 ld l ll txt1 txt2 txt3 txt4 M1b M2b M1f M2f tx1 tx2 tx3 tx4;\n ic = 0;\n format;\n \n \n function callbackfun_001(mysrc,myevt)\n\n callback_tracker(mysrc,myevt,mfilename('fullpath'));\n printdlg;\n end\n \n function callbackfun_002(mysrc,myevt)\n\n callback_tracker(mysrc,myevt,mfilename('fullpath'));\n \n end\n \n function callbackfun_003(mysrc,myevt)\n\n callback_tracker(mysrc,myevt,mfilename('fullpath'));\n dM=str2double(freq_field1.String);\n freq_field1.String=num2str(dM);\n end\n \n function callbackfun_004(mysrc,myevt)\n\n callback_tracker(mysrc,myevt,mfilename('fullpath'));\n mf=str2double(freq_field2.String);\n freq_field2.String=num2str(mf);\n end\n \n function callbackfun_005(mysrc,myevt)\n\n callback_tracker(mysrc,myevt,mfilename('fullpath'));\n fac=str2double(freq_field3.String);\n freq_field3.String=num2str(fac);\n end\n \n function callbackfun_006(mysrc,myevt)\n\n callback_tracker(mysrc,myevt,mfilename('fullpath'));\n ic = 2;\n bvalfit;\n end\n \n function callbackfun_007(mysrc,myevt)\n\n callback_tracker(mysrc,myevt,mfilename('fullpath'));\n printdlg;\n end\n \n function callbackfun_008(mysrc,myevt)\n\n callback_tracker(mysrc,myevt,mfilename('fullpath'));\n f1=gcf;\n f2=gpf;\n set(f1,'Visible','off');\n end\n \n function callbackfun_009(mysrc,myevt)\n\n callback_tracker(mysrc,myevt,mfilename('fullpath'));\n zmaphelp(ttlStr,hlpStr1map,hlpStr2map,hlpStr3map);\n end\n \n function callbackfun_010(mysrc,myevt)\n\n callback_tracker(mysrc,myevt,mfilename('fullpath'));\n delete(uic);\n synsig;\n end\n \nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/bvalfit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387956435735, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49751941568444674}} {"text": "function [f,g,H] = taylorModel(d,f,g,H,T)\n\np = length(d);\n\nfd3 = 0;\ngd2 = zeros(p,1);\nHd = zeros(p);\nfor t1 = 1:p\n for t2 = 1:p\n for t3 = 1:p\n fd3 = fd3 + T(t1,t2,t3)*d(t1)*d(t2)*d(t3);\n\n if nargout > 1\n gd2(t3) = gd2(t3) + T(t1,t2,t3)*d(t1)*d(t2);\n end\n\n if nargout > 2\n Hd(t2,t3) = Hd(t2,t3) + T(t1,t2,t3)*d(t1);\n end\n end\n\n end\nend\n\nf = f + g'*d + (1/2)*d'*H*d + (1/6)*fd3;\n\nif nargout > 1\n g = g + H*d + (1/2)*gd2;\nend\n\nif nargout > 2\n H = H + Hd;\nend\n\nif any(abs(d) > 1e5)\n % We want the optimizer to stop if the solution is unbounded\n g = zeros(p,1);\nend", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/minFunc_2012/minFunc/taylorModel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.49750892541268266}} {"text": "function varargout = slice(f)\n%SLICE Plots slices (cross sections) of a BALLFUN.\n% SLICE(F) creates a slice plot of the BALLFUN at x = 0, y = 0 and z = 0.\n%\n% See also BALLFUN/PLOT.\n\n% Copyright 2019 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Check if the function is empty\nif isempty(f)\n error('CHEBFUN:BALLFUN:slice:isempty','Function is empty.');\nend\n\n% Add a warning of the function is not real\nif (f.isReal == 0)\n warning('CHEBFUN:BALLFUN:slice:isReal','Function is not real, plotting the real part.');\nend\n\n% Is the plot currently being held?\nplotOnHold = ishold;\n% Default plotting options\ndefaultOpts = {'facecolor', 'interp','edgecolor', 'none'};\n\n% Define the size of f: \n[m,n,p] = size(f);\n\n% m >= 25 and n, p >= 28\nm = 25*(m < 25) + m*(m >= 25);\nn = 28*(n < 28) + n*(n>=28);\np = 28*(p < 28) + p*(p>=28);\n\n% Impose m = 1 [6] and n, p = 0 [4] to avoid errors in the plot\nm = m + mod(1-mod(m,6),6);\nn = n + mod(4-mod(n,4),4);\np = p + mod(4-mod(p,4),4);\n\n% Discretization points\nr = chebpts(m); r = r(floor(m/2)+1:end);\nlam = linspace(-pi,pi,n);\nth = linspace(0,pi,p);\n\n% Evaluate the function at x = 0, y < 0\nff = permute(fevalm(f,r,-pi/2,th),[1 3 2]);\nff = real(ff);\n% Plot the result\nh = surf(zeros(length(r),length(th)),-r*sin(th),r*cos(th),ff,defaultOpts{:});\n\nhold on\n\n% Evaluate the function at x = 0, y > 0\nff = permute(fevalm(f,r,pi/2,th),[1 3 2]);\nff = real(ff);\n% Plot the result\nsurf(zeros(length(r),length(th)),r*sin(th),r*cos(th),ff,defaultOpts{:})\n\n% Evaluate the function at y = 0, x < 0\nff = permute(fevalm(f,r,pi,th),[1 3 2]);\nff = real(ff);\n% Plot the result\nsurf(-r*sin(th),zeros(length(r),length(th)),r*cos(th),ff,defaultOpts{:})\n% Evaluate the function at y = 0, x > 0\nff = permute(fevalm(f,r,0,th),[1 3 2]);\nff = real(ff);\n% Plot the result\nsurf(r*sin(th),zeros(length(r),length(th)),r*cos(th),ff,defaultOpts{:})\n\n% Evaluate the function at z = 0\nff = fevalm(f,r,lam,pi/2);\nff = real(ff);\n% Plot the result\nsurf(r*cos(lam),r*sin(lam),zeros(length(r),length(lam)),ff,defaultOpts{:})\n\nif ~plotOnHold\n hold off;\nend\n\ncamlight('headlight');\nlighting phong;\nmaterial dull;\n\naxis([-1 1 -1 1 -1 1])\ndaspect([1 1 1])\n\nif ( nargout > 0 )\n varargout = { h }; \nend\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@ballfun/slice.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.49750164185203993}} {"text": "function [y] = spm_int_D(P,M,U)\n% integrates a MIMO bilinear system dx/dt = f(x,u) = A*x + B*x*u + Cu + D;\n% FORMAT [y] = spm_int_D(P,M,U)\n% P - model parameters\n% M - model structure\n% M.delays - sampling delays (s); a vector with a delay for each output\n% M.states - a vector of indices if M.x(:) to be used in updating df/dx\n% M.nsteps - increase number of time steps by this number (default = 1)\n%\n% U - input structure or matrix\n%\n% y - response y = g(x,u,P)\n%__________________________________________________________________________\n% Integrates the bilinear approximation to the MIMO system described by\n%\n% dx/dt = f(x,u,P) = A*x + u*B*x + C*u + D\n% y = g(x,u,P) = L*x;\n%\n% at v = M.ns is the number of samples [default v = size(U.u,1)]\n%\n% spm_int_D will also handle static observation models by evaluating\n% g(x,u,P). It will also handle timing delays if specified in M.delays\n%\n%--------------------------------------------------------------------------\n%\n% SPM solvers or integrators\n%\n% spm_int_ode: uses ode45 (or ode113) which are one and multi-step solvers\n% respectively. They can be used for any ODEs, where the Jacobian is\n% unknown or difficult to compute; however, they may be slow.\n%\n% spm_int_J: uses an explicit Jacobian-based update scheme that preserves\n% nonlinearities in the ODE: dx = (expm(dt*J) - I)*inv(J)*f. If the\n% equations of motion return J = df/dx, it will be used; otherwise it is\n% evaluated numerically, using spm_diff at each time point. This scheme is\n% infallible but potentially slow, if the Jacobian is not available (calls\n% spm_dx).\n%\n% spm_int_E: As for spm_int_J but uses the eigensystem of J(x(0)) to eschew\n% matrix exponentials and inversion during the integration. It is probably\n% the best compromise, if the Jacobian is not available explicitly.\n%\n% spm_int_B: As for spm_int_J but uses a first-order approximation to J\n% based on J(x(t)) = J(x(0)) + dJdx*x(t).\n%\n% spm_int_L: As for spm_int_B but uses J(x(0)).\n%\n% spm_int_U: like spm_int_J but only evaluates J when the input changes.\n% This can be useful if input changes are sparse (e.g., boxcar functions).\n% It is used primarily for integrating EEG models\n%\n% spm_int_D: Fast integrator that uses a bilinear approximation to the\n% Jacobian evaluated using spm_soreduce. This routine will also allow for\n% sparse sampling of the solution and delays in observing outputs. It is\n% used primarily for integrating fMRI models\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: spm_int_D.m 5667 2013-10-02 18:26:06Z karl $\n \n \n% convert U to U.u if necessary\n%--------------------------------------------------------------------------\nif ~isstruct(U), u.u = U; U = u; end\ntry, dt = U.dt; catch, U.dt = 1; end\n \n % number of times to sample (v) and number of microtime bins (u)\n%--------------------------------------------------------------------------\nu = size(U.u,1);\ntry, v = M.ns; catch, v = u; end\n\n\n% get expansion point\n%--------------------------------------------------------------------------\nx = [1; spm_vec(M.x)];\n \n% add [0] states if not specified\n%--------------------------------------------------------------------------\nif ~isfield(M,'f')\n M.f = inline('sparse(0,1)','x','u','P','M');\n M.n = 0;\n M.x = sparse(0,0);\nend\n \n\n \n% output nonlinearity, if specified\n%--------------------------------------------------------------------------\ntry\n g = fcnchk(M.g,'x','u','P','M');\ncatch\n g = inline('x','x','u','P','M');\n M.g = g;\nend\n \n% Bilinear approximation (1st order)\n%--------------------------------------------------------------------------\n[M0,M1,M2] = spm_soreduce(M,P);\nn = length(M2); % n states\nm = length(M1); % m inputs\n \n \n% delays\n%--------------------------------------------------------------------------\ntry\n D = max(round(M.delays/U.dt),1);\ncatch\n D = ones(M.l,1)*round(u/v);\nend\n \n% state-dependent effects to include during integration\n%--------------------------------------------------------------------------\ntry\n M2 = M2(M.states);\n n = length(M2);\nend\n\n% decrease integration time steps\n%--------------------------------------------------------------------------\ntry\n N = max(M.nsteps,1);\ncatch\n N = 1;\nend\n\n\n% Evaluation times (t) and indicator array for inputs (su) and output (sy)\n%==========================================================================\n \n% get times that the input changes\n%--------------------------------------------------------------------------\ni = [1 (1 + find(any(diff(U.u),2))')];\nsu = sparse(1,i,1,1,u);\n \n% get times that the response is sampled\n%--------------------------------------------------------------------------\ns = ceil([0:v - 1]*u/v);\nfor j = 1:M.l\n i = s + D(j);\n sy(j,:) = sparse(1,i,1:v,1,u);\nend\n \n% get (N) intervening times to evaluate\n%--------------------------------------------------------------------------\ni = ceil((0:(v - 1)*N)*u/v/N) + D(1);\nsx = sparse(1,i,1,1,u);\n \n% time in seconds\n%--------------------------------------------------------------------------\nt = find(su | any(sy,1) | sx);\nsy = full(sy(:,t));\ndt = [diff(t) 0]*U.dt;\n \n% Integrate\n%--------------------------------------------------------------------------\ny = zeros(M.l,v);\nJ = M0;\nU.u = full(U.u);\nfor i = 1:length(t)\n \n % input dependent changes in Jacobian\n %----------------------------------------------------------------------\n u = U.u(t(i),:);\n J = M0;\n for j = 1:m\n J = J + u(j)*M1{j};\n end\n \n % state dependent changes in Jacobian\n %----------------------------------------------------------------------\n for j = 1:n\n J = J + (x(j + 1) - M.x(j))*M2{j};\n end\n \n % output sampled\n %----------------------------------------------------------------------\n if any(sy(:,i))\n q = spm_unvec(x(2:end),M.x);\n q = spm_vec(feval(g,q,u,P,M));\n j = find(sy(:,i));\n s = sy(j(1),i);\n y(j,s) = q(j);\n end\n \n % compute updated states x = expm(J*dt)*x;\n %----------------------------------------------------------------------\n x = spm_expm(J*dt(i),x);\n \n % check for convergence\n %----------------------------------------------------------------------\n if norm(x,1) > 1e6, break, end\n \nend\ny = real(y');\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_int_D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4973996919166685}} {"text": "% OP_V_GRADP: assemble the matrix B = [b(i,j)], b(i,j) = (epsilon grad p_i, v_j).\n%\n% mat = op_v_gradp (spv, spp, msh, epsilon);\n% [rows, cols, values] = op_v_gradp (spv, spp, msh, epsilon);\n%\n% INPUT:\n% \n% spv: structure representing the space of vectorial trial functions (see sp_vector/sp_evaluate_col)\n% spp: structure representing the space of scalar test functions (see sp_scalar/sp_evaluate_col)\n% msh: structure containing the domain partition and the quadrature rule (see msh_cartesian/msh_evaluate_col)\n% epsilon: physical parameter\n%\n% OUTPUT:\n%\n% mat: assembled matrix\n% rows: row indices of the nonzero entries\n% cols: column indices of the nonzero entries\n% values: values of the nonzero entries\n% \n% Copyright (C) 2009, 2010 Carlo de Falco\n% Copyright (C) 2011, 2017 Rafael Vazquez\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\nfunction varargout = op_v_gradp (spv, spp, msh, coeff)\n\n ndir = size (spp.shape_function_gradients, 1);\n \n if (ndir ~= spv.ncomp)\n error ('Inconsistent dimensions between the number of components of v and the gradient of p') \n end\n\n rows = zeros (msh.nel * spp.nsh_max * spv.nsh_max, 1);\n cols = zeros (msh.nel * spp.nsh_max * spv.nsh_max, 1);\n values = zeros (msh.nel * spp.nsh_max * spv.nsh_max, 1);\n\n jacdet_weights = msh.jacdet .* msh.quad_weights .* coeff;\n\n ncounter = 0;\n for iel = 1:msh.nel\n if (all (msh.jacdet(:, iel)))\n shpv_iel = reshape (spv.shape_functions(:, :, :, iel), spv.ncomp, msh.nqn, 1, spv.nsh_max);\n gradp_iel = reshape (spp.shape_function_gradients(:, :, :, iel), ndir, msh.nqn, spp.nsh_max, 1);\n\n jacdet_iel = reshape (jacdet_weights(:,iel), [1,msh.nqn,1,1]);\n \n jacdet_shpv = bsxfun (@times, jacdet_iel, shpv_iel);\n tmp1 = sum (bsxfun (@times, jacdet_shpv, gradp_iel), 1);\n elementary_values = reshape (sum (tmp1, 2), spp.nsh_max, spv.nsh_max);\n\n [rows_loc, cols_loc] = ndgrid (spp.connectivity(:,iel), spv.connectivity(:,iel));\n indices = rows_loc & cols_loc;\n rows(ncounter+(1:spv.nsh(iel)*spp.nsh(iel))) = rows_loc(indices);\n cols(ncounter+(1:spv.nsh(iel)*spp.nsh(iel))) = cols_loc(indices);\n values(ncounter+(1:spv.nsh(iel)*spp.nsh(iel))) = elementary_values(indices);\n ncounter = ncounter + spv.nsh(iel)*spp.nsh(iel);\n else\n warning ('geopdes:jacdet_zero_at_quad_node', 'op_v_gradp: singular map in element number %d', iel)\n end\n end\n\n if (nargout == 1 || nargout == 0)\n varargout{1} = sparse (rows(1:ncounter), cols(1:ncounter), ...\n values(1:ncounter), spp.ndof, spv.ndof);\n elseif (nargout == 3)\n varargout{1} = rows(1:ncounter);\n varargout{2} = cols(1:ncounter);\n varargout{3} = values(1:ncounter);\n else\n error ('op_v_gradp: wrong number of output arguments')\n end\n\nend\n\n\n%% COPY OF THE FIRST VERSION OF THE FUNCTION (MORE UNDERSTANDABLE)\n% function mat = op_v_gradp (spv, spp, msh, coeff)\n% \n% mat = spalloc(spp.ndof, spv.ndof, 1);\n% ndir = size (spp.shape_function_gradients, 1);\n% for iel = 1:msh.nel\n% if (all (msh.jacdet(:,iel)))\n% mat_loc = zeros (spp.nsh(iel), spv.nsh(iel));\n% for idof = 1:spp.nsh(iel)\n% ishg = reshape(spp.shape_function_gradients(:,:,idof,iel),ndir,[]);\n% for jdof = 1:spv.nsh(iel)\n% jshg = reshape(spv.shape_functions(:,:,jdof,iel),ndir,[]);\n% % The cycle on the quadrature points is vectorized\n% %for inode = 1:msh.nqn\n% mat_loc(idof, jdof) = mat_loc(idof, jdof) + ...\n% sum (msh.jacdet(:, iel) .* msh.quad_weights(:, iel) .* ...\n% sum (ishg .* jshg, 1).' .* coeff(:, iel));\n% %end \n% end\n% end\n% mat(spp.connectivity(:, iel), spv.connectivity(:, iel)) = ...\n% mat(spp.connectivity(:, iel), spv.connectivity(:, iel)) + mat_loc;\n% else\n% warning ('geopdes:jacdet_zero_at_quad_node', 'op_v_gradp: singular map in element number %d', iel)\n% end\n% end\n% \n% end", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/operators/op_v_gradp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.4972988704952897}} {"text": "function exact = p13_exact ( )\n\n%*****************************************************************************80\n%\n%% P13_EXACT returns the estimated integral for problem 13.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 July 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real EXACT, the estimated value of the integral.\n%\n exact = pi / 2.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/laguerre_test_int/p13_exact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.4972988669899628}} {"text": "function [x,options] = lsqnonneg_fast(C,d,options)\n%LSQNONNEG Linear least squares with nonnegativity constraints.\n%\n%function [x,resnorm,resid,exitflag,output,lambda] =\n%lsqnonneg(C,d,x0,options)\n%\n% X = LSQNONNEG(C,d) returns the vector X that minimizes NORM(C*X - d)\n% subject to X >= 0. C and d must be real.\n%\n% X = LSQNONNEG(C,d,X0) uses X0 as the starting point if all(X0 > 0);\n% otherwise the default is used. The default start point is the \n% origin (the default is used when X0==[] or when only two input \n% arguments are provided). \n%\n% X = LSQNONNEG(C,d,X0,OPTIONS) minimizes with the default optimization\n% parameters replaced by values in the structure OPTIONS, an argument\n% created with the OPTIMSET function. See OPTIMSET for details. Used\n% options are Display and TolX. (A default tolerance TolX of \n% 10*MAX(SIZE(C))*NORM(C,1)*EPS is used). \n% \n% [X,RESNORM] = LSQNONNEG(...) also returns the value of the squared 2-norm of \n% the residual: norm(C*X-d)^2.\n%\n% [X,RESNORM,RESIDUAL] = LSQNONNEG(...) also returns the value of the \n% residual: C*X-d.\n% \n% [X,RESNORM,RESIDUAL,EXITFLAG] = LSQNONNEG(...) returns an EXITFLAG that \n% describes the exit condition of LSQNONNEG. \n% If EXITFLAG is:\n% 1 then LSQNONNEG converged with a solution X.\n% 0 then the iteration count was exceeded. Increasing the tolerance\n% (OPTIONS.TolX) may lead to a solution.\n% \n% [X,RESNORM,RESIDUAL,EXITFLAG,OUTPUT] = LSQNONNEG(...) returns a structure\n% OUTPUT with the number of steps taken in OUTPUT.iterations and the type \n% of algorithm used in OUTPUT.algorithm.\n%\n% [X,RESNORM,RESIDUAL,EXITFLAG,OUTPUT,LAMBDA] = LSQNONNEG(...) returns \n% the dual vector LAMBDA where LAMBDA(i) <= 0 when X(i) is (approximately) 0 \n% and LAMBDA(i) is (approximately) 0 when X(i) > 0.\n% \n% See also LSCOV, SLASH.\n\n% L. Shure 5-8-87\n% Revised, 12-15-88,8-31-89 LS, 5-26-98 MAB.\n% Copyright (c) 1984-98 by The MathWorks, Inc.\n% $Revision: 1.6 $ $Date: 1998/08/25 15:18:02 $\n\n% Reference:\n% Lawson and Hanson, \"Solving Least Squares Problems\", Prentice-Hall, 1974.\n\nif nargin<3\n %disp('Calculating optimset');\n \n defaultopt = optimset('display','final','TolX','10*eps*norm(C,1)*length(C)');\n if ~isreal(C) || ~isreal(d), error('C and d must be real.'); end\n options = [];\n options = optimset(defaultopt,options);\n printtype = optimget(options,'display');\n tol = optimget(options,'tolx');\n \n % In case the defaults were gathered from calling: optimset('fminsearch'):\n c=C;\n if ischar(tol)\n tol = eval(tol);\n end\n \n switch printtype\n case {'none','off'}\n verbosity = 0;\n case 'iter'\n warning('''iter'' value not valid for ''Display'' parameter for lsqnonneg');\n verbosity = 2;\n case 'final'\n verbosity = 1;\n otherwise\n error('Bad value for options parameter: ''Display''');\n end\nend\ntol = optimget(options,'tolx');\nc=C;\nif ischar(tol)\n tol = eval(tol);\nend\n\n[m,n] = size(C);\nP = zeros(1,n);\nZ = 1:n;\nx = P';\n\nZZ=Z;\nresid = d-C*x;\nw = C'*(resid);\n\n% set up iteration criterion\nouteriter = 0;\niter = 0;\nitmax = 3*n;\nexitflag = 1;\n\n% outer loop to put variables into set to hold positive coefficients\nwhile any(Z) && any(w(ZZ) > tol)\n outeriter = outeriter + 1;\n [wt,t] = max(w(ZZ));\n t = ZZ(t);\n P(1,t) = t;\n Z(t) = 0;\n PP = find(P);\n ZZ = find(Z);\n nzz = size(ZZ);\n CP(1:m,PP) = C(:,PP);\n CP(:,ZZ) = zeros(m,nzz(2));\n z = pinv(CP)*d;\n z(ZZ) = zeros(nzz(2),nzz(1));\n % inner loop to remove elements from the positive set which no longer belong\n while any((z(PP) <= tol))\n iter = iter + 1;\n if iter > itmax\n if verbosity \n warnstr = sprintf('Exiting: Iteration count is exceeded, exiting LSQNONNEG.', ...\n '\\n','Try raising the tolerance (OPTIONS.TolX).');\n disp(warnstr);\n end\n exitflag = 0;\n output.iterations = outeriter;\n resnorm = sum(resid.*resid);\n x = z;\n lambda = w;\n return\n end\n QQ = find((z <= tol) & P');\n alpha = min(x(QQ)./(x(QQ) - z(QQ)));\n x = x + alpha*(z - x);\n ij = find(abs(x) < tol & P' ~= 0);\n Z(ij)=ij';\n P(ij)=zeros(1,length(ij));\n PP = find(P);\n ZZ = find(Z);\n nzz = size(ZZ);\n CP(1:m,PP) = C(:,PP);\n CP(:,ZZ) = zeros(m,nzz(2));\n z = pinv(CP)*d;\n z(ZZ) = zeros(nzz(2),nzz(1));\n end\n x = z;\n resid = d-C*x;\n w = C'*(resid);\nend\n\nlambda = w;\nresnorm = sum(resid.*resid);\noutput.iterations = outeriter;\noutput.algorithm = 'active-set using svd';\n\nverbosity =0;\n\nif verbosity > 0\n disp('Optimization terminated successfully.'); \nend\n\n", "meta": {"author": "zhouyuanzxcv", "repo": "Hyperspectral", "sha": "f32dcca86677f8d37596376f57e9c733058f8cff", "save_path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral", "path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral/Hyperspectral-f32dcca86677f8d37596376f57e9c733058f8cff/GMM_SantaBarbara/competing_methods/AAM/lsqnonneg_fast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.4970903936797587}} {"text": "function z = h2z(h);\n\n% Z = h2z(H)\n%\n% Hybrid to Admittance transformation\n% only for 2-by-2 matrices\n%\n% martie 27\n\nif h(2,2) == 0\n disp('correspondent admittance matrix non-existent');\nelse\nz(1,1) = h(1,1) - h(1,2)*h(2,1)/h(2,2);\nz(1,2) = h(1,2)/h(2,2);\nz(2,1) = -h(2,1)/h(2,2);\nz(2,2) = 1/h(2,2);\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/6080-s-parameter-toolbox-+-z-y-h-g-abcd-t/sbox/h2z.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672320414786, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49703234086919673}} {"text": "function [EB] = MB2EB(MB)\n% Convert computery things from megabytes to exabytes.\n% Chad A. Greene 2012\nEB = MB*2^-40 ;", "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/MB2EB.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4970224201171112}} {"text": "function [x, infos] = smu_nmf(V, rank, in_options)\n% Stochastic multiplicative update for non-negative matrix factorization (SMU-NMF) algorithm.\n%\n% Inputs:\n% matrix V\n% rank rank\n% options options\n% Output:\n% w solution of w\n% infos information\n%\n% \n% This file is part of NMFLibrary.\n%\n% Created by H.Kasai on Mar. 28, 2017\n%\n% Change log: \n%\n% Mar. 15, 2018 (Hiroyuki Kasai): Fixed algorithm. \n%\n% May. 20, 2019 (Hiroyuki Kasai): Added initialization module.\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.W_sub_mode = 'Precon';\n local_options.H_sub_mode = 'STD';\n local_options.accel = false;\n local_options.ls = false;\n local_options.precon = false;\n local_options.h_repeat = 1;\n local_options.rep_mode = 'fix';\n local_options.robust = false;\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 Wt = init_factors.W;\n H = init_factors.H; \n R = init_factors.R;\n\n % determine sub_mode \n if options.accel\n options.H_sub_mode = 'ACC';\n else\n if options.ls\n options.H_sub_mode = 'LS';\n else\n options.H_sub_mode = 'STD'; \n end\n options.h_repeat = 1;\n end \n \n if options.precon\n options.W_sub_mode = 'Precon';\n else\n options.W_sub_mode = 'STD';\n end \n\n % permute samples\n if options.permute_on\n perm_idx = randperm(n);\n else\n perm_idx = 1:n;\n end \n V = V(:,perm_idx);\n H = H(:,perm_idx); \n\n % initialize\n method_name = sprintf('SMU-NMF (%s,%s)', options.W_sub_mode, options.H_sub_mode);\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 if strcmp(options.rep_mode, 'adaptive')\n rhoh = 1+(m+m*rank)/(1*(rank+1));\n alpha = 2;\n delta = 0.01; \n end \n \n % store initial info\n clear infos;\n [infos, f_val, optgap] = store_nmf_info(V, Wt, H, R, options, [], epoch, grad_calc_count, 0);\n \n if options.verbose > 1\n fprintf('SMU-NMF (%s,%s): Epoch = 0000, cost = %.16e, optgap = %.4e\\n', options.W_sub_mode, options.H_sub_mode, f_val, optgap); \n end \n \n % set start time\n start_time = tic();\n\n % main outer 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 cnt = 0;\n \n % main inner loop\n for t = 1 : options.batch_size : n - 1\n cnt = cnt + 1;\n\n % retrieve vt and ht\n vt = V(:,t:t+options.batch_size-1);\n ht = H(:,t:t+options.batch_size-1);\n \n % uddate ht\n Wtv = Wt.' * vt;\n WtW = Wt.' * Wt;\n if strcmp(options.H_sub_mode, 'ACC')\n if strcmp(options.rep_mode, 'adaptive')\n gamma = 1; \n eps0 = 1; \n j = 1;\n rhoh_alpha = rhoh*alpha;\n %while j <= floor(1+rhoh*alpha) && gamma >= delta*eps0 \n while j <= rhoh_alpha && gamma >= delta*eps0 \n ht0 = ht;\n ht = ht .* (Wtv) ./ (WtW * ht);\n ht = ht + (htB (and B->A)\nt2 = 0.02; % Period B->C (abd C->B)\nperiod = 2*(t1+t2); % Time it takes to move to the right\nt = rem(current_time,period); % Time (moded out)\n\n% Cubic Interpolation Information\np1 = 0.25;\np2 = 0.925;\n\n% a COEFFICIENTS\na0 = 0; \na1 = 0; \na2 = 0; \na3 = 4.324324324324318;\n\n% b COEFFICIENTS\nb0 = 0.123456790123457;\nb1 = -1.481481481481478;\nb2 = 5.925925925925911;\nb3 = -3.576910243576897;\n\n% c COEFFICIENTS\nc0 = -16.777777777777700;\nc1 = 53.333333333333101;\nc2 = -53.333333333333101;\nc3 = 17.777777777777700;\n\n%\n% START THE INTERPOLATING BETWEEN STATES!\n% \nif t <= t1 % STATE A -> STATE B\n \n A = read_In_State('State_A.pts');\n B = read_In_State('State_B.pts');\n \n % Scaling time for appropriate use in interp. function so tTilde\\in[0,1]\n tTilde = (t/t1); \n \n % Evaluate Pieceise Cubic Interpolation Poly\n if tTilde<=p1\n gFUNC = a0 + a1*tTilde + a2*tTilde^2 + a3*tTilde^3; \n elseif tTilde<=p1+p2\n gFUNC = b0 + b1*tTilde + b2*tTilde^2 + b3*tTilde^3; \n else\n gFUNC = c0 + c1*tTilde + c2*tTilde^2 + c3*tTilde^3; \n end\n \n targets(:,2) = A(:,1) + gFUNC*( B(:,1) - A(:,1) );\n targets(:,3) = A(:,2) + gFUNC*( B(:,2) - A(:,2) );\n \nelseif t <= (t1+t2) % STATE B -> C\n \n B = read_In_State('State_B.pts');\n C = read_In_State('State_C.pts');\n \n % Scaling time for appropriate use in interp. function so tTilde\\in[0,1]\n tTilde = (t-t1)/t2; \n \n % Evaluate Pieceise Cubic Interpolation Poly\n if tTilde<=p1\n gFUNC = a0 + a1*tTilde + a2*tTilde^2 + a3*tTilde^3; \n elseif tTilde<=p1+p2\n gFUNC = b0 + b1*tTilde + b2*tTilde^2 + b3*tTilde^3; \n else\n gFUNC = c0 + c1*tTilde + c2*tTilde^2 + c3*tTilde^3; \n end\n \n targets(:,2) = B(:,1) + gFUNC * ( C(:,1) - B(:,1) );\n targets(:,3) = B(:,2) + gFUNC * ( C(:,2) - B(:,2) );\n \nelseif t <= (t1+2*t2) % STATE C -> B\n \n B = read_In_State('State_B.pts');\n C = read_In_State('State_C.pts');\n \n % Scaling time for appropriate use in interp. function so tTilde\\in[0,1]\n tTilde = (t-t1-t2)/(t2); \n \n % Evaluate Pieceise Cubic Interpolation Poly\n if tTilde<=p1\n gFUNC = a0 + a1*tTilde + a2*tTilde^2 + a3*tTilde^3; \n elseif tTilde<=p1+p2\n gFUNC = b0 + b1*tTilde + b2*tTilde^2 + b3*tTilde^3; \n else\n gFUNC = c0 + c1*tTilde + c2*tTilde^2 + c3*tTilde^3; \n end\n \n targets(:,2) = C(:,1) + gFUNC * ( B(:,1) - C(:,1) );\n targets(:,3) = C(:,2) + gFUNC * ( B(:,2) - C(:,2) );\n \nelse % STATE B -> A\n \n A = read_In_State('State_A.pts');\n B = read_In_State('State_B.pts');\n \n % Scaling time for appropriate use in interp. function so tTilde\\in[0,1]\n tTilde = (t-t1-2*t2)/(2*t2-2*t1); \n \n % Evaluate Pieceise Cubic Interpolation Poly\n if tTilde<=p1\n gFUNC = a0 + a1*tTilde + a2*tTilde^2 + a3*tTilde^3; \n elseif tTilde<=p1+p2\n gFUNC = b0 + b1*tTilde + b2*tTilde^2 + b3*tTilde^3; \n else\n gFUNC = c0 + c1*tTilde + c2*tTilde^2 + c3*tTilde^3; \n end\n \n targets(:,2) = B(:,1) + gFUNC * ( A(:,1) - B(:,1) );\n targets(:,3) = B(:,2) + gFUNC * ( A(:,2) - B(:,2) );\n \nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Reads in the # of vertex pts and all the vertex pts from the\n% .vertex file.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction PTS = read_In_State(struct_name)\n\n\nfilename = struct_name; %Name of file to read in\nfileID = fopen(filename);\n\n% Read in the file, use 'CollectOutput' to gather all similar data together\n% and 'CommentStyle' to to end and be able to skip lines in file.\nC = textscan(fileID,'%f %f','CollectOutput',1);\n\nfclose(fileID); %Close the data file.\n\nvertices = C{1}; %Stores all read in data in vertices (N+1,2) array\n\nPTS = vertices(1:end,1:2);\n", "meta": {"author": "nickabattista", "repo": "IB2d", "sha": "392d99c228cc801ff65766889c72e2e1492fe747", "save_path": "github-repos/MATLAB/nickabattista-IB2d", "path": "github-repos/MATLAB/nickabattista-IB2d/IB2d-392d99c228cc801ff65766889c72e2e1492fe747/matIB2d/Examples/Examples_Education/Interpolation/Moving_Circle/Cubic_Interp/update_Target_Point_Positions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.49683881304994276}} {"text": "% Eldar reconstruction\n\nN = 3; % Nth order nonuniform sampling\nTQ = 1; % Nyquist Period \nL=20; % Resolution factor for fraction delay\n\nT = [2*TQ 3*TQ 6*TQ]; % Decimation Periods\nK = 0.5*lcm(2*T(1), 2*T(2)); K = 0.5*lcm(2*K, 2*T(3))/TQ;\ncapT = K*TQ; M = capT./T;\ncapM = lcm(M(1), M(2)); capM = lcm(capM, M(3));\nexcess = ceil((K-1)/capM);\nmaxf = K/(excess*capM+1);\nTQ1 = maxf*TQ;\nK1 = K/maxf;\n\nML = 400; % number of slices\nw_c = 0.85;\nNS = 100; % Number of Sinusoids\n\nLF = capM*2*K1+1; %359,159,239 % min length of LF should be capM*2*K1\nn = -(LF-1)/2:1:(LF-1)/2;\nHd = firpm(LF-1,[0 w_c],[0 w_c*pi],'differentiator');\ndelayV = (LF-1)/2;\n\n\nstd = [1e-6 1e-5 1e-4 1e-3 1e-2 1e-1];%5*1e-1];\n\nserE = zeros(size(std));\n\nMCruns = 25;\nMCruns1 = 25;\n\nfor tt = 1:length(std)\n aa = 0;\n display(tt);\n for rrr = 1:MCruns1\n taus = [0 1.1+std(tt)*randn 2.2+std(tt)*randn]*TQ; \n if or(taus(2)==TQ,or(taus(2)==2*TQ,or(taus(3)==2*TQ,or(taus(2)==taus(3),taus(2)==taus(1)))))\n aa = aa+1;\n display(taus);\n continue;\n end\n \n tausI = sort([taus(1) taus(2) taus(3) T(1)+taus(1) T(2)+taus(2) 2*T(1)+taus(1)]);\n a = zeros(1,K);\n for p = 1:K\n a(p) = 1;\n for q = 1:K\n if q ~= p\n a(p) = a(p)/sin(pi*(tausI(p)-tausI(q))/capT);\n end;\n end;\n end;\n \n for pp = 1:MCruns;\n Frq = rand(1,NS)*w_c/2;\n Amp = rand(1,NS)/(sqrt(NS)*2);\n Phi = rand(1,NS)*2*pi;\n inputN = zeros(1,ML*K1);\n input = zeros(1,ML*K);\n for k = 1:NS\n inputN = inputN + Amp(k)*sin(2*pi*Frq(k)*(0:ML*K1-1)*TQ1+Phi(k));\n input = input + Amp(k)*sin(2*pi*Frq(k)*(0:ML*K-1)*TQ+Phi(k));\n end;\n end\n \n y = zeros(N,ML*K1);\n for p = 1:N\n tau = taus(p)+(0:ML*M(p)-1)*T(p);\n x1 = zeros(1,ML*M(p));\n for k = 1:NS\n x1 = x1 + Amp(k)*sin(2*pi*Frq(k)*tau+Phi(k));\n end;\n\n y1 = upsample(x1,K1);\n\n LFE = M(p)*capM*2*K1+1; %359,159,239 % min length of LF should be capM*2*K1\n nE = -(LFE-1)/2:1:(LFE-1)/2;\n h = sinc((nE/K1)-(taus(p)/T(p))).*kaiser_mine1(LFE,18,-K1*(taus(p)/T(p)));\n aaa = ones(1,M(p));\n bb = ones(M(p),LFE);\n for l = 1:M(p)\n for q = 1:N\n if q ~= p\n aaa(l) = aaa(l)*sin(pi*(taus(p)-taus(q)+(l-1)*T(p))/T(q));\n bb(l,:) = bb(l,:).*sin(pi*((nE*TQ1/M(p))-taus(q)+(l-1)*T(p))/T(q));\n end;\n end;\n bb(l,:) = bb(l,:)/aaa(l);\n end;\n\n bbb = zeros(M(p),LFE);\n bbn = zeros(M(p),LFE);\n for m = 1:M(p)\n for l = 1:M(p)\n bbb(l,:) = bb(l,:)*exp(1i*(2*pi/M(p))*(m-1)*(l-1));\n end\n bbb = sum(bbb,1);\n bbn(m,:) = bbb.*exp(1i*(2*pi/M(p))*(m-1)*nE);\n end;\n bbn = sum(bbn,1);\n bbn = bbn.*h/M(p);\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n y1 = conv(y1,bbn);\n delay = (length(h)-1)/2;\n y1 = y1(1+delay:M(p):end-delay);\n y(p,:) = y1;\n end;\n y = real(sum(y,1));\n x = inputN;\n y = y(160:end-60);\n x = x(160:end-60);\n serE(tt) = serE(tt)+20*log10(norm(x,2)/norm(y-x,2));\n end\nend\n\nserE = serE/(MCruns*(MCruns1-aa));\n\nplot(std,serE);\nxlabel('Standard Deviation (\\sigma)','fontsize',14,'fontweight','b');\nylabel('SNR in dB','fontsize',14,'fontweight','b');\ngrid on;box on;\nset(gca,'fontsize',14,'fontweight','b')", "meta": {"author": "yueyuzhao", "repo": "gyrophone", "sha": "aa816eec3d7a17d9e30ab7afa0d4b79ef0a7a82e", "save_path": "github-repos/MATLAB/yueyuzhao-gyrophone", "path": "github-repos/MATLAB/yueyuzhao-gyrophone/gyrophone-aa816eec3d7a17d9e30ab7afa0d4b79ef0a7a82e/SindhiPrabhu/eldar_n3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4968388078459679}} {"text": "% Copyright 2013 Oliver Johnson, Srikanth Patala\n% \n% This file is part of MisorientationMaps.\n% \n% MisorientationMaps 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% MisorientationMaps 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 MisorientationMaps. If not, see .\n\nfunction S=colormap222(v)\n\npts = reshape(double(v),[],3);\n\nk1 = sqrt(3)*max(pts,[],2)./(sum(pts,2) + 1*(sum(pts,2) == 0));\npts = [k1.*pts(:,1) k1.*pts(:,2) k1.*pts(:,3)];\n\n%%% Rotate Prism %%%%%%%%\ng1 = rotvec2mat([1,1,1,pi/4]);g2 = rotvec2mat([-1,1,0,acos(1/sqrt(3))]);\ng3 = rotvec2mat([0,0,1,-pi/3]);pts = pts*g1*g2*g3;pts(:,3)=pts(:,3)-1;\n\n%%%%%% Prism --> Cone %%%%%%%%%%%\nphi=atan2(pts(:,2),pts(:,1));maxphi = 2*pi; phi = mod(phi,maxphi);\nrfin = hypot(pts(:,1),pts(:,2)).*sin(pi/6+mod(phi,2*pi/3))./(sin(pi/6));\npts = [sqrt(1/2).*rfin.*cos(phi) sqrt(1/2).*rfin.*sin(phi) pts(:,3)];\n\n%%%%%% Cone --> Hemisphere %%%%%%\nr = sqrt(pts(:,1).^2 + pts(:,2).^2 + pts(:,3).^2);\nrad = sqrt(pts(:,1).^2 + pts(:,2).^2);\n\npts = [pts(:,1).*(rad - pts(:,3))./(r+1*(r==0)) ...\n pts(:,2).*(rad - pts(:,3))./(r+1*(r==0)) ...\n pts(:,3).*(rad - pts(:,3))./(r+1*(r==0))];\n\n%%%%% Hemisphere --> Sphere\n\nphi1 = atan2(pts(:,2),pts(:,1));phi1 = mod(phi1,2*pi);\nind1=find(phi1 < 2*pi/3 & phi1 > 0*pi/3);ind2=find(phi1 < 4*pi/3 & phi1 > 2*pi/3);\nind3=find(phi1 < 6*pi/3 & phi1 > 4*pi/3);ind = [ind1;ind2;ind3];\n\ng4 = rotvec2mat([0,0,1,pi/3]);g5 = rotvec2mat([0,0,1,pi]);g6 = rotvec2mat([0,0,1,5*pi/3]);\npts(ind1,:) = pts(ind1,:)*g4;pts(ind2,:) = pts(ind2,:)*g5;pts(ind3,:) = pts(ind3,:)*g6;\n\nphi2 = atan2(pts(ind,2),pts(ind,1));rad1 = hypot(pts(ind,2),pts(ind,1));\npts(ind,:) = [rad1.*cos(3*phi2/2) rad1.*sin(3*phi2/2) pts(ind,3)];\n\nmult = 1 + 1;\nphi4 = atan2(pts(ind,1),-pts(ind,3));rad4 = hypot(pts(ind,1),pts(ind,3));\npts(ind,:) = [rad4.*sin(mult*phi4) pts(ind,2) rad4.*-cos(mult*phi4)];\n\nphi3 = atan2(pts(ind,2),pts(ind,1));rad3 = hypot(pts(ind,2),pts(ind,1));\npts(ind,:) = [rad3.*cos(2*phi3/3) rad3.*sin(2*phi3/3) pts(ind,3)];\n\npts(ind1,:) = pts(ind1,:)*g4';pts(ind2,:) = pts(ind2,:)*g5';pts(ind3,:) = pts(ind3,:)*g6';\n\ng1 = rotvec2mat([0,0,1,pi/3]);\npts=pts*g1;\n\nS = hsvsphere(pts);\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/plotting/orientationColorKeys/@PatalaColorKey/private/colormap222.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695836, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4966681204783366}} {"text": "function b = generative_model(A,D,m,modeltype,modelvar,params,epsilon)\n%GENERATIVE_MODEL run generative model code\n%\n% B = GENERATIVE_MODEL(A,D,m,modeltype,modelvar,params)\n%\n% Generates synthetic networks using the models described in the study by\n% Betzel et al (2016) in Neuroimage.\n%\n% Inputs:\n% A, binary network of seed connections\n% D, Euclidean distance/fiber length matrix\n% m, number of connections that should be present in\n% final synthetic network\n% modeltype, specifies the generative rule (see below)\n% modelvar, specifies whether the generative rules are based on\n% power-law or exponential relationship\n% ({'powerlaw'}|{'exponential})\n% params, either a vector (in the case of the geometric\n% model) or a matrix (for all other models) of\n% parameters at which the model should be evaluated.\n% epsilon, the baseline probability of forming a particular\n% connection (should be a very small number\n% {default = 1e-5}).\n%\n% Output:\n% B, m x number of networks matrix of connections\n%\n%\n% Full list of model types:\n% (each model type realizes a different generative rule)\n%\n% 1. 'sptl' spatial model\n% 2. 'neighbors' number of common neighbors\n% 3. 'matching' matching index\n% 4. 'clu-avg' average clustering coeff.\n% 5. 'clu-min' minimum clustering coeff.\n% 6. 'clu-max' maximum clustering coeff.\n% 7. 'clu-diff' difference in clustering coeff.\n% 8. 'clu-prod' product of clustering coeff.\n% 9. 'deg-avg' average degree\n% 10. 'deg-min' minimum degree\n% 11. 'deg-max' maximum degree\n% 12. 'deg-diff' difference in degree\n% 13. 'deg-prod' product of degree\n%\n%\n% Example usage:\n%\n% load demo_generative_models_data\n%\n% % get number of bi-directional connections\n% m = nnz(A)/2;\n% \n% % get cardinality of network\n% n = length(A);\n% \n% % set model type\n% modeltype = 'neighbors';\n% \n% % set whether the model is based on powerlaw or exponentials\n% modelvar = [{'powerlaw'},{'powerlaw'}];\n% \n% % choose some model parameters\n% params = [-2,0.2; -5,1.2; -1,1.5];\n% nparams = size(params,1);\n% \n% % generate synthetic networks\n% B = generative_model(Aseed,D,m,modeltype,modelvar,params);\n%\n% % store them in adjacency matrix format\n% Asynth = zeros(n,n,nparams);\n% for i = 1:nparams; \n% a = zeros(n); a(B(:,i)) = 1; a = a + a'; \n% Asynth(:,:,i) = a; \n% end\n%\n% Reference: Betzel et al (2016) Neuroimage 124:1054-64.\n%\n% Richard Betzel, Indiana University/University of Pennsylvania, 2015\n\nif ~exist('epsilon','var')\n epsilon = 1e-5;\nend\n\nn = length(D);\nnparams = size(params,1);\nb = zeros(m,nparams);\n\nswitch modeltype\n \n case 'clu-avg'\n clu = clustering_coef_bu(A);\n Kseed = bsxfun(@plus,clu(:,ones(1,n)),clu')/2;\n for iparam = 1:nparams\n eta = params(iparam,1);\n gam = params(iparam,2);\n b(:,iparam) = fcn_clu_avg(A,Kseed,D,m,eta,gam,modelvar,epsilon);\n end\n \n case 'clu-diff'\n clu = clustering_coef_bu(A);\n Kseed = abs(bsxfun(@minus,clu(:,ones(1,n)),clu'));\n for iparam = 1:nparams\n eta = params(iparam,1);\n gam = params(iparam,2);\n b(:,iparam) = fcn_clu_diff(A,Kseed,D,m,eta,gam,modelvar,epsilon);\n end\n \n case 'clu-max'\n clu = clustering_coef_bu(A);\n Kseed = bsxfun(@max,clu(:,ones(1,n)),clu');\n for iparam = 1:nparams\n eta = params(iparam,1);\n gam = params(iparam,2);\n b(:,iparam) = fcn_clu_max(A,Kseed,D,m,eta,gam,modelvar,epsilon);\n end\n \n case 'clu-min'\n clu = clustering_coef_bu(A);\n Kseed = bsxfun(@min,clu(:,ones(1,n)),clu');\n for iparam = 1:nparams\n eta = params(iparam,1);\n gam = params(iparam,2);\n b(:,iparam) = fcn_clu_min(A,Kseed,D,m,eta,gam,modelvar,epsilon);\n end\n \n case 'clu-prod'\n clu = clustering_coef_bu(A);\n Kseed = clu*clu';\n for iparam = 1:nparams\n eta = params(iparam,1);\n gam = params(iparam,2);\n b(:,iparam) = fcn_clu_prod(A,Kseed,D,m,eta,gam,modelvar,epsilon);\n end\n \n case 'deg-avg'\n kseed = sum(A,2);\n Kseed = bsxfun(@plus,kseed(:,ones(1,n)),kseed')/2;\n for iparam = 1:nparams\n eta = params(iparam,1);\n gam = params(iparam,2);\n b(:,iparam) = fcn_deg_avg(A,Kseed,D,m,eta,gam,modelvar,epsilon);\n end\n \n case 'deg-diff'\n kseed = sum(A,2);\n Kseed = abs(bsxfun(@minus,kseed(:,ones(1,n)),kseed'));\n for iparam = 1:nparams\n eta = params(iparam,1);\n gam = params(iparam,2);\n b(:,iparam) = fcn_deg_diff(A,Kseed,D,m,eta,gam,modelvar,epsilon);\n end\n \n case 'deg-max'\n kseed = sum(A,2);\n Kseed = bsxfun(@max,kseed(:,ones(1,n)),kseed');\n for iparam = 1:nparams\n eta = params(iparam,1);\n gam = params(iparam,2);\n b(:,iparam) = fcn_deg_max(A,Kseed,D,m,eta,gam,modelvar,epsilon);\n end\n \n case 'deg-min'\n kseed = sum(A,2);\n Kseed = bsxfun(@min,kseed(:,ones(1,n)),kseed');\n for iparam = 1:nparams\n eta = params(iparam,1);\n gam = params(iparam,2);\n b(:,iparam) = fcn_deg_min(A,Kseed,D,m,eta,gam,modelvar,epsilon);\n end\n \n case 'deg-prod'\n kseed = sum(A,2);\n Kseed = (kseed*kseed').*~eye(n);\n for iparam = 1:nparams\n eta = params(iparam,1);\n gam = params(iparam,2);\n b(:,iparam) = fcn_deg_prod(A,Kseed,D,m,eta,gam,modelvar,epsilon);\n end\n \n case 'neighbors'\n Kseed = (A*A).*~eye(n);\n for iparam = 1:nparams\n eta = params(iparam,1);\n gam = params(iparam,2);\n b(:,iparam) = fcn_nghbrs(A,Kseed,D,m,eta,gam,modelvar,epsilon);\n end\n \n case 'matching'\n Kseed = matching_ind(A);\n Kseed = Kseed + Kseed';\n for iparam = 1:nparams\n eta = params(iparam,1);\n gam = params(iparam,2);\n b(:,iparam) = fcn_matching(A,Kseed,D,m,eta,gam,modelvar,epsilon);\n end\n \n case 'sptl'\n for iparam = 1:nparams\n eta = params(iparam,1);\n b(:,iparam) = fcn_sptl(A,D,m,eta,modelvar{1});\n end\n \nend\n\nfunction b = fcn_clu_avg(A,K,D,m,eta,gam,modelvar,epsilon)\nK = K + epsilon;\nn = length(D);\nmseed = nnz(A)/2;\nA = A > 0;\nmv1 = modelvar{1};\nmv2 = modelvar{2};\nswitch mv1\n case 'powerlaw'\n Fd = D.^eta;\n case 'exponential'\n Fd = exp(eta*D);\nend\nswitch mv2\n case 'powerlaw'\n Fk = K.^gam;\n case 'exponential'\n Fk = exp(gam*K);\nend\n\nc = clustering_coef_bu(A);\nk = sum(A,2);\n\nFf = Fd.*Fk.*~A;\n[u,v] = find(triu(ones(n),1));\nindx = (v - 1)*n + u;\nP = Ff(indx);\n\nfor i = (mseed + 1):m\n C = [0; cumsum(P)];\n r = sum(rand*C(end) >= C);\n uu = u(r);\n vv = v(r);\n A(uu,vv) = 1;\n A(vv,uu) = 1;\n k([uu,vv]) = k([uu,vv]) + 1;\n bu = A(uu,:);\n su = A(bu,bu);\n bv = A(vv,:);\n sv = A(bv,bv);\n bth = bu & bv;\n c(bth) = c(bth) + 2./(k(bth).^2 - k(bth));\n c(uu) = nnz(su)/(k(uu)*(k(uu) - 1));\n c(vv) = nnz(sv)/(k(vv)*(k(vv) - 1));\n c(k <= 1) = 0;\n bth([uu,vv]) = true;\n K(:,bth) = bsxfun(@plus,c(:,ones(1,sum(bth))),c(bth,:)')/2 + epsilon;\n K(bth,:) = bsxfun(@plus,c(:,ones(1,sum(bth))),c(bth,:)')'/2 + epsilon;\n\n switch mv2\n case 'powerlaw'\n Ff(bth,:) = Fd(bth,:).*((K(bth,:)).^gam);\n Ff(:,bth) = Fd(:,bth).*((K(:,bth)).^gam);\n case 'exponential'\n Ff(bth,:) = Fd(bth,:).*exp((K(bth,:))*gam);\n Ff(:,bth) = Fd(:,bth).*exp((K(:,bth))*gam);\n end\n Ff = Ff.*~A;\n P = Ff(indx);\nend\nb = find(triu(A,1));\n\nfunction b = fcn_clu_diff(A,K,D,m,eta,gam,modelvar,epsilon)\nK = K + epsilon;\nn = length(D);\nmseed = nnz(A)/2;\nA = A > 0;\nmv1 = modelvar{1};\nmv2 = modelvar{2};\nswitch mv1\n case 'powerlaw'\n Fd = D.^eta;\n case 'exponential'\n Fd = exp(eta*D);\nend\nswitch mv2\n case 'powerlaw'\n Fk = K.^gam;\n case 'exponential'\n Fk = exp(gam*K);\nend\n\nc = clustering_coef_bu(A);\nk = sum(A,2);\n\nFf = Fd.*Fk.*~A;\n[u,v] = find(triu(ones(n),1));\nindx = (v - 1)*n + u;\nP = Ff(indx);\n\nfor i = (mseed + 1):m\n C = [0; cumsum(P)];\n r = sum(rand*C(end) >= C);\n uu = u(r);\n vv = v(r);\n A(uu,vv) = 1;\n A(vv,uu) = 1;\n k([uu,vv]) = k([uu,vv]) + 1;\n bu = A(uu,:);\n su = A(bu,bu);\n bv = A(vv,:);\n sv = A(bv,bv);\n bth = bu & bv;\n c(bth) = c(bth) + 2./(k(bth).^2 - k(bth));\n c(uu) = nnz(su)/(k(uu)*(k(uu) - 1));\n c(vv) = nnz(sv)/(k(vv)*(k(vv) - 1));\n c(k <= 1) = 0;\n bth([uu,vv]) = true;\n K(:,bth) = abs(bsxfun(@minus,c(:,ones(1,sum(bth))),c(bth,:)')) + epsilon;\n K(bth,:) = abs(bsxfun(@minus,c(:,ones(1,sum(bth))),c(bth,:)'))' + epsilon;\n\n switch mv2\n case 'powerlaw'\n Ff(bth,:) = Fd(bth,:).*((K(bth,:)).^gam);\n Ff(:,bth) = Fd(:,bth).*((K(:,bth)).^gam);\n case 'exponential'\n Ff(bth,:) = Fd(bth,:).*exp((K(bth,:))*gam);\n Ff(:,bth) = Fd(:,bth).*exp((K(:,bth))*gam);\n end\n Ff = Ff.*~A;\n P = Ff(indx);\nend\nb = find(triu(A,1));\n\nfunction b = fcn_clu_max(A,K,D,m,eta,gam,modelvar,epsilon)\nK = K + epsilon;\nn = length(D);\nmseed = nnz(A)/2;\nA = A > 0;\nmv1 = modelvar{1};\nmv2 = modelvar{2};\nswitch mv1\n case 'powerlaw'\n Fd = D.^eta;\n case 'exponential'\n Fd = exp(eta*D);\nend\nswitch mv2\n case 'powerlaw'\n Fk = K.^gam;\n case 'exponential'\n Fk = exp(gam*K);\nend\n\nc = clustering_coef_bu(A);\nk = sum(A,2);\n\nFf = Fd.*Fk.*~A;\n[u,v] = find(triu(ones(n),1));\nindx = (v - 1)*n + u;\nP = Ff(indx);\n\nfor i = (mseed + 1):m\n C = [0; cumsum(P)];\n r = sum(rand*C(end) >= C);\n uu = u(r);\n vv = v(r);\n A(uu,vv) = 1;\n A(vv,uu) = 1;\n k([uu,vv]) = k([uu,vv]) + 1;\n bu = A(uu,:);\n su = A(bu,bu);\n bv = A(vv,:);\n sv = A(bv,bv);\n bth = bu & bv;\n c(bth) = c(bth) + 2./(k(bth).^2 - k(bth));\n c(uu) = nnz(su)/(k(uu)*(k(uu) - 1));\n c(vv) = nnz(sv)/(k(vv)*(k(vv) - 1));\n c(k <= 1) = 0;\n bth([uu,vv]) = true;\n K(:,bth) = bsxfun(@max,c(:,ones(1,sum(bth))),c(bth,:)') + epsilon;\n K(bth,:) = bsxfun(@max,c(:,ones(1,sum(bth))),c(bth,:)')' + epsilon;\n\n switch mv2\n case 'powerlaw'\n Ff(bth,:) = Fd(bth,:).*((K(bth,:)).^gam);\n Ff(:,bth) = Fd(:,bth).*((K(:,bth)).^gam);\n case 'exponential'\n Ff(bth,:) = Fd(bth,:).*exp((K(bth,:))*gam);\n Ff(:,bth) = Fd(:,bth).*exp((K(:,bth))*gam);\n end\n Ff = Ff.*~A;\n P = Ff(indx);\nend\nb = find(triu(A,1));\n\nfunction b = fcn_clu_min(A,K,D,m,eta,gam,modelvar,epsilon)\nK = K + epsilon;\nn = length(D);\nmseed = nnz(A)/2;\nA = A > 0;\nmv1 = modelvar{1};\nmv2 = modelvar{2};\nswitch mv1\n case 'powerlaw'\n Fd = D.^eta;\n case 'exponential'\n Fd = exp(eta*D);\nend\nswitch mv2\n case 'powerlaw'\n Fk = K.^gam;\n case 'exponential'\n Fk = exp(gam*K);\nend\n\nc = clustering_coef_bu(A);\nk = sum(A,2);\n\nFf = Fd.*Fk.*~A;\n[u,v] = find(triu(ones(n),1));\nindx = (v - 1)*n + u;\nP = Ff(indx);\n\nfor i = (mseed + 1):m\n C = [0; cumsum(P)];\n r = sum(rand*C(end) >= C);\n uu = u(r);\n vv = v(r);\n A(uu,vv) = 1;\n A(vv,uu) = 1;\n k([uu,vv]) = k([uu,vv]) + 1;\n bu = A(uu,:);\n su = A(bu,bu);\n bv = A(vv,:);\n sv = A(bv,bv);\n bth = bu & bv;\n c(bth) = c(bth) + 2./(k(bth).^2 - k(bth));\n c(uu) = nnz(su)/(k(uu)*(k(uu) - 1));\n c(vv) = nnz(sv)/(k(vv)*(k(vv) - 1));\n c(k <= 1) = 0;\n bth([uu,vv]) = true;\n K(:,bth) = bsxfun(@min,c(:,ones(1,sum(bth))),c(bth,:)') + epsilon;\n K(bth,:) = bsxfun(@min,c(:,ones(1,sum(bth))),c(bth,:)')' + epsilon;\n\n switch mv2\n case 'powerlaw'\n Ff(bth,:) = Fd(bth,:).*((K(bth,:)).^gam);\n Ff(:,bth) = Fd(:,bth).*((K(:,bth)).^gam);\n case 'exponential'\n Ff(bth,:) = Fd(bth,:).*exp((K(bth,:))*gam);\n Ff(:,bth) = Fd(:,bth).*exp((K(:,bth))*gam);\n end\n Ff = Ff.*~A;\n P = Ff(indx);\nend\nb = find(triu(A,1));\n\nfunction b = fcn_clu_prod(A,K,D,m,eta,gam,modelvar,epsilon)\nK = K + epsilon;\nn = length(D);\nmseed = nnz(A)/2;\nA = A > 0;\nmv1 = modelvar{1};\nmv2 = modelvar{2};\nswitch mv1\n case 'powerlaw'\n Fd = D.^eta;\n case 'exponential'\n Fd = exp(eta*D);\nend\nswitch mv2\n case 'powerlaw'\n Fk = K.^gam;\n case 'exponential'\n Fk = exp(gam*K);\nend\n\nc = clustering_coef_bu(A);\nk = sum(A,2);\n\nFf = Fd.*Fk.*~A;\n[u,v] = find(triu(ones(n),1));\nindx = (v - 1)*n + u;\nP = Ff(indx);\n\nfor i = (mseed + 1):m\n C = [0; cumsum(P)];\n r = sum(rand*C(end) >= C);\n uu = u(r);\n vv = v(r);\n A(uu,vv) = 1;\n A(vv,uu) = 1;\n k([uu,vv]) = k([uu,vv]) + 1;\n bu = A(uu,:);\n su = A(bu,bu);\n bv = A(vv,:);\n sv = A(bv,bv);\n bth = bu & bv;\n c(bth) = c(bth) + 2./(k(bth).^2 - k(bth));\n c(uu) = nnz(su)/(k(uu)*(k(uu) - 1));\n c(vv) = nnz(sv)/(k(vv)*(k(vv) - 1));\n c(k <= 1) = 0;\n bth([uu,vv]) = true;\n K(bth,:) = (c(bth,:)*c') + epsilon;\n K(:,bth) = (c*c(bth,:)') + epsilon;\n \n switch mv2\n case 'powerlaw'\n Ff(bth,:) = Fd(bth,:).*((K(bth,:)).^gam);\n Ff(:,bth) = Fd(:,bth).*((K(:,bth)).^gam);\n case 'exponential'\n Ff(bth,:) = Fd(bth,:).*exp((K(bth,:))*gam);\n Ff(:,bth) = Fd(:,bth).*exp((K(:,bth))*gam);\n end\n Ff = Ff.*~A;\n P = Ff(indx);\nend\nb = find(triu(A,1));\n\nfunction b = fcn_deg_avg(A,K,D,m,eta,gam,modelvar,epsilon)\nn = length(D);\nmseed = nnz(A)/2;\nk = sum(A,2);\n[u,v] = find(triu(ones(n),1));\nindx = (v - 1)*n + u;\nD = D(indx);\nmv1 = modelvar{1};\nmv2 = modelvar{2};\nswitch mv1\n case 'powerlaw'\n Fd = D.^eta;\n case 'exponential'\n Fd = exp(eta*D);\nend\nK = K + epsilon;\nswitch mv2\n case 'powerlaw'\n Fk = K.^gam;\n case 'exponential'\n Fk = exp(gam*K);\nend\nP = Fd.*Fk(indx).*~A(indx);\nb = zeros(m,1);\nb(1:mseed) = find(A(indx));\nfor i = (mseed + 1):m\n C = [0; cumsum(P)];\n r = sum(rand*C(end) >= C);\n w = [u(r),v(r)];\n k(w) = k(w) + 1;\n switch mv2\n case 'powerlaw'\n Fk(:,w) = [((k + k(w(1)))/2) + epsilon, ((k + k(w(2)))/2) + epsilon].^gam;\n Fk(w,:) = ([((k + k(w(1)))/2) + epsilon, ((k + k(w(2)))/2) + epsilon].^gam)';\n case 'exponential'\n Fk(:,w) = exp([((k + k(w(1)))/2) + epsilon, ((k + k(w(2)))/2) + epsilon]*gam);\n Fk(w,:) = exp([((k + k(w(1)))/2) + epsilon, ((k + k(w(2)))/2) + epsilon]*gam)';\n end\n P = Fd.*Fk(indx);\n b(i) = r;\n P(b(1:i)) = 0;\nend\nb = indx(b);\n\nfunction b = fcn_deg_diff(A,K,D,m,eta,gam,modelvar,epsilon)\nn = length(D);\nmseed = nnz(A)/2;\nk = sum(A,2);\n[u,v] = find(triu(ones(n),1));\nindx = (v - 1)*n + u;\nD = D(indx);\nmv1 = modelvar{1};\nmv2 = modelvar{2};\nswitch mv1\n case 'powerlaw'\n Fd = D.^eta;\n case 'exponential'\n Fd = exp(eta*D);\nend\nK = K + epsilon;\nswitch mv2\n case 'powerlaw'\n Fk = K.^gam;\n case 'exponential'\n Fk = exp(gam*K);\nend\nP = Fd.*Fk(indx).*~A(indx);\nb = zeros(m,1);\nb(1:mseed) = find(A(indx));\nfor i = (mseed + 1):m\n C = [0; cumsum(P)];\n r = sum(rand*C(end) >= C);\n \n w = [u(r),v(r)];\n k(w) = k(w) + 1;\n switch mv2\n case 'powerlaw'\n Fk(:,w) = (abs([k - k(w(1)), k - k(w(2))]) + epsilon).^gam;\n Fk(w,:) = ((abs([k - k(w(1)), k - k(w(2))]) + epsilon).^gam)';\n case 'exponential'\n Fk(:,w) = exp((abs([k - k(w(1)), k - k(w(2))]) + epsilon)*gam);\n Fk(w,:) = exp((abs([k - k(w(1)), k - k(w(2))]) + epsilon)*gam)';\n end\n P = Fd.*Fk(indx);\n b(i) = r;\n P(b(1:i)) = 0;\nend\nb = indx(b);\n\nfunction b = fcn_deg_min(A,K,D,m,eta,gam,modelvar,epsilon)\nn = length(D);\nmseed = nnz(A)/2;\nk = sum(A,2);\n[u,v] = find(triu(ones(n),1));\nindx = (v - 1)*n + u;\nD = D(indx);\nmv1 = modelvar{1};\nmv2 = modelvar{2};\nswitch mv1\n case 'powerlaw'\n Fd = D.^eta;\n case 'exponential'\n Fd = exp(eta*D);\nend\nK = K + epsilon;\nswitch mv2\n case 'powerlaw'\n Fk = K.^gam;\n case 'exponential'\n Fk = exp(gam*K);\nend\nP = Fd.*Fk(indx).*~A(indx);\nb = zeros(m,1);\nb(1:mseed) = find(A(indx));\nfor i = (mseed + 1):m\n C = [0; cumsum(P)];\n r = sum(rand*C(end) >= C);\n w = [u(r),v(r)];\n k(w) = k(w) + 1;\n switch mv2\n case 'powerlaw'\n Fk(:,w) = [min(k,k(w(1))) + epsilon, min(k,k(w(2))) + epsilon].^gam;\n Fk(w,:) = ([min(k,k(w(1))) + epsilon, min(k,k(w(2))) + epsilon].^gam)';\n case 'exponential'\n Fk(:,w) = exp([min(k,k(w(1))) + epsilon, min(k,k(w(2))) + epsilon]*gam);\n Fk(w,:) = exp([min(k,k(w(1))) + epsilon, min(k,k(w(2))) + epsilon]*gam)';\n end\n P = Fd.*Fk(indx);\n b(i) = r;\n P(b(1:i)) = 0;\nend\nb = indx(b);\n\nfunction b = fcn_deg_max(A,K,D,m,eta,gam,modelvar,epsilon)\nn = length(D);\nmseed = nnz(A)/2;\nk = sum(A,2);\n[u,v] = find(triu(ones(n),1));\nindx = (v - 1)*n + u;\nD = D(indx);\nmv1 = modelvar{1};\nmv2 = modelvar{2};\nswitch mv1\n case 'powerlaw'\n Fd = D.^eta;\n case 'exponential'\n Fd = exp(eta*D);\nend\nK = K + epsilon;\nswitch mv2\n case 'powerlaw'\n Fk = K.^gam;\n case 'exponential'\n Fk = exp(gam*K);\nend\nP = Fd.*Fk(indx).*~A(indx);\nb = zeros(m,1);\nb(1:mseed) = find(A(indx));\nfor i = (mseed + 1):m\n C = [0; cumsum(P)];\n r = sum(rand*C(end) >= C);\n w = [u(r),v(r)];\n k(w) = k(w) + 1;\n switch mv2\n case 'powerlaw'\n Fk(:,w) = [max(k,k(w(1))) + epsilon, max(k,k(w(2))) + epsilon].^gam;\n Fk(w,:) = ([max(k,k(w(1))) + epsilon, max(k,k(w(2))) + epsilon].^gam)';\n case 'exponential'\n Fk(:,w) = exp([max(k,k(w(1))) + epsilon, max(k,k(w(2))) + epsilon]*gam);\n Fk(w,:) = exp([max(k,k(w(1))) + epsilon, max(k,k(w(2))) + epsilon]*gam)';\n end\n P = Fd.*Fk(indx);\n b(i) = r;\n P(b(1:i)) = 0;\nend\nb = indx(b);\n\nfunction b = fcn_deg_prod(A,K,D,m,eta,gam,modelvar,epsilon)\nn = length(D);\nmseed = nnz(A)/2;\nk = sum(A,2);\n[u,v] = find(triu(ones(n),1));\nindx = (v - 1)*n + u;\nD = D(indx);\nmv1 = modelvar{1};\nmv2 = modelvar{2};\nswitch mv1\n case 'powerlaw'\n Fd = D.^eta;\n case 'exponential'\n Fd = exp(eta*D);\nend\nK = K + epsilon;\nswitch mv2\n case 'powerlaw'\n Fk = K.^gam;\n case 'exponential'\n Fk = exp(gam*K);\nend\nP = Fd.*Fk(indx).*~A(indx);\nb = zeros(m,1);\nb(1:mseed) = find(A(indx));\nfor i = (mseed + 1):m\n C = [0; cumsum(P)];\n r = sum(rand*C(end) >= C);\n w = [u(r),v(r)];\n k(w) = k(w) + 1;\n switch mv2\n case 'powerlaw'\n Fk(:,w) = ([k*k(w(1)) + epsilon, k*k(w(2)) + epsilon].^gam);\n Fk(w,:) = (([k*k(w(1)) + epsilon, k*k(w(2)) + epsilon].^gam)');\n case 'exponential'\n Fk(:,w) = exp([k*k(w(1)) + epsilon, k*k(w(2)) + epsilon]*gam);\n Fk(w,:) = exp([k*k(w(1)) + epsilon, k*k(w(2)) + epsilon]*gam)';\n end\n P = Fd.*Fk(indx);\n b(i) = r;\n P(b(1:i)) = 0;\nend\nb = indx(b);\n\nfunction b = fcn_nghbrs(A,K,D,m,eta,gam,modelvar,epsilon)\nK = K + epsilon;\nn = length(D);\nmseed = nnz(A)/2;\nA = A > 0;\nmv1 = modelvar{1};\nmv2 = modelvar{2};\nswitch mv1\n case 'powerlaw'\n Fd = D.^eta;\n case 'exponential'\n Fd = exp(eta*D);\nend\nswitch mv2\n case 'powerlaw'\n% gam = abs(gam);\n Fk = K.^gam;\n case 'exponential'\n Fk = exp(gam*K);\nend\nFf = Fd.*Fk.*~A;\n[u,v] = find(triu(ones(n),1));\nindx = (v - 1)*n + u;\nP = Ff(indx);\nfor i = (mseed + 1):m\n C = [0; cumsum(P)];\n r = sum(rand*C(end) >= C);\n uu = u(r);\n vv = v(r);\n x = A(uu,:);\n y = A(:,vv);\n A(uu,vv) = 1;\n A(vv,uu) = 1;\n K(uu,y) = K(uu,y) + 1;\n K(y,uu) = K(y,uu) + 1;\n K(vv,x) = K(vv,x) + 1;\n K(x,vv) = K(x,vv) + 1;\n switch mv2\n case 'powerlaw'\n Ff(uu,y) = Fd(uu,y).*(K(uu,y).^gam);\n Ff(y,uu) = Ff(uu,y)';\n Ff(vv,x) = Fd(vv,x).*(K(vv,x).^gam);\n Ff(x,vv) = Ff(vv,x)';\n case 'exponential'\n Ff(uu,y) = Fd(uu,y).*exp(K(uu,y)*gam);\n Ff(y,uu) = Ff(uu,y)';\n Ff(vv,x) = Fd(vv,x).*exp(K(vv,x)*gam);\n Ff(x,vv) = Ff(vv,x)';\n end\n Ff(A) = 0;\n P = Ff(indx);\nend\nb = find(triu(A,1));\n\nfunction b = fcn_matching(A,K,D,m,eta,gam,modelvar,epsilon)\nK = K + epsilon;\nn = length(D);\nmseed = nnz(A)/2;\nmv1 = modelvar{1};\nmv2 = modelvar{2};\nswitch mv1\n case 'powerlaw'\n Fd = D.^eta;\n case 'exponential'\n Fd = exp(eta*D);\nend\nswitch mv2\n case 'powerlaw'\n Fk = K.^gam;\n case 'exponential'\n Fk = exp(gam*K);\nend\nFf = Fd.*Fk.*~A;\n[u,v] = find(triu(ones(n),1));\nindx = (v - 1)*n + u;\nP = Ff(indx);\nfor ii = (mseed + 1):m\n \n C = [0; cumsum(P)];\n r = sum(rand*C(end) >= C);\n uu = u(r);\n vv = v(r);\n \n A(uu,vv) = 1;\n A(vv,uu) = 1;\n \n updateuu = find(A*A(:,uu));\n updateuu(updateuu == uu) = [];\n updateuu(updateuu == vv) = [];\n \n updatevv = find(A*A(:,vv));\n updatevv(updatevv == uu) = [];\n updatevv(updatevv == vv) = [];\n \n c1 = [A(:,uu)', A(uu,:)];\n for i = 1:length(updateuu)\n j = updateuu(i);\n c2 = [A(:,j)' A(j,:)];\n use = ~(~c1&~c2);\n use(uu) = 0; use(uu+n) = 0;\n use(j) = 0; use(j+n) = 0;\n ncon = sum(c1(use))+sum(c2(use));\n if (ncon==0)\n K(uu,j) = epsilon;\n K(j,uu) = epsilon;\n else\n K(uu,j) = (2*(sum(c1(use)&c2(use))/ncon)) + epsilon;\n K(j,uu) = K(uu,j);\n end\n \n end\n \n c1 = [A(:,vv)', A(vv,:)];\n for i = 1:length(updatevv)\n j = updatevv(i);\n c2 = [A(:,j)' A(j,:)];\n use = ~(~c1&~c2);\n use(vv) = 0; use(vv+n) = 0;\n use(j) = 0; use(j+n) = 0;\n ncon = sum(c1(use))+sum(c2(use));\n if (ncon==0)\n K(vv,j) = epsilon;\n K(j,vv) = epsilon;\n else\n K(vv,j) = (2*(sum(c1(use)&c2(use))/ncon)) + epsilon;\n K(j,vv) = K(vv,j);\n end\n end\n switch mv2\n case 'powerlaw'\n Fk = K.^gam;\n case 'exponential'\n Fk = exp(gam*K);\n end\n Ff = Fd.*Fk.*~A;\n P = Ff(indx);\nend\nb = find(triu(A,1));\n\nfunction b = fcn_sptl(A,D,m,eta,modelvar)\nn = length(D);\nmseed = nnz(A)/2;\nswitch modelvar\n case 'powerlaw'\n Fd = D.^eta;\n case 'exponential'\n Fd = exp(eta*D);\nend\n[u,v] = find(triu(ones(n),1));\nindx = (v - 1)*n + u;\nP = Fd(indx).*~A(indx);\nb = zeros(m,1);\nb(1:mseed) = find(A(indx));\nfor i = (mseed + 1):m\n C = [0; cumsum(P)];\n r = sum(rand*C(end) >= C);\n b(i) = r;\n P = Fd(indx);\n P(b(1:i)) = 0;\nend\nb = indx(b);\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/bct/generative_model.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.49658279395002336}} {"text": "%% Epipolar Geometry\n%\n% In this sample:\n%\n% * We will learn about the basics of multiview geometry\n% * We will see what is epipole, epipolar lines, epipolar constraint etc.\n%\n% Sources:\n%\n% * \n%\n\n%% Theory\n%\n% When we take an image using pin-hole camera, we loose an important\n% information, i.e depth of the image, or how far is each point in the image\n% from the camera because it is a 3D-to-2D conversion. So it is an important\n% question whether we can find the depth information using these cameras. And\n% the answer is to use more than one camera. Our eyes works in similar way\n% where we use two cameras (two eyes) which is called stereo vision. So let's\n% see what OpenCV provides in this field.\n%\n% (_Learning OpenCV_ by Gary Bradsky has a lot of information in this field.)\n%\n% Before going to depth images, let's first understand some basic concepts in\n% multiview geometry. In this section we will deal with epipolar geometry. See\n% the image below which shows a basic setup with two cameras taking the image\n% of same scene.\n%\n% <>\n%\n% If we are using only the left camera, we can't find the 3D point\n% corresponding to the point $x$ in image because every point on the line\n% $OX$ projects to the same point on the image plane. But consider the right\n% image also. Now different points on the line $OX$ projects to different\n% points ($x'$) in right plane. So with these two images, we can triangulate\n% the correct 3D point. This is the whole idea.\n%\n% The projection of the different points on $OX$ form a line on right plane\n% (line $l'$). We call it *epiline* corresponding to the point $x$. It means,\n% to find the point $x$ on the right image, search along this epiline. It\n% should be somewhere on this line. (Think of it this way, to find the\n% matching point in other image, you need not search the whole image, just\n% search along the epiline. So it provides better performance and accuracy).\n% This is called *Epipolar Constraint*. Similarly all points will have its\n% corresponding epilines in the other image. The plane $XOO'$ is called\n% *Epipolar Plane*.\n%\n% $O$ and $O'$ are the camera centers. From the setup given above, you can see\n% that projection of right camera $O'$ is seen on the left image at the point,\n% $e$. It is called the *epipole*. Epipole is the point of intersection of\n% line through camera centers and the image planes. Similarly $e'$ is the\n% epipole of the left camera. In some cases, you won't be able to locate the\n% epipole in the image, they may be outside the image (which means, one camera\n% doesn't see the other).\n%\n% All the epilines pass through its epipole. So to find the location of\n% epipole, we can find many epilines and find their intersection point.\n%\n% So in this session, we focus on finding epipolar lines and epipoles. But to\n% find them, we need two more ingredients, *Fundamental Matrix (F)* and\n% *Essential Matrix (E)*. Essential Matrix contains the information about\n% translation and rotation, which describe the location of the second camera\n% relative to the first in global coordinates. See the image below\n% (Image courtesy: _Learning OpenCV_ by Gary Bradsky):\n%\n% <>\n%\n% But we prefer measurements to be done in pixel coordinates, right?\n% Fundamental Matrix contains the same information as Essential Matrix in\n% addition to the information about the intrinsics of both cameras so that we\n% can relate the two cameras in pixel coordinates. (If we are using rectified\n% images and normalize the point by dividing by the focal lengths, $F=E$). In\n% simple words, Fundamental Matrix F, maps a point in one image to a line\n% (epiline) in the other image. This is calculated from matching points from\n% both the images. A minimum of 8 such points are required to find the\n% fundamental matrix (while using 8-point algorithm). More points are\n% preferred and use RANSAC to get a more robust result.\n%\n\n%% Code\n%\n% First we need to find as many possible matches between two images to find\n% the fundamental matrix. For this, we use SIFT descriptors with FLANN based\n% matcher and ratio test.\n%\n% Next we find the Fundamental Matrix from the list of best matches from both\n% the images.\n%\n% Then we find the epilines. Epilines corresponding to the points in first\n% image are drawn on second image. So mentioning of correct images are\n% important here. We get an array of lines. So we define a new function to\n% draw these lines on the images.\n%\n% Below is the result we get:\n%\n% <>\n%\n% You can see in the left image that all epilines are converging at a point\n% outside the image at right side. That meeting point is the epipole.\n%\n% For better results, images with good resolution and many non-planar points\n% should be used.\n%\n% Notes:\n%\n% * One important topic is the forward movement of camera. Then epipoles will\n% be seen at the same locations in both with epilines emerging from a fixed\n% point. See\n% .\n% * Fundamental Matrix estimation is sensitive to quality of matches, outliers\n% etc. It becomes worse when all selected matches lie on the same plane. See\n% .\n%\n\nfunction epipolar_geometry_demo()\n %%\n % a pair of stereo images (grayscale)\n img1 = cv.imread(fullfile(mexopencv.root(),'test','books_left.jpg'), ...\n 'Grayscale',true); % query image\n img2 = cv.imread(fullfile(mexopencv.root(),'test','books_right.jpg'), ...\n 'Grayscale',true); % train image\n\n %%\n % detect keypoints and calculate descriptors using SIFT\n obj = cv.SIFT('ConstrastThreshold',0.03);\n [kp1,desc1] = obj.detectAndCompute(img1);\n [kp2,desc2] = obj.detectAndCompute(img2);\n\n %%\n % match descriptors using FLANN\n matcher = cv.DescriptorMatcher('FlannBasedMatcher', ...\n 'Index',{'KDTree', 'Trees',5}, 'Search',{'Checks',50});\n m = matcher.knnMatch(desc1, desc2, 2);\n\n %%\n % keep only \"good\" matches (ratio test as per Lowe's paper)\n m = cat(1, m{:}); % N-by-2 array of structs\n idx_good = ([m(:,1).distance] < 0.8*[m(:,2).distance]);\n m = m(idx_good,1);\n\n %%\n % extract keypoints from filtered matches\n pts1 = cat(1, kp1([m.queryIdx]+1).pt);\n pts2 = cat(1, kp2([m.trainIdx]+1).pt);\n if true\n pts1 = int32(pts1);\n pts2 = int32(pts2);\n end\n\n %%\n % find Fundamental matrix\n [F,mask] = cv.findFundamentalMat(pts1, pts2, 'Method','LMedS');\n mask = logical(mask);\n\n %%\n % select only inlier points\n pts1 = pts1(mask,:);\n pts2 = pts2(mask,:);\n\n %%\n % random colors to draw matching points and lines\n clrs = randi([0 255], [size(pts1,1) 3], 'uint8');\n clrs(:,4) = 0;\n\n %%\n % find epilines corresponding to points in right image (second image)\n % and draw its lines on left image\n lines1 = cv.computeCorrespondEpilines(pts2, F, 'WhichImage',2);\n [img11,~] = drawlines(img1, img2, lines1, pts1, pts2, clrs);\n\n %%\n % find epilines corresponding to points in left image (first image)\n % and draw its lines on right image\n lines2 = cv.computeCorrespondEpilines(pts1, F, 'WhichImage',1);\n [img22,~] = drawlines(img2, img1, lines2, pts2, pts1, clrs);\n\n %%\n % show result\n if ~mexopencv.isOctave() && mexopencv.require('images')\n imshowpair(img11, img22, 'montage')\n title('Left/Right')\n else\n figure('Position',[200 200 1200 400])\n subplot(121), imshow(img11), title('Left')\n subplot(122), imshow(img22), title('Right')\n end\nend\n\nfunction [img1,img2] = drawlines(img1, img2, lines, pts1, pts2, clrs)\n %DRAWLINES Draw epilines and points on images\n %\n % [img1,img2] = drawlines(img1, img2, lines, pts1, pts2, clrs)\n %\n % ## Input\n % * __img1__ first image\n % * __img2__ second image\n % * __lines__ epilines corresponding to `pts2` in `img2`\n % * __pts1__ points in `img1`\n % * __pts2__ points in `img2`\n % * __clrs__ color of each line and matching points\n %\n % ## Output\n % * __img1__ image with drawn points and epilines for the points in `img2`\n % * __img2__ image with drawn points\n %\n % Epilines corresponding to the points in 1st image is drawn on 2nd image.\n %\n % See also: estimateFundamentalMatrix, epipolarLine, lineToBorderPoints\n %\n\n % convert to RGB\n img1 = cv.cvtColor(img1, 'GRAY2RGB');\n img2 = cv.cvtColor(img2, 'GRAY2RGB');\n\n % epilines\n w = size(img1,2);\n N = size(lines,1);\n p1 = int32([zeros(N,1), -lines(:,3)./lines(:,2)]);\n p2 = int32([ones(N,1)*w, -(lines(:,3)+lines(:,1)*w)./lines(:,2)]);\n img1 = cv.line(img1, p1, p2, 'Colors',clrs, 'LineType','AA');\n\n % matching points\n img1 = cv.circle(img1, pts1, 5, 'Colors',clrs, 'Thickness','Filled');\n img2 = cv.circle(img2, pts2, 5, 'Colors',clrs, 'Thickness','Filled');\nend\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/samples/epipolar_geometry_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.4965194104752961}} {"text": "% Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9)\n%\n% Copyright (C) 1993-2011, by Peter I. Corke\n%\n% This file is part of The Robotics Toolbox for MATLAB (RTB).\n% \n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with RTB. If not, see .\n%\n% http://www.petercorke.com\nfunction q = interp(Q1, Q2, r)\n%Quaternion.interp Interpolate rotations expressed by quaternion objects\n%\n% QI = Q1.interp(Q2, R) is a unit-quaternion that interpolates between Q1 for R=0 \n% to Q2 for R=1. This is a spherical linear interpolation (slerp) that can be \n% interpretted as interpolation along a great circle arc on a sphere.\n%\n% If R is a vector QI is a vector of quaternions, each element\n% corresponding to sequential elements of R.\n%\n% Notes:\n% - the value of r is clipped to the interval 0 to 1\n%\n% See also ctraj, Quaternion.scale.\n\n q1 = double(Q1);\n q2 = double(Q2);\n\n theta = acos(q1*q2');\n count = 1;\n\n % clip values of r\n r(r<0) = 0;\n r(r>1) = 1;\n\n if length(r) == 1\n if theta == 0\n q = Q1;\n else\n q = Quaternion( (sin((1-r)*theta) * q1 + sin(r*theta) * q2) / sin(theta) );\n end\n else\n for R=r(:)'\n if theta == 0\n qq = Q1;\n else\n qq = Quaternion( (sin((1-R)*theta) * q1 + sin(R*theta) * q2) / sin(theta) );\n end\n q(count) = qq;\n count = count + 1;\n end\n end\nend\n", "meta": {"author": "petercorke", "repo": "robotics-toolbox-matlab", "sha": "bd7a9d75176c660f43fc799b24d838f70b02250c", "save_path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab/robotics-toolbox-matlab-bd7a9d75176c660f43fc799b24d838f70b02250c/Octave/@Quaternion/interp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.49651939700099124}} {"text": "function tapas_hgf_jget_plotTraj(r)\n% Plots the estimated trajectories for the HGF perceptual model for\n% the JGET project\n% Usage example: est = tapas_fitModel(responses, inputs); tapas_hgf_plotTraj(est);\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2013 Christoph Mathys, TNU, UZH & ETHZ\n%\n% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or .\n\n% Optional plotting of standard deviations (true or false)\nplotsd = true;\n\n% Set up display\nscrsz = get(0,'screenSize');\nouterpos = [0.2*scrsz(3),0.2*scrsz(4),0.8*scrsz(3),0.8*scrsz(4)];\nfigure(...\n 'OuterPosition', outerpos,...\n 'Name', 'HGF trajectories');\n\n% Time axis\nif size(r.u,2) > 1 && ~isempty(find(strcmp(fieldnames(r.c_prc),'irregular_intervals'))) && r.c_prc.irregular_intervals\n t = r.u(:,end)';\nelse\n t = ones(1,size(r.u,1));\nend\n\nts = cumsum(t);\nts = [0, ts];\n\n% Do we know the generative parameters?\nif size(r.u,2) > 2\n genpar = true;\n mean = r.u(:,2);\n sd = r.u(:,3);\nelse\n genpar = false;\nend\n\n% Number of levels\ntry\n l = r.c_prc.n_levels;\ncatch\n l = length(r.p_prc.p)/8;\nend\n\n% Upper levels\nfor j = 1:l-1\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Left subplot (x) %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n subplot(l+1,2,2*j-1);\n\n if plotsd == true\n upperprior = r.p_prc.mux_0(l-j+1) +1.96*sqrt(r.p_prc.sax_0(l-j+1));\n lowerprior = r.p_prc.mux_0(l-j+1) -1.96*sqrt(r.p_prc.sax_0(l-j+1));\n upper = [upperprior; r.traj.mux(:,l-j+1)+1.96*sqrt(r.traj.sax(:,l-j+1))];\n lower = [lowerprior; r.traj.mux(:,l-j+1)-1.96*sqrt(r.traj.sax(:,l-j+1))];\n \n plot(0, upperprior, 'ob', 'LineWidth', 1);\n hold all;\n plot(0, lowerprior, 'ob', 'LineWidth', 1);\n fill([ts, fliplr(ts)], [(upper)', fliplr((lower)')], ...\n 'b', 'EdgeAlpha', 0, 'FaceAlpha', 0.15);\n end\n plot(ts, [r.p_prc.mux_0(l-j+1); r.traj.mux(:,l-j+1)], 'b', 'LineWidth', 1.5);\n hold all;\n plot(0, r.p_prc.mux_0(l-j+1), 'ob', 'LineWidth', 1.5); % prior\n xlim([0 ts(end)]);\n title(['Posterior expectation of x_' num2str(l-j+1)], 'FontWeight', 'bold');\n ylabel(['\\mu x_', num2str(l-j+1)]);\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Right subplot (alpha) %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n subplot(l+1,2,2*j);\n\n if plotsd == true\n upperprior = r.p_prc.mua_0(l-j+1) +1.96*sqrt(r.p_prc.saa_0(l-j+1));\n lowerprior = r.p_prc.mua_0(l-j+1) -1.96*sqrt(r.p_prc.saa_0(l-j+1));\n upper = [upperprior; r.traj.mua(:,l-j+1)+1.96*sqrt(r.traj.saa(:,l-j+1))];\n lower = [lowerprior; r.traj.mua(:,l-j+1)-1.96*sqrt(r.traj.saa(:,l-j+1))];\n \n plot(0, upperprior, 'ob', 'LineWidth', 1);\n hold all;\n plot(0, lowerprior, 'ob', 'LineWidth', 1);\n fill([ts, fliplr(ts)], [(upper)', fliplr((lower)')], ...\n 'b', 'EdgeAlpha', 0, 'FaceAlpha', 0.15);\n end\n plot(ts, [r.p_prc.mua_0(l-j+1); r.traj.mua(:,l-j+1)], 'b', 'LineWidth', 1.5);\n hold all;\n plot(0, r.p_prc.mua_0(l-j+1), 'ob', 'LineWidth', 1.5); % prior\n xlim([0 ts(end)]);\n title(['Posterior expectation of \\alpha_' num2str(l-j+1)], 'FontWeight', 'bold');\n ylabel(['\\mu \\alpha_', num2str(l-j+1)]);\nend\n\n\n% Input level\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Left subplot (x) %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nsubplot(l+1,2,2*l-1);\n\nif plotsd == true\n upperprior = r.p_prc.mux_0(1) +1.96*sqrt(r.p_prc.sax_0(1));\n lowerprior = r.p_prc.mux_0(1) -1.96*sqrt(r.p_prc.sax_0(1));\n upper = [upperprior; r.traj.mux(:,1)+1.96*sqrt(r.traj.sax(:,1))];\n lower = [lowerprior; r.traj.mux(:,1)-1.96*sqrt(r.traj.sax(:,1))];\n \n plot(0, upperprior, 'or', 'LineWidth', 1);\n hold all;\n plot(0, lowerprior, 'or', 'LineWidth', 1);\n fill([ts, fliplr(ts)], [(upper)', fliplr((lower)')], ...\n 'r', 'EdgeAlpha', 0, 'FaceAlpha', 0.15);\nend\nplot(ts, [r.p_prc.mux_0(1); r.traj.mux(:,1)], 'r', 'LineWidth', 1.5);\nhold all;\nplot(0, r.p_prc.mux_0(1), 'or', 'LineWidth', 1.5); % prior\nplot(ts(2:end), r.u(:,1), '.', 'Color', [0 0.6 0]); % inputs\nif genpar\n plot(ts(2:end), mean, '-', 'Color', 'k', 'LineWidth', 1); % mean of input distribution\n plot(ts(2:end), mean +1.96.*sd, '--', 'Color', 'k', 'LineWidth', 1); % 95% interval of input distribution\n plot(ts(2:end), mean -1.96.*sd, '--', 'Color', 'k', 'LineWidth', 1); % 95% interval of input distribution\nend\nxlim([0 ts(end)]);\ntitle(['Input u (green) and posterior expectation of x_1 (red) for \\kappa_x=', ...\n num2str(r.p_prc.kax), ', \\omega_x=', num2str(r.p_prc.omx)], 'FontWeight', 'bold');\nylabel('u, \\mu x_1');\nhold off;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Right subplot (alpha) %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nsubplot(l+1,2,2*l);\n\nif plotsd == true\n upperprior = r.p_prc.mua_0(1) +1.96*sqrt(r.p_prc.saa_0(1));\n lowerprior = r.p_prc.mua_0(1) -1.96*sqrt(r.p_prc.saa_0(1));\n upper = [upperprior; r.traj.mua(:,1)+1.96*sqrt(r.traj.saa(:,1))];\n lower = [lowerprior; r.traj.mua(:,1)-1.96*sqrt(r.traj.saa(:,1))];\n\n transupperprior = sqrt(exp(r.p_prc.kau *upperprior +r.p_prc.omu));\n translowerprior = sqrt(exp(r.p_prc.kau *lowerprior +r.p_prc.omu));\n transupper = sqrt(exp(r.p_prc.kau *upper +r.p_prc.omu));\n translower = sqrt(exp(r.p_prc.kau *lower +r.p_prc.omu));\n\n plot(0, transupperprior, 'or', 'LineWidth', 1);\n hold all;\n plot(0, translowerprior, 'or', 'LineWidth', 1);\n fill([ts, fliplr(ts)], [(transupper)', fliplr((translower)')], ...\n 'r', 'EdgeAlpha', 0, 'FaceAlpha', 0.15);\nend\ntransmuaprior = sqrt(exp(r.p_prc.kau *r.p_prc.mua_0(1) +r.p_prc.omu));\nplot(ts, [transmuaprior; sqrt(exp(r.p_prc.kau *r.traj.mua(:,1) +r.p_prc.omu))], 'r', 'LineWidth', 1.5);\nhold all;\nplot(0, transmuaprior, 'or', 'LineWidth', 1.5); % prior\nif genpar\n plot(ts(2:end), sd, '--', 'Color', 'k', 'LineWidth', 1);\nend\nxlim([0 ts(end)]);\ntitle(['Belief on noise (red) for \\kappa_\\alpha=', ...\n num2str(r.p_prc.kaa), ', \\omega_\\alpha=', num2str(r.p_prc.oma)], 'FontWeight', 'bold');\nylabel('\\mu \\alpha_1');\nhold off;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Decision model %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nsubplot(l+1,2,2*l+1);\n\nif plotsd == true\n upper = r.traj.muxhat(:,1)+1.96*sqrt(r.p_obs.ze +r.traj.saxhat(:,1));\n lower = r.traj.muxhat(:,1)-1.96*sqrt(r.p_obs.ze +r.traj.saxhat(:,1));\n\n fill([ts(2:end), fliplr(ts(2:end))], [(upper)', fliplr((lower)')], ...\n 'r', 'EdgeAlpha', 0, 'FaceAlpha', 0.15);\n hold all;\nend\nplot(ts(2:end), r.traj.muxhat(:,1), 'Color', [153/256 17/256 153/256], 'LineWidth', 1.5);\nhold all;\nplot(ts(2:end), r.y(:,1), '.', 'Color', [1 0.65 0], 'MarkerSize', 15); % responses\nif genpar\n plot(ts(2:end), mean, '-', 'Color', 'k', 'LineWidth', 1); % mean of input distribution\n plot(ts(2:end), mean +1.96.*sd, '--', 'Color', 'k', 'LineWidth', 1); % 95% interval of input distribution\n plot(ts(2:end), mean -1.96.*sd, '--', 'Color', 'k', 'LineWidth', 1); % 95% interval of input distribution\nend\nxlim([1 ts(end)]);\ntitle('Decision model: prediction of decision (purple) and decision (orange)', 'FontWeight', 'bold');\nylabel('y, \\^{\\mu} x_1');\nxlabel({'Trial number', ' '}); % A hack to get the relative subplot sizes right\nhold off;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Learning rate %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif genpar\nsubplot(l+1,2,2*l+2);\n[AX, H1, H2 ] = plotyy(ts(2:end), mean, ts(2:end), r.traj.lrx(:,1));\nhold all;\nylim(AX(1), [min(mean -1.96.*sd-3), max(mean +1.96.*sd+3)]);\nplot(AX(1), ts(2:end), mean +1.96.*sd, '--', 'Color', 'k', 'LineWidth', 1.1); % 95% interval of input distribution\nplot(AX(1), ts(2:end), mean -1.96.*sd, '--', 'Color', 'k', 'LineWidth', 1.1); % 95% interval of input distribution\nset(H1, 'Color', 'k', 'LineWidth', 1.1);\nset(H2, 'Color', [178/256, 34/256, 34/256], 'LineWidth', 1.5);\nset(AX(1), 'YColor', 'k');\nset(AX(2), 'YColor', 'k');\nxlim(AX(1), [1 ts(end)]);\nxlim(AX(2), [1 ts(end)]);\ntitle('Learning rate (bordeaux) and input sampling distribution (black)', 'FontWeight', 'bold');\nylabel(AX(1), 'Input');\nylabel(AX(2), '\\sigma_x');\nxlabel('Trial number');\nhold off;\nend", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/HGF/tapas_hgf_jget_plotTraj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.4964887717678952}} {"text": "% MP_SP_DRCHLT_L2_PROJ_UDOTN: assign the normal degrees of freedom trough an L2 projection for a multipatch geometry. \n% To be used with the 'RT' and 'NDL' spaces. The imposed condition reads u \\cdot n = h \\cdot n\n%\n% [vel, normal_dofs] = mp_sp_drchlt_l2_proj_udotn (space, msh, gnum, ornt, bnd_sides, bnd_func)\n%\n% INPUTS:\n% \n% space: space object (see sp_vector_div_transform)\n% msh: mesh object (see msh_cartesian)\n% gnum: global numbering of the degrees of freedom (see mp_interface_hdiv)\n% ornt: global orientation of the degrees of freedom (see mp_interface_hdiv)\n% boundaries: array of structures containing the information for the boundaries (see mp_geo_load)\n% bnd_sides: boundary sides on which the Dirichlet condition is imposed\n% bnd_func: the condition to be imposed (h in the equation)\n% \n% OUTPUT:\n%\n% vel: assigned value to the normal degrees of freedom\n% normal_dofs: global numbering of the normal basis functions\n%\n% Copyright (C) 2014, 2015 Rafael Vazquez\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\nfunction [u, normal_dofs] = mp_sp_drchlt_l2_proj_udotn (space, msh, gnum, ornt, boundaries, refs, bnd_func)\n\n if (isa (space, 'sp_multipatch'))\n warning ('For spaces of the class SP_MULTIPATCH, using the function SP_DRCHLT_PROJ_L2_UDOTN inside the class')\n [u, dofs] = sp_drchlt_proj_l2_udotn (sp, msh, refs, bnd_func);\n return\n end\n \n ndof = max ([gnum{:}]);\n M = spalloc (ndof, ndof, 3*ndof);\n rhs = zeros (ndof, 1);\n\n normal_dofs = [];\n for iref = refs\n for bnd_side = 1:boundaries(iref).nsides\n iptc = boundaries(iref).patches(bnd_side);\n iside = boundaries(iref).faces(bnd_side);\n\n if (strcmpi (space{iptc}.transform, 'div-preserving'))\n msh_side = msh_eval_boundary_side (msh{iptc}, iside);\n sp_side = sp_eval_boundary_side (space{iptc}, msh_side);\n else\n error ('The function only works with div-conforming spaces')\n end\n\n normal_dofs = union (normal_dofs, gnum{iptc}(sp_side.dofs));\n for idim = 1:msh{iptc}.rdim\n x{idim} = reshape (msh_side.geo_map(idim,:,:), msh_side.nqn, msh_side.nel);\n end\n g = bnd_func (x{:}, iref);\n\n M_loc = op_u_v (sp_side, sp_side, msh_side, ones(size(x{1})));\n rhs_loc = op_fdotn_v (sp_side, msh_side, g);\n \n global_dofs = gnum{iptc}(sp_side.dofs);\n M(global_dofs, global_dofs) = M(global_dofs, global_dofs) + M_loc;\n rhs(global_dofs) = rhs(global_dofs) + rhs_loc;\n end\n end\n \n u = M(normal_dofs, normal_dofs) \\ rhs(normal_dofs);\n \nend\n", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/obsolete/mp_sp_drchlt_l2_proj_udotn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.4964887616936177}} {"text": "function [image_information_metric, rniirs, diagnostic] = RGIQE(filename, varargin)\n% RGIQE Radar generalized image quality equation\n% [image_information_metric, rniirs] = RGIQE(bandwidth, nesz_db, graze_degrees)\n% [image_information_metric, rniirs] = RGIQE(filename, 'PropertyName', PropertyValue, ...)\n%\n% An implementation of a generalized image quality equation to provide a\n% quantitative image quality metric and an RNIIRS prediction.\n%\n% RNIIRS (Radar National Imagery Interpretation Rating Scale) is an image\n% quality scale from 1 to 9. This \"quality\" refers to local image fidelity\n% and a users ability to perform certain detection and recognition tasks\n% with an image. The \"quality\" that RNIIRS attempts to capture does NOT\n% refer to image size, geopositioning accuracy, radiometric accuracy, or\n% any other host of characterists that may improve an image's utility.\n% Although RNIIRS is subjective, generally assessed by a trained analyst,\n% an image quality equation (IQE) may be used to predict RNIIRS for a given\n% SAR collect.\n%\n% The General Image Quality Equation (GIQE) provided here uses generic,\n% fundamental, sensor-indepenedent parameters of radar collection to\n% measure local image fidelity by quantifying the information density in\n% the ground in terms of bits\\m^2, using Shannon's channel capacity\n% theorem. Unlike RNIIRS, this value is quantitative and not subjective or\n% based on analysts' assessments. We can however compute an RNIIRS\n% prediction based off of it by fitting the information metric to analysts\n% ratings. Both the information theory metric and the RNIIRS prediction\n% are computed in this function.\n%\n% [image_information_metric, rniirs] = RGIQE(bandwidth, nesz_db, graze_degrees)\n% INPUTS:\n%\n% bandwidth Transmitted (and processed) bandwidth in Hz.\n% nesz_db Noise equivalent sigma-0 in dB. Should\n% capture all noise, including multiplicative\n% sources.\n% graze_degrees Grazing angle in degrees.\n%\n%\n% [image_information_metric, rniirs] = RGIQE(filename, 'PropertyName', PropertyValue, ...)\n% INPUTS:\n%\n% filename Must either be a complex image in a format\n% recognized by the MATLAB SAR Toolbox or an\n% XML file with SICD-formatted XML. If empty\n% or not passed, the user will be prompted to\n% select a file with a dialog box.\n%\n% Property name Description\n% multi_noise Multiplicative noise. This value is equal to:\n%\n% MNR * sigma_0_background\n%\n% where MNR is the multiplicative noise ratio\n% and sigma_0_background is the assumed power\n% level of the background and ambiguous\n% areas.\n% MNR can further be broken down into:\n%\n% MNR = ISLR + QNR + AMBR\n%\n% where ISLR is the integrated sidelobe\n% ratio, QNR is the quantization noise ratio,\n% and AMBR is the ambiguity ratio.\n% (Default = 0)\n% interactive \"AUTO\", \"NOISE\", \"SIGNAL\", \"BOTH\", or \"NONE\".\n% Enable interactive measurement of noise and\n% signal levels. \"AUTO\" only runs\n% interactive measurment if metadata from\n% source file does not provide it. (Default\n% is \"AUTO\").\n% frames If a file contains more than one complex\n% dataset, this value specifies for which of\n% those datasets to compute metrics. (Default\n% is all datasets in the file.)\n% signal_sigma_override Allows caller to override signal level used\n% for computation (and INTERACTIVE input\n% parameter). In general, this is not\n% recommended, as RNIIRS estimation function\n% was trained using the default values. If\n% the dataset provided is radiometrically\n% calibrated, this value will be treated as\n% calibrated signal level in the ground plane\n% (sigma-0). If the dataset is not\n% calibrated, this value will be assume to be\n% average pixel power. (Default is 1 square\n% meter of radar return per square meter on\n% the ground for co-pol, 0.25 for cross-pol.)\n%\n% Note that the selection of signal level and noise level are fundamentally\n% different in this model. Noise is measureable, quantifiable, and likely\n% fairy accuractely predictable (at least for additive noise). There is a\n% right answer for what the noise level is for any given dataset. On the\n% other hand, signal level is somewhat arbitrarily chosen, selected to be\n% the power level of the scene content that one may be most interested in\n% examining. It is for this reason that this function allows for a signal\n% level override, but not a direct noise level override (although noise can\n% be adjusted with the MULTI_NOISE input parameter.)\n%\n% Author: Wade Schwartzkopf, NGA/Research\n\n% Of the lines in this file, >95% is file and input parameter parsing and\n% documention, and <5% actually computing the image quality metrics...\n\n%% Bandwidth formulation\n% Assumes azimuth bandwidth to match range in ground plane\n% NESZ provided should capture all noise, including multiplicative sources\nif nargin == 3 && isnumeric(filename) && isnumeric(varargin{1}) && isnumeric(varargin{2})\n bandwidth = filename; % Hz\n nesz = varargin{1}; % in dB\n graze = varargin{2}; % in degrees\n bandwidth = bandwidth*2/SPEED_OF_LIGHT; % Convert units from Hz to cycles/m\n bandwidth = bandwidth*cosd(graze); % Convert from slant plane to ground plane\n bandwidth = bandwidth.^2; % Convert from 1D bandwidth to 2D bandwidth area (assumes azimuth bandwidth same as range)\n image_information_metric = bandwidth.*log2(1+1/(10^(nesz/10)));\n rniirs = estimate_rniirs(image_information_metric);\n diagnostic = struct(); % No diagnostics for this version\n return;\nend\n\n%% SICD/SLC version.\n%% Open input file\nif ((nargin<1)||isempty(filename)) % If no filename was give, use dialog box to ask for one\n % Recall last interactively selected path used\n if ispref('matlab_sar_toolbox','last_used_directory')\n pathname = getpref('matlab_sar_toolbox','last_used_directory');\n if ~ischar(pathname)||~exist(pathname,'dir')\n pathname = pwd;\n end\n else\n pathname = pwd;\n end\n [filename,pathname]=uigetfile(sar_file_extensions(),...\n 'Open SAR Data File',pathname);\n setpref('matlab_sar_toolbox','last_used_directory',pathname);\nelse % Path was already passed in with filenames\n pathname='';\nend\nif(filename)\n fullfilename=[pathname filename];\nelse % filename=0. Cancel was pressed, instead of a file being chosen.\n return;\nend\nif ~isempty(pathname)\n setpref('matlab_sar_toolbox','last_used_directory',pathname); %store path\nend\ntry\n ro = open_reader(fullfilename);\n % Check for multiple images\n if ~iscell(ro)\n ro = {ro};\n end\n meta = cell(numel(ro),1);\n for i = 1:numel(ro)\n meta{i} = ro{i}.get_meta();\n end\ncatch\n try\n fid = fopen(fullfilename);\n meta = {sicdxml2struct(xmlread( java.io.StringBufferInputStream( char(fread(fid)'))))};\n fclose(fid);\n catch\n error('RGIQE:InvalidFile','Invalid File.');\n end\nend\n\n%% Parse other input parameters\np = inputParser;\np.addParameter('multi_noise', 0, @(x) isnumeric(x) && isscalar(x));\np.addParameter('interactive', 'AUTO', @(x) ismember(upper(x), ...\n {'AUTO', 'NOISE', 'SIGNAL', 'BOTH', 'NONE'}));\np.addParameter('frames', 1:numel(meta), @(x) all(ismember(x, 1:numel(meta))));\np.addParameter('signal_sigma_override', [], @(x) isnumeric(x) && isscalar(x));\nparse(p,varargin{:})\n\n%% Iterate through datasets provided\nmeta = meta(p.Results.frames);\nimage_information_metric = zeros(numel(meta),1);\nrniirs = zeros(numel(meta),1);\nfor i = 1:numel(meta)\n meta{i} = derived_sicd_fields(meta{i}); % Assure all radiometric fields are derived if not there\n\n %% Get noise level\n if isfield(meta{i}, 'Radiometric') && ...\n isfield(meta{i}.Radiometric,'NoiseLevel') && ...\n isfield(meta{i}.Radiometric.NoiseLevel,'NoiseLevelType') && ...\n strcmpi(meta{i}.Radiometric.NoiseLevel.NoiseLevelType,'ABSOLUTE') && ...\n isfield(meta{i}.Radiometric.NoiseLevel,'NoisePoly') && ...\n ~ismember(upper(p.Results.interactive), {'NOISE', 'BOTH'})\n % SICD metadata can only tell us additive noise. Estimation of\n % multiplicative noise must come from elsewhere.\n noise_sigma = 10^(meta{i}.Radiometric.NoiseLevel.NoisePoly(1)/10) + p.Results.multi_noise;\n elseif ismember(upper(p.Results.interactive), {'AUTO', 'NOISE', 'BOTH'})\n % Measured noise contains both additive and multiplicative noise\n uiwait(msgbox('Please select a noise region for measurement.','Noise measurement'));\n aoi = mitm_viewer(fullfilename,'mode','aoi','closeAfterSelect',true,'initialFrame',i);\n if isempty(aoi), return; end % Cancel was selected\n cdata = double(ro{i}.read_chip(...\n [aoi(1) aoi(1)+aoi(3)-1],[aoi(2) aoi(2)+aoi(4)-1]));\n noise_sigma = mean(abs(cdata(:)).^2);\n else\n noise_sigma = NaN;\n end\n if isfield(meta{i}, 'Radiometric') && ...\n isfield(meta{i}.Radiometric, 'SigmaZeroSFPoly')\n % Scale to be equal to noise equivalent sigma zero\n noise_sigma = meta{i}.Radiometric.SigmaZeroSFPoly(1) * noise_sigma;\n end\n\n %% Get signal level\n % One issue with using the Shannon-Hartley channel capacity formulation\n % is that it requires a signal level. Certainly the amount of\n % information a SAR image conveys is related to its signal level, so\n % this is how we hope it would behave. A target with brighter returns\n % is always easier to interpret than a target that is in the noise.\n % However, it presents a problem to image quality prediction, since the\n % signal level can't be known prior to measurement. This constraint is\n % implicitly true for traditional RNIIRS assessments as well, which\n % assumes specific types of targets.\n % One approach for setting the signal level used in the channel\n % capacity equation would be to assume a fixed radiometric signal level\n % that is representative of the sorts of scene content we are generally\n % interested in and use that same signal level across all images for\n % which we compute this metric. This allows for an even\n % apples-to-apples comparison across images of varying content and is\n % consistent with the traditional RNIIRS viewpoint, which assumes\n % specific types of tasks and scene content.\n % Another approach would be to use the signal level in the actual scene\n % by measuring the average pixel power across a full image or AOI. This\n % approach may be more accurate at measuring the true information in\n % any given image area. However, it may be less consistent with the\n % traditional RNIIRS viewpoint, and this approach can only be used\n % after the collection has been made, not prior to it for planning\n % collection and predicting image quality.\n % We also allow the caller of the function to pass their own signal\n % level. Passing a non-default signal level is not recommended for\n % RNIIRS estimation, since the RNIIRS function was trained on the\n % default values. However, we provide this flexibility in case it\n % might be educational to see how it affects the information theory\n % metric.\n if ~ismember('signal_sigma_override', p.UsingDefaults)\n signal_sigma = p.Results.signal_sigma_override;\n elseif isfield(meta{i}, 'Radiometric') && ...\n isfield(meta{i}.Radiometric, 'SigmaZeroSFPoly') && ...\n ~ismember(upper(p.Results.interactive), {'SIGNAL', 'BOTH'})\n % Default value: 1 square meter of return per square meter on\n % the ground (roughly similar to a large vehicle over its area).\n % Ulaby plots show cross-pol generally 5-10dB lower than\n % co-pol. We pick 1/4 as simple round number.\n if isfield(meta{i},'ImageFormation') && ...\n isfield(meta{i}.ImageFormation,'TxRcvPolarizationProc') && ...\n numel(unique(split(meta{i}.ImageFormation.TxRcvPolarizationProc,':')))>1\n signal_sigma = 0.25;\n else\n signal_sigma = 1;\n end\n elseif ismember(upper(p.Results.interactive), {'AUTO', 'SIGNAL', 'BOTH'})\n ButtonName = questdlg(['Do you want to use average signal '...\n 'power across entire image or select an AOI?'], ...\n 'Signal level estimation', ...\n 'Image', 'AOI', 'Image');\n if isempty(ButtonName), return; end %window was closed CANCEL\n if strcmpi(ButtonName,'AOI')\n aoi = mitm_viewer(fullfilename,'mode','aoi','closeAfterSelect',true,'initialFrame',i);\n if isempty(aoi), return; end % Cancel was selected\n cdata = double(ro{i}.read_chip(...\n [aoi(1) aoi(1)+aoi(3)-1],[aoi(2) aoi(2)+aoi(4)-1]));\n signal_sigma = mean(abs(cdata(:)).^2) - noise_sigma;\n else\n samplesize=[1000 1000]; % Exract 1000x1000 array of samples to estimate mean\n subsample=ceil(double([meta{i}.ImageData.NumCols meta{i}.ImageData.NumRows])./samplesize);\n data = abs(single(ro{i}.read_chip([1 meta{i}.ImageData.NumCols],...\n [1 meta{i}.ImageData.NumRows],subsample)));\n signal_sigma = mean(abs(data(:)).^2) - noise_sigma;\n end\n if isfield(meta{i}, 'Radiometric') && ...\n isfield(meta{i}.Radiometric, 'SigmaZeroSFPoly')\n % Scale to be equal to noise equivalent sigma zero\n signal_sigma = meta{i}.Radiometric.SigmaZeroSFPoly * signal_sigma;\n end\n warning('RGIQE:SignalLevelMeasured',['More uncertainty with ' ...\n 'RNIIRS estimates exists when signal level is sampled, ' ...\n 'rather than when using a radiometric constant.']);\n else\n signal_sigma = NaN;\n end\n\n %% Save some diagnostic statistics\n if isfield(meta{i}, 'Radiometric') && ...\n isfield(meta{i}.Radiometric, 'SigmaZeroSFPoly')\n diagnostic.nesz(i) = 10*log10(noise_sigma);\n end\n diagnostic.snr(i) = signal_sigma/noise_sigma;\n diagnostic.sp_resolution(i) = sqrt(meta{i}.Grid.Row.ImpRespWid * ...\n meta{i}.Grid.Col.ImpRespWid);\n diagnostic.ellipicity(i) = max(meta{i}.Grid.Row.ImpRespWid, ...\n meta{i}.Grid.Col.ImpRespWid)/min(meta{i}.Grid.Row.ImpRespWid, ...\n meta{i}.Grid.Col.ImpRespWid);\n if numel(meta)>1\n diagnostic.meta{i} = meta{i};\n else\n diagnostic.meta = meta{i};\n end\n\n %% Compute bandwidth area\n % The cosine of the slope angle is proper scale factor to project the\n % bandwidth area into the ground plane.\n diagnostic.bandwidth_area(i) = ...\n meta{i}.Grid.Col.ImpRespBW * meta{i}.Grid.Row.ImpRespBW * ...\n cosd(meta{i}.SCPCOA.SlopeAng);\n % Computing area from vertices is much more work, but it may help\n % visualize.\n % Project slant plane spatial frequency bounds to ground plane\n % coords_slant_x = meta{i}.Grid.Col.KCtr + ...\n % meta{i}.Grid.Col.ImpRespBW * [-1 1 1 -1 -1]/2;\n % coords_slant_y = meta{i}.Grid.Row.KCtr + ...\n % meta{i}.Grid.Row.ImpRespBW * [1 1 -1 -1 1]/2;\n % ruvect = [meta{i}.Grid.Row.UVectECF.X meta{i}.Grid.Row.UVectECF.Y meta{i}.Grid.Row.UVectECF.Z];\n % cuvect = [meta{i}.Grid.Col.UVectECF.X meta{i}.Grid.Col.UVectECF.Y meta{i}.Grid.Col.UVectECF.Z];\n % coords_slant_3d = ruvect'*coords_slant_y + cuvect'*coords_slant_x;\n % Compute basis vectors for ground plane\n % gpn = wgs_84_norm([meta{i}.GeoData.SCP.ECF.X meta{i}.GeoData.SCP.ECF.Y meta{i}.GeoData.SCP.ECF.Z])';\n % gruvect = project_ground(ruvect, gpn); % Project range vector to ground plane\n % gruvect = gruvect/norm(gruvect);\n % gcuvect = cross(gruvect,gpn);\n % gcuvect = gcuvect/norm(gcuvect);\n % Project spatial frequencies to ground plane\n % coords_ground_3d = coords_slant_3d;\n % coords_ground_x = zeros(size(coords_slant_x));\n % coords_ground_y = zeros(size(coords_slant_y));\n % for j=1:numel(coords_slant_x)\n % % Planes in ECF\n % coords_ground_3d(:,j) = project_ground(coords_slant_3d(:,j)',gpn)';\n % % Convert to 2D basis vectors in ground plane\n % coords_ground_x(j) = dot(coords_ground_3d(:,j),gcuvect);\n % coords_ground_y(j) = dot(coords_ground_3d(:,j),gruvect);\n % end\n % This is a way to compute the area of a any polygon from its vertices.\n % diagnostic.bandwidth_area = sum((coords_ground_x(1:(end-1)).*coords_ground_y(2:end)) - ...\n % (coords_ground_y(1:(end-1)).*coords_ground_x(2:end)))/2;\n % Visualize spatial frequency projections in slant and ground planes\n % figure;\n % title('Spatial frequency bounds 3D');\n % g_plane = gruvect'*[100 100 -100 -100 100] + gcuvect'*[-100 100 100 -100 -100];\n % plot3(coords_slant_3d(1,:),coords_slant_3d(2,:),coords_slant_3d(3,:),...\n % coords_ground_3d(1,:),coords_ground_3d(2,:),coords_ground_3d(3,:),...\n % g_plane(1,:),g_plane(2,:),g_plane(3,:));\n % legend('Slant plane bounds', 'Ground plane bounds', 'Ground plane')\n % figure;\n % plot(coords_slant_x, coords_slant_y, coords_ground_x, coords_ground_y);\n % title('Spatial frequency bounds');\n % legend('Slant plane bounds', 'Ground plane bounds')\n\n %% After 300+ line of setup code and comments, we finally compute quality metric...\n % Shannon-Hartley theorem of channel capacity\n % C = B * log2(1 + (S/N))\n % We propose a 2-dimension information rate based on a 2-dimensional\n % bandwidth. This 2D bandwidth is an area in a space where each axis\n % is cycles/m, as opposed to 1D distance in Hz (cycles per second).\n % Therefore the units of this metric are bits/m^2.\n image_information_metric(i) = diagnostic.bandwidth_area(i) * log2(1 + diagnostic.snr(i));\n\n %% Map bits/m^2 into RNIIRS\n if ismember('signal_sigma_override', p.UsingDefaults)\n rniirs(i) = estimate_rniirs(image_information_metric(i));\n else % If assumed signal is not default, this RNIIRS mapping is not valid\n rniirs(i) = NaN;\n end\nend\ntry\n for i = 1:numel(meta)\n ro{i}.close();\n end\nend\n\nend\n\nfunction rniirs = estimate_rniirs(image_information_metric)\n % The coefficients here were derived by fitting hundreds of SAR\n % datasets with varying parameters to analysts ratings. This\n % author prefers the information metric but also provides this as\n % well for comparison to this legacy scale.\n % coeffs = [0.3960 3.7555]; % Probably more digits of precision than we really have\n coeffs = [0.4357 3.4761]; % Coefficients were updated by NGA NIQU (Feb 1, 2022) to more accruately represent RNIIRS tables\n rniirs = polyval(coeffs,log2(image_information_metric));\n % For completeness, we handle the very low RNIIRS case where the\n % logarithmic equation would have been negative. Negative is not\n % allowed in the RNIIRS scale. We compute where a line tangent to\n % the bits/m^2-to-RNIIRS function intersects with the origin. We\n % will use this tangent line as the mapping for very low RNIIRS,\n % since it approaches zero as information approaches zero and\n % remains non-negative. This way the entire mapping function\n % between bits/m^2 and RNIIRS is continuous and has a continuous\n % derivative. The function will be logarithmic with respect to the\n % information metric above this point (presumably nearly all data\n % will fit in here) and linear with respect to the metric below\n % this point (extremely low RNIIRS). Note that since NGA has no\n % precedent or analysts ratings for RNIIRS<1, we are really free to\n % define this however we want.\n linlog_transition = exp(1 - coeffs(2)*log(2)/coeffs(1));\n % Derivative of linear portion (as well as intersection with log portion)\n d_rniirs = coeffs(1)/(log(2)*linlog_transition);\n % This is what the two lines would look line at very low RNIIRS:\n % x=linspace(0,.02,1000);\n % figure; plot(x, polyval(coeffs,log2(x)), x, x*d_rniirs);\n % That was a lot of explanation for a case that will likely rarely\n % be used, wasn't it?\n if image_information_metric=0 and real(Z2)>=0\nind = (real(Z1)>=0) & (real(Z2)>=0);\nif any(any(ind))\n g(ind) = preFactor1(ind) - preFactor2(ind) + preFactor3(ind);\nend;\n% Evaluation of Upsilon when real(Z1)<0 and real(Z2)>=0\nind = (real(Z1)<0) & (real(Z2)>=0);\nif any(any(ind))\n g(ind) = preFactor2(ind) + preFactor3(ind);\nend\n% Evaluation of Upsilon when real(Z1)>=0 and real(Z2)<0\nind = (real(Z1)>=0) & (real(Z2)<0);\nif any(any(ind))\n g(ind) = - preFactor2(ind) - preFactor3(ind);\nend;\n% Evaluation of Upsilon when real(Z1)<0 and real(Z2)<0\nind = (real(Z1)<0) & (real(Z2)<0);\nif any(any(ind))\n g(ind) = -preFactor1(ind) + preFactor2(ind) - preFactor3(ind);\nend;\n\nif mode==4\n g = g.';\nend\n\n\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/lfmGradientUpsilon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4964293757223931}} {"text": "% Intrinsic and Extrinsic Camera Parameters\n%\n% This script file can be directly excecuted under Matlab to recover the camera intrinsic and extrinsic parameters.\n% IMPORTANT: This file contains neither the structure of the calibration objects nor the image coordinates of the calibration points.\n% All those complementary variables are saved in the complete matlab data file Calib_Results.mat.\n% For more information regarding the calibration model visit http://www.vision.caltech.edu/bouguetj/calib_doc/\n\n\n%-- Focal length:\nfc = [ 1588.853342543796771 ; 1589.141065148706048 ];\n\n%-- Principal point:\ncc = [ 336.852104684709388 ; 166.220483494858200 ];\n\n%-- Skew coefficient:\nalpha_c = 0.000000000000000;\n\n%-- Distortion coefficients:\nkc = [ -0.183448717338282 ; -0.034396151458065 ; -0.005473481906443 ; 0.004392952805618 ; 0.000000000000000 ];\n\n%-- Focal length uncertainty:\nfc_error = [ 31.801580904116800 ; 29.314132245923947 ];\n\n%-- Principal point uncertainty:\ncc_error = [ 49.273756028476519 ; 39.985395373378047 ];\n\n%-- Skew coefficient uncertainty:\nalpha_c_error = 0.000000000000000;\n\n%-- Distortion coefficients uncertainty:\nkc_error = [ 0.066741056034172 ; 0.873747062658826 ; 0.006527073109278 ; 0.004504614774849 ; 0.000000000000000 ];\n\n%-- Image size:\nnx = 640;\nny = 480;\n\n\n%-- Various other variables (may be ignored if you do not use the Matlab Calibration Toolbox):\n%-- Those variables are used to control which intrinsic parameters should be optimized\n\nn_ima = 15;\t\t\t\t\t\t% Number of calibration images\nest_fc = [ 1 ; 1 ];\t\t\t\t\t% Estimation indicator of the two focal variables\nest_aspect_ratio = 1;\t\t\t\t% Estimation indicator of the aspect ratio fc(2)/fc(1)\ncenter_optim = 1;\t\t\t\t\t% Estimation indicator of the principal point\nest_alpha = 0;\t\t\t\t\t\t% Estimation indicator of the skew coefficient\nest_dist = [ 1 ; 1 ; 1 ; 1 ; 0 ];\t% Estimation indicator of the distortion coefficients\n\n\n%-- Extrinsic parameters:\n%-- The rotation (omc_kk) and the translation (Tc_kk) vectors for every calibration image and their uncertainties\n\n%-- Image #1:\nomc_1 = [ -1.557681e+00 ; -2.205804e+00 ; 1.330361e+00 ];\nTc_1 = [ 1.734034e+02 ; 5.794926e+01 ; 2.044993e+03 ];\nomc_error_1 = [ 2.933522e-02 ; 2.081152e-02 ; 3.616192e-02 ];\nTc_error_1 = [ 6.355186e+01 ; 5.156988e+01 ; 3.664085e+01 ];\n\n%-- Image #2:\nomc_2 = [ -1.702089e+00 ; -2.256995e+00 ; 1.267502e+00 ];\nTc_2 = [ -6.722390e+01 ; 5.941507e+01 ; 2.057353e+03 ];\nomc_error_2 = [ 3.035591e-02 ; 2.055681e-02 ; 3.795895e-02 ];\nTc_error_2 = [ 6.380940e+01 ; 5.186705e+01 ; 3.924807e+01 ];\n\n%-- Image #3:\nomc_3 = [ -1.701930e+00 ; -2.253495e+00 ; 1.271626e+00 ];\nTc_3 = [ -2.657159e+02 ; 5.535306e+01 ; 2.111954e+03 ];\nomc_error_3 = [ 3.119852e-02 ; 2.203487e-02 ; 3.792260e-02 ];\nTc_error_3 = [ 6.555459e+01 ; 5.345885e+01 ; 4.297524e+01 ];\n\n%-- Image #4:\nomc_4 = [ 1.893838e+00 ; 1.951405e+00 ; -6.883375e-01 ];\nTc_4 = [ 1.355395e+02 ; 6.304476e+01 ; 2.007853e+03 ];\nomc_error_4 = [ 1.462647e-02 ; 2.105632e-02 ; 3.955605e-02 ];\nTc_error_4 = [ 6.234890e+01 ; 5.068514e+01 ; 3.911636e+01 ];\n\n%-- Image #5:\nomc_5 = [ 1.908480e+00 ; 1.850529e+00 ; -5.507656e-01 ];\nTc_5 = [ -9.864709e+01 ; 6.448043e+01 ; 2.021515e+03 ];\nomc_error_5 = [ 1.405146e-02 ; 2.113590e-02 ; 3.862142e-02 ];\nTc_error_5 = [ 6.272370e+01 ; 5.106967e+01 ; 4.131143e+01 ];\n\n%-- Image #6:\nomc_6 = [ 1.889738e+00 ; 1.980019e+00 ; -7.390048e-01 ];\nTc_6 = [ -3.575459e+02 ; 6.164224e+01 ; 2.073652e+03 ];\nomc_error_6 = [ 1.076545e-02 ; 2.434070e-02 ; 4.112093e-02 ];\nTc_error_6 = [ 6.427989e+01 ; 5.275973e+01 ; 4.590561e+01 ];\n\n%-- Image #7:\nomc_7 = [ 1.904119e+00 ; 1.613811e+00 ; -2.469117e-01 ];\nTc_7 = [ 1.050648e+02 ; 6.953312e+01 ; 1.959883e+03 ];\nomc_error_7 = [ 1.877046e-02 ; 1.939786e-02 ; 3.660657e-02 ];\nTc_error_7 = [ 6.086765e+01 ; 4.946251e+01 ; 3.876840e+01 ];\n\n%-- Image #8:\nomc_8 = [ 1.874544e+00 ; 1.387578e+00 ; 5.963331e-03 ];\nTc_8 = [ -1.316064e+02 ; 7.296929e+01 ; 1.962026e+03 ];\nomc_error_8 = [ 1.991265e-02 ; 1.966408e-02 ; 3.477026e-02 ];\nTc_error_8 = [ 6.097585e+01 ; 4.958890e+01 ; 3.966239e+01 ];\n\n%-- Image #9:\nomc_9 = [ 1.867279e+00 ; 1.338834e+00 ; 5.192820e-02 ];\nTc_9 = [ -3.848199e+02 ; 7.244019e+01 ; 2.003159e+03 ];\nomc_error_9 = [ 1.905893e-02 ; 2.014607e-02 ; 3.409265e-02 ];\nTc_error_9 = [ 6.267821e+01 ; 5.108076e+01 ; 4.288011e+01 ];\n\n%-- Image #10:\nomc_10 = [ -1.715796e+00 ; -2.041805e+00 ; 9.303852e-01 ];\nTc_10 = [ 1.012077e+02 ; 7.501598e+01 ; 1.710616e+03 ];\nomc_error_10 = [ 2.385211e-02 ; 2.111071e-02 ; 3.698204e-02 ];\nTc_error_10 = [ 5.316514e+01 ; 4.311025e+01 ; 3.065417e+01 ];\n\n%-- Image #11:\nomc_11 = [ -1.805616e+00 ; -2.089567e+00 ; 8.651741e-01 ];\nTc_11 = [ -6.268099e+01 ; 8.236545e+01 ; 1.672806e+03 ];\nomc_error_11 = [ 2.455832e-02 ; 2.181052e-02 ; 3.822892e-02 ];\nTc_error_11 = [ 5.190998e+01 ; 4.218558e+01 ; 3.143920e+01 ];\n\n%-- Image #12:\nomc_12 = [ -1.897248e+00 ; -2.132223e+00 ; 7.958098e-01 ];\nTc_12 = [ -2.617251e+02 ; 8.772964e+01 ; 1.655251e+03 ];\nomc_error_12 = [ 2.597201e-02 ; 2.298575e-02 ; 3.987007e-02 ];\nTc_error_12 = [ 5.154881e+01 ; 4.202592e+01 ; 3.365145e+01 ];\n\n%-- Image #13:\nomc_13 = [ 2.114980e+00 ; 2.117562e+00 ; -3.547934e-01 ];\nTc_13 = [ 3.651036e+01 ; 1.009631e+02 ; 1.516712e+03 ];\nomc_error_13 = [ 1.733561e-02 ; 1.778940e-02 ; 4.120690e-02 ];\nTc_error_13 = [ 4.712996e+01 ; 3.839118e+01 ; 3.001941e+01 ];\n\n%-- Image #14:\nomc_14 = [ 2.128866e+00 ; 2.219968e+00 ; -5.388805e-01 ];\nTc_14 = [ -6.343915e+01 ; 1.021354e+02 ; 1.517822e+03 ];\nomc_error_14 = [ 1.478417e-02 ; 2.098690e-02 ; 4.310996e-02 ];\nTc_error_14 = [ 4.710837e+01 ; 3.841050e+01 ; 2.980588e+01 ];\n\n%-- Image #15:\nomc_15 = [ 2.121751e+00 ; 2.168024e+00 ; -4.694731e-01 ];\nTc_15 = [ -2.722483e+02 ; 1.012912e+02 ; 1.548764e+03 ];\nomc_error_15 = [ 1.690688e-02 ; 2.488503e-02 ; 4.454520e-02 ];\nTc_error_15 = [ 4.814071e+01 ; 3.949586e+01 ; 3.320000e+01 ];\n\n", "meta": {"author": "zhixy", "repo": "Laser-Camera-Calibration-Toolbox", "sha": "f0bd1b984c51dea79840c344c1fec8cb3d088730", "save_path": "github-repos/MATLAB/zhixy-Laser-Camera-Calibration-Toolbox", "path": "github-repos/MATLAB/zhixy-Laser-Camera-Calibration-Toolbox/Laser-Camera-Calibration-Toolbox-f0bd1b984c51dea79840c344c1fec8cb3d088730/sample_results/Calib_Results.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4964293661129056}} {"text": "function [flips,scorepath,covmats_unflipped] = findflip(data,T,options)\n% Finds an optimal permutation of the channels, where goodness is measured\n% as the mean lagged partial cross-correlation across pair of channels and lags.\n% In other words, it finds a permutation where the signs of the lagged\n% partial correlations agree as much as possible across subjects.\n%\n% INPUTS\n% data observations, either a struct with X (time series)\n% or just a matrix containing the time series\n% Alternatively, it can be an (unflipped) array of\n% autocorrelation matrices (ndim x ndim x no.lags x no. trials),\n% as computed for example by getCovMats()\n% T length of series. If data is supplied as the\n% autocorrelation matrices, then this is not required and\n% can be specified as []\n% options:\n% maxlag max lag to consider\n% nbatch no. of channels to evaluate at each iteration (0 for all)\n% noruns how many random initialisations will be carried out\n% standardise if 1, standardise the data\n% partial if 1, base on partial correlation instead of correlation\n% maxcyc for each initialization, maximum number of cycles of the greedy algorithm\n% verbose do we get loud?\n%\n% data_ref and T_ref refer to having a previous data set to\n% with which we want to be consistent (see above). These are assumed to be\n% already sign-disambiguated\n\n% OUTPUT\n% flips (length(T) X No. channels) binary matrix saying which channels must be\n% flipped for each time series\n% scorepath cell with the score of the winning solutions\n% covmats_unflipped the disambiguated covariance matrices\n%\n% Author: Diego Vidaurre, University of Oxford.\n\nif nargin < 3, options = struct; end\n\noptions = checkoptions_flip(options);\ncovmats_unflipped = Get_Global_Variables_For_BitFlip_Evaluation(data,T,options);\nN = size(covmats_unflipped,4);\n\nndim = size(covmats_unflipped,1);\nscore = -Inf;\nscorepath = cell(options.noruns,1);\n\nif isinf(options.maxcyc) && (options.nbatch > 0)\n error('If maxcyc is Inf, options.nbatch must be 0')\nend\n\n% repetitions of the search\nfor r = 1:options.noruns\n \n flipsr = Init_Solution(N,ndim,options,r);\n score_r = EvaluateFlips(flipsr,covmats_unflipped);\n scorepath{r} = score_r;\n if options.verbose\n fprintf('Run %d, Init, score %f \\n',r,score_r)\n end\n \n for cyc = 1:options.maxcyc\n \n if options.nbatch > 0\n channels = randperm(ndim,options.nbatch);\n else\n channels = randperm(ndim);\n end\n \n ScoreMatrix = zeros(N,ndim);\n for d = channels\n for j = 1:N\n ScoreMatrix(j,d) = EvaluateFlips(flipsr,covmats_unflipped,j,d);\n end\n end\n \n [score_r,I] = max(ScoreMatrix(:));\n [j,d] = ind2sub([N ndim],I);\n \n ds = score_r - max(scorepath{r});\n if ds > options.threshold\n flipsr(j,d) = ~flipsr(j,d);\n if options.verbose\n fprintf('Run %d, Cycle %d, score +%f, flipped (%d,%d) \\n',r,cyc,ds,j,d)\n end\n scorepath{r} = [scorepath{r} score_r];\n elseif options.nbatch == 0\n break\n else\n fprintf('Run %d, Cycle %d, score +0 \\n',r,cyc)\n end\n \n end\n \n if options.verbose\n fprintf('Run %d, Finish, score %f \\n',r,scorepath{r}(end))\n end\n \n if scorepath{r}(end) > score\n score = scorepath{r}(end);\n flips = flipsr;\n end\n \nend\n\nif options.verbose\n fprintf('Final Score=%f\\n',score)\nend\n\n% Among the equivalent flippings, we keep the one w/ the lowest no. of flips\nfor j = 1:N\n if mean(flips(j,:))>0.5\n flips(j,:) = 1 - flips(j,:);\n end\nend\n\nend\n\n\nfunction options = checkoptions_flip(options)\nif ~isfield(options,'maxlag'), options.maxlag = 10; end\nif ~isfield(options,'noruns'), options.noruns = 1; end\nif ~isfield(options,'probinitflip'), options.probinitflip = 0.25; end\nif ~isfield(options,'standardise'), options.standardise = 1; end\nif ~isfield(options,'partial'), options.partial = 0; end\nif ~isfield(options,'verbose'), options.verbose = 1; end\nif ~isfield(options,'nbatch'), options.nbatch = 0; end\nif ~isfield(options,'maxcyc'), options.maxcyc = 10000; end\nif ~isfield(options,'threshold'), options.threshold = 0.00001; end\nend\n\n\nfunction flipsr = Init_Solution(N,ndim,options,r)\n% Prepare the necessary data structures\nif ~isfield(options,'Flips')\n if r==1 % first run starts at no flips\n flipsr = zeros(N,ndim);\n else\n flipsr = binornd(1,options.probinitflip,N,ndim); % random init\n end\nelse\n flipsr = options.Flips;\nend\nend\n\n\nfunction covmats_unflipped = Get_Global_Variables_For_BitFlip_Evaluation(data,T,options)\n% Prepare the necessary data structures\nif length(size(data))==4 % it is an array of autocorrelation matrices already\n covmats_unflipped = data; clear data\nelse\n covmats_unflipped = getAllCovMats(data,T,options);\nend\nend\n\n\nfunction s = EvaluateFlips(flipsr,covmats_unflipped,j,d)\n% evaluate for a change in subject j and channel d\nif nargin>3, flipsr(j,d) = ~flipsr(j,d); end\nsignmats = getSignMat(flipsr);\ncovmats = applySign(covmats_unflipped,signmats);\ns = getscore(covmats);\nend\n\n\nfunction score = getscore(M)\n% get the score from the (flipped) matrices of autocorrelation contained in M\n% M is a matrix (ndim x ndim x lags x subjects) with autocovariances matrix for all subjects\nN = size(M,4); ndim = size(M,1); L = size(M,3);\nM = reshape(M,[(ndim^2)*L N]);\nC = corr(M);\nscore = mean(C(triu(true(N),1)));\nend\n\n\nfunction CovMats = applySign(CovMats,SignMats)\n% apply matrices of sign flipping to the autocorrelation matrices\nN = size(SignMats,3); nlags = size(CovMats,3);\nfor j = 1:N\n CovMats(:,:,:,j) = CovMats(:,:,:,j) .* repmat(SignMats(:,:,j),[1 1 nlags]);\nend\nend\n\n\nfunction SignMats = getSignMat(Flips)\n% Construct matrices of sign flipping for the autocorrelation matrices\n[N,ndim] = size(Flips);\nSignMats = zeros(ndim,ndim,N);\nfor j = 1:N \n flips = ones(1,ndim);\n flips(Flips(j,:)==1) = -1;\n SignMats(:,:,j) = flips' * flips;\nend\nend\n", "meta": {"author": "OHBA-analysis", "repo": "HMM-MAR", "sha": "bb0433b75482e473980791a2b30afe2012cf6578", "save_path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR", "path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR/HMM-MAR-bb0433b75482e473980791a2b30afe2012cf6578/utils/signflip/findflip.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.49627552923722823}} {"text": "function [amu] = mg2amu(mg)\n% Convert mass from milligrams to atomic mass units. \n% Chad Greene 2012\namu = mg*602213665167500000000;", "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/mg2amu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.49622589512650683}} {"text": "classdef BundleAdjust < matlab.mixin.Copyable\n \n properties\n % Cameras and landmarks are represented by graph nodes\n % coord(camera) -> camera pose, 6 vector\n % vdata(camera) -> index into state vector or [] if a fixed camera\n % coord(landmark) -> landmark position, first 3 elements of 6 vector\n % vdata(landmark) -> index into state vector\n %\n % An edge from camera to a landmark holds the observed projection as a\n % property\n % edata(edge) -> uv*\n \n g % PGraph object describing visibility\n \n \n camera % camera projection model\n \n cameras % list of graph nodes corresponding to cameras\n points % list of graph nodes corresponding to landmarks\n \n fixedcam % logical array of cameras that are fixed\n fixedpoint % logical array of landmarks that are fixed\n end\n \n properties (Dependent=true)\n ncams % number of cameras\n nlandmarks % number of landmark points\n ndim % size of the linear system\n end\n \n \n methods\n \n function ba = BundleAdjust(camera)\n %BundleAdjust.BundleAdjust Bundle adjustment problem constructor\n %\n % Notes::\n % - A cameraModel file must exist on the path to evaluate the point projection\n % and Jacobians.\n \n ba.camera = camera; % stash the camera model\n ba.g = PGraph(6); % initialize the graph, nodes have 6D coordinates\n end\n \n function n = get.ncams(ba)\n n = length(ba.cameras);\n end\n \n function n = get.nlandmarks(ba)\n n = length(ba.points);\n end\n \n function n = get.ndim(ba)\n n = 6*(ba.ncams - sum(ba.fixedcam)) + 3*(ba.nlandmarks - sum(ba.fixedpoint));\n end\n \n \n function n = cameraIdx(ba, i)\n n = 6*i - 5;\n end\n \n function n = landmarkIdx(ba, j)\n n = ba.ncams*6 + 3*j-2;\n end\n \n function n = cameraIdx2(ba, i)\n if ba.fixedcam(i)\n n = 0;\n else\n n = 6*(i - sum(ba.fixedcam(1:i))) - 5;\n end\n end\n \n function n = landmarkIdx2(ba, j)\n if ba.fixedpoint(j)\n n = 0;\n else\n n = 6*(ba.ncams - sum(ba.fixedcam)) + 3 * (j - sum(ba.fixedpoint(1:j))) - 2;\n end\n end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % METHODS TO SUPPORT BUILDING PROBLEMS\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n function vc = add_camera(ba, T, varargin)\n %BundleAdjust.add_camera Add camera to bundle adjustment problem\n %\n % VC = BA.add_camera(T, options) is the vertex id of a camera node added to\n % a bundle adjustment problem. The camera has pose T which can be SE3 or a\n % vector (1x7) comprising translation and quaternion.\n %\n % VC = BA.add_camera() as above but the camera pose is the null pose in SE3.\n %\n % Options::\n % 'fixed' This camera is fixed (anchored) and will not be adjusted in\n % the optimization process.\n %\n % See also BundleAdjust.add_landmark, BundleAdjust.add_projection, PGraph.\n \n \n if nargin == 1\n T = SE3();\n end\n \n opt.fixed = false;\n opt = tb_optparse(opt, varargin);\n \n if isvec(T, 7)\n t = T(1:3); q = T(4:7);\n else\n [R,t] = tr2rt(T);\n q = UnitQuaternion(R).double;\n t = t';\n end\n \n if q(1) < 0\n q = -q;\n end\n x = [t q(2:4)];\n vc = ba.g.add_node(x);\n ba.cameras = [ba.cameras vc];\n ba.g.setvdata(vc, length(ba.cameras));\n \n \n ba.fixedcam = [ba.fixedcam opt.fixed];\n end\n \n function vp = add_landmark(ba, P, varargin)\n %BundleAdjust.add_landmark Add landmark to bundle adjustment problem\n %\n % VL = BA.add_landmark(P, options) is the vertex id of a landmark node added to\n % a bundle adjustment problem. The landmark has position P (3x1).\n %\n % Options::\n % 'fixed' This landmark is fixed (anchored) and will not be adjusted in\n % the optimization process.\n %\n % See also BundleAdjust.add_camera, BundleAdjust.add_projection, PGraph.\n\n assert(isvec(P), 'P must be a 3-vector');\n \n opt.fixed = false;\n opt = tb_optparse(opt, varargin);\n \n x = [P(:); 0; 0; 0];\n vp = ba.g.add_node(x);\n ba.points = [ba.points vp];\n ba.g.setvdata(vp, length(ba.points));\n \n ba.fixedpoint = [ba.fixedpoint opt.fixed];\n \n end\n \n function e = add_projection(ba, c, p, uv)\n %BundleAdjust.add_projection Add camera to bundle adjustment problem\n %\n % EP = BA.add_projection(VC, VL, UV) is the edge id of an edge added to\n % a bundle adjustment problem. it represents the observed projection UV (2x1) of the landmark node VL as\n % seen by the camera node VC.\n %\n % See also BundleAdjust.add_camera, BundleAdjust.add_landmark, PGraph.\n\n assert(isvec(uv, 2), 'uv must be a 2-vector');\n \n e = ba.g.add_edge(c, p);\n ba.g.setedata(e, uv(:));\n end\n \n\n \n function load_sba(ba, cameraFile, pointFile, calibFile)\n %BundleAdjust.load_sba Load bundle adjustment problem from files\n %\n % BA.load_sba(camfile, pointfile, calibfile) loads a bundle adjustment\n % problem from data files as distributed with the SBA package\n %\n % Example::\n % \n % To solve the 7-point bundle adjustment problem distributed with SBA:\n %\n % ba = BundleAdjust();\n % pth = 'sba-1.6/demo/'\n % ba.load_sba([pth '7cams.txt'], [pth '7pts.txt'], [pth 'calib.txt']);\n %\n % Reference::\n % - Sparse Bundle Adjustment package by Manolis Lourakis\n % http://users.ics.forth.gr/~lourakis/sba\n %\n % See also BundleAdjust.add_camera, BundleAdjust.add_landmark, BundleAdjust.add_projection, PGraph.\n \n % adopted from sba-1.6/matlab/eucsbademo.m \n \n % read in camera parameters\n [q1, q2, q3, q4, tx, ty, tz] = textread(cameraFile, '%f%f%f%f%f%f%f', 'commentstyle', 'shell');\n \n for i=1:length(q1)\n ba.add_camera( [tx(i) ty(i) tz(i) q1(i) q2(i) q3(i) q4(i)] );\n end\n \n \n % read points file line by line\n %\n % each line is a world point\n fid = fopen(pointFile);\n npts = 0;\n while ~feof(fid)\n line = fgets(fid);\n [A, count, errmsg, nextindex] = sscanf(line, '%f%f%f%f', [1, 4]); % read X, Y, Z, nframes\n if(size(A, 2)>0) % did we read anything?\n npts=npts+1;\n \n % create a node for this point\n lm = ba.add_landmark(A(1:3));\n \n % now find which cameras it was seen by\n nframes = A(4);\n for i=1:nframes % read \"nframes\" id, x, y triplets\n [A, count, errmsg, j] = sscanf(line(nextindex:length(line)), '%f%f%f', [1, 3]); % read id, x, y\n nextindex=nextindex+j; % skip the already read line prefix\n \n % add a landmark projection\n ba.add_projection( ba.cameras(A(1)+1), lm, A(2:3) );\n end\n end\n end\n fclose(fid);\n \n % read in calibration parameters\n [a1, a2, a3] = textread(calibFile, '%f%f%f', 'commentstyle', 'shell');\n % a1(1) a2(1) a3(1) a2(2) a3(2)];\n % f/rho_u skew u0 f/rho_v v0\n \n ba.camera.f = a1(1);\n ba.camera.rho = [1 a1(1)/a2(2)];\n ba.camera.pp = [a3(1) a3(2)];\n end\n \n function T = getcamera(ba, ii)\n assert(all(ii > 0), 'camera indices must be > 0');\n assert(all(ii <= ba.ncams), 'camera index out of range'); \n if nargin == 1\n ii = [1:ba.ncams];\n end\n for k=1:length(ii)\n i = ii(k);\n node = ba.cameras(i);\n qv = ba.g.coord(node);\n T(k) = SE3(qv(1:3)') * UnitQuaternion.vec(qv(4:6)).SE3;\n end\n \n end\n \n function P = getlandmark(ba, jj)\n assert(all(jj > 0), 'landmark indices must be > 0');\n assert(all(jj <= ba.nlandmarks), 'landmark index out of range');\n if nargin == 1\n jj = [1:ba.nlandmarks];\n end\n for k=1:length(jj)\n j = jj(k);\n node = ba.points(j);\n qv = ba.g.coord(node);\n P(:,k) = qv(1:3);\n end\n end\n\n\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % METHODS TO SOLVE PROBLEMS\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n function [ba2,e] = optimize(ba, varargin)\n %BundleAdjust.optimize Optimize the solution\n %\n % BA2 = BA.optimize(\n \n\n \n opt.iterations = 1000;\n opt.animate = false;\n opt.retain = false;\n opt.lambda = 0.1;\n opt.lambdamin = 1e-8;\n opt.dxmin = 1e-8;\n opt.tol = 0.05;\n \n [opt,args] = tb_optparse(opt, varargin);\n \n %g2 = PGraph(pg.graph); % deep copy\n \n if length(args) > 0 && isvec(args{1}, ba.ndim)\n X = args{1};\n else\n X = ba.getstate();\n end\n \n lambda = opt.lambda;\n \n X0 = X;\n \n t0 = cputime();\n \n fprintf('Initial cost %g\\n', ba.errors(X));\n \n for i=1:opt.iterations\n if opt.animate\n if ~opt.retain\n clf\n end\n g2.plot();\n pause(0.5)\n end\n \n tic\n \n % solve for the step\n [dX,energy] = ba.solve(X, lambda);\n % update the state\n Xnew = ba.updatestate(X, dX);\n % compute new value of cost\n enew = ba.errors(Xnew);\n \n dt = toc;\n fprintf(' total cost %g (solved in %.2g sec)', enew, dt);\n \n \n % are we there yet?\n if enew < opt.tol\n break\n end\n \n % have we stopped moving\n if norm(dX) < opt.dxmin\n break\n end\n\n \n % do the Levenberg-Marquadt thing, was it a good update?\n if enew < energy\n % step is accepted\n X = Xnew;\n if lambda > opt.lambdamin\n lambda = lambda/sqrt(2);\n end\n if opt.verbose\n fprintf(' -- step accepted: lambda = %g', lambda);\n end\n else\n % step is rejected\n lambda = lambda*4;\n if opt.verbose\n fprintf(' -- step rejected: lambda = %g', lambda);\n end\n end\n \n fprintf('\\n');\n end\n \n tf = cputime();\n fprintf('\\n * %d iterations in %.1f seconds\\n', i, tf-t0);\n fprintf(' * %.2f pixels RMS error\\n', sqrt(enew/ba.g.ne));\n \n % copy the object and update it\n ba2 = copy(ba);\n ba2.g = copy(ba.g);\n ba2.setstate(X);\n \n \n if nargout > 1\n e = enew;\n end\n end\n \n function [deltax,err] = solve(ba, X, lambda)\n \n if nargin < 3\n lambda =0;\n end\n \n %ba.init_tables();\n \n % create the Hessian and error vector\n [H,b,e] = ba.build_linear_system(X);\n \n % add damping term to the diagonal\n for i=1:ba.ndim\n H(i,i) = H(i,i) + lambda;\n end\n \n % solve for the state update\n % - could replace this with the Schur complement trick\n deltax = H \\ b;\n \n if nargout > 1\n err = e;\n end\n end\n \n \n % build the Hessian and measurement vector\n function [H,b,etotal,J] = build_linear_system(ba, X)\n \n % allocate storage\n H = sparse(ba.ndim, ba.ndim);\n b = zeros(ba.ndim,1);\n \n etotal = 0;\n \n % loop over cameras\n for i=1:ba.ncams\n \n k = ba.cameraIdx(i);\n x = X(k:k+5);\n \n t = x(1:3); qv = x(4:6);\n \n % loop over all points viewed from this camera\n for p=ba.g.edges( ba.cameras(i) )\n v = ba.g.vertices(p);\n j = ba.g.vdata(v(2));\n \n k = ba.landmarkIdx(j);\n x = X(k:k+2);\n \n P = x';\n \n uv = ba.g.edata(p);\n \n % compute Jacobians and projection\n \n [uvhat,JA,JB] = ba.camera.derivs(t, qv, P);\n \n \n % compute reprojection error\n e = uvhat - uv;\n etotal = etotal + e'*e;\n \n ii = ba.cameraIdx2(i); jj = ba.landmarkIdx2(j);\n \n \n % compute the block components of H and b for this edge\n \n if ~ba.fixedcam(i) & ~ba.fixedpoint(j)\n % adjustable point and camera\n H_ii= JA'*JA;\n H_ij= JA'*JB;\n H_jj= JB'*JB;\n \n H(ii:ii+5,ii:ii+5) = H(ii:ii+5,ii:ii+5) + H_ii;\n H(ii:ii+5,jj:jj+2) = H(ii:ii+5,jj:jj+2) + H_ij;\n H(jj:jj+2,ii:ii+5) = H(jj:jj+2,ii:ii+5) + H_ij';\n H(jj:jj+2,jj:jj+2) = H(jj:jj+2,jj:jj+2) + H_jj;\n \n b_i = -JA'*e;\n b_j = -JB'*e;\n \n b(ii:ii+5) = b(ii:ii+5) + b_i;\n b(jj:jj+2) = b(jj:jj+2) + b_j;\n \n \n elseif ba.fixedcam(i) & ~ba.fixedpoint(j)\n % fixed camera and adjustable point\n \n H_jj= JB'*JB;\n \n H(jj:jj+2,jj:jj+2) = H(jj:jj+2,jj:jj+2) + H_jj;\n \n b_j = -JB'*e;\n \n b(jj:jj+2) = b(jj:jj+2) + b_j;\n \n elseif ~ba.fixedcam(i) & ba.fixedpoint(j)\n % adjustable camera and fixed point\n \n H_ii= JA'*JA;\n \n H(ii:ii+5,ii:ii+5) = H(ii:ii+5,ii:ii+5) + H_ii;\n \n b_i = -JA'*e;\n \n b(ii:ii+5) = b(ii:ii+5) + b_i;\n end\n \n end\n end\n \n end\n \n \n function spyH(ba, X)\n H = build_linear_system(ba, X);\n spy(H);\n end\n\n \n function X = getstate(ba)\n %BundleAdjust.getstate Get the state vector\n %\n % X = BA.getstate() is a row vector containing the state vector of the\n % problem: all camera poses followed by all landmark coordinates.\n %\n % Notes::\n % - The length of the vector is given by BA.ndim.\n \n X = [];\n \n i = 0;\n for c=ba.cameras % step through camera nodes\n X = [X ba.g.coord(c)'];\n end\n \n \n for p=ba.points % step through landmark nodes\n P = ba.g.coord( p );\n X = [X P(1:3)'];\n end\n end\n \n function setstate(ba, X)\n %BundleAdjust.getstate Get the state vector\n %\n % X = BA.getstate() is a row vector containing the state vector of the\n % problem: all camera poses followed by all landmark coordinates.\n %\n % Notes::\n % - The length of the vector is given by BA.ndim.\n \n \n for i=1:ba.ncams % step through camera nodes\n if ~ba.fixedcam(i)\n k = ba.cameraIdx(i);\n c = ba.cameras(i);\n ba.g.setcoord(c, X(k:k+5));\n end\n end\n \n for j=1:ba.nlandmarks\n if ~ba.fixedpoint(j)\n k = ba.landmarkIdx(j);\n lm = ba.points(j);\n ba.g.setcoord(lm, [X(k:k+2) 0 0 0]);\n end\n end\n end\n \n \n function Xnew = updatestate(ba, X, dX)\n dX = dX(:)';\n \n % for each camera we need to compound the camera pose with the\n % incremental relative pose\n for i=1:ba.ncams\n k = ba.cameraIdx(i);\n if ba.fixedcam(i)\n Xnew(k:k+5) = X(k:k+5);\n else\n x = X(k:k+5);\n t = x(1:3); qv = x(4:6); % get current pose\n \n k2 = ba.cameraIdx2(i);\n dx = dX(k2:k2+5);\n dt = dx(1:3); dqv = dx(4:6); % get incremental pose\n tnew = t+dt; % assume translation in old frame\n % compound the quaternion vector rotations\n % - function qvmul is symbolically generated by ba\n %qvnew = qvmul(qv(1), qv(2), qv(3), dqv(1), dqv(2), dqv(3));\n qvnew = UnitQuaternion.qvmul(qv, dqv);\n \n Xnew(k:k+5) = [tnew qvnew];\n end\n end\n \n % for each landmark we add the increment to its position\n for j=1:ba.nlandmarks\n k = ba.landmarkIdx(j);\n x = X(k:k+2);\n if ba.fixedpoint(j)\n Xnew(k:k+2) = x;\n else\n k2 = ba.landmarkIdx2(j);\n dx = dX(k2:k2+2);\n Xnew(k:k+2) = x + dx;\n end\n end\n end\n \n % Compute total squared reprojection error\n function etotal = errors(ba, X)\n \n if nargin < 2\n X = ba.getstate();\n end\n r = ba.getresidual(X);\n \n etotal = sum(r(:));\n end\n \n function r = getresidual(ba, X)\n % this is the squared reprojection errors\n \n if nargin == 1\n X = ba.getstate();\n end\n \n % loop over cameras\n for i=1:ba.ncams\n \n k = ba.cameraIdx(i);\n x = X(k:k+5);\n \n t = x(1:3); qv = x(4:6);\n \n % loop over all points viewed from this camera\n for p=ba.g.edges( ba.cameras(i) )\n v = ba.g.vertices(p);\n j = ba.g.vdata(v(2));\n \n k = ba.landmarkIdx(j);\n x = X(k:k+2);\n \n P = x';\n \n uv = ba.g.edata(p);\n \n uvhat = ba.camera.derivs(t, qv, P);\n \n % compute reprojection error\n e = uvhat - uv;\n r(i,j) = e'*e;\n end\n end\n end\n \n \n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % SUPPORT METHODS\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n function plot(ba, varargin)\n clf\n ba.g.plot('dims', 3, 'only', ba.points, 'EdgeColor', 0.8*[1 1 1], varargin{:});\n axis equal\n hold on\n \n colorOrder = get(gca, 'ColorOrder');\n for i=1:ba.ncams\n T = ba.getcamera(i);\n cam(i) = ba.camera.move(T);\n cidx = mod(i-1, numrows(colorOrder))+1;\n color = colorOrder(cidx,:);\n cam(i).plot_camera('scale', 0.2, 'color', color, 'persist')\n end\n hold off\n axis equal\n xlabel('X (m)')\n ylabel('Y (m)')\n zlabel('Z (m)')\n grid on\n end\n \n function display(ba)\n %BundleAdjust.display BundleAdjust parameters\n %\n % BA.display() displays the bundle adjustment parameters in compact format.\n %\n % Notes::\n % - This method is invoked implicitly at the command line when the result\n % of an expression is a BundleAdjust object and the command has no trailing\n % semicolon.\n %\n % See also BundleAdjust.char.\n loose = strcmp( get(0, 'FormatSpacing'), 'loose');\n if loose\n disp(' ');\n end\n disp([inputname(1), ' = '])\n disp( char(ba) );\n end % display()\n \n function s = char(ba)\n %BundleAdjust.char Convert to string\n %\n % BA.char() is a string showing bundle adjustment parameters in compact format.\n %\n %\n % See also BundleAdjust.display.\n s = 'Bundle adjustment problem:';\n s = strvcat(s, sprintf(' %d cameras', ba.ncams));\n if any(ba.fixedcam)\n s = strvcat(s, sprintf(' locked cameras: %s', num2str(find(ba.fixedcam))));\n end\n \n s = strvcat(s, sprintf(' %d landmarks', ba.nlandmarks));\n \n s = strvcat(s, sprintf(' %d projections', ba.g.ne));\n \n s = strvcat(s, sprintf(' %d dimension linear problem', ba.ndim));\n c = ba.g.connectivity(ba.cameras);\n s = strvcat(s, sprintf(' landmarks per camera: min=%.1f, max=%.1f, avg=%.1f', min(c), max(c), mean(c)));\n c = ba.g.connectivity(ba.points);\n s = strvcat(s, sprintf(' cameras per landmark: min=%.1f, max=%.1f, avg=%.1f', min(c), max(c), mean(c)));\n end\n \n end % methods\n \nend % classdef\n", "meta": {"author": "petercorke", "repo": "machinevision-toolbox-matlab", "sha": "2d791168c19c5e56acef74d22eafd227b4b58e42", "save_path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab/machinevision-toolbox-matlab-2d791168c19c5e56acef74d22eafd227b4b58e42/BundleAdjust.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.49622588845927673}} {"text": "function [x,zo,xs]=v_estnoisem(yf,tz,pp)\n%V_ESTNOISEM - estimate noise spectrum using minimum statistics\n%\n% Usage: ninc=round(0.016*fs); % frame increment [fs=sample frequency]\n% ovf=2; % overlap factor\n% f=v_rfft(v_enframe(s,v_windows(2,ovf*ninc,'l'),ninc),ovf*ninc,2);\n% f=f.*conj(f); % convert to power spectrum\n% x=v_estnoisem(f,ninc/fs); % estimate the noise power spectrum\n%\n% Inputs:\n% yf input power spectra (one row per frame)\n% tz frame increment in seconds\n% Alternatively, the input state from a previous call (see below)\n% pp algorithm parameters [optional]\n%\n% Outputs:\n% x estimated noise power spectra (one row per frame)\n% zo output state\n% xs estimated std error of x (one row per frame)\n% xs seems often to be an underestimate by a factor of 2 or 3\n%\n% The algorithm parameters are defined in reference [1] from which equation\n% numbers are given in parentheses. They are as follows:\n%\n% pp.taca % (11): smoothing time constant for alpha_c [0.0449 seconds]\n% pp.tamax % (3): max smoothing time constant [0.392 seconds]\n% pp.taminh % (3): min smoothing time constant (upper limit) [0.0133 seconds]\n% pp.tpfall % (12): time constant for P to fall [0.064 seconds]\n% pp.tbmax % (20): max smoothing time constant [0.0717 seconds]\n% pp.qeqmin % (23): minimum value of Qeq [2]\n% pp.qeqmax % max value of Qeq per frame [14]\n% pp.av % (23)+13 lines: fudge factor for bc calculation [2.12]\n% pp.td % time to take minimum over [1.536 seconds]\n% pp.nu % number of subwindows to use [3]\n% pp.qith % Q-inverse thresholds to select maximum noise slope [0.03 0.05 0.06 Inf ]\n% pp.nsmdb % corresponding noise slope thresholds in dB/second [47 31.4 15.7 4.1]\n%\n% Example use: y=v_enframe(s,w,ni); % divide speech signal s(n) into\n% % overlapping frames using window w(n)\n% yf=v_rfft(y,nf,2); % take fourier transform\n% dp=v_estnoisem(yf.*conj(yf),tinc); % estimate the noise\n%\n% If convenient, you can call v_estnoisem in chunks of arbitrary size. Thus the following are equivalent:\n%\n% (a) dp=v_estnoisem(yp(1:300),tinc);\n%\n% (b) [dp(1:100),z]=v_estnoisem(yp(1:100),tinc);\n% [dp(101:200),z]=v_estnoisem(yp(101:200),z);\n% [dp(201:300),z]=v_estnoisem(yp(201:300),z);\n\n\n% This is intended to be a precise implementation of [1] with Table III\n% replaced by the updated table 5 from [2]. The only deliberate algorithm\n% change is the introduction of a minimum value for 1/Qeq in equation (23).\n% This change only affects the first few frames and improves the\n% convergence of the algorithm. A minor improveemnt was reported in [3] but\n% this has not yet been included.\n%\n% Refs:\n% [1] Rainer Martin.\n% Noise power spectral density estimation based on optimal smoothing and minimum statistics.\n% IEEE Trans. Speech and Audio Processing, 9(5):504-512, July 2001.\n% [2] Rainer Martin.\n% Bias compensation methods for minimum statistics noise power spectral density estimation\n% Signal Processing, 2006, 86, 1215-1229\n% [3] Dirk Mauler and Rainer Martin\n% Noise power spectral density estimation on highly correlated data\n% Proc IWAENC, 2006\n\n%\t Copyright (C) Mike Brookes 2008\n% Version: $Id: v_estnoisem.m 10865 2018-09-21 17:22:45Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[nr,nrf]=size(yf); % number of frames and freq bins\nx=zeros(nr,nrf); % initialize output arrays\nxs=zeros(nr,nrf); % will hold std error in the future\nif isempty(yf) && isstruct(tz) % no real data\n zo=tz; % just keep the same state\nelse\n if isstruct(tz) % take parameters from a previous call\n nrcum=tz.nrcum;\n p=tz.p; % smoothed power spectrum\n ac=tz.ac; % correction factor (9)\n sn2=tz.sn2; % estimated noise power\n pb=tz.pb; % smoothed noisy speech power (20)\n pb2=tz.pb2;\n pminu=tz.pminu;\n actmin=tz.actmin; % Running minimum estimate\n actminsub=tz.actminsub; % sub-window minimum estimate\n subwc=tz.subwc; % force a buffer switch on first loop\n actbuf=tz.actbuf; % buffer to store subwindow minima\n ibuf=tz.ibuf;\n lminflag=tz.lminflag; % flag to remember local minimum\n tinc=tz.tinc; % frame increment\n qq=tz.qq; % parameter structure\n else\n tinc = tz; % second argument is frame increment\n nrcum=0; % no frames so far\n % default algorithm constants\n\n qq.taca=0.0449; % smoothing time constant for alpha_c = -tinc/log(0.7) in equ (11)\n qq.tamax=0.392; % max smoothing time constant in (3) = -tinc/log(0.96)\n qq.taminh=0.0133; % min smoothing time constant (upper limit) in (3) = -tinc/log(0.3)\n qq.tpfall=0.064; % time constant for P to fall (12)\n qq.tbmax=0.0717; % max smoothing time constant in (20) = -tinc/log(0.8)\n qq.qeqmin=2; % minimum value of Qeq (23)\n qq.qeqmax=14; % max value of Qeq per frame\n qq.av=2.12; % fudge factor for bc calculation (23 + 13 lines)\n qq.td=1.536; % time to take minimum over\n qq.nu=8; % number of subwindows\n qq.qith=[0.03 0.05 0.06 Inf]; % noise slope thresholds in dB/s\n qq.nsmdb=[47 31.4 15.7 4.1];\n\n if nargin>=3 && ~isempty(pp)\n qqn=fieldnames(qq);\n for i=1:length(qqn)\n if isfield(pp,qqn{i})\n qq.(qqn{i})=pp.(qqn{i});\n end\n end\n end\n end\n\n % unpack parameter structure\n\n taca=qq.taca; % smoothing time constant for alpha_c = -tinc/log(0.7) in equ (11)\n tamax=qq.tamax; % max smoothing time constant in (3) = -tinc/log(0.96)\n taminh=qq.taminh; % min smoothing time constant (upper limit) in (3) = -tinc/log(0.3)\n tpfall=qq.tpfall; % time constant for P to fall (12)\n tbmax=qq.tbmax; % max smoothing time constant in (20) = -tinc/log(0.8)\n qeqmin=qq.qeqmin; % minimum value of Qeq (23)\n qeqmax=qq.qeqmax; % max value of Qeq per frame\n av=qq.av; % fudge factor for bc calculation (23 + 13 lines)\n td=qq.td; % time to take minimum over\n nu=qq.nu; % number of subwindows\n qith=qq.qith; % noise slope thresholds in dB/s\n nsmdb=qq.nsmdb; % maximum permitted +ve noise slope in dB/s\n\n % derived algorithm constants\n\n aca=exp(-tinc/taca); % smoothing constant for alpha_c in equ (11) = 0.7\n acmax=aca; % min value of alpha_c = 0.7 in equ (11) also = 0.7\n amax=exp(-tinc/tamax); % max smoothing constant in (3) = 0.96\n aminh=exp(-tinc/taminh); % min smoothing constant (upper limit) in (3) = 0.3\n bmax=exp(-tinc/tbmax); % max smoothing constant in (20) = 0.8\n snrexp = -tinc/tpfall;\n nv=round(td/(tinc*nu)); % length of each subwindow in frames\n if nv<4 % algorithm doesn't work for miniscule frames\n nv=4;\n nu=max(round(td/(tinc*nv)),1);\n end\n nd=nu*nv; % length of total window in frames\n [md,hd]=mhvals(nd); % calculate the constants M(D) and H(D) from Table III\n [mv,hv]=mhvals(nv); % calculate the constants M(D) and H(D) from Table III\n nsms=10.^(nsmdb*nv*tinc/10); % [8 4 2 1.2] in paper\n qeqimax=1/qeqmin; % maximum value of Qeq inverse (23)\n qeqimin=1/qeqmax; % minumum value of Qeq per frame inverse\n\n if isempty(yf) % provide dummy initialization\n ac=1; % correction factor (9)\n subwc=nv; % force a buffer switch on first loop\n ibuf=0;\n p=x; % smoothed power spectrum\n sn2=p; % estimated noise power\n pb=p; % smoothed noisy speech power (20)\n pb2=pb.^2;\n pminu=p;\n actmin=repmat(Inf,1,nrf); % Running minimum estimate\n actminsub=actmin; % sub-window minimum estimate\n actbuf=repmat(Inf,nu,nrf); % buffer to store subwindow minima\n lminflag=zeros(1,nrf); % flag to remember local minimum\n else\n\n if ~nrcum % initialize values for first frame\n p=yf(1,:); % smoothed power spectrum\n ac=1; % correction factor (9)\n sn2=p; % estimated noise power\n pb=p; % smoothed noisy speech power (20)\n pb2=pb.^2;\n pminu=p;\n actmin=repmat(Inf,1,nrf); % Running minimum estimate\n actminsub=actmin; % sub-window minimum estimate\n subwc=nv; % force a buffer switch on first loop\n actbuf=repmat(Inf,nu,nrf); % buffer to store subwindow minima\n ibuf=0;\n lminflag=zeros(1,nrf); % flag to remember local minimum\n end\n\n % loop for each frame\n\n for t=1:nr % we use t instead of lambda in the paper\n yft=yf(t,:); % noise speech power spectrum\n acb=(1+(sum(p)./sum(yft)-1).^2).^(-1); % alpha_c-bar(t) (9)\n ac=aca*ac+(1-aca)*max(acb,acmax); % alpha_c(t) (10)\n ah=amax*ac.*(1+(p./sn2-1).^2).^(-1); % alpha_hat: smoothing factor per frequency (11)\n snr=sum(p)/sum(sn2);\n ah=max(ah,min(aminh,snr^snrexp)); % lower limit for alpha_hat (12)\n\n p=ah.*p+(1-ah).*yft; % smoothed noisy speech power (3)\n b=min(ah.^2,bmax); % smoothing constant for estimating periodogram variance (22 + 2 lines)\n pb=b.*pb + (1-b).*p; % smoothed periodogram (20)\n pb2=b.*pb2 + (1-b).*p.^2; \t% smoothed periodogram squared (21)\n\n qeqi=max(min((pb2-pb.^2)./(2*sn2.^2),qeqimax),qeqimin/(t+nrcum)); % Qeq inverse (23)\n qiav=sum(qeqi)/nrf; % Average over all frequencies (23+12 lines) (ignore non-duplication of DC and nyquist terms)\n bc=1+av*sqrt(qiav); % bias correction factor (23+11 lines)\n bmind=1+2*(nd-1)*(1-md)./(qeqi.^(-1)-2*md); % we use the simplified form (17) instead of (15)\n bminv=1+2*(nv-1)*(1-mv)./(qeqi.^(-1)-2*mv); % same expression but for sub windows\n kmod=bc*p.*bmind1 && subwc=nv % end of buffer - do a buffer switch\n ibuf=1+rem(ibuf,nu); \t% increment actbuf storage pointer\n actbuf(ibuf,:)=actmin; \t% save sub-window minimum\n pminu=min(actbuf,[],1);\n i=find(qiavpminu;\n if any(lmin)\n pminu(lmin)=actminsub(lmin);\n actbuf(:,lmin)=repmat(pminu(lmin),nu,1);\n end\n lminflag(:)=0;\n actmin(:)=Inf;\n subwc=0;\n end\n end\n subwc=subwc+1;\n x(t,:)=sn2;\n qisq=sqrt(qeqi);\n % empirical formula for standard error based on Fig 15 of [2]\n xs(t,:)=sn2.*sqrt(0.266*(nd+100*qisq).*qisq/(1+0.005*nd+6/nd)./(0.5*qeqi.^(-1)+nd-1));\n end\n end\n if nargout>1 % we need to store the state for next time\n zo.nrcum=nrcum+nr; % number of frames so far\n zo.p=p; % smoothed power spectrum\n zo.ac=ac; % correction factor (9)\n zo.sn2=sn2; % estimated noise power\n zo.pb=pb; % smoothed noisy speech power (20)\n zo.pb2=pb2;\n zo.pminu=pminu;\n zo.actmin=actmin; % Running minimum estimate\n zo.actminsub=actminsub; % sub-window minimum estimate\n zo.subwc=subwc; % force a buffer switch on first loop\n zo.actbuf=actbuf; % buffer to store subwindow minima\n zo.ibuf=ibuf;\n zo.lminflag=lminflag; % flag to remember local minimum\n zo.tinc=tinc; % must be the last one\n zo.qq=qq;\n end\n if ~nargout\n clf;\n subplot(212);\n plot((1:nr)*tinc,10*log10([sum(yf,2) sum(x,2)]))\n ylabel('Frame Energy (dB)');\n xlabel(sprintf('Time (s) [%d ms frame incr]',round(tinc*1000)));\n v_axisenlarge([-1 -1.05]);\n legend('input','noise','Location','Best');\n subplot(211);\n plot(1:nrf,10*log10([sum(yf,1)'/nr sum(x,1)'/nr]))\n ylabel('Power (dB)');\n xlabel('Frequency bin');\n v_axisenlarge([-1 -1.05]);\n legend('input','noise','Location','Best');\n end\nend\n\nfunction [m,h,d]=mhvals(d)\n% Values are taken from Table 5 in [2]\n%[2] R. Martin,\"Bias compensation methods for minimum statistics noise power\n% spectral density estimation\", Signal Processing Vol 86, pp1215-1229, 2006.\n\n% approx: plot(d.^(-0.5),[m 1-d.^(-0.5)],'x-'), plot(d.^0.5,h,'x-')\npersistent dmh\nif isempty(dmh)\n dmh=[\n 1 0 0;\n 2 0.26 0.15;\n 5 0.48 0.48;\n 8 0.58 0.78;\n 10 0.61 0.98;\n 15 0.668 1.55;\n 20 0.705 2;\n 30 0.762 2.3;\n 40 0.8 2.52;\n 60 0.841 3.1;\n 80 0.865 3.38;\n 120 0.89 4.15;\n 140 0.9 4.35;\n 160 0.91 4.25;\n 180 0.92 3.9;\n 220 0.93 4.1;\n 260 0.935 4.7;\n 300 0.94 5];\nend\n\nif nargin>=1\n i=find(d<=dmh(:,1));\n if isempty(i)\n i=size(dmh,1);\n j=i;\n else\n i=i(1);\n j=i-1;\n end\n if d==dmh(i,1)\n m=dmh(i,2);\n h=dmh(i,3);\n else\n qj=sqrt(dmh(i-1,1)); % interpolate using sqrt(d)\n qi=sqrt(dmh(i,1));\n q=sqrt(d);\n h=dmh(i,3)+(q-qi)*(dmh(j,3)-dmh(i,3))/(qj-qi);\n m=dmh(i,2)+(qi*qj/q-qj)*(dmh(j,2)-dmh(i,2))/(qi-qj);\n end\nelse\n d=dmh(:,1);\n m=dmh(:,2);\n h=dmh(:,3);\nend", "meta": {"author": "ImperialCollegeLondon", "repo": "sap-voicebox", "sha": "28f2654b7584f724277ec81de533debe28ff51ac", "save_path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox", "path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox/sap-voicebox-28f2654b7584f724277ec81de533debe28ff51ac/voicebox/v_estnoisem.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.496219064872765}} {"text": "\n% -------------------------------------------------------------------------\n% Downloaded 10.08.2018 from:\n% http://www.columbia.edu/~bsm2105/type2sdt/archive/index.html\n% Author: Brian Maniscalco\n% Contact: brian@psych.columbia.edu\n\n% 10.08.2018: OKH added calculation for type 1 c to the results\n\n% NOTE FROM WEBPAGE:\n% If you use this analysis file, please reference the Consciousness &\n% Cognition paper:\n% Maniscalco, B., & Lau, H. (2012). A signal detection \n% theoretic approach for estimating metacognitive sensitivity from \n% confidence ratings. Consciousness and Cognition, 21(1), 422–430. \n% doi:10.1016/j.concog.2011.09.021)\n% And the website:\n% http://www.columbia.edu/~bsm2105/type2sdt/archive/index.html\n% -------------------------------------------------------------------------\n\nfunction fit = tapas_fit_meta_d_MLE(nR_S1, nR_S2, s, fncdf, fninv)\n\n% fit = fit_meta_d_MLE(nR_S1, nR_S2, s, fncdf, fninv)\n%\n% Given data from an experiment where an observer discriminates between two\n% stimulus alternatives on every trial and provides confidence ratings,\n% provides a type 2 SDT analysis of the data.\n%\n% INPUTS\n%\n% * nR_S1, nR_S2\n% these are vectors containing the total number of responses in\n% each response category, conditional on presentation of S1 and S2.\n%\n% e.g. if nR_S1 = [100 50 20 10 5 1], then when stimulus S1 was\n% presented, the subject had the following response counts:\n% responded S1, rating=3 : 100 times\n% responded S1, rating=2 : 50 times\n% responded S1, rating=1 : 20 times\n% responded S2, rating=1 : 10 times\n% responded S2, rating=2 : 5 times\n% responded S2, rating=3 : 1 time\n%\n% The ordering of response / rating counts for S2 should be the same as it\n% is for S1. e.g. if nR_S2 = [3 7 8 12 27 89], then when stimulus S2 was\n% presented, the subject had the following response counts:\n% responded S1, rating=3 : 3 times\n% responded S1, rating=2 : 7 times\n% responded S1, rating=1 : 8 times\n% responded S2, rating=1 : 12 times\n% responded S2, rating=2 : 27 times\n% responded S2, rating=3 : 89 times\n%\n% N.B. if nR_S1 or nR_S2 contain zeros, this may interfere with estimation of\n% meta-d'.\n%\n% Some options for dealing with response cell counts containing zeros are:\n% \n% (1) Add a small adjustment factor, e.g. adj_f = 1/(length(nR_S1), to each \n% input vector:\n% \n% adj_f = 1/length(nR_S1);\n% nR_S1_adj = nR_S1 + adj_f;\n% nR_S2_adj = nR_S2 + adj_f;\n% \n% This is a generalization of the correction for similar estimation issues of\n% type 1 d' as recommended in\n% \n% Hautus, M. J. (1995). Corrections for extreme proportions and their biasing \n% effects on estimated values of d'. Behavior Research Methods, Instruments, \n% & Computers, 27, 46-51.\n% \n% When using this correction method, it is recommended to add the adjustment \n% factor to ALL data for all subjects, even for those subjects whose data is \n% not in need of such correction, in order to avoid biases in the analysis \n% (cf Snodgrass & Corwin, 1988).\n% \n% (2) Collapse across rating categories.\n% \n% e.g. if your data set has 4 possible confidence ratings such that length(nR_S1)==8,\n% defining new input vectors\n% \n% nR_S1_new = [sum(nR_S1(1:2)), sum(nR_S1(3:4)), sum(nR_S1(5:6)), sum(nR_S1(7:8))];\n% nR_S2_new = [sum(nR_S2(1:2)), sum(nR_S2(3:4)), sum(nR_S2(5:6)), sum(nR_S2(7:8))];\n% \n% might be sufficient to eliminate zeros from the input without using an adjustment.\n%\n% * s\n% this is the ratio of standard deviations for type 1 distributions, i.e.\n%\n% s = sd(S1) / sd(S2)\n%\n% if not specified, s is set to a default value of 1.\n% For most purposes, we recommend setting s = 1. \n% See http://www.columbia.edu/~bsm2105/type2sdt for further discussion.\n%\n% * fncdf\n% a function handle for the CDF of the type 1 distribution.\n% if not specified, fncdf defaults to @normcdf (i.e. CDF for normal\n% distribution)\n%\n% * fninv\n% a function handle for the inverse CDF of the type 1 distribution.\n% if not specified, fninv defaults to @norminv\n%\n% OUTPUT\n%\n% Output is packaged in the struct \"fit.\" \n% In the following, let S1 and S2 represent the distributions of evidence \n% generated by stimulus classes S1 and S2.\n% Then the fields of \"fit\" are as follows:\n% \n% fit.d1 = mean(S2) - mean(S1), in room-mean-square(sd(S1),sd(S2)) units\n% fit.c1 = type 1 criterion\n% fit.s = sd(S1) / sd(S2)\n% fit.meta_d = meta-d' in RMS units\n% fit.M_diff = meta_da - da\n% fit.M_ratio = meta_da / da\n% fit.meta_c1 = type 1 criterion for meta-d' fit, RMS units\n% fit.t2ca_rS1 = type 2 criteria of \"S1\" responses for meta-d' fit, RMS units\n% fit.t2ca_rS2 = type 2 criteria of \"S2\" responses for meta-d' fit, RMS units\n%\n% fit.S1units = contains same parameters in sd(S1) units.\n% these may be of use since the data-fitting is conducted \n% using parameters specified in sd(S1) units.\n% \n% fit.logL = log likelihood of the data fit\n%\n% fit.est_HR2_rS1 = estimated (from meta-d' fit) type 2 hit rates for S1 responses\n% fit.obs_HR2_rS1 = actual type 2 hit rates for S1 responses\n% fit.est_FAR2_rS1 = estimated type 2 false alarm rates for S1 responses\n% fit.obs_FAR2_rS1 = actual type 2 false alarm rates for S1 responses\n% \n% fit.est_HR2_rS2 = estimated type 2 hit rates for S2 responses\n% fit.obs_HR2_rS2 = actual type 2 hit rates for S2 responses\n% fit.est_FAR2_rS2 = estimated type 2 false alarm rates for S2 responses\n% fit.obs_FAR2_rS2 = actual type 2 false alarm rates for S2 responses\n%\n% If there are N ratings, then there will be N-1 type 2 hit rates and false\n% alarm rates. \n\n% 2015/07/23 - fixed bug for output fit.meta_ca and fit.S1units.meta_c1. \n% - added comments to help section as well as a warning output \n% for nR_S1 or nR_S2 inputs containing zeros\n% 2014/10/14 - updated discussion of \"s\" input in the help section above.\n% 2010/09/07 - created\n\n\n%% parse inputs\n\n% check inputs\nif ~mod(length(nR_S1),2)==0, error('input arrays must have an even number of elements'); end\nif length(nR_S1)~=length(nR_S2), error('input arrays must have the same number of elements'); end\n\nif any(nR_S1 == 0) || any(nR_S2 == 0)\n disp(' ')\n disp('WARNING!!')\n disp('---------')\n disp('Your inputs')\n disp(' ')\n disp(['nR_S1 = [' num2str(nR_S1) ']'])\n disp(['nR_S2 = [' num2str(nR_S2) ']'])\n disp(' ')\n disp('contain zeros! This may interfere with proper estimation of meta-d''.')\n disp('See ''help fit_meta_d_MLE'' for more information.')\n disp(' ')\n disp(' ')\nend\n\n% assign input default values\nif ~exist('s','var') || isempty(s)\n s = 1;\nend\n\nif ~exist('fncdf','var') || isempty(fncdf)\n fncdf = @normcdf;\nend\n\nif ~exist('fninv','var') || isempty(fninv)\n fninv = @norminv;\nend\n\nnRatings = length(nR_S1) / 2;\nnCriteria = 2*nRatings - 1;\n\n\n%% set up constraints for MLE estimation\n\n% parameters\n% meta-d' - 1\n% t2c - nCriteria-1\n\nA = [];\nb = [];\n\n% constrain type 2 criteria values,\n% such that t2c(i) is always <= t2c(i+1)\n% want t2c(i) <= t2c(i+1) \n% --> t2c(i+1) >= c(i) + 1e-5 (i.e. very small deviation from equality) \n% --> t2c(i) - t2c(i+1) <= -1e-5 \nfor i = 2 : nCriteria-1\n\n A(end+1,[i i+1]) = [1 -1];\n b(end+1) = -1e-5;\n\nend\n\n% lower bounds on parameters\nLB = [];\nLB = [LB -10]; % meta-d'\nLB = [LB -20*ones(1,(nCriteria-1)/2)]; % criteria lower than t1c\nLB = [LB zeros(1,(nCriteria-1)/2)]; % criteria higher than t1c\n\n% upper bounds on parameters\nUB = [];\nUB = [UB 10]; % meta-d'\nUB = [UB zeros(1,(nCriteria-1)/2)]; % criteria lower than t1c\nUB = [UB 20*ones(1,(nCriteria-1)/2)]; % criteria higher than t1c\n\n\n%% select constant criterion type\n\nconstant_criterion = 'meta_d1 * (t1c1 / d1)'; % relative criterion\n\n\n%% set up initial guess at parameter values\n\nratingHR = [];\nratingFAR = [];\nfor c = 2:nRatings*2\n ratingHR(end+1) = sum(nR_S2(c:end)) / sum(nR_S2);\n ratingFAR(end+1) = sum(nR_S1(c:end)) / sum(nR_S1);\nend\n\nt1_index = nRatings;\nt2_index = setdiff(1:2*nRatings-1, t1_index);\n\nd1 = (1/s) * fninv( ratingHR(t1_index) ) - fninv( ratingFAR(t1_index) );\nmeta_d1 = d1;\nc = -0.5 .* (fninv(ratingHR(t1_index)) + fninv(ratingFAR(t1_index)));\nc1 = (-1/(1+s)) * ( fninv( ratingHR ) + fninv( ratingFAR ) );\nt1c1 = c1(t1_index);\nt2c1 = c1(t2_index);\n\nguess = [meta_d1 t2c1 - eval(constant_criterion)];\n\n\n\n%% find the best fit for type 2 hits and FAs\n\n% save fit_meta_d_MLE.mat nR_S1 nR_S2 t2FAR_rS2 t2HR_rS2 t2FAR_rS1 t2HR_rS1 nRatings t1c1 s d1 fncdf constant_criterion\nsave fit_meta_d_MLE.mat nR_S1 nR_S2 nRatings d1 t1c1 s constant_criterion fncdf fninv\n\nop = optimset(@fmincon);\nop = optimset(op,'MaxFunEvals',100000);\n\n[x f] = fmincon(@fit_meta_d_logL,guess,A,b,[],[],LB,UB,[],op);\n\nmeta_d1 = x(1);\nt2c1 = x(2:end) + eval(constant_criterion);\nlogL = -f;\n\n\n%% data is fit, now to package it...\n\n%% find observed t2FAR and t2HR \n\n% I_nR and C_nR are rating trial counts for incorrect and correct trials\n% element i corresponds to # (in)correct w/ rating i\nI_nR_rS2 = nR_S1(nRatings+1:end);\nI_nR_rS1 = nR_S2(nRatings:-1:1);\n\nC_nR_rS2 = nR_S2(nRatings+1:end);\nC_nR_rS1 = nR_S1(nRatings:-1:1);\n\nfor i = 2:nRatings\n obs_FAR2_rS2(i-1) = sum( I_nR_rS2(i:end) ) / sum(I_nR_rS2);\n obs_HR2_rS2(i-1) = sum( C_nR_rS2(i:end) ) / sum(C_nR_rS2);\n \n obs_FAR2_rS1(i-1) = sum( I_nR_rS1(i:end) ) / sum(I_nR_rS1);\n obs_HR2_rS1(i-1) = sum( C_nR_rS1(i:end) ) / sum(C_nR_rS1); \nend\n\n\n%% find estimated t2FAR and t2HR\n\nS1mu = -meta_d1/2; S1sd = 1;\nS2mu = meta_d1/2; S2sd = S1sd/s;\n\nmt1c1 = eval(constant_criterion);\n\nC_area_rS2 = 1-fncdf(mt1c1,S2mu,S2sd);\nI_area_rS2 = 1-fncdf(mt1c1,S1mu,S1sd);\n\nC_area_rS1 = fncdf(mt1c1,S1mu,S1sd);\nI_area_rS1 = fncdf(mt1c1,S2mu,S2sd);\n\nfor i=1:nRatings-1\n \n t2c1_lower = t2c1(nRatings-i);\n t2c1_upper = t2c1(nRatings-1+i);\n \n I_FAR_area_rS2 = 1-fncdf(t2c1_upper,S1mu,S1sd);\n C_HR_area_rS2 = 1-fncdf(t2c1_upper,S2mu,S2sd);\n\n I_FAR_area_rS1 = fncdf(t2c1_lower,S2mu,S2sd);\n C_HR_area_rS1 = fncdf(t2c1_lower,S1mu,S1sd);\n \n \n est_FAR2_rS2(i) = I_FAR_area_rS2 / I_area_rS2;\n est_HR2_rS2(i) = C_HR_area_rS2 / C_area_rS2;\n\n est_FAR2_rS1(i) = I_FAR_area_rS1 / I_area_rS1;\n est_HR2_rS1(i) = C_HR_area_rS1 / C_area_rS1;\n \nend\n\n\n%% package output\n\nfit.d1 = sqrt(2/(1+s^2)) * s * d1;\nfit.c1 = c;\nfit.s = s;\nfit.meta_d = sqrt(2/(1+s^2)) * s * meta_d1;\nfit.M_diff = fit.meta_d - fit.d1;\nfit.M_ratio = fit.meta_d / fit.d1;\n\nmt1c1 = eval(constant_criterion);\nfit.meta_c1 = ( sqrt(2).*s ./ sqrt(1+s.^2) ) .* mt1c1;\n\nt2ca = ( sqrt(2).*s ./ sqrt(1+s.^2) ) .* t2c1;\nfit.t2ca_rS1 = t2ca(1:nRatings-1);\nfit.t2ca_rS2 = t2ca(nRatings:end);\n\nfit.S1units.d1 = d1;\nfit.S1units.meta_d1 = meta_d1;\nfit.S1units.s = s;\nfit.S1units.meta_c1 = mt1c1;\nfit.S1units.t2c1_rS1 = t2c1(1:nRatings-1);\nfit.S1units.t2c1_rS2 = t2c1(nRatings:end);\n\nfit.logL = logL;\n\nfit.est_HR2_rS1 = est_HR2_rS1;\nfit.obs_HR2_rS1 = obs_HR2_rS1;\n\nfit.est_FAR2_rS1 = est_FAR2_rS1;\nfit.obs_FAR2_rS1 = obs_FAR2_rS1;\n\nfit.est_HR2_rS2 = est_HR2_rS2;\nfit.obs_HR2_rS2 = obs_HR2_rS2;\n\nfit.est_FAR2_rS2 = est_FAR2_rS2;\nfit.obs_FAR2_rS2 = obs_FAR2_rS2;\n\n\n%% clean up\ndelete fit_meta_d_MLE.mat\n\nend\n\n\n%% function to find the likelihood of parameter values, given observed data\nfunction logL = fit_meta_d_logL(parameters)\n\n% set up parameters\nmeta_d1 = parameters(1);\nt2c1 = parameters(2:end);\n\n% loads:\n% nR_S1 nR_S2 nRatings d1 t1c1 s constant_criterion fncdf fninv\nload fit_meta_d_MLE.mat\n\n\n% define mean and SD of S1 and S2 distributions\nS1mu = -meta_d1/2; S1sd = 1;\nS2mu = meta_d1/2; S2sd = S1sd/s;\n\n\n% adjust so that the type 1 criterion is set at 0\n% (this is just to work with optimization toolbox constraints...\n% to simplify defining the upper and lower bounds of type 2 criteria)\nS1mu = S1mu - eval(constant_criterion);\nS2mu = S2mu - eval(constant_criterion);\n\nt1c1 = 0;\n\n\n\n%%% set up MLE analysis\n\n% get type 2 response counts\nfor i = 1:nRatings\n \n % S1 responses\n nC_rS1(i) = nR_S1(i);\n nI_rS1(i) = nR_S2(i);\n \n % S2 responses\n nC_rS2(i) = nR_S2(nRatings+i);\n nI_rS2(i) = nR_S1(nRatings+i);\n \nend\n\n% get type 2 probabilities\nC_area_rS1 = fncdf(t1c1,S1mu,S1sd);\nI_area_rS1 = fncdf(t1c1,S2mu,S2sd);\n\nC_area_rS2 = 1-fncdf(t1c1,S2mu,S2sd);\nI_area_rS2 = 1-fncdf(t1c1,S1mu,S1sd);\n\nt2c1x = [-Inf t2c1(1:nRatings-1) t1c1 t2c1(nRatings:end) Inf];\n\nfor i = 1:nRatings\n prC_rS1(i) = ( fncdf(t2c1x(i+1),S1mu,S1sd) - fncdf(t2c1x(i),S1mu,S1sd) ) / C_area_rS1;\n prI_rS1(i) = ( fncdf(t2c1x(i+1),S2mu,S2sd) - fncdf(t2c1x(i),S2mu,S2sd) ) / I_area_rS1;\n \n prC_rS2(i) = ( (1-fncdf(t2c1x(nRatings+i),S2mu,S2sd)) - (1-fncdf(t2c1x(nRatings+i+1),S2mu,S2sd)) ) / C_area_rS2;\n prI_rS2(i) = ( (1-fncdf(t2c1x(nRatings+i),S1mu,S1sd)) - (1-fncdf(t2c1x(nRatings+i+1),S1mu,S1sd)) ) / I_area_rS2;\nend\n \n\n% calculate logL\nlogL = 0;\nfor i = 1:nRatings\n \n logL = logL + nC_rS1(i)*log(prC_rS1(i)) + nI_rS1(i)*log(prI_rS1(i)) + ...\n nC_rS2(i)*log(prC_rS2(i)) + nI_rS2(i)*log(prI_rS2(i));\n \nend\n\nif isnan(logL), logL=-Inf; end\n\nlogL = -logL;\n \nend", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/task/FDT/scripts/tapas_fit_meta_d_MLE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49618279526433795}} {"text": "function [ gpos ] = point_image_to_ground( im_points, sicd_meta, varargin )\n%POINT_IMAGE_TO_GROUND Transforms pixel row, col to ground ECF coordinate\n% This function implements the SICD Image Projections Description Document:\n% http://www.gwg.nga.mil/ntb/baseline/docs/SICD/index.html\n%\n% gpos = point_image_to_ground(im_points, sicd_meta, 'PropertyName', PropertyValue, ...)\n%\n% Inputs:\n% im_points - [2xN] (row; column) coordinates of N points in image (or\n% subimage if FirstRow/FirstCol are nonzero). Zero-based,\n% following SICD convention (rather than MATLAB\n% convention, which is one-based); that is, upper-left\n% pixel is [0;0].\n% sicd_meta - SICD meta data structure\n%\n% Property name Description\n% projection_type 'plane', 'hae', 'dem', 'best' (try DEM first\n% then HAE). Default plane.\n% gref Ground plane reference point ECF coordinates (m).\n% Default is SCP. Only valid if projection_type is\n% 'plane'.\n% ugpn Ground plane unit normal vector. Default is\n% tangent to the surface of constant geodetic\n% height above the WGS-84 reference ellipsoid\n% passing through GREF. Only valid if\n% projection_type is 'plane'.\n% hae0 Surface height (m) above the WGS-84 reference\n% ellipsoid for projection point. Only valid if\n% projection_type is 'hae'.\n% delta_hae_max Height threshold for convergence of iterative\n% constant HAE computation (m). Default 1 meter.\n% Only valid if projection_type is 'hae'.\n% hae_nlim Maximum number of iterations allowed for constant\n% hae computation. Default 3. Only valid if\n% projection_type is 'hae'.\n% dem SRTM pathname or structure with\n% lats/lons/elevations fields where are all are\n% arrays of same size and elevation is height above\n% WGS-84 ellipsoid.\n% Only valid if projection_type is 'dem'.\n% del_DISTrrc Maximum distance between adjacent points along\n% the R/Rdot contour. Recommended value: 10.0 m.\n% Only valid if projection_type is 'dem'.\n% del_HDlim Height difference threshold for determining if a\n% point on the R/Rdot contour is on the DEM\n% surface (m). Recommended value: 0.001 m. Only\n% valid if projection_type is 'dem'.\n% delta_arp ARP position adjustable parameter (ECF, m). Default 0.\n% delta_varp VARP position adjustable parameter (ECF, m/s). Default 0.\n% range_bias Range bias adjustable parameter (m). Default 0.\n% adj_params_frame Coordinate frame used for expressing delta_arp\n% and delta_varp adjustable parameters. Allowed\n% values: 'ECF', 'RIC_ECF', 'RIC_ECI'. Default ECF.\n%\n% Outputs:\n% gpos - [3xN] ECF Ground Points along the R/Rdot contour\n%\n% Contributors: Thomas McDowall, Harris Corporation\n% Lisa Talbot, NGA/IB\n% Rocco Corsetti, NGA/IB\n% Wade Schwartzkopf, NGA/IDT\n%\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED ///\n% //////////////////////////////////////////\n\n%% Parse input parameters\nif isvector(im_points), im_points = im_points(:); end % Assure orientation\nscp = [sicd_meta.GeoData.SCP.ECF.X; ...\n sicd_meta.GeoData.SCP.ECF.Y; ...\n sicd_meta.GeoData.SCP.ECF.Z]; % Default values for some input arguments require this\nscp_llh = ecf_to_geodetic(scp); % Also should be available in sicd_meta.GeoData.SCP.LLH\nscp_hae = scp_llh(3);\np = inputParser;\np.addParamValue('projection_type','plane', @(x) any(strcmp(x,{'plane','hae','hae_newton','dem','best'})));\np.addParamValue('gref',scp, @(x) (size(x,1)==3)||(numel(x)==3)); % ECF (meters)\nif isfield(sicd_meta,'PFA')&&isfield(sicd_meta.PFA,'FPN')\n default_ugpn=[sicd_meta.PFA.FPN.X; sicd_meta.PFA.FPN.Y; sicd_meta.PFA.FPN.Z];\nelse\n default_ugpn=wgs_84_norm(scp);\nend\np.addParamValue('ugpn',default_ugpn, @(x) (size(x,1)==3)||(numel(x)==3)); % ECF\np.addParamValue('hae0',scp_hae, @isscalar); % meters\np.addParamValue('delta_hae_max', 1, @(x) isscalar(x) && (x>0)); % meters\np.addParamValue('hae_nlim', 3, @isscalar);\np.addParamValue('dem',[]);\np.addParamValue('del_DISTrrc', 10, @isscalar);\np.addParamValue('del_HDlim', 0.001, @isscalar);\n% Adjustable parameters\np.addParamValue('delta_arp',[0 0 0], @(x) numel(x)==3); % ECF? (meters)\np.addParamValue('delta_varp',[0 0 0], @(x) numel(x)==3); % ECF? (meters/s)\np.addParamValue('range_bias',0, @isscalar); % meters\np.addParamValue('adj_params_frame','ECF', @(x) any(strcmpi(x,{'ECF','RIC_ECF','RIC_ECI'})));\np.FunctionName = mfilename;\np.parse(varargin{:});\n\n%% Chapter 4: Compute projection parameters \ntry\n % Computation of r/rdot is specific to image formation type\n [r, rdot, arp_coa, varp_coa] = coa_projection_set(sicd_meta, im_points);\ncatch % If full metadata not available, try to make the approximation of uniformly sampled grid\n sicd_meta.Grid.Type = 'PLANE';\n if ~isfield(sicd_meta.Grid, 'TimeCOAPoly') % Another approximation that may have to be made\n sicd_meta.Grid.TimeCOAPoly = sicd_meta.Timeline.CollectDuration/2;\n end\n [r, rdot, arp_coa, varp_coa] = coa_projection_set(sicd_meta, im_points);\n warning('point_image_to_ground:IncompleteMetadata',...\n 'Unable to compute precise position due to incomplete metadata. Resorting to approximation.');\nend\n% After r/rdot is computed, the rest is generic to all SAR.\n\n%% Apply adjustable parameters\nif strcmpi(p.Results.adj_params_frame,'ECF')\n % No transformation necessary\n delta_arp = p.Results.delta_arp(:);\n delta_varp = p.Results.delta_varp(:);\nelse % Translate from RIC frame to ECF frame\n % Use the RIC frame at SCP COA time, not at COA time for im_points\n ARP_SCP_COA = [sicd_meta.SCPCOA.ARPPos.X; ...\n sicd_meta.SCPCOA.ARPPos.Y; ...\n sicd_meta.SCPCOA.ARPPos.Z];\n VARP_SCP_COA = [sicd_meta.SCPCOA.ARPVel.X; ...\n sicd_meta.SCPCOA.ARPVel.Y; ...\n sicd_meta.SCPCOA.ARPVel.Z];\n if strcmpi(p.Results.adj_params_frame,'RIC_ECI')\n T_ECEF_RIC = ric_ecf_mat(ARP_SCP_COA, VARP_SCP_COA, 'eci');\n else % RIC_ECF\n T_ECEF_RIC = ric_ecf_mat(ARP_SCP_COA, VARP_SCP_COA, 'ecf');\n end\n delta_arp = T_ECEF_RIC * p.Results.delta_arp(:);\n delta_varp = T_ECEF_RIC * p.Results.delta_varp(:);\nend\narp_coa = arp_coa + repmat(delta_arp,1,size(arp_coa,2));\nvarp_coa = varp_coa + repmat(delta_varp,1,size(arp_coa,2));\nr = r + p.Results.range_bias;\n\n%% Perform actual projection\nswitch p.Results.projection_type\n case 'plane' % Chapter 5 of SICD document\n gpos = point_to_ground_plane(r, rdot, arp_coa, varp_coa, ...\n p.Results.gref, p.Results.ugpn);\n case 'hae' % Chapter 9 of SICD projection document (draft)\n gpos = point_to_hae(r, rdot, arp_coa, varp_coa, scp, ...\n p.Results.hae0, p.Results.delta_hae_max, p.Results.hae_nlim);\n case 'hae_newton' % Spotlight Synthetic Aperture Radar (SAR) Sensor Model, NGA.SIG.0005_1.0, 2010-03-30\n if ~strcmp(sicd_meta.CollectionInfo.RadarMode.ModeType,'SPOTLIGHT')\n error('point_image_to_ground:invalid_projection_mode','HAE_NEWTON projection method only valid for spotlight data.');\n end\n gpos = point_to_hae_newton(r, rdot, arp_coa, varp_coa, scp, ...\n p.Results.hae0);\n case 'dem' % Chapter 10 of SICD document (draft)\n gpos = point_to_DEM(r, rdot, arp_coa, varp_coa, scp, ...\n p.Results.delta_hae_max, p.Results.hae_nlim, p.Results.dem, ...\n p.Results.del_DISTrrc, p.Results.del_HDlim);\n case 'best' % Best available. Use DEM if valid, otherwise use HAE\n try\n gpos = point_to_DEM(r, rdot, arp_coa, varp_coa, scp, ...\n p.Results.delta_hae_max, p.Results.hae_nlim, p.Results.dem, ...\n p.Results.del_DISTrrc, p.Results.del_HDlim);\n catch\n warning('point_image_to_ground:invalid_dem','Best projection reverted to HAE.');\n gpos = point_to_hae(r, rdot, arp_coa, varp_coa, scp, ...\n p.Results.hae0, p.Results.delta_hae_max, p.Results.hae_nlim);\n end\n otherwise\n % Unrecognized projection type\nend\n\nend\n\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED ///\n% //////////////////////////////////////////", "meta": {"author": "ngageoint", "repo": "MATLAB_SAR", "sha": "6291feff8e200d387e271f49ec09b1acd5514c4e", "save_path": "github-repos/MATLAB/ngageoint-MATLAB_SAR", "path": "github-repos/MATLAB/ngageoint-MATLAB_SAR/MATLAB_SAR-6291feff8e200d387e271f49ec09b1acd5514c4e/Geometry/Projections/point_image_to_ground.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677545357568, "lm_q2_score": 0.5851011542032313, "lm_q1q2_score": 0.4961469119059936}} {"text": "function paracellularAbsorption = calculateParacellularAbsorption(DrugLogP, DrugMolecularWeight)\n% calculate the paracellular absorption rate using the heuristics presented\n% in Eq. 2 in: \n% Peters, S. A. (2008). Evaluation of a generic physiologically based pharmacokinetic model for lineshape analysis. Clinical pharmacokinetics, 47(4), 261-75.\n% Copyright 2012 The MathWorks, Inc.\n\nparacellularAbsorption = 0;\nif DrugLogP > 0.7, \n paracellularAbsorption = 0; \nelseif DrugLogP < 0.1 && (DrugMolecularWeight > 200 && DrugMolecularWeight < 360), \n paracellularAbsorption = 0.1;\nelseif DrugMolecularWeight < 200, \n paracellularAbsorption = -0.0045*DrugMolecularWeight+1;\nend\n\n%paracellularAbsorption = paracellularAbsorption*5;", "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/37132-physiologically-based-pharmacokinetic-pbpk-model-for-simbiology/calculateParacellularAbsorption.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4961121617164271}} {"text": "classdef MMF5 < PROBLEM\n% \n% Multi-modal multi-objective test function\n\n%------------------------------- Reference --------------------------------\n% C. Yue, B. Qu, and J. Liang, A multi-objective particle swarm optimizer\n% using ring topology for solving multimodal multiobjective Problems, IEEE\n% Transactions on Evolutionary Computation, 2018, 22(5): 805-817.\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 POS; % Pareto optimal set for IGDX calculation\n end\n methods\n %% Default settings of the problem\n function Setting(obj)\n obj.M = 2;\n obj.D = 2;\n obj.lower = [1,-1];\n obj.upper = [3,3];\n obj.encoding = ones(1,obj.D);\n end\n %% Calculate objective values\n function PopObj = CalObj(obj,X)\n temp = X(:,2) <= 1;\n y = zeros(size(X,1),1);\n y(temp) = X(temp,2) - sin(6*pi*abs(X(temp,1)-2)+pi);\n y(~temp) = X(~temp,2) - 2 - sin(6*pi*abs(X(~temp,1)-2)+pi);\n PopObj(:,1) = abs(X(:,1)-2); \n PopObj(:,2) = 1 - sqrt(PopObj(:,1)) + 2*y.^2;\n end\n %% Generate Pareto optimal solutions\n function R = GetOptimum(obj,N)\n % Generate points in Pareto optimal set\n obj.POS(:,1) = linspace(1,3,N/2)';\n obj.POS(:,2) = sin(6*pi*abs(obj.POS(:,1)-2)+pi);\n obj.POS = [obj.POS;obj.POS(:,1),obj.POS(:,2)+2];\n % Generate points on Pareto front\n R(:,1) = linspace(0,1,N)';\n R(:,2) = 1 - sqrt(R(:,1));\n end\n %% Generate the image of Pareto front\n function R = GetPF(obj)\n R(:,1) = linspace(0,1,100)';\n R(:,2) = 1 - sqrt(R(:,1));\n end\n %% Calculate the metric value\n function score = CalMetric(obj,metName,Population)\n switch metName\n case 'IGDX'\n score = feval(metName,Population,obj.POS);\n otherwise\n score = feval(metName,Population,obj.optimum);\n end\n end\n %% Display a population in the objective space\n function DrawObj(obj,Population)\n PopDec = Population.decs;\n temp1 = PopDec(:,1)<=2;\n temp2 = PopDec(:,2)<=1;\n Draw(Population(temp1&temp2).objs,'o','MarkerSize',6,'Marker','o','Markerfacecolor',[1 .5 .5],'Markeredgecolor',[1 .2 .2],{'\\it f\\rm_1','\\it f\\rm_2',[]});\n Draw(Population(temp1&~temp2).objs+0.05,'o','MarkerSize',6,'Marker','o','Markerfacecolor',[.5 .5 1],'Markeredgecolor',[.2 .2 1]);\n Draw(Population(~temp1&temp2).objs+0.1,'o','MarkerSize',6,'Marker','o','Markerfacecolor',[.5 1 .5],'Markeredgecolor',[.2 1 .2]);\n Draw(Population(~temp1&~temp2).objs+0.15,'o','MarkerSize',6,'Marker','o','Markerfacecolor',[1 .5 1],'Markeredgecolor',[1 .2 1]);\n Draw(obj.PF,'-','LineWidth',1,'Color',[1 .2 .2]);\n Draw(obj.PF+0.05,'-','LineWidth',1,'Color',[.2 .2 1]);\n Draw(obj.PF+0.1,'-','LineWidth',1,'Color',[.2 1 .2]);\n Draw(obj.PF+0.15,'-','LineWidth',1,'Color',[1 .2 1]);\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/MMF/MMF5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.49583797235897226}} {"text": "function c = tapas_hgf_ar1_binary_mab_config\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Contains the configuration for the Hierarchical Gaussian Filter (HGF) for AR(1) processes in a\n% multi-armded bandit situation for binary inputs in the absence of perceptual uncertainty.\n%\n% The HGF is the model introduced in \n%\n% Mathys C, Daunizeau J, Friston, KJ, and Stephan KE. (2011). A Bayesian foundation\n% for individual learning under uncertainty. Frontiers in Human Neuroscience, 5:39.\n%\n% The binary HGF model has since been augmented with a positive factor kappa1 which\n% scales the second level with respect to the first, i.e., the relation between the\n% first and second level is\n%\n% p(x1=1|x2) = s(kappa1*x2), where s(.) is the logistic sigmoid.\n%\n% By default, kappa1 is fixed to 1, leading exactly to the model introduced in\n% Mathys et al. (2011).\n%\n% This file refers to BINARY inputs (Eqs 1-3 in Mathys et al., (2011));\n% for continuous inputs, refer to tapas_hgf_config.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% The HGF configuration consists of the priors of parameters and initial values. All priors are\n% Gaussian in the space where the quantity they refer to is estimated. They are specified by their\n% sufficient statistics: mean and variance (NOT standard deviation).\n% \n% Quantities are estimated in their native space if they are unbounded (e.g., the omegas). They are\n% estimated in log-space if they have a natural lower bound at zero (e.g., the sigmas).\n% \n% The phis are estimated in 'logit space' because they are confined to the interval from 0 to 1.\n% 'Logit-space' is a logistic sigmoid transformation of native space with a variable upper bound\n% a>0:\n% \n% tapas_logit(x) = ln(x/(a-x)); x = a/(1+exp(-tapas_logit(x)))\n%\n% Parameters can be fixed (i.e., set to a fixed value) by setting the variance of their prior to\n% zero. Aside from being useful for model comparison, the need for this arises whenever the scale\n% and origin at the j-th level are arbitrary. This is the case if the observation model does not\n% contain the representations mu_j and sigma_j. A choice of scale and origin is then implied by\n% fixing the initial value mu_j_0 of mu_j and either kappa_j-1 or omega_j-1.\n%\n% Fitted trajectories can be plotted by using the command\n%\n% >> tapas_hgf_binary_mab_plotTraj(est)\n% \n% where est is the stucture returned by tapas_fitModel. This structure contains the estimated\n% perceptual parameters in est.p_prc and the estimated trajectories of the agent's\n% representations (cf. Mathys et al., 2011). Their meanings are:\n% \n% est.p_prc.mu_0 row vector of initial values of mu (in ascending order of levels)\n% est.p_prc.sa_0 row vector of initial values of sigma (in ascending order of levels)\n% est.p_prc.phi row vector of phis (representing reversion slope to attractor; in ascending order of levels)\n% est.p_prc.m row vector of ms (representing attractors; in ascending order of levels)\n% est.p_prc.ka row vector of kappas (in ascending order of levels)\n% est.p_prc.om row vector of omegas (in ascending order of levels)\n%\n% Note that the first entry in all of the row vectors will be NaN because, at the first level,\n% these parameters are either determined by the second level (mu_0 and sa_0) or undefined (rho,\n% kappa, and omega).\n%\n% est.traj.mu mu (rows: trials, columns: levels, 3rd dim: bandits)\n% est.traj.sa sigma (rows: trials, columns: levels, 3rd dim: bandits)\n% est.traj.muhat prediction of mu (rows: trials, columns: levels, 3rd dim: bandits)\n% est.traj.sahat precisions of predictions (rows: trials, columns: levels, 3rd dim: bandits)\n% est.traj.v inferred variance of random walk (rows: trials, columns: levels)\n% est.traj.w weighting factors (rows: trials, columns: levels)\n% est.traj.da volatility prediction errors (rows: trials, columns: levels)\n% est.traj.ud updates with respect to prediction (rows: trials, columns: levels)\n% est.traj.psi precision weights on prediction errors (rows: trials, columns: levels)\n% est.traj.epsi precision-weighted prediction errors (rows: trials, columns: levels)\n% est.traj.wt full weights on prediction errors (at the first level,\n% this is the learning rate) (rows: trials, columns: levels)\n%\n% Note that in the absence of sensory uncertainty (which is the assumption here), the first\n% column of mu, corresponding to the first level, will be equal to the inputs. Likewise, the\n% first column of sa will be 0 always.\n%\n% Tips:\n% - When analyzing a new dataset, take your inputs u and responses y and use\n%\n% >> est = tapas_fitModel(y, u, 'tapas_hgf_ar1_binary_mab_config', 'tapas_bayes_optimal_binary_config');\n%\n% to determine the Bayes optimal perceptual parameters (given your current priors as defined in\n% this file here, so choose them wide and loose to let the inputs influence the result). You can\n% then use the optimal parameters as your new prior means for the perceptual parameters.\n%\n% - If you get an error saying that the prior means are in a region where model assumptions are\n% violated, lower the prior means of the omegas, starting with the highest level and proceeding\n% downwards.\n%\n% - Alternatives are lowering the prior means of the kappas, if they are not fixed, or adjusting\n% the values of the kappas or omegas, if any of them are fixed.\n%\n% - If the log-model evidence cannot be calculated because the Hessian poses problems, look at\n% est.optim.H and fix the parameters that lead to NaNs.\n%\n% - Your guide to all these adjustments is the log-model evidence (LME). Whenever the LME increases\n% by at least 3 across datasets, the adjustment was a good idea and can be justified by just this:\n% the LME increased, so you had a better model.\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2013-2017 Christoph Mathys, TNU, UZH & ETHZ\n%\n% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or .\n\n\n% Config structure\nc = struct;\n\n% Model name\nc.model = 'hgf_ar1_binary_mab';\n\n% Number of levels (minimum: 3)\nc.n_levels = 3;\n\n% Number of bandits\nc.n_bandits = 3;\n\n% Coupling\n% This may only be set to true if c.n_bandits is set to 2 above. If\n% true, it means that the two bandits' winning probabilities are\n% coupled in the sense that they add to 1 and are both updated on\n% each trial even though only the outcome for one of them is observed.\nc.coupled = false;\n\n% Input intervals\n% If input intervals are irregular, the last column of the input\n% matrix u has to contain the interval between inputs k-1 and k\n% in the k-th row, and this flag has to be set to true\nc.irregular_intervals = false;\n\n% Sufficient statistics of Gaussian parameter priors\n\n% Initial mus and sigmas\n% Format: row vectors of length n_levels\n% For all but the first two levels, this is usually best\n% kept fixed to 1 (determines origin on x_i-scale). The \n% first level is NaN because it is determined by the second,\n% and the second implies neutrality between outcomes when it\n% is centered at 0.\nc.mu_0mu = [NaN, 0, 1];\nc.mu_0sa = [NaN, 1, 1];\n\nc.logsa_0mu = [NaN, log(0.1), log(1)];\nc.logsa_0sa = [NaN, 1, 1];\n\n% Phis\n% Format: row vector of length n_levels.\n% Undefined (therefore NaN) at the first level.\n% Fix this to zero (-Inf in logit space) to set to zero.\nc.logitphimu = [NaN, tapas_logit(0.4,1), tapas_logit(0.2,1)];\nc.logitphisa = [NaN, 1, 1];\n\n% ms\n% Format: row vector of length n_levels.\n% This should be fixed for all levels where the omega of\n% the next lowest level is not fixed because that offers\n% an alternative parametrization of the same model.\nc.mmu = [NaN, c.mu_0mu(2), c.mu_0mu(3)];\nc.msa = [NaN, 0, 0];\n\n% Kappas\n% Format: row vector of length n_levels-1.\n% Fixing log(kappa1) to log(1) leads to the original HGF model.\n% Higher log(kappas) should be fixed (preferably to log(1)) if the\n% observation model does not use mu_i+1 (kappa then determines the\n% scaling of x_i+1).\nc.logkamu = [log(1), log(1)];\nc.logkasa = [ 0, 0.1];\n\n% Omegas\n% Format: row vector of length n_levels.\n% Undefined (therefore NaN) at the first level.\nc.ommu = [NaN, -2, -2];\nc.omsa = [NaN, 1, 1];\n\n% Gather prior settings in vectors\nc.priormus = [\n c.mu_0mu,...\n c.logsa_0mu,...\n c.logitphimu,...\n c.mmu,...\n c.logkamu,...\n c.ommu,...\n ];\n\nc.priorsas = [\n c.mu_0sa,...\n c.logsa_0sa,...\n c.logitphisa,...\n c.msa,...\n c.logkasa,...\n c.omsa,...\n ];\n\n% Check whether we have the right number of priors\nexpectedLength = 5*c.n_levels+(c.n_levels-1);\nif length([c.priormus, c.priorsas]) ~= 2*expectedLength;\n error('tapas:hgf:PriorDefNotMatchingLevels', 'Prior definition does not match number of levels.')\nend\n\n% Model function handle\nc.prc_fun = @tapas_hgf_ar1_binary_mab;\n\n% Handle to function that transforms perceptual parameters to their native space\n% from the space they are estimated in\nc.transp_prc_fun = @tapas_hgf_ar1_binary_mab_transp;\n\nreturn;\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/HGF/tapas_hgf_ar1_binary_mab_config.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.495837962367358}} {"text": "classdef cheboppref < chebpref\n%CHEBOPPREF Class for managing preferences for the Chebfun ODE suite.\n% CHEBOPPREF is a class for managing CHEBOP construction-time and solver\n% preferences, such as what solver is used for linear problem, the error or\n% residual tolerance for nonlinear problems, whether damped Newton iteration\n% should be performed for nonlinear problems, and how much information is to\n% be printed to the console during while the solver is active. \n%\n% Available Preferences:\n%\n% bvpTol - Error tolerance for boundary value problems\n% [5e-13]\n%\n% This is the relative tolerance used to test convergence during the\n% adaptive solution of linear boundary value problems. For nonlinear\n% boundary value problems the Newton convergence tolerance is set to\n% 200*bvpTol.\n%\n% domain - Construction domain.\n% [-1, 1]\n%\n% This sets the default domain that will be used for CHEBOP construction if\n% no domain argument is explicitly passed to the constructor.\n%\n% discretization - Discretization of linear problems\n% ['values']\n% 'coeffs'\n% @chebcolloc1\n% @chebcolloc2\n% @ultraS\n% @trigcolloc\n% @trigspec\n%\n% This options determines whether linear operators are discretized using\n% rectangular collocation methods or the ultraspherical method. Please\n% observe that\n% * 'values' and 'coeffs' are convenient ways of specifying the \n% @chebcolloc2 and @ultraS options respectively (when the boundary \n% conditions are not periodic), and @trigcolloc and @trigspec \n% respectively (when the boundary conditions are periodic).\n% * The @trigcolloc/@trigspec options are only supported for problems\n% that are specified to have periodic boundary conditions. \n% * Specifying the @chebcolloc1 option causes the CHEBFUN solution\n% returned to be based on the @chebtech1 tech. The @chebtech2/@ultraS\n% option causes the CHEBFUN solution returned to be based on the\n% @chebtech2 tech. The @trigcolloc/@trigspec option causes the \n% CHEBFUN solution to be periodic, based on the @trigtech tech.\n% \n% damping - Should Newton's method be damped?\n% [true]\n% false\n%\n% If true, damped Newton iteration in function space is performed for\n% nonlinear problems. If false, undamped Newton iteration is performed, that\n% is, the solver will always take full Newton steps.\n%\n% display - How much information is to be printed\n% 'final'\n% ['iter']\n% 'off'\n%\n% If 'final', information is only printed after the solver of BVPs has\n% finished. If 'iter', information is printed at every Newton step. If\n% 'off', no information is printed.\n%\n% happinessCheck - Routine for checking that solution converged\n% [@standardCheck]\n% @basicCheck\n% @plateauCheck\n% @classicCheck\n% @looseCheck\n% @strictCheck\n% @happinessCheck\n% @linopV4Check\n%\n% This options determines which routine is used to determine that the\n% approximate solution has converged. Any of the above options may be\n% used, as well as any user defined function handle that conforms to \n% the happinessCheck standards.\n%\n% ivpAbsTol - Absolute tolerance for the ivpSolver\n% [1e5*eps]\n%\n% This options specifies the option for the absolute tolerance passed as an\n% option to the built-in MATLAB ODE solver when solving IVPs.\n%\n% ivpRelTol - Relavtive tolerance for the ivpSolver\n% [100*eps]\n%\n% This options specifies the option for the relative tolerance passed as an\n% option to the built-in MATLAB ODE solver when solving IVPs.\n%\n% ivpRestartSolver - Restart IVP solvers at breakpoints\n% false\n% [true]\n%\n% This option specifies whether the MATLAB built in solvers should be\n% restarted at breakpoints. That is, whether each subinterval of a piecewise\n% problem will get integrated separately. This can be very useful for e.g.\n% short forcing pulses, which otherwise might get overlooked.\n%\n% ivpSolver - Solver for IVPs\n% ['ode113']\n% 'ode15s'\n% 'ode45'\n% 'values'\n% 'coeffs'\n%\n% This options determines which of the MATLAB built-in IVP solvers is used\n% for solving IVPs posed with the CHEBOP class. Any option of\n% CHEBOPPREF.discretization (see above) is allowed, which causes IVPs to be\n% solved globally via spectral methods, rather than reformulating them as\n% first-order problems and then solved via time-stepping method.\n%\n% lambdaMin - Minimum allowed step-size for Newton's method\n% [1e-6]\n%\n% The value of lambdaMin determines the minimum allowed step-size that the\n% damped Newton iteration is allowed to take.\n%\n% maxDimension\n% [4096]\n%\n% The maximum number of gridpoints/coefficients used as linear operators are\n% discretized at finer and finer grids to resolve the solution. The\n% intermediate values for the discretization between cheboppref.minDimension\n% and cheboppref.maxDimension depend on the discretization used for the\n% operator.\n%\n% maxIter - Maximum number of Newton steps\n% [25]\n%\n% The maximum number of steps that the (damped) Newton iteration is allowed to\n% take, before it is considered to be non-convergent.\n%\n% minDimension\n% [32]\n%\n% The minimum number of gridpoints/coefficients used as linear operators are\n% discretized at finer and finer grids to resolve the solution. The\n% intermediate values for the discretization between cheboppref.minDimension\n% and cheboppref.maxDimension depend on the discretization used for the\n% operator.\n%\n% plotting - Plotting of intermediate Newton steps\n% DELAY\n% 'on'\n% ['off']\n% 'pause'\n%\n% If plotting = 'on', the current iterate in the Newton solution is plotted at\n% every step, as well as the current Newton correction. If plotting = DELAY,\n% where DELAY has a numerical value, the iteration is paused and the plots are\n% shown for the time DELAY seconds. If plotting = 'pause', the iteration is\n% paused and the plots are shown until the user presses a button. If plotting\n% = 'off', no plots are shown during the Newton iteration.\n%\n% vectorize - Automatic vectorization of anon. functions\n% [true]\n% false\n%\n% Determines whether the CHEBOP class should try to automatically try to\n% vectorize anonymous functions used for describing the differential equation\n% and boundary condition(s).\n%\n%\n% The default values for any of these preferences may be globally overridden\n% using CHEBOPPREF.SETDEFAULTS(); see the documentation for that function for\n% further details.\n%\n% Constructor inputs:\n% P = CHEBOPPREF() creates a CHEBOPPREF object with the default values of the\n% preferences. For a list of all available preferences, see above.\n%\n% P = CHEBOPPREF(Q), where Q is a MATLAB structure uses the field/value pairs\n% in Q to set the properties of P. If a field of Q has a name which matches\n% a property of P, the value of that property of P is set to the value\n% associated to that field in Q. If a field of Q has a name that does not\n% correspond to a known preference, then an error is thrown.\n%\n% P = CHEBOPPREF(Q), where Q is a CHEBOPPREF, sets P to be a copy of Q.\n%\n% See also CHEBFUNPREF.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% TODO: Further documentation of CHEBOPPREF preferences.\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %% CLASS CONSTRUCTOR:\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n methods ( Access = public, Static = false )\n\n function outPref = cheboppref(inPref, varargin)\n if ( (nargin == 1) && isa(inPref, 'cheboppref') )\n outPref = inPref;\n return\n elseif ( nargin < 1 )\n inPref = struct();\n elseif ( ischar(inPref) )\n if ( nargin == 1 )\n error('CHEBFUN:CHEBOPPREF:cheboppref:deprecated', ...\n ['cheboppref() no longer supports queries of ', ...\n 'the form cheboppref(''prop'').\\n', ...\n 'Please use cheboppref().prop.']);\n else\n error('CHEBFUN:CHEBOPPREF:cheboppref:deprecated', ...\n ['cheboppref() no longer supports assignment ', ...\n 'via cheboppref(''prop'', val).\\n', ...\n 'Please use cheboppref.setDefaults(''prop'', val).']);\n end\n elseif ( nargin > 1 )\n error('CHEBFUN:CHEBOPPREF:cheboppref:inputs', ...\n 'Too many input arguments.')\n end\n\n % Initialize default preference values.\n outPref.prefList = cheboppref.manageDefaultPrefs('get');\n\n % Copy fields from q, merging incomplete substructures.\n for field = fieldnames(inPref).'\n field1 = field{1};\n if ( isfield(outPref.prefList, field1) )\n if ( isstruct(outPref.prefList.(field1)) )\n outPref.prefList.(field1) = ...\n chebpref.mergePrefStructs(...\n outPref.prefList.(field1), ...\n inPref.(field1));\n else\n outPref.prefList.(field1) = inPref.(field1);\n end\n else\n error('CHEBFUN:CHEBOPPREF:cheboppref:badPref', ...\n 'Unrecognized preference name.');\n end\n end\n end\n \n end\n \n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %% CLASS METHODS:\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n methods ( Access = public, Static = false )\n\n function display(pref)\n %DISPLAY Display a CHEBOPPREF object.\n % DISPLAY(PREF) prints out a list of the preferences stored in the\n % CHEBOPPREF object PREF.\n\n % Compute the screen column in which pref values start.\n valueCol = 24; % length(' blowup: ');\n\n % A subfunction to pad strings for formatting.\n function s = padString(s)\n %PADSTRING Add whitespace to string for formatting.\n s = [s repmat(' ', 1, valueCol - length(s))];\n end\n\n % Print values of \"known\" preferences.\n prefList = pref.prefList;\n\n fprintf('cheboppref object with the following preferences:\\n');\n fprintf([padString(' bvpTol:') '%g\\n'], ...\n prefList.bvpTol);\n fprintf([padString(' domain:') '[%g, %g]\\n'], ...\n prefList.domain(1), prefList.domain(end));\n if ( isa(prefList.discretization,'function_handle') )\n fprintf([padString(' discretization:') '%s\\n'], ...\n func2str(prefList.discretization));\n elseif ( isa(prefList.discretization,'char') )\n fprintf([padString(' discretization:') '%s\\n'], ...\n prefList.discretization);\n end\n \n fprintf([padString(' damping:') '%d\\n'], ...\n prefList.damping);\n fprintf([padString(' display:') '%s\\n'], ...\n prefList.display);\n fprintf([padString(' happinessCheck:') '%s\\n'], ...\n func2str(prefList.happinessCheck));\n fprintf([padString(' ivpAbsTol:') '%g\\n'], ...\n prefList.ivpAbsTol);\n fprintf([padString(' ivpRelTol:') '%g\\n'], ...\n prefList.ivpRelTol);\n fprintf([padString(' ivpRestartSolver:') '%d\\n'], ...\n prefList.ivpRestartSolver);\n fprintf([padString(' ivpSolver:') '%s\\n'], ...\n func2str(prefList.ivpSolver));\n fprintf([padString(' lambdaMin:') '%g\\n'], ...\n prefList.lambdaMin);\n fprintf([padString(' maxDimension:') '%d\\n'], ...\n prefList.maxDimension);\n fprintf([padString(' maxIter:') '%d\\n'], ...\n prefList.maxIter);\n fprintf([padString(' minDimension:') '%d\\n'], ...\n prefList.minDimension);\n fprintf([padString(' plotting:') '%s\\n'], ...\n prefList.plotting);\n fprintf([padString(' vectorize:') '%i\\n'], ...\n prefList.vectorize);\n end\n\n function pref = subsasgn(pref, ind, val)\n %SUBSASGN Subscripted assignment for CHEBOPPREF.\n % P.PROP = VAL, where P is a CHEBOPPREF object, assigns the value\n % VAL to the CHEBOPPREF property PROP stored in P. If PROP is not a\n % CHEBOPPREF property, an error will be thrown.\n %\n % CHEBOPPREF does not support any other subscripted assignment types,\n % including '()' and '{}'.\n \n % Support user-friendlier syntax for specifying discretization\n % choice:\n val = cheboppref.parseDiscretization(val);\n \n % Support user-friendlier syntax for specifying IVP solver choice:\n val = cheboppref.parseIVPsolver(val);\n \n % Call the superclass method.\n pref = subsasgn@chebpref(pref, ind, val);\n end \n \n end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %% STATIC METHODS:\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n methods ( Access = public, Static = true )\n \n function pref = getFactoryDefaults()\n %GETFACTORYDEFAULTS Get factory default preferences.\n % PREF = CHEBOPPREF.GETFACTORYDEFAULTS() returns a CHEBOPPREF\n % object with the preferences set to their factory defaults,\n % irrespective of the currently defined values of the default\n % preferences. This function is useful if the user wishes to\n % solve ODEs with CHEBOP using the factory defaults when other\n % user-set defaults are currently in force.\n %\n % See also SETDEFAULTS.\n\n fd = cheboppref.factoryDefaultPrefs();\n pref = cheboppref(fd);\n end\n\n function setDefaults(varargin)\n %SETDEFAULTS Set default preferences.\n % CHEBOPPREF.SETDEFAULTS(PREF1, VAL1, PREF2, VAL2, ...) sets the\n % default values for the preferences whose names are stored in the\n % strings PREF1, PREF2, ..., etc. to VAL1, VAL2, ..., etc. All\n % subsequently constructed CHEBOPPREF objects will use these values\n % as the defaults.\n %\n % CHEBOPPREF.SETDEFAULTS(PREF) sets the default values to the\n % preferences stored in the CHEBOPPREF object PREF. PREF can also\n % be a MATLAB structure, in which case it is converted to a\n % CHEBOPPREF as described in the documentation for the CHEBOPPREF\n % constructor first.\n %\n % CHEBOPPREF.SETDEFAULTS('factory') resets the default preferences to\n % their factory values.\n %\n % See also GETFACTORYDEFAULTS.\n\n % The reason we don't just use manageDefaults as the second\n % argument to chebpref.setDefaults and wrap it in an additional\n % anonymous function instead is to get around what seems to be a\n % bug in MATLAB. See commit messages for more information.\n manageDefaults = @cheboppref.manageDefaultPrefs;\n chebpref.setDefaults(@(inPref) cheboppref(inPref), ...\n @(varargin) manageDefaults(varargin{:}), varargin{:});\n end\n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %% PRIVATE STATIC METHODS\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n methods ( Static = true, Access = private )\n\n function varargout = manageDefaultPrefs(varargin)\n %MANAGEDEFAULTPREFS Private method for handling default preferences.\n % CHEBOPPREF.MANAGEDEFAULTPREFS('get') returns a structure suitable\n % for storing in the prefList property of a CHEBOPPREF with all of\n % the currently stored default preferences suitable for initializing\n % a CHEBOPPREF object.\n %\n % CHEBOPPREF.MANAGEDEFAULTPREFS('set-factory') restores the default\n % preferences to their \"factory\" values.\n %\n % CHEBOPPREF.MANAGEDEFAULTPREFS('set', PREFLIST) sets the default\n % values to those stored in the structure PREFLIST. PREFLIST should\n % be a structure suitable for use as a CHEBOPPREF prefList.\n %\n % CHEBOPPREF.MANAGEDEFAULTPREFS('set', PREF1, VAL1, PREF2, VAL2, ...)\n % sets the default values for PREF1, PREF2, ..., etc. to VAL1, VAL2,\n % ..., etc.\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % DEVELOPER NOTE:\n % - MATLAB has no equivalent to what might be called a \"static\" class\n % variable in other languages, so a persistent variable is the best\n % we can do for providing this feature. Persistent variables are\n % local to a specific function, so we can have only a single\n % function for managing it. As a result, this function has a mildly\n % awkward syntax and so is not user-facing.\n % - More importantly, this function is also not user-facing because\n % its inputs and outputs depend on the internal representation of a\n % CHEBOPPREF as a MATLAB structure, and that's not something with\n % which anyone outside of CHEBOPPREF should be concerned.\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n persistent defaultPrefs;\n\n if ( isempty(defaultPrefs) )\n defaultPrefs = cheboppref.factoryDefaultPrefs();\n end\n\n if ( strcmp(varargin{1}, 'get') )\n varargout{1} = defaultPrefs;\n elseif ( strcmp(varargin{1}, 'set-factory') )\n defaultPrefs = cheboppref.factoryDefaultPrefs();\n elseif ( strcmp(varargin{1}, 'set') )\n varargin(1) = [];\n if ( isstruct(varargin{1}) )\n defaultPrefs = varargin{1};\n else\n while ( ~isempty(varargin) )\n prefName = varargin{1};\n prefValue = varargin{2};\n \n % Support user-friendlier syntax for specifying\n % discretization choice:\n prefValue = cheboppref.parseDiscretization(prefValue);\n prefValue = cheboppref.parseHappinessCheck(prefValue);\n prefValue = cheboppref.parseIVPsolver(prefValue);\n if ( isfield(defaultPrefs, prefName) )\n defaultPrefs.(prefName) = prefValue;\n else\n error('CHEBFUN:CHEBOPPREF:cheboppref:badPref', ...\n 'Unrecognized preference name.');\n end\n varargin(1:2) = [];\n end\n end\n end\n end\n\n function factoryPrefs = factoryDefaultPrefs()\n %FACTORYDEFAULTPREFS Get structure of factory default preferences.\n % S = CHEBOPPREF.FACTORYDEFAULTPREFS() returns a structure suitable\n % for storing in the prefList property of a CHEBOPPREF object that\n % contains all of the \"factory default\" values of the CHEBOP\n % preferences.\n\n factoryPrefs.bvpTol = 5e-13;\n factoryPrefs.domain = [-1 1];\n factoryPrefs.discretization = 'values';\n factoryPrefs.scale = NaN;\n factoryPrefs.damping = 1;\n factoryPrefs.display = 'off';\n factoryPrefs.happinessCheck = @standardCheck;\n factoryPrefs.ivpAbsTol = 1e5*eps;\n factoryPrefs.ivpRelTol = 100*eps;\n factoryPrefs.ivpRestartSolver = true;\n factoryPrefs.ivpSolver = @chebfun.ode113;\n factoryPrefs.lambdaMin = 1e-6;\n factoryPrefs.maxDimension = 4096;\n factoryPrefs.maxIter = 25;\n factoryPrefs.minDimension = 32;\n factoryPrefs.plotting = 'off';\n factoryPrefs.vectorize = true;\n end\n \n function val = parseDiscretization(val)\n %PARSEDISCRETIZATION Allow different syntax for specifying\n % discretization.\n \n % We want to allow user-friendly syntax for specifying the\n % discretization (#433). So check whether we have some of the\n % strings we want to allow, and convert them to the correct function\n % handle:\n if ( any(strcmpi(val, {'ultraspherical', 'ultraS'})) )\n warning('CHEBOPPREF:PARSEDISCRETIZATION', ...\n ['''ULTRAS''/''ULTRASPHERICAL'' is deprecated. \\n' ...\n 'Please use ''COEFFS''/@ultraS.']);\n val = @ultraS;\n \n elseif ( any(strcmpi(val, {'chebcolloc2', 'collocation', 'colloc2'})) )\n warning('CHEBOPPREF:PARSEDISCRETIZATION', ...\n ['''COLLOCATION''/''COLLOC2''/''CHEBCOLLOC2'' is deprecated. \\n' ...\n 'Please use ''VALUES''/@chebcolloc2.']);\n val = @chebcolloc2;\n \n elseif ( any(strcmpi(val, {'chebcolloc1', 'colloc1'})) )\n warning('CHEBOPPREF:PARSEDISCRETIZATION', ...\n ['''COLLOC1''/''CHEBCOLLOC1'' is deprecated. \\n' ...\n 'Please use ''VALUES''/@chebcolloc2.']);\n val = @chebcolloc1;\n \n elseif ( any(strcmpi(val, {'trigcolloc', 'periodic'})) )\n warning('CHEBOPPREF:PARSEDISCRETIZATION', ...\n ['''TRIGCOLLOC''/''PERIODIC'' is deprecated. \\n' ...\n 'Please use ''VALUES''/@trigcolloc.']);\n val = @trigcolloc;\n end\n \n end\n \n function val = parseHappinessCheck(val)\n %PARSEHAPPINESSCHECK Allow different syntax for specifying\n % happinessCheck.\n \n % handle:\n if ( any(strcmpi(val, {'classic', 'classicCheck'})) )\n val = @classicCheck;\n \n elseif ( any(strcmpi(val, {'plateau', 'plateauCheck'})) )\n val = @plateauCheck;\n \n elseif ( any(strcmpi(val, {'strict', 'strictCheck'})) )\n val = @strictCheck;\n \n elseif ( any(strcmpi(val, {'loose', 'looseCheck'})) )\n val = @looseCheck;\n \n elseif ( any(strcmpi(val, {'happiness', 'happinessCheck'})) )\n val = @happinessCheck;\n \n elseif ( any(strcmpi(val, {'linopV4', 'linopV4Check'})) )\n val = @linopV4Check;\n \n end\n \n end\n \n function val = parseIVPsolver(val)\n %PARSEIVPSOLVER Allow different syntax for specifying the IVPsolver.\n \n % Check whether we got pref.ivpSolver = @ode113/@ode45/@ode15s, that\n % is, a function handle, but not the CHEBFUN overload of it.\n if ( isa(val, 'function_handle') && ...\n any(strcmpi(func2str(val), {'ode113', 'ode15s', 'ode45'})) )\n val = eval(['@chebfun.', func2str(val)]);\n \n % Check whether we got a string argument, e.g. \n % pref.ivpSolver = 'ode113'.\n elseif ( any(strcmpi(val, {'ode113', 'ode15s', 'ode45'})) )\n val = eval(['@chebfun.', val]);\n end\n end\n\n end\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/@cheboppref/cheboppref.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.49583519176738555}} {"text": "function r = mpower(p,q)\n% MEAS/MPOWER Implement p^q for meas.\n\n% make a meas called r\nr = meas();\n\n% give it the right entries\nr.value = p.value^q;\nr.error = r.value * q * (p.error / p.value);", "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/16606-error-propagation-class/@meas/mpower.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4957212630301061}} {"text": "function [U] = hyperAmee(M, q, Smin, Smax, Imax)\n% HYPERAMEE Performs the AMEE algorithm to find q endmembers\n% Performs the Automated Morphological Endmember Extraction (AMEE) \n% algorithm to find q endmembers. If only M is\n% given as input, this function calls hyperHfcVd to estimate the number\n% of endmembers (q) and then hyperPct to reduce dimensionality to (q-1).\n%\n% Usage\n% [U] = hyperAmee(M, q, Smin)\n% [U] = hyperAmee(M, q, Smin, Smax)\n% [U] = hyperAmee(M, q, Smin, Smax, Imax)\n% Inputs\n% M - 3d matrix of HSI data (m x n x p)\n% q - Number of endmembers to find\n% Smin - minimum kernel size (Smin x Smin)\n% Smax - maximum kernel size (Smax x Smax)\n% Imax - maximum iterations\n% Outputs\n% U - Recovered endmembers (p x q)\n% \n% References\n% Plaza, Antonio, et al. \"Spatial/spectral endmember extraction \n% by multidimensional morphological operations.\" Geoscience and \n% Remote Sensing, IEEE Transactions on 40.9 (2002): 2025-2041.\n\n% Error trapping\nif nargin < 3 || nargin > 5\n help hyperAmee\n error('Not enough input arguments. See function description.')\nelseif nargin == 3\n % i.e. Smax and Imax not given\n Smax = Smin;\n Imax = 1;\nelseif nargin == 4\n % i.e. if Imax not given\n if Smin <= Smax\n Imax = round((Smax-Smin)/2)+1;\n else\n help hyperAmee\n error('Smax cannot be less than Smin. See function description.')\n end\nelseif nargin == 5\n if Smin == Smax && Imax < 2\n help hyperAmee\n error('Cannot iterate more than once with these S limits.')\n elseif Imax > (Smax-Smin+1)\n Imax = round((Smax-Smin)/2)+1;\n end\nend\n\nif ndims(M) ~= 3\n error('Input image must be (m x n x p)');\nelse\n [h, w, p] = size(M);\nend\n\n\n% Build pixel vectors from M\npixVec = cell(h, w);\nfor hIter = 1:h\n for wIter = 1:w\n pixVec{hIter,wIter} = squeeze(M(hIter,wIter,:));\n end\nend\n\n% Morphological Eccentricity Index Score (MEI)\nMEI = zeros(h, w);\n\n% Kernel (structuring element)\nfor B = round(linspace(Smin, Smax, Imax));\n % Create non-overlapping arrays (to reduce computational load)\n hArray = 1:B:h; hArray(end) = h-B+1;\n wArray = 1:B:w; wArray(end) = w-B+1;\n\n % Move B though all pixels in M\n for wPixel = wArray;\n for hPixel = hArray;\n % (hPixel,wPixel) defines the top-left pixel of the current kernel\n ker = pixVec(hPixel:hPixel+B-1, wPixel:wPixel+B-1);\n [x, y, mei] = spatialSearch( ker );\n % global (x,y) from local (x,y)\n x = x+hPixel-1;\n y = y+wPixel-1;\n % set MEI value at max pixel location\n MEI(x, y) = mei;\n end\n end\nend\n\n% Find q largest MEI values\n[tmp,idx] = sort(MEI(:), 'descend');\ntop = idx(1:q)';\n\n% Return endmembers\nU = cell2mat(pixVec(top));\n\nend % hyperAmee function\n\n\nfunction [xMax, yMax, mei] = spatialSearch( ker )\n%function [xMax, yMax, mei] = spatialSearch( ker )\n% spatialSearch finds the max and min cumulative distances\n% between each pixel vector and its neighbors inside a kernel\n% of size (B x B) and computes the local MEI.\n\nif ~iscell(ker)\n error('ker is not a cell! See line 57 of hyperAmee.m')\nend\n\nB = size(ker,1);\n\ndist = zeros(B);\nfor i = 1:B;\n for j = 1:B;\n dist(i,j) = Dist(ker{i,j}, ker);\n end\nend\n\n% Morphological erosion to find minimum pixel vector in region B\n[tmp,rowIdx] = min(dist);\n[val,colIdx] = min(tmp);\nxMin = rowIdx(colIdx);\nyMin = colIdx;\n\n% Morphological dilation to find maximum pixel vector in region B\n[tmp,rowIdx] = max(dist);\n[val,colIdx] = max(tmp);\nxMax = rowIdx(colIdx);\nyMax = colIdx;\n\n% MEI computation\nmei = Dist(ker{xMin, yMin}, ker{xMax, yMax});\n\nend % spatialSearch function\n\n\n\nfunction dist = Dist(a, C)\n%function dist = Dist(a, C)\n% Cumulative distance measure between a pixel vector and its neighbor(s).\n% Plaza et al. used the Spectral Angle Mapper (SAM) measure.\n% \n% Inputs\n% a - pixel vector of interest (p x 1)\n% C - all pixels in neighborhood (or a single pixel vector)\n% Outpus\n% dist - (cumulative) SAM distance\n\nif ~iscell(C)\n dist = acos(dot(a,C)/(norm(a)*norm(C)));\nelse\n dist = 0;\n for k = 1:numel(C);\n dist = dist + acos(dot(a,C{k})/(norm(a)*norm(C{k})));\n end\nend\n\nend % Dist function\n\n\n\n", "meta": {"author": "davidkun", "repo": "HyperSpectralToolbox", "sha": "147d58e6efe839e8945dc0d4e8d65029884137f1", "save_path": "github-repos/MATLAB/davidkun-HyperSpectralToolbox", "path": "github-repos/MATLAB/davidkun-HyperSpectralToolbox/HyperSpectralToolbox-147d58e6efe839e8945dc0d4e8d65029884137f1/newFunctions/hyperAmee.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.49572126303010605}} {"text": "function [U,output] = cpd_rnd(size_tens,R,options)\n%CPD_RND Pseudorandom initialization for CPD.\n% U = cpd_rnd(size_tens,R) generates pseudorandom factor matrices U{1},\n% ..., U{N} of dimensions size_tens(n)-by-R that can be used to\n% initialize algorithms that compute the CPD of an N-th order tensor.\n%\n% cpd_rnd(T,R) is shorthand for cpd_rnd(size(T),R) if T is real. If T is\n% complex, then U{n} will be generated as complex matrices by default\n% (cf. options).\n%\n% cpd_rnd(size_tens,R,options) and cpd_rnd(T,R,options) may be used to\n% set the following options:\n%\n% options.Real = - The type of random number generator used to\n% [{@randn}|@rand|0] generate the real part of each factor\n% matrix. If 0, there is no real part.\n% options.Imag = - The type of random number generator used to\n% [@randn|@rand|0|... generate the imaginary part of each factor\n% {'auto'}] matrix. If 0, there is no imaginary part.\n% On 'auto', options.Imag is 0 unless the\n% first argument is a complex tensor T, in\n% which case it is equal to options.Real.\n% options.Orth = - If true, the generated factor matrices are\n% [true|false|{'auto'}] orthogonalized using a QR factorization.\n% On 'auto', options.Orth is false if the\n% first argument is a vector size_tens, and\n% true if the first argument is a tensor T.\n%\n% See also btd_rnd, lmlra_rnd, cpdgen.\n\n% Authors: Laurent Sorber (Laurent.Sorber@cs.kuleuven.be)\n% Marc Van Barel (Marc.VanBarel@cs.kuleuven.be)\n% Lieven De Lathauwer (Lieven.DeLathauwer@kuleuven-kulak.be)\n\n% Process input.\nisSizeVector = isnumeric(size_tens) && isvector(size_tens);\nif ~isSizeVector\n T = size_tens;\n if isstruct(T), size_tens = T.size;\n else size_tens = size(T); end\nend\nN = length(size_tens);\n\n% Check the options structure.\nisfunc = @(f)isa(f,'function_handle');\nif nargin < 3, options = struct; end\nif ~isfield(options,'Real'), options.Real = @randn; end\nif ~isfunc(options.Real), options.Real = @zeros; end\nif ~isfield(options,'Imag'), options.Imag = 'auto'; end\nif ischar(options.Imag) && strcmpi(options.Imag,'auto')\n if ~isSizeVector && ((isstruct(T) && ~isreal(T.val)) || ...\n (isnumeric(T) && ~isreal(T)))\n options.Imag = options.Real;\n else\n options.Imag = 0;\n end\nend\nif ~isfield(options,'Orth'), options.Orth = 'auto'; end\nif ischar(options.Orth) && strcmpi(options.Orth,'auto')\n\toptions.Orth = ~isSizeVector;\nend\n\n% Generate factor matrices.\nU = arrayfun(@(n)options.Real(size_tens(n),R),1:N,'UniformOutput',0);\nif isfunc(options.Imag)\n Ui = arrayfun(@(n)options.Imag(size_tens(n),R),1:N,'UniformOutput',0);\n U = cellfun(@(ur,ui)ur+ui*1i,U,Ui,'UniformOutput',0);\nend\nfor n = 1:N*options.Orth\n if size(U{n},1) >= size(U{n},2), [U{n},~] = qr(U{n},0);\n else [Q,~] = qr(U{n}.',0); U{n} = Q.'; end\nend\noutput = struct;\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/libs/+tensorlab/cpd_rnd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225279, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.495683904984271}} {"text": "%This Matlab script can be used to reproduce Figure 7.2 in the monograph:\n%\n%Emil Bjornson, Jakob Hoydis and Luca Sanguinetti (2017),\n%\"Massive MIMO Networks: Spectral, Energy, and Hardware Efficiency\",\n%Foundations and Trends in Signal Processing: Vol. 11, No. 3-4,\n%pp. 154-655. DOI: 10.1561/2000000093.\n%\n%For further information, visit: https://www.massivemimobook.com\n%\n%This is version 1.0 (Last edited: 2017-11-04)\n%\n%License: This code is licensed under the GPLv2 license. If you in any way\n%use this code for research that results in publications, please cite our\n%monograph as described above.\n%\n%Note: This script require additional software packages to be used, which\n%need to be downloaded and installed separately. These packages are\n%developed independently and are delivered with separate licenses.\n%\n%The downlink power allocation is optimized using CVX from CVX Research,\n%Inc. (http://cvxr.com/cvx/). This script has been tested with CVX 2.1,\n%using the solver Mosek, version 7.1.0.12. We discourage the use of the\n%solvers SDPT3 and SeDuMi since these crashed during the test.\n\n\n%Empty workspace and close figures\nclose all;\nclear;\n\n\n%Number of BSs\nL = 16;\n\n%Number of UEs per BS\nK = 10;\n\n%Number of BS antennas\nM = 100;\n\n%Define the pilot reuse factor\nf = 2;\n\n%Select the number of setups with random UE locations\nnbrOfSetups = 50;\n\n%Select the number of channel realizations per setup\nnbrOfRealizations = 500;\n\n\n%% Propagation parameters\n\n%Communication bandwidth\nB = 20e6;\n\n%Total uplink transmit power per UE (mW)\np = 100;\n\n%Total downlink transmit power per UE (mW)\nrho = 100;\n\n%Maximum downlink transmit power per BS (mW)\nPmax = K*rho;\n\n%Compute downlink power per UE in case of equal power allocation\nrhoEqual = (Pmax/K)*ones(K,L);\n\n%Define noise figure at BS (in dB)\nnoiseFigure = 7;\n\n%Compute noise power\nnoiseVariancedBm = -174 + 10*log10(B) + noiseFigure;\n\n%Select length of coherence block\ntau_c = 200;\n\n%Use the approximation of the Gaussian local scattering model\naccuracy = 2;\n\n%Angular standard deviation in the local scattering model (in degrees)\nASDdeg = 10;\n\n\n%Prepare to save simulation results\nSE_MR_equal = zeros(K,L,nbrOfSetups);\nSE_RZF_equal = zeros(K,L,nbrOfSetups);\nSE_MMMSE_equal = zeros(K,L,nbrOfSetups);\n\nSE_MR_maxmin = zeros(K,L,nbrOfSetups);\nSE_RZF_maxmin = zeros(K,L,nbrOfSetups);\nSE_MMMSE_maxmin = zeros(K,L,nbrOfSetups);\n\nSE_MR_maxprod = zeros(K,L,nbrOfSetups);\nSE_RZF_maxprod = zeros(K,L,nbrOfSetups);\nSE_MMMSE_maxprod = zeros(K,L,nbrOfSetups);\n\n\n%% Go through all setups\nfor n = 1:nbrOfSetups\n \n %Output simulation progress\n disp([num2str(n) ' setups out of ' num2str(nbrOfSetups)]);\n \n %Compute channel statistics for one setup\n [R,channelGaindB] = functionExampleSetup(L,K,M,accuracy,ASDdeg);\n \n %Compute the normalized average channel gain, where the normalization\n %is based on the noise power\n channelGainOverNoise = channelGaindB - noiseVariancedBm;\n \n \n %Generate channel realizations with estimates and estimation\n %error correlation matrices\n [Hhat,C,tau_p,~,H] = functionChannelEstimates(R,channelGainOverNoise,nbrOfRealizations,M,K,L,p,f);\n \n %Compute the signal and interference terms of the DL SEs using the\n %hardening bound in Theorem 4.6\n [signal_MR,interf_MR,signal_RZF,interf_RZF,signal_MMMSE,interf_MMMSE,prelogFactor] = functionComputeSINR_DL(H,Hhat,C,tau_c,tau_p,nbrOfRealizations,M,K,L,p);\n \n %Delete large matrices\n clear Hhat C H R;\n \n %Compute the SEs with equal power allocation\n SE_MR_equal(:,:,n) = functionComputeSE_DL_poweralloc(rhoEqual,signal_MR,interf_MR,prelogFactor);\n SE_RZF_equal(:,:,n) = functionComputeSE_DL_poweralloc(rhoEqual,signal_RZF,interf_RZF,prelogFactor);\n SE_MMMSE_equal(:,:,n) = functionComputeSE_DL_poweralloc(rhoEqual,signal_MMMSE,interf_MMMSE,prelogFactor);\n \n %Compute the SEs with max-min fairness power allocation\n disp('Solve max-min fairness problem'); %Output simulation progress\n SE_MR_maxmin(:,:,n) = functionPowerOptimization_maxmin(signal_MR,interf_MR,Pmax,prelogFactor);\n SE_RZF_maxmin(:,:,n) = functionPowerOptimization_maxmin(signal_RZF,interf_RZF,Pmax,prelogFactor);\n SE_MMMSE_maxmin(:,:,n) = functionPowerOptimization_maxmin(signal_MMMSE,interf_MMMSE,Pmax,prelogFactor);\n \n %Compute the SEs with max-min fairness power allocation\n disp('Solve max product SINR problem'); %Output simulation progress\n SE_MR_maxprod(:,:,n) = functionPowerOptimization_prodSINR(signal_MR,interf_MR,Pmax,prelogFactor);\n SE_RZF_maxprod(:,:,n) = functionPowerOptimization_prodSINR(signal_RZF,interf_RZF,Pmax,prelogFactor);\n SE_MMMSE_maxprod(:,:,n) = functionPowerOptimization_prodSINR(signal_MMMSE,interf_MMMSE,Pmax,prelogFactor);\n \nend\n\n\n%% Plot the simulation results\n\nfigure;\nhold on; box on;\n\nplot(sort(SE_MR_maxmin(:)),linspace(0,1,K*L*nbrOfSetups),'k--','LineWidth',1);\nplot(sort(SE_MR_equal(:)),linspace(0,1,K*L*nbrOfSetups),'k-','LineWidth',1);\nplot(sort(SE_MR_maxprod(:)),linspace(0,1,K*L*nbrOfSetups),'k-.','LineWidth',1);\n\nplot(sort(SE_RZF_equal(:)),linspace(0,1,K*L*nbrOfSetups),'b-','LineWidth',1);\nplot(sort(SE_MMMSE_equal(:)),linspace(0,1,K*L*nbrOfSetups),'r','LineWidth',1);\n\nplot(sort(SE_RZF_maxprod(:)),linspace(0,1,K*L*nbrOfSetups),'b-.','LineWidth',1);\nplot(sort(SE_MMMSE_maxprod(:)),linspace(0,1,K*L*nbrOfSetups),'r-.','LineWidth',1);\n\nplot(sort(SE_RZF_maxmin(:)),linspace(0,1,K*L*nbrOfSetups),'b--','LineWidth',1);\nplot(sort(SE_MMMSE_maxmin(:)),linspace(0,1,K*L*nbrOfSetups),'r--','LineWidth',1);\n\nlegend('Max-min fairness','Equal power','Max product SINR','Location','SouthEast');\n\nxlabel('SE per UE [bit/s/Hz]');\nylabel('CDF');\n", "meta": {"author": "emilbjornson", "repo": "massivemimobook", "sha": "4e429497dea72d52172972f3f686b34d1d047013", "save_path": "github-repos/MATLAB/emilbjornson-massivemimobook", "path": "github-repos/MATLAB/emilbjornson-massivemimobook/massivemimobook-4e429497dea72d52172972f3f686b34d1d047013/Code/section7_figure2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6723316860482762, "lm_q1q2_score": 0.4956147903643921}} {"text": "function coeffS = setGaussOrder(coeffS,derivativeOrder)\n% function coeffS = setOrder(coeffS,derivativeOrder)\n%\n% APA, 6/13/2018\n\nA1(1) = 1.3530;\nB1(1) = 1.8151;\ncoeffS.W1 = 0.6681;\ncoeffS.L1 = -1.3932;\nA2(1) = -0.3531;\nB2(1) = 0.0902;\ncoeffS.W2 = 2.0787;\ncoeffS.L2 = -1.3732;\n\nA1(2) = -0.6724;\nB1(2) = -3.4327;\nA2(2) = 0.6724;\nB2(2) = 0.6100;\n\nA1(3) = -1.3563;\nB1(3) = 5.2318;\nA2(3) = 0.3446;\nB2(3) = -2.2355;\n\n\nswitch derivativeOrder\n \n case 'zero'\n % Zero'th order (Gaussian)\n coeffS.across_scale_normalization = 1.0;\n \n coeffS = computeDcoeffs(coeffS);\n \n coeffS.A1 = A1(1);\n coeffS.B1 = B1(1);\n coeffS.A2 = A2(1);\n coeffS.B2 = B2(1);\n coeffS = computeNcoeffs(coeffS);\n coeffS.alpha0 = 2 * coeffS.SN / coeffS.SD - coeffS.N0;\n coeffS.N0 = coeffS.N0 * coeffS.across_scale_normalization / coeffS.alpha0;\n coeffS.N1 = coeffS.N1 * coeffS.across_scale_normalization / coeffS.alpha0;\n coeffS.N2 = coeffS.N2 * coeffS.across_scale_normalization / coeffS.alpha0;\n coeffS.N3 = coeffS.N3 * coeffS.across_scale_normalization / coeffS.alpha0;\n symmetric = true;\n coeffS = computeMcoeffs(coeffS,symmetric);\n \n \n case 'second'\n \n \n % Second order (Laplacian Of Gaussian)\n %coeffS.across_scale_normalization = coeffS.sigma^2;\n coeffS.across_scale_normalization = 1.0;\n \n coeffS = computeDcoeffs(coeffS);\n \n coeffS.A1 = A1(1);\n coeffS.B1 = B1(1);\n coeffS.A2 = A2(1);\n coeffS.B2 = B2(1);\n coeffS.N0 = 0;\n coeffS.N1 = 0;\n coeffS.N2 = 0;\n coeffS.N3 = 0;\n coeffS.SN = 0;\n coeffS.DN = 0;\n coeffS.EN = 0;\n coeffS = computeNcoeffs(coeffS);\n coeffS.N0_0 = coeffS.N0;\n coeffS.N1_0 = coeffS.N1;\n coeffS.N2_0 = coeffS.N2;\n coeffS.N3_0 = coeffS.N3;\n coeffS.SN0 = coeffS.SN;\n coeffS.DN0 = coeffS.DN;\n coeffS.EN0 = coeffS.EN;\n \n coeffS.A1 = A1(3);\n coeffS.B1 = B1(3);\n coeffS.A2 = A2(3);\n coeffS.B2 = B2(3);\n coeffS.N0 = 0;\n coeffS.N1 = 0;\n coeffS.N2 = 0;\n coeffS.N3 = 0;\n coeffS.SN = 0;\n coeffS.DN = 0;\n coeffS.EN = 0;\n coeffS = computeNcoeffs(coeffS);\n coeffS.N0_2 = coeffS.N0;\n coeffS.N1_2 = coeffS.N1;\n coeffS.N2_2 = coeffS.N2;\n coeffS.N3_2 = coeffS.N3;\n coeffS.SN2 = coeffS.SN;\n coeffS.DN2 = coeffS.DN;\n coeffS.EN2 = coeffS.EN;\n \n \n coeffS.beta = -( 2 * coeffS.SN2 - coeffS.SD * coeffS.N0_2 ) / ( 2 * coeffS.SN0 - coeffS.SD * coeffS.N0_0 );\n coeffS.N0 = coeffS.N0_2 + coeffS.beta * coeffS.N0_0;\n coeffS.N1 = coeffS.N1_2 + coeffS.beta * coeffS.N1_0;\n coeffS.N2 = coeffS.N2_2 + coeffS.beta * coeffS.N2_0;\n coeffS.N3 = coeffS.N3_2 + coeffS.beta * coeffS.N3_0;\n coeffS.SN = coeffS.SN2 + coeffS.beta * coeffS.SN0;\n coeffS.DN = coeffS.DN2 + coeffS.beta * coeffS.DN0;\n coeffS.EN = coeffS.EN2 + coeffS.beta * coeffS.EN0;\n \n coeffS.alpha2 = coeffS.EN * coeffS.SD * coeffS.SD - ...\n coeffS.ED * coeffS.SN * coeffS.SD - ...\n 2 * coeffS.DN * coeffS.DD * coeffS.SD + ...\n 2 * coeffS.DD * coeffS.DD * coeffS.SN;\n \n coeffS.alpha2 = coeffS.alpha2 / (coeffS.SD * coeffS.SD * coeffS.SD);\n \n coeffS.N0 = coeffS.N0 * coeffS.across_scale_normalization / coeffS.alpha2;\n coeffS.N1 = coeffS.N1 * coeffS.across_scale_normalization / coeffS.alpha2;\n coeffS.N2 = coeffS.N2 * coeffS.across_scale_normalization / coeffS.alpha2;\n coeffS.N3 = coeffS.N3 * coeffS.across_scale_normalization / coeffS.alpha2;\n \n symmetric = true;\n coeffS = computeMcoeffs(coeffS,symmetric);\n \nend\n\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/PlanMetrics/recursiveFilters/setGaussOrder.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49553457545519475}} {"text": "function x = cs_dmsol (A,b)\n%CS_DMSOL x=A\\b using the coarse Dulmage-Mendelsohn decomposition.\n% x = cs_dmsol(A,b) computes x=A\\b where A may be rectangular and/or\n% structurally rank deficient, and b is a full vector.\n%\n% Example:\n% Prob = UFget ('HB/arc130') ; A = Prob.A ; b = rand (size (A,1),1) ;\n% x = cs_dmsol (A,b) ; norm (A*x-b)\n%\n% See also CS_QRSOL, CS_LUSOL, CS_DMPERM, SPRANK, RANK.\n\n% Copyright 2006-2007, Timothy A. Davis.\n% http://www.cise.ufl.edu/research/sparse\n\n[m n] = size (A) ;\n[p q r s cc rr] = cs_dmperm (A) ;\nC = A (p,q) ;\nb = b (p) ;\nx = zeros (n,1) ;\nif (rr(3) <= m & cc(4) <= n) %#ok\n x (cc(4):n) = cs_qrsol (C (rr(3):m, cc(4):n), b (rr(3):m)) ;\n b (1:rr(3)-1) = b (1:rr(3)-1) - C (1:rr(3)-1, cc(4):n) * x (cc(4):n) ;\nend\nif (rr(2) < rr (3) & cc(3) < cc(4)) %#ok\n x (cc(3):cc(4)-1) = ...\n cs_lusol (C (rr(2):rr(3)-1, cc(3):cc(4)-1), b (rr(2):rr(3)-1)) ;\n b (1:rr(2)-1) = ...\n b (1:rr(2)-1) - C (1:rr(2)-1, cc(3):cc(4)-1) * x (cc(3):cc(4)-1) ;\nend\nif (rr(2) > 1 & cc(3) > 1) %#ok\n x (1:cc(3)-1) = cs_qrsol (C (1:rr(2)-1, 1:cc(3)-1), b (1:rr(2)-1)) ;\nend\nx (q) = x ;\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/CXSparse/MATLAB/CSparse/cs_dmsol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.6926419831347362, "lm_q1q2_score": 0.49553270362689317}} {"text": "function check = chi_square_noncentral_check ( a, b )\n\n%*****************************************************************************80\n%\n%% CHI_SQUARE_NONCENTRAL_CHECK checks the parameters of the noncentral Chi Squared PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer A, the parameter of the PDF.\n% 1.0 <= A.\n%\n% Input, real B, the noncentrality parameter of the PDF.\n% 0.0 <= B.\n%\n if ( a < 1.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CHI_SQUARE_NONCENTRAL_CHECK - Fatal error!\\n' );\n fprintf ( 1, ' A < 1.\\n' );\n check = 0;\n error ( 'CHI_SQUARE_NONCENTRAL_CHECK - Fatal error!' );\n end\n\n if ( b < 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CHI_SQUARE_NONCENTRAL_CHECK - Fatal error!\\n' );\n fprintf ( 1, ' B < 0.\\n' );\n check = 0;\n error ( 'CHI_SQUARE_NONCENTRAL_CHECK - Fatal error!' );\n end\n\n check = 1;\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/chi_square_noncentral_check.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.4955326913554616}} {"text": "function [img,nrg] = rayImage(ray,mic,rad,rMax)\n%+========================================================================+\n%| |\n%| OPENRAY - LIBRARY FOR TRI-DIMENSIONAL RAY TRACING |\n%| openRay is part of the GYPSILAB toolbox for Matlab |\n%| |\n%| COPYRIGHT : Matthieu Aussal (c) 2017-2018. |\n%| PROPERTY : Centre de Mathematiques Appliquees, Ecole polytechnique, |\n%| route de Saclay, 91128 Palaiseau, France. All rights reserved. |\n%| LICENCE : This program is free software, distributed in the hope that|\n%| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use, |\n%| redistribute and/or modify it under the terms of the GNU General Public|\n%| License, as published by the Free Software Foundation (version 3 or |\n%| later, http://www.gnu.org/licenses). For private use, dual licencing |\n%| is available, please contact us to activate a \"pay for remove\" option. |\n%| CONTACT : matthieu.aussal@polytechnique.edu |\n%| WEBSITE : www.cmap.polytechnique.fr/~aussal/gypsilab Ā Ā Ā Ā  |\n%| |\n%| Please acknowledge the gypsilab toolbox in programs or publications in |\n%| which you use it. |\n%|________________________________________________________________________|\n%| '&` | |\n%| # | FILE : rayImage.m |\n%| # | VERSION : 0.41 |\n%| _#_ | AUTHOR(S) : Matthieu Aussal |\n%| ( # ) | CREATION : 14.03.2017 |\n%| / 0 \\ | LAST MODIF : 01.04.2018 |\n%| ( === ) | SYNOPSIS : Image-sources from ray-tracing |\n%| `---' | |\n%+========================================================================+\n\n% Material properties (http://www.odeon.dk/material-manufactures)\nload('odeon.mat')\nmat = odeon.mat(ray.msh.col,:);\nNfrq = size(mat,2);\n\n% Air absorbing formulae for T = 20°C (bouquin Jouhaneau p 68-69)\nrhm = 30;\nair = 5.5 * (50/rhm) .* (odeon.frq/1000).^1.7 * 1e-4;\n\n% Measures\n[Isrc,src] = ray.measure(mic,rad,rMax);\n\n% Initialization\nimg = cell(size(src));\nnrg = cell(size(src));\nrfl = ones(length(ray),Nfrq);\n\n% Loop on images sources\nfor i = 1:length(src)\n % Unicity for images\n [~,Ia,Ic] = unique(round(src{i}*1e12),'rows','stable');\n \n % Image coordinates\n img{i} = src{i}(Ia,:) - ones(length(Ia),1)*mic;\n \n % Image Energy\n nrg{i} = zeros(length(Ia),Nfrq);\n for j = 1:Nfrq\n nrg{i}(:,j) = accumarray(Ic,rfl(Isrc{i},j),[length(Ia),1]); \n end\n \n % Update reflecting coeff\n ind = (ray.iel(:,i+1) > 0);\n rfl(ind,:) = rfl(ind,:) .* (1 - mat(ray.iel(ind,i+1),:)); \n rfl(~ind,:) = 0;\nend\n\n% Vectoriel format\nimg = cell2mat(img);\nnrg = cell2mat(nrg);\n\n% Atmosphere dissipation\ndst = sqrt(sum(img.^2,2));\nnrg = nrg .* exp(-dst*air);\n\n% Sort in phase\n[~,ind] = sort(dst);\nimg = img(ind,:);\nnrg = nrg(ind,:);\n\n% Normalisation\nnrg = nrg ./ max(max(nrg)); \nend\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/gypsilabModified/openRay/rayImage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.49551220569109716}} {"text": "function check = discrete_check ( a, b )\n\n%*****************************************************************************80\n%\n%% DISCRETE_CHECK checks the parameters of the Discrete CDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 October 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer A, the number of probabilities assigned.\n%\n% Input, real B(A), the relative probabilities of\n% outcomes 1 through A. Each entry must be nonnegative.\n%\n% Output, logical CHECK, is true if the parameters are legal.\n%\n for j = 1 : a\n if ( b(j) < 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'DISCRETE_CHECK - Fatal error!\\n' );\n fprintf ( 1, ' Negative probabilities not allowed.\\n' );\n check = 0;\n return\n end\n end\n\n b_sum = sum ( b(1:a) );\n\n if ( b_sum == 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'DISCRETE_CHECK - Fatal error!\\n' );\n fprintf ( 1, ' Total probablity is zero.\\n' );\n check = 0;\n return\n end\n\n check = 1;\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/discrete_check.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863698, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.4954607942137183}} {"text": "function p29_title ( )\n\n%*****************************************************************************80\n%\n%% P29_TITLE prints a title for problem 29.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 March 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% None\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'Problem 29\\n' );\n fprintf ( 1, ' Name: Genz #3 / Patterson #8, Corner Peak\\n' );\n fprintf ( 1, ' Region: 0 <= X(i) <= 1\\n' );\n fprintf ( 1, ' Integrand: F(X) = 1 / ( 1 + sum( C(i) * X(i) ) )^R\\n' );\n fprintf ( 1, ' Parameters:\\n' );\n fprintf ( 1, ' R, defaults to 0.3\\n' );\n fprintf ( 1, ' C(1:DIM_NUM) defaults to 1/DIM_NUM.\\n' );\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/quadrature_test/p29_title.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.49546079421371825}} {"text": "function [X,E,obj,err,iter] = lrtcR_tnn(M,omega,lambda,opts)\n\n% Solve the Noisy Low-Rank Tensor Completion (LRTC) problem by ADMM\n%\n% min_{X,E} ||X||_*+lambda*loss(E), s.t. P_Omega(X) + E = M.\n% loss(E) = ||E||_1 or 0.5*||E||_F^2\n%\n% ---------------------------------------------\n% Input:\n% M - d1*d2*d3 tensor\n% omega - index of the observed entries\n% lambda - >=0, parameter\n% opts - Structure value in Matlab. The fields are\n% opts.loss - 'l1' (default): loss(E) = ||E||_1 \n% 'l2': loss(E) = 0.5*||E||_F^2\n% opts.tol - termination tolerance\n% opts.max_iter - maximum number of iterations\n% opts.mu - stepsize for dual variable updating in ADMM\n% opts.max_mu - maximum stepsize\n% opts.rho - rho>=1, ratio used to increase mu\n% opts.DEBUG - 0 or 1\n%\n% Output:\n% X - d1*d2*d3 tensor\n% E - d1*d2*d3 tensor\n% obj - objective function value\n% err - residual\n% iter - number of iterations\n%\n% version 1.0 - 27/06/2016\n%\n% Written by Canyi Lu (canyilu@gmail.com)\n% \n\ntol = 1e-8; \nmax_iter = 500;\nrho = 1.1;\nmu = 1e-4;\nmax_mu = 1e10;\nDEBUG = 0;\nloss = 'l1';\n\nif ~exist('opts', 'var')\n opts = [];\nend \nif isfield(opts, 'loss'); loss = opts.loss; end\nif isfield(opts, 'max_iter'); max_iter = opts.max_iter; end\nif isfield(opts, 'rho'); rho = opts.rho; end\nif isfield(opts, 'mu'); mu = opts.mu; end\nif isfield(opts, 'max_mu'); max_mu = opts.max_mu; end\nif isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end\n\n\ndim = size(M);\nX = zeros(dim);\nZ = X;\nE = X;\nY1 = X;\nY2 = X;\nomegac = setdiff(1:prod(dim),omega);\n\niter = 0;\nfor iter = 1 : max_iter\n Xk = X;\n Zk = Z;\n Ek = E;\n % first super block {X,E}\n [X,tnnX] = prox_tnn(Z-Y2/mu,1/mu);\n temp = M-Y1/mu;\n temp(omega) = temp(omega)-Z(omega);\n if strcmp(loss,'l1')\n E = prox_l1(temp,lambda/mu);\n elseif strcmp(loss,'l2')\n E = temp*(mu/(lambda+mu));\n else\n error('not supported loss function');\n end\n \n % second super block {Z}\n Z(omega) = (-E(omega)+M(omega)-(Y1(omega)-Y2(omega))/mu+X(omega))/2;\n Z(omegac) = X(omegac)+Y2(omegac)/mu;\n \n dY1 = E-M;\n dY1(omega) = dY1(omega)+Z(omega);\n dY2 = X-Z; \n chgX = max(abs(Xk(:)-X(:)));\n chgE = max(abs(Ek(:)-E(:)));\n chgZ = max(abs(Zk(:)-Z(:)));\n chg = max([chgX chgE chgZ max(abs(dY1(:))) max(abs(dY2(:)))]);\n if DEBUG\n if iter == 1 || mod(iter, 10) == 0\n obj = tnnX+lambda*comp_loss(E,loss);\n err = sqrt(norm(dY1(:))^2+norm(dY2(:))^2);\n disp(['iter ' num2str(iter) ', mu=' num2str(mu) ...\n ', obj=' num2str(obj) ', err=' num2str(err)]); \n end\n end\n \n if chg < tol\n break;\n end \n Y1 = Y1 + mu*dY1;\n Y2 = Y2 + mu*dY2;\n mu = min(rho*mu,max_mu); \nend\nobj = tnnX+lambda*comp_loss(E,loss);\nerr = sqrt(norm(dY1(:))^2+norm(dY2(:))^2);", "meta": {"author": "canyilu", "repo": "LibADMM-toolbox", "sha": "fa9bc9458b8fbe22ac264c6008b26e7e41e70742", "save_path": "github-repos/MATLAB/canyilu-LibADMM-toolbox", "path": "github-repos/MATLAB/canyilu-LibADMM-toolbox/LibADMM-toolbox-fa9bc9458b8fbe22ac264c6008b26e7e41e70742/algorithms/lrtcR_tnn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.49546078711679165}} {"text": "function [ ap, kpvt, info ] = sspfa ( ap, n )\n\n%*****************************************************************************80\n%\n%% SSPFA factors a real symmetric matrix stored in packed form.\n%\n% Discussion:\n%\n% To solve A*X = B, follow SSPFA by SSPSL.\n%\n% To compute inverse(A)*C, follow SSPFA by SSPSL.\n%\n% To compute determinant(A), follow SSPFA by SSPDI.\n%\n% To compute inertia(A), follow SSPFA by SSPDI.\n%\n% To compute inverse(A), follow SSPFA by SSPDI.\n%\n% Packed storage:\n%\n% The following program segment will pack the upper triangle of a \n% symmetric matrix.\n%\n% k = 0\n% do j = 1, n\n% do i = 1, j\n% k = k + 1\n% ap(k) = a(i,j)\n% end\n% end\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 November 2006\n%\n% Author:\n%\n% 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 AP(N*(N+1)/2), the packed form of a\n% symmetric matrix A. The columns of the upper triangle are stored\n% sequentially in a one-dimensional array. \n%\n% Input, integer N, the order of the matrix.\n%\n% Output, real AP(N*(N+1)/2), a block diagonal matrix and the \n% multipliers which were used to obtain it stored in \n% packed form. The factorization can be written A = U*D*U' where U \n% is a product of permutation and unit upper triangular matrices, U' \n% is the transpose of U, and D is block diagonal with 1 by 1 and 2 \n% by 2 blocks.\n%\n% Output, integer KPVT(N), the pivot indices.\n%\n% Output, integer INFO, error flag.\n% 0, normal value.\n% K, if the K-th pivot block is singular. This is not an error \n% condition for this subroutine, but it does indicate that SSPSL or \n% SSPDI may divide by zero if called.\n%\n\n%\n% ALPHA is used in choosing pivot block size.\n%\n alpha = ( 1.0 + sqrt ( 17.0 ) ) / 8.0;\n\n info = 0;\n%\n% Main loop on K, which goes from N to 1.\n%\n k = n;\n ik = floor ( ( n * ( n - 1 ) ) / 2 );\n\n while ( 1 )\n%\n% Leave the loop if K = 0 or K = 1.\n%\n if ( k == 0 )\n break\n end\n\n if ( k == 1 )\n kpvt(1) = 1;\n if ( ap(1) == 0.0 )\n info = 1;\n end\n break\n end\n%\n% This section of code determines the kind of elimination to be performed. \n% When it is completed, KSTEP will be set to the size of the pivot block, \n% and SWAP will be set to .true. if an interchange is required.\n%\n km1 = k - 1;\n kk = ik + k;\n absakk = abs ( ap(kk) );\n%\n% Determine the largest off-diagonal element in column K.\n%\n imax = isamax ( k-1, ap(ik+1:ik+k-1), 1 );\n imk = ik + imax;\n colmax = abs ( ap(imk) );\n\n if ( alpha * colmax <= absakk )\n\n kstep = 1;\n swap = 0;\n%\n% Determine the largest off-diagonal element in row IMAX.\n%\n else\n\n rowmax = 0.0;\n imaxp1 = imax + 1;\n im = floor ( imax * ( imax - 1 ) ) / 2;\n imj = im + 2 * imax;\n\n for j = imaxp1 : k\n rowmax = max ( rowmax, abs ( ap(imj) ) );\n imj = imj + j;\n end\n\n if ( imax ~= 1 )\n jmax = isamax ( imax-1, ap(im+1:im+imax-1), 1 );\n jmim = jmax + im;\n rowmax = max ( rowmax, abs ( ap(jmim) ) );\n end\n\n imim = imax + im;\n\n if ( alpha * rowmax <= abs ( ap(imim) ) )\n kstep = 1;\n swap = 1;\n elseif ( alpha * colmax * ( colmax / rowmax ) <= absakk )\n kstep = 1;\n swap = 0;\n else\n kstep = 2;\n swap = ( imax ~= km1 );\n end\n\n end\n%\n% Column K is zero. Set INFO and iterate the loop.\n%\n if ( max ( absakk, colmax ) == 0.0 )\n\n kpvt(k) = k;\n info = k;\n\n else\n\n if ( kstep ~= 2 )\n%\n% 1 x 1 pivot block.\n%\n if ( swap )\n%\n% Perform an interchange.\n%\n temp(1:imax) = ap(im+1:im+imax);\n ap(im+1:im+imax) = ap(ik+1:ik+imax);\n ap(ik+1:ik+imax) = temp(1:imax);\n\n imj = ik + imax;\n\n for jj = imax : k\n j = k + imax - jj;\n jk = ik + j;\n t = ap(jk);\n ap(jk) = ap(imj);\n ap(imj) = t;\n imj = imj - ( j - 1 );\n end\n\n end\n%\n% Perform the elimination.\n%\n ij = ik - ( k - 1 );\n\n for jj = 1 : km1\n j = k - jj;\n jk = ik + j;\n mulk = -ap(jk) / ap(kk);\n t = mulk;\n ap(ij+1:ij+j) = saxpy ( j, t, ap(ik+1:ik+j), 1, ap(ij+1:ij+j), 1 );\n ijj = ij + j;\n ap(jk) = mulk;\n ij = ij - ( j - 1 );\n end\n%\n% Set the pivot array.\n%\n if ( swap ) then\n kpvt(k) = imax;\n else\n kpvt(k) = k;\n end\n\n else\n%\n% 2 x 2 pivot block.\n%\n km1k = ik + k - 1;\n ikm1 = ik - ( k - 1 );\n%\n% Perform an interchange.\n%\n if ( swap )\n\n temp(1:imax) = ap(im+1:im+imax);\n ap(im+1:im+imax) = ap(ikm1+1:ikm1+imax);\n ap(ikm1+1:ikm1+imax) = temp(1:imax);\n\n imj = ikm1 + imax;\n\n for jj = imax : km1\n j = km1 + imax - jj;\n jkm1 = ikm1 + j;\n t = ap(jkm1);\n ap(jkm1) = ap(imj);\n ap(imj) = t;\n imj = imj - ( j - 1 );\n end\n\n t = ap(km1k);\n ap(km1k) = ap(imk);\n ap(imk) = t;\n\n end\n%\n% Perform the elimination.\n%\n if ( k-2 ~= 0 )\n\n ak = ap(kk) / ap(km1k);\n km1km1 = ikm1 + k - 1;\n akm1 = ap(km1km1) / ap(km1k);\n denom = 1.0 - ak * akm1;\n ij = ik - ( k - 1 ) - ( k - 2 );\n\n for jj = 1 : k-2\n\n j = km1 - jj;\n jk = ik + j;\n bk = ap(jk) / ap(km1k);\n jkm1 = ikm1 + j;\n bkm1 = ap(jkm1) / ap(km1k);\n mulk = ( akm1 * bk - bkm1 ) / denom;\n mulkm1 = ( ak * bkm1 - bk ) / denom;\n t = mulk;\n ap(ij+1:ij+j) = saxpy ( j, t, ap(ik+1:ik+j), 1, ap(ij+1:ij+j), 1 );\n t = mulkm1;\n ap(ij+1:ij+j) = saxpy ( j, t, ap(ikm1+1:ikm1+j), 1, ap(ij+1:ij+j), 1 );\n ap(jk) = mulk;\n ap(jkm1) = mulkm1;\n ijj = ij + j;\n ij = ij - ( j - 1 );\n end\n\n end\n%\n% Set the pivot array.\n%\n if ( swap )\n kpvt(k) = -imax;\n else\n kpvt(k) = 1 - k;\n end\n\n kpvt(k-1) = kpvt(k);\n\n end\n\n end\n\n ik = ik - ( k - 1 );\n if ( kstep == 2 )\n ik = ik - ( k - 2 );\n end\n\n k = k - kstep;\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_s/sspfa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.4954534907164791}} {"text": "function [f,nodes] = evalSectionsEquispacedFFT(SO3F,varargin)\n% Evaluate an @SO3FunHarmonic on @ODFSections by using an equispaced grid \n% along the other 2 Euler angles\n% $$(\\alpha_a,\\beta_b,\\gamma_c) = (\\frac{2\\pi a}{H_1},\\frac{\\pi b}{H_2-1},\\gamma_c)$$\n% where $a=0,...,H_1-1$, $b=0,...,H_2-1$ and $c=0,...,S_{num}$.\n%\n% Therefore we transform the SO(3) Fourier series to an usual Fourier series\n% equivalent as in the function .\n% But we use an 2-variate equispaced FFT instead of the NFFT analogously to\n% \n%\n% Syntax\n% f = evalSectionsEquispacedFFT(SO3F)\n% f = evalSectionsEquispacedFFT(SO3F,'resolution',2.5*degree)\n% [f,nodes] = evalSectionsEquispacedFFT(SO3F,'resolution',[2*degree,2.5*degree])\n% f = evalSectionsEquispacedFFT(SO3F,oS)\n%\n% Input\n% SO3F - @SO3FunHarmonic\n% oS - @ODFSection (phi2,gamma,phi1)\n%\n% Options\n% 'resolution' - shape constant along Euler angles. (default = 2.5°)\n%\n% Output\n% nodes - @orientation\n% f - values at this grid points\n%\n% See also\n% SO3FunHarmonic/evalV2 SO3FunHarmonic/evalEquispacedFFT SO3FunHarmonic/eval\n\nN = SO3F.bandwidth;\n\nif isa(varargin{1},'ODFSections'), oS = varargin{1}; else, oS =[]; end\n[a_max,b_max,g_max] = fundamentalRegionEuler(SO3F.CS,SO3F.SS,varargin{:});\nif isempty(oS)\n gamma = mod((0:5)*g_max/6+pi/2,2*pi);\n shift = 1;\nelseif isa(oS,'gammaSections')\n gamma = oS.gamma;\n shift = 0;\nelseif isa(oS,'phi2Sections')\n gamma = mod(oS.phi2+pi/2,2*pi);\n shift = 1;\nelseif isa(oS,'phi1Sections')\n % phi1-sections are analogous to alpha sections. We transform SO3F(R(a,b,g))\n % to SO3F(R(g,b,a)).\n fhat = SO3F.fhat;\n for n=0:N\n ind = deg2dim(n)+1 : deg2dim(n+1);\n fhat(ind) = (-1).^((1:2*n+1)+(1:2*n+1).') .* reshape(fhat(ind),2*n+1,2*n+1).';\n end\n a_max = g_max;\n SO3F = SO3FunHarmonic(fhat,SO3F.SS,SO3F.CS);\n gamma = mod(oS.phi1-pi/2,2*pi);\n shift = -1;\nend\n\n\n\n% get grid size along 1st and 2nd Euler angles\nres = get_option(varargin,'resolution',2.5*degree);\nif length(res)==1\n res = [1,1]*res;\nend\n% [a_max,b_max,~] = fundamentalRegionEuler(SO3F.CS,SO3F.SS,varargin{:});\ns = ceil([a_max,b_max]./res);\nres = [a_max,b_max]./s;\nH = 2*pi./res;\nif any(s<=1)\n error('The resolution is to big.')\nend\n\n\nshiftGrid = get_option(varargin,'shiftGrid',[0,0]);\nif check_option(varargin,'shiftGrid')\n s = s-1;\nend\n\n\n\n% compute ghat\nif SO3F.isReal\n\n % compute ghat -> k x j x l\n % with k = -N:N\n % j = -N:N -> use ghat(k,-j,l) = (-1)^(k+l) * ghat(k,-j,l) (*)\n % l = 0:N -> use ghat(-k,-j,-l) = conj(ghat(k,j,l)) (**)\n % flags: 2^0 -> use L_2-normalized Wigner-D functions\n % 2^2 -> fhat are the fourier coefficients of a real valued function\n % 2^4 -> use right and left symmetry\n flags = 2^0+2^2+2^4;\n sym = [min(SO3F.SRight.multiplicityPerpZ,2),SO3F.SRight.multiplicityZ,...\n min(SO3F.SLeft.multiplicityPerpZ,2),SO3F.SLeft.multiplicityZ];\n ghat = representationbased_coefficient_transform(N,SO3F.fhat,flags,sym);\n ghat = permute(ghat,[3,2,1]);\n % correct ghat by i^(-k+l)\n z = - (0:N)'+ reshape(-N:N,1,1,[]) + shift * (0:N)';\n ghat = ghat.*(1i).^z;\n\n if check_option(varargin,'shiftGrid')\n ghat = ghat.*exp(-1i * (shiftGrid(1)*(0:N)' + shiftGrid(2)*(-N:N)) );\n end\n\nelse\n\n % compute ghat\n % flags: 2^0 -> use L_2-normalized Wigner-D functions\n % 2^4 -> use right and left symmetry\n flags = 2^0+2^4;\n sym = [min(SO3F.SRight.multiplicityPerpZ,2),SO3F.SRight.multiplicityZ,...\n min(SO3F.SLeft.multiplicityPerpZ,2),SO3F.SLeft.multiplicityZ];\n ghat = representationbased_coefficient_transform(N,SO3F.fhat,flags,sym);\n ghat = permute(ghat,[3,2,1]);\n % correct ghat by i^(-k+l)\n z = - (-N:N)' + reshape(-N:N,1,1,[]) + shift * (-N:N)';\n ghat = ghat.*(1i).^z;\n \n if check_option(varargin,'shiftGrid')\n ghat = ghat.*exp(-1i * (shiftGrid(1)*(-N:N)' + shiftGrid(2)*(-N:N)) );\n end\n\nend\n\n\n\n% use rotational symmetries around Z-axis to speed up (cut zeros in ghat)\nSRightZ = SO3F.SRight.multiplicityZ;\nSLeftZ = SO3F.SLeft.multiplicityZ;\nH(1) = H(1) / SLeftZ;\nif SLeftZ>1 || SRightZ>1\n if SO3F.isReal\n ind1 = (0:SLeftZ:N)+1;\n else\n ind1 = [-flip(SLeftZ:SLeftZ:N),(0:SLeftZ:N)] + (N+1);\n end\n ind3 = [-flip(SRightZ:SRightZ:N),(0:SRightZ:N)] + (N+1);\n ghat = ghat(ind1,:,ind3);\nend\n\n\n\n% For small H we go through a smaller FFT(H) several times. Hence we reduce \n% the size of the fourier coefficient matrix ghat by adding the coefficients \n% with same complex exponentials.\nsz = size(ghat,1,2);\nif any(H1\n if check_option(varargin,'shiftGrid')\n grid = combvec((0:s(1))*res(1)-shift*pi/2,(0:s(2))*res(2),gamma);\n grid = grid + [shiftGrid,0];\n else\n grid = combvec((0:s(1))*res(1)-shift*pi/2,(0:s(2))*res(2),gamma);\n end\n if isa(oS,'phi1Sections')\n grid = grid(:,[3,2,1]);\n grid = orientation.byEuler(grid,'nfft',SO3F.SS,SO3F.CS);\n else\n grid = orientation.byEuler(grid,'nfft',SO3F.CS,SO3F.SS);\n end\n nodes = reshape(grid,size(f));\nend\n\nend\n\n\n\n\n\nfunction v = combvec(v1,v2,v3)\n% This function does the same as the combvec() function from Digital \n% Processing Toolbox and additionaly transpose the output matrix.\n% It is a simple version for the special case of three input vectors.\n l1 = length(v1);\n l2 = length(v2);\n l3 = length(v3);\n\n V1 = repmat(v1.',l2*l3,1);\n V2 = repmat(v2,l1,l3);\n V3 = repmat(v3,l1*l2,1);\n\n v = [V1,V2(:),V3(:)];\nend", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/SO3Fun/@SO3FunHarmonic/evalSectionsEquispacedFFT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4954525502379851}} {"text": "function [dLdp] = spm_mci_adjoint_sun (Pr,M,U,Y)\n% Gradient of log joint from adjoint method (via Sundials)\n% FORMAT [dLdp] = spm_mci_adjoint_sun (Pr,M,U,Y)\n%\n% Pr Parameters (vectorised and in M.V subspace)\n% M Model structure\n% U Inputs [Nin x N]\n% Y Data\n% \n% dLdp Gradient [Np x 1]\n%\n% For M.adjlike=1, dLdp is gradient of log likelihood not log joint\n% (useful for debugging).\n%\n% For M.backint=1 (default), compute the integral underlying dLdp\n% *during* backwards integration of adjoint. For M.backint=0, this \n% integral is computed *after* adjoint (useful for debugging).\n%\n% B. Sengupta, K. Friston and W. Penny (2014) Efficient Gradient\n% Computation for Dynamical Models. Neuroimage,98, 521-527. \n%__________________________________________________________________________\n% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny and Biswa Sengupta\n% $Id: spm_mci_adjoint_sun.m 6697 2016-01-27 14:57:28Z spm $\n\ntry, backint=M.backint; catch, backint=1; end\ntry, adjlike=M.adjlike; catch, adjlike=0; end\n\n% Tolerances \ntol_scale = 1e-3;\nreltol = 1e-3;\nabstol = 1e-4;\n\n% Parameters in original space\nP = M.V*Pr+M.vpE;\n\n%tDur=[0 M.t(end)];\n%tDur=[M.t(1) M.t(end)];\n\nt0=0;\n%tf=M.T;\n%dt=M.t(2)-M.t(1);\n%t0=M.t(1)-dt;\ntf=M.T;\n\nif isempty(U)\n U=zeros(1,M.N);\nend\n\ndata.U=U;\ndata.P=P;\ndata.M=M;\ndata.Y=Y;\n\noptions = CVodeSetOptions('UserData', data,...\n 'RelTol',reltol, ...\n 'AbsTol',abstol, ...\n 'LinearSolver','Dense', ...\n 'JacobianFn',@djacfn);\n\nCVodeInit(@spm_mci_flow_sun, 'BDF', 'Newton', t0, M.x0, options);\n\nCVodeAdjInit(150, 'Hermite');\n\noptionsB = CVodeSetOptions('UserData',data,...\n 'MaxNumSteps',50000, ...\n 'RelTol',reltol,...\n 'AbsTol',abstol,...\n 'LinearSolver','Dense',...\n 'JacobianFn',@djacBfn);\n\nlambda_init=zeros(M.n,1);\niB = CVodeInitB(@rhsadjoint, 'BDF', ...\n 'Newton', tf, lambda_init, optionsB);\n\nif backint\n % Use CVODE to compute the integral underlying dLdp\n % *during* backwards integration of adjoint (backint=1)\n\n [status,t,y] = CVode(tf,'Normal');\n \n optionsQB = CVodeQuadSetOptions('ErrControl',true,...\n 'RelTol',reltol,...\n 'AbsTol',abstol);\n \n qB1 = zeros(M.Np,1);\n CVodeQuadInitB(iB, @paramgrad, qB1, optionsQB);\n \n % Backward integration of the adjoint equation\n % (yB is the adjoint vector)\n [status,t,yB,qB] = CVodeB(M.t(2),'Normal');\n %[status,t,yB,qB] = CVodeB(t0,'Normal');\n if status == -1\n error('Adjoint integration failed');\n end\n qB = -qB';\n dt = M.t(2)-M.t(1);\n dLdp = qB/dt;\nelse\n % Compute integral underlying dLdp *after* backwards\n % integration of adjoint\n \n ntout = 1000;\n dt = (tf-t0)/ntout;\n tt = linspace(t0+dt,tf,ntout-1);\n \n %[status,ttf,x] = CVode(M.t(2:end),'Normal');\n %[status,ttf,x] = CVode(tt,'Normal');\n %[status,ttf,x] = CVode(M.t(2:end),'Normal');\n [status,ttf,x] = CVode(M.t,'Normal');\n interp_x = (interp1q(ttf',x',M.t))';\n \n %tm(1) = tDur(2);\n %t = tDur(2);\n tm(1) = tf;\n t = tf;\n it = 1;\n % Integrate adjoint equation\n while t > M.t(2)\n %while t > t0+2*dt\n it = it+1;\n % The adjoint vector is yB\n %[status,t,yB] = CVodeB(tDur(1),'OneStep');\n [status,t,yB] = CVodeB(M.t(1),'OneStep');\n %[status,t,yB] = CVodeB(t0+2*dt,'OneStep');\n if status == -1\n error('Adjoint integration failed');\n end\n tm(it) = t;\n dldp(it,:) = feval(@paramgrad,t, interp_x, yB, data);\n end\n dldp_int=interp1(tm,dldp,M.t,'spline');\n dLdp=sum(dldp_int);\nend\nCVodeFree;\n\nif ~adjlike\n dlogpriordp = spm_mci_gprior_deriv (Pr,M);\n dLdp=dLdp+dlogpriordp;\nend\n\nend\n\n% -----------------------------------------------------------\nfunction [qBd, flag, new_data] = paramgrad(t, x, yB, data)\n% Np quadratures for parametric gradient\n% t time \n% x state\n% yB adjoint vector, lambda^T\n% data contains P,M,U,Y\n%\n% yBd dlambda^T/dt\n\nP = data.P;\nM = data.M;\nU = data.U;\n\n% If observation function becomes dependent on parameters\n% we'll need to update term1\nterm1 = 0;\n\n% Find nearest time point for which we have pre-computed input\nif isempty(U)\n ut=[];\nelse\n [tmp,ind]=min(abs(t-M.t));\n ut=U(:,ind);\nend\n\n% Evaluate parameter Jacobian\nif isfield(M,'dfdp')\n dfdp = feval(M.dfdp,x,ut,P,M);\nelse\n dfdp = spm_diff(M.f,x,ut,P,M,3);\nend\nterm2 = -yB'*dfdp;\nqBd = term1 + term2;\n\nflag = 0;\nnew_data = [];\n\nend\n\n% -----------------------------------------------------------\nfunction [yBd, flag, new_data] = rhsadjoint(t, x, yB, data)\n% Adjoint equation\n% FORMAT [yBd, flag, new_data] = rhsadjoint(t, x, yB, data)\n%\n% t time \n% x state\n% yB adjoint vector, lambda^T\n% data contains P,M,U,Y\n%\n% yBd dlambda^T/dt\n\nY = data.Y;\nM = data.M;\nU = data.U;\nP = data.P;\n\n% Interpolate data to required time point\nfor j=1:M.l,\n ydata(j)=interp1q(M.t,Y(:,j),t);\nend\n[y,L]=feval(M.g,x,U(:,1),P,M);\ne=ydata-y';\n\nterm1 = (djacfn(t,x,[],data))'*yB; % (f_y)^T \\lambda\n\n% When computing output sensitivities, assume dydx=L, ie not a\n% function of x. Generalise later\ndydx=L;\n\nterm2 = e*M.iCe*dydx;\nyBd = (-term1 + term2')';\n\nflag = 0;\nnew_data = [];\n\nend\n\n% -----------------------------------------------------------\nfunction [JB, flag, new_data] = djacBfn(t, y, yB, fyB, data)\n% Backward problem Jacobian function\n\nJ = djacfn(t,y,[],data);\nJB = -J';\n\nflag = 0;\nnew_data = [];\n\nend\n\n% -----------------------------------------------------------\nfunction [J, flag, new_data] = djacfn(t, y, fy, data)\n% State Jacobian at time t\n\nP=data.P;\nM=data.M;\nU=data.U;\n\n% Find nearest time point for which we have pre-computed input\nif isempty(U)\n ut=[];\nelse\n [tmp,ind]=min(abs(t-M.t));\n ut=U(:,ind);\nend\n\n% Evaluate state Jacobian\nif isfield(M,'dfdx')\n J = feval(M.dfdx,y,ut,P,M);\nelse\n J = spm_diff(M.f,y,ut,P,M,1);\nend\n\nflag = 0;\nnew_data = [];\n\nend\n\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/mci/gradients/spm_mci_adjoint_sun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6187804337438502, "lm_q1q2_score": 0.49545254435216646}} {"text": "function [y] = local2globalVel2(V, lon,lat)\n\n% SYNTAX:\n% [y] = local2globalVel2(V, X);\n%\n% INPUT:\n% V = local position vector(s)\n% lon = longitude of orifin vector in radians\n% lat = latirude of orifin vector in radians\n%\n% OUTPUT:\n% y = global position vector(s)\n%\n% DESCRIPTION:\n% Rototation from local-level reference frame to Earth-fixed reference frame\n\n%--- * --. --- --. .--. ... * ---------------------------------------------\n% ___ ___ ___\n% __ _ ___ / __| _ | __|\n% / _` / _ \\ (_ | _|__ \\\n% \\__, \\___/\\___|_| |___/\n% |___/ v 1.0RC1\n%\n%--------------------------------------------------------------------------\n% Copyright (C) 2021 Geomatics Research & Development srl (GReD)\n% Written by:\n% Contributors: ...\n% A list of all the historical goGPS contributors is in CREDITS.nfo\n%--------------------------------------------------------------------------\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n%--------------------------------------------------------------------------\n% 01100111 01101111 01000111 01010000 01010011\n%--------------------------------------------------------------------------\n\n%initialize new position vector\ny = zeros(size(V));\n\nfor i = 1 : size(V,2)\n %rotation matrix from global to local reference system\n R = [-sin(lon) cos(lon) 0;\n -sin(lat)*cos(lon) -sin(lat)*sin(lon) cos(lat);\n +cos(lat)*cos(lon) +cos(lat)*sin(lon) sin(lat)];\n\n %rototraslation\n y(:,i) = R\\V(:,i);\nend\n", "meta": {"author": "goGPS-Project", "repo": "goGPS_MATLAB", "sha": "30644df61d2459e3347ac5f3e31b71d9f69f4b01", "save_path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB", "path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB/goGPS_MATLAB-30644df61d2459e3347ac5f3e31b71d9f69f4b01/source/utility/local2globalVel2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4953091177680388}} {"text": "function [ xnew, ynew, w ] = quaequad0 ( mmax, kk )\n\n%*****************************************************************************80\n%\n%% QUAEQUAD0 returns the requested quadrature rule.\n%\n% Licensing:\n%\n% This code is distributed under the GNU GPL license.\n%\n% Modified:\n%\n% 28 June 2014\n%\n% Author:\n%\n% Original FORTRAN77 version by Hong Xiao, Zydrunas Gimbutas.\n% This MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Hong Xiao, Zydrunas Gimbutas,\n% A numerical algorithm for the construction of efficient quadrature\n% rules in two and higher dimensions,\n% Computers and Mathematics with Applications,\n% Volume 59, 2010, pages 663-676.\n%\n% Parameters:\n%\n% Input, integer MMAX, the degree of the quadrature (the \n% maximum degree of the polynomials of two variables that are integrated\n% exactly. 1 <= MMAX <= 50.\n%\n% Input, integer KK, the number of points in the compressed rule.\n%\n% Output, real XNEW(KK), YNEW(KK), the\n% coordinates of the nodes.\n%\n% Output, real W(Kk), the weights.\n%\n\n%\n% Copy the arrays defining the compressed rule.\n%\n if ( mmax == 1 )\n [ xnew, ynew, w ] = rule01 ( );\n elseif ( mmax == 2 )\n [ xnew, ynew, w ] = rule02 ( );\n elseif ( mmax == 3 )\n [ xnew, ynew, w ] = rule03 ( );\n elseif ( mmax == 4 )\n [ xnew, ynew, w ] = rule04 ( );\n elseif ( mmax == 5 )\n [ xnew, ynew, w ] = rule05 ( );\n elseif ( mmax == 6 )\n [ xnew, ynew, w ] = rule06 ( );\n elseif ( mmax == 7 )\n [ xnew, ynew, w ] = rule07 ( );\n elseif ( mmax == 8 )\n [ xnew, ynew, w ] = rule08 ( );\n elseif ( mmax == 9 )\n [ xnew, ynew, w ] = rule09 ( );\n elseif ( mmax == 10 )\n [ xnew, ynew, w ] = rule10 ( );\n elseif ( mmax == 11 )\n [ xnew, ynew, w ] = rule11 ( );\n elseif ( mmax == 12 )\n [ xnew, ynew, w ] = rule12 ( );\n elseif ( mmax == 13 )\n [ xnew, ynew, w ] = rule13 ( );\n elseif ( mmax == 14 )\n [ xnew, ynew, w ] = rule14 ( );\n elseif ( mmax == 15 )\n [ xnew, ynew, w ] = rule15 ( );\n elseif ( mmax == 16 )\n [ xnew, ynew, w ] = rule16 ( );\n elseif ( mmax == 17 )\n [ xnew, ynew, w ] = rule17 ( );\n elseif ( mmax == 18 )\n [ xnew, ynew, w ] = rule18 ( );\n elseif ( mmax == 19 )\n [ xnew, ynew, w ] = rule19 ( );\n elseif ( mmax == 20 )\n [ xnew, ynew, w ] = rule20 ( );\n elseif ( mmax == 21 )\n [ xnew, ynew, w ] = rule21 ( );\n elseif ( mmax == 22 )\n [ xnew, ynew, w ] = rule22 ( );\n elseif ( mmax == 23 )\n [ xnew, ynew, w ] = rule23 ( );\n elseif ( mmax == 24 )\n [ xnew, ynew, w ] = rule24 ( );\n elseif ( mmax == 25 )\n [ xnew, ynew, w ] = rule25 ( );\n elseif ( mmax == 26 )\n [ xnew, ynew, w ] = rule26 ( );\n elseif ( mmax == 27 )\n [ xnew, ynew, w ] = rule27 ( );\n elseif ( mmax == 28 )\n [ xnew, ynew, w ] = rule28 ( );\n elseif ( mmax == 29 )\n [ xnew, ynew, w ] = rule29 ( );\n elseif ( mmax == 30 )\n [ xnew, ynew, w ] = rule30 ( );\n elseif ( mmax == 31 )\n [ xnew, ynew, w ] = rule31 ( );\n elseif ( mmax == 32 )\n [ xnew, ynew, w ] = rule32 ( );\n elseif ( mmax == 33 )\n [ xnew, ynew, w ] = rule33 ( );\n elseif ( mmax == 34 )\n [ xnew, ynew, w ] = rule34 ( );\n elseif ( mmax == 35 )\n [ xnew, ynew, w ] = rule35 ( );\n elseif ( mmax == 36 )\n [ xnew, ynew, w ] = rule36 ( );\n elseif ( mmax == 37 )\n [ xnew, ynew, w ] = rule37 ( );\n elseif ( mmax == 38 )\n [ xnew, ynew, w ] = rule38 ( );\n elseif ( mmax == 39 )\n [ xnew, ynew, w ] = rule39 ( );\n elseif ( mmax == 40 )\n [ xnew, ynew, w ] = rule40 ( );\n elseif ( mmax == 41 )\n [ xnew, ynew, w ] = rule41 ( );\n elseif ( mmax == 42 )\n [ xnew, ynew, w ] = rule42 ( );\n elseif ( mmax == 43 )\n [ xnew, ynew, w ] = rule43 ( );\n elseif ( mmax == 44 )\n [ xnew, ynew, w ] = rule44 ( );\n elseif ( mmax == 45 )\n [ xnew, ynew, w ] = rule45 ( );\n elseif ( mmax == 46 )\n [ xnew, ynew, w ] = rule46 ( );\n elseif ( mmax == 47 )\n [ xnew, ynew, w ] = rule47 ( );\n elseif ( mmax == 48 )\n [ xnew, ynew, w ] = rule48 ( );\n elseif ( mmax == 49 )\n [ xnew, ynew, w ] = rule49 ( );\n elseif ( mmax == 50 )\n [ xnew, ynew, w ] = rule50 ( );\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'QUAEQUAD0 - Fatal error!\\n' );\n fprintf ( 1, ' Illegal input value of MMAX.\\n' );\n fprintf ( 1, ' 1 <= MMAX <= 50 required.\\n' );\n error ( 'QUAEQUAD0 - Fatal error!' );\n end\n\n for i = 1 : kk\n%\n% The lower-left 1/6.\n%\n iitype = 2;\n nbool2 = quaeinside ( iitype, xnew(i), ynew(i) );\n%\n% The lower 1/3.\n%\n iitype = 1;\n nbool1 = quaeinside ( iitype, xnew(i), ynew(i) );\n%\n% The whole triangle.\n%\n iitype = 0;\n nbool0 = quaeinside ( iitype, xnew(i), ynew(i) );\n\n if ( nbool2 == 1 )\n\n elseif ( nbool1 == 1 )\n xnew(i) = -xnew(i);\n ynew(i) = ynew(i);\n elseif ( nbool0 == 1 )\n x0 = xnew(i);\n y0 = ynew(i);\n [ x1, y1 ] = quaerotate ( x0, y0 );\n xnew(i) = x1;\n ynew(i) = y1;\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'QUAEQUAD0 - Fatal error!\\n' );\n fprintf ( 1, ' Point does not lie inside triangle.\\n' );\n error ( 'QUAEQUAD0 - Fatal error!' );\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/triangle_symq_rule/quaequad0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540518, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4952648148628389}} {"text": "function K = simwhiteXsimwhiteKernCompute(simKern1, simKern2, t1, t2)\n\n% SIMWHITEXSIMWHITEKERNCOMPUTE Compute a cross kernel between two SIM-WHITE\n% kernels.\n% FORMAT\n% DESC computes cross kernel terms between two SIM-WHITE kernels for\n% the multiple output kernel.\n% ARG simKern1 : the kernel structure associated with the first SIM-WHITE\n% kernel.\n% ARG simKern2 : the kernel structure associated with the second SIM-WHITE\n% kernel.\n% ARG t1 : inputs for which kernel is to be computed.\n% RETURN K : block of values from kernel matrix.\n%\n% FORMAT\n% DESC computes cross kernel terms between two SIM-WHITE kernels for\n% the multiple output kernel. \n% ARG simKern1 : the kernel structure associated with the first SIM-WHITE\n% kernel.\n% ARG simKern2 : the kernel structure associated with the second SIM-WHITE\n% kernel.\n% ARG t1 : row inputs for which kernel is to be computed.\n% ARG t2 : column inputs for which kernel is to be computed.\n% RETURN K : block of values from kernel matrix.\n%\n% SEEALSO : multiKernParamInit, multiKernCompute, simwhiteKernParamInit\n%\n% COPYRIGHT : David Luengo, 2009\n\n% KERN\n\nif nargin < 4\n t2 = t1;\nend\nif size(t1, 2) > 1 | size(t2, 2) > 1\n error('Input can only have one column');\nend\nif simKern1.variance ~= simKern2.variance\n error('Kernels cannot be cross combined if they have different variances.')\nend\n\n% Parameters of the kernels required in the computation\nvariance = simKern1.variance;\nsensitivity1 = simKern1.sensitivity;\nsensitivity2 = simKern2.sensitivity;\ndecay1 = simKern1.decay;\ndecay2 = simKern2.decay;\n\nisStationary = (simKern1.isStationary == true) & (simKern2.isStationary == true);\n\n% Auxiliary constants and matrices\nc = variance * sensitivity1 * sensitivity2 / (decay1 + decay2);\nT1 = repmat(t1, 1, size(t2, 1));\nT2 = repmat(t2.', size(t1, 1), 1);\nind = (T1 < T2);\nDv = decay2 .* ind + decay1 .* (~ind);\nK = exp(-Dv .* abs(T1-T2));\nif (isStationary == false)\n K = K - exp(-(decay1 * T1 + decay2 * T2));\nend\nK = c*K;\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/simwhiteXsimwhiteKernCompute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.49516396004274227}} {"text": "function [au] = m2au(m)\n% Convert length from meters to astronomical units. \n% Chad A. Greene 2012\nau = m*6.684587122671e-12;", "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/m2au.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.4951639374009059}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Copyright (C) 2010, John T. Ramshur, jramshur@gmail.com\n% \n% This file is part of HRVAS\n%\n% HRVAS 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% HRVAS 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 HRVAS. If not, see .\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction output=poincareHRV(ibi)\n%poincareHRV(ibi) - calculates poincare HRV\n%\n%Inputs: ibi = 2dim array containing [t (s),ibi (s)]\n% \n%Outputs: output is a structure containg HRV.\n\n\n %check inputs\n ibi(:,2)=ibi(:,2).*1000; %convert ibi to ms\n %assumes ibi units are seconds\n \n% if abs(range(ibi(:,2)))<50 %assume ibi units are seconds \n% ibi(:,2)=ibi(:,2).*1000; %convert ibi to ms\n% end\n% if abs(range(diff(ibi(:,1))))>50 %assume time unites are ms\n% ibi(:,1)=ibi(:,1)./1000; %convert time to s\n% end\n\n sd=diff(ibi(:,2)); %successive differences\n rr=ibi(:,2);\n SD1=sqrt( 0.5*std(sd)^2 );\n SD2=sqrt( 2*(std(rr)^2) - (0.5*std(sd)^2) );\n \n %format decimal places\n output.SD1=round(SD1*10)/10; %ms\n output.SD2=round(SD2*10)/10; %ms\n\nend", "meta": {"author": "jramshur", "repo": "HRVAS", "sha": "ffe2465a0b8f8bf21bc78db474e5da4890761a44", "save_path": "github-repos/MATLAB/jramshur-HRVAS", "path": "github-repos/MATLAB/jramshur-HRVAS/HRVAS-ffe2465a0b8f8bf21bc78db474e5da4890761a44/poincareHRV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4951596751866843}} {"text": "function [v1,v2,v3]=vehicle()\n\n% [v1,v2,v3]=vehicle;\n% creates 3 different vehicle configurations, which vary one \n% from another only by the distance between prow and wings.\n\n% -----------------------------------------------------------------------\n% configuration # 1\n\n% phisical world variables\nv1.g_e=[0; 0; 9.81];\t% Gravitational acceleration\nv1.rho=1033;\t\t\t% Marine water density\n\n% mass\nv1.m=1444.0;\t\t\t% mass (kg)\n\n\n% Rigid body mass matrix [Kg Kg*m; Kg*m Kg*m^2]\n\nv1.Mrb=[\t1444\t0\t0\t0\t252.7\t0\t;\n\t\t\t0\t1444\t0\t-252.7\t0\t-2527\t;\n\t\t\t0\t0\t1444\t0\t2527\t0\t;\n\t\t\t0\t-252.7\t0\t142.8\t0\t0\t;\n\t\t\t252.7\t0\t2527\t0\t2796\t0\t;\n\t\t\t0\t-2527\t0\t0\t0\t2778\t];\n\n\n% Added mass matrix [Kg Kg*m; Kg*m Kg*m^2]\n\nv1.Ma=[\t55.7\t0\t0\t0\t0\t0\t;\n\t\t\t0\t1460\t0\t0\t0\t-102\t;\n\t\t\t0\t0\t1460\t0\t102\t0\t;\n\t\t\t0\t0\t0\t83.4\t0\t0\t;\n\t\t\t0\t0\t102\t0\t3401\t0\t;\n\t\t\t0\t-102\t0\t0\t0\t3401\t];\n\n\n% inverse total mass matrix \nv1.iM=inv(v1.Mrb+v1.Ma);\n\n% geometric variables\n\nv1.l=3.5;\t\t\t% Fuselage length (m)\nv1.d=0.7;\t\t\t% Fuselage diameter (m)\nv1.vol=1.39787;\t\t% Fuselage volume (m^3)\n\n\n% vectors\n\nv1.P_b=[0; 0; 0];\t\t% Pole wrt B (m)\nv1.G_b=[-1.75; 0; 0.175];\t% Center of mass wrt B (m)\nv1.B_b=[-1.75; 0; 0];\t% Center of buoyancy wrt B (m)\n\n\n% wings\n\nv1.sw=0.2;\t\t\t% Wing surface (m^2)\nv1.cw=0.4;\t\t\t% Wing width (m)\nv1.bw=0.5;\t\t\t% Wing length (m)\n\n% Position of wings wrt B along x (m) in config 1\nlw=-1.65;\n\n% distance of wing middle point from prow and from axis in config 1\ndpfw = -lw +0.25*v1.cw;\ndafw = v1.d/2 +0.43*v1.bw;\n\n% wings middle point positions wrt B in config 1\nv1.P1_b = [-dpfw; dafw; 0];\nv1.P2_b = [-dpfw; 0; dafw];\nv1.P3_b = [-dpfw;-dafw; 0]; \nv1.P4_b = [-dpfw; 0;-dafw];\n\n\n% tails\n\nv1.st=0.2;\t\t\t% Tail surface (m^2)\nv1.ct=0.4;\t\t\t% Tail width (m)\nv1.bt=0.5;\t\t\t% Tail length (m)\n\nlt=-3.1;\t\t\t\t% Position of tails along x wrt B (m)\n\n% distance of tail middle point from prow and from axis\ndpft = -lt +0.25*v1.ct;\ndaft = v1.d/2 +0.43*v1.bt;\n\n% tails middle point positions wrt B\nv1.P5_b = [-dpft; daft; 0];\nv1.P6_b = [-dpft; 0; daft];\nv1.P7_b = [-dpft;-daft; 0]; \nv1.P8_b = [-dpft; 0;-daft];\n\n\n% -----------------------------------------------------------------------\n% configuration # 2\n\nv2=v1;\n\n% Position of wings wrt B along x (m) in config 2\nlw=-1.15;\n\n% distance of wing middle point from prow and from axis in config 2\ndpfw = -lw +0.25*v2.cw;\ndafw = v2.d/2 +0.43*v2.bw;\n\n% wings middle point positions wrt B in config 2\nv2.P1_b = [-dpfw; dafw; 0];\nv2.P2_b = [-dpfw; 0; dafw];\nv2.P3_b = [-dpfw;-dafw; 0];\nv2.P4_b = [-dpfw; 0;-dafw];\n\n% -----------------------------------------------------------------------\n% configuration # 3\n\nv3=v1;\n\n% Position of wings wrt B along x (m) in config 3\nlw=-0.35;\n\n% distance of wing middle point from prow and from axis in config 3\ndpfw = -lw +0.25*v3.cw;\ndafw = v3.d/2 +0.43*v3.bw;\n\n% wings middle point positions wrt B in config 2\nv3.P1_b = [-dpfw; dafw; 0];\nv3.P2_b = [-dpfw; 0; dafw];\nv3.P3_b = [-dpfw;-dafw; 0];\nv3.P4_b = [-dpfw; 0;-dafw];\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/1207-shark/vehicle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4949619055487271}} {"text": "%computes the key of the input audio (super simple variant)\n%>\n%> @param x: time domain sample data, dimension samples X channels\n%> @param f_s: sample rate of audio data\n%> @param afWindow: FFT window of length iBlockLength (default: hann), can be [] empty\n%> @param iBlockLength: internal block length (default: 4096 samples)\n%> @param iHopLength: internal hop length (default: 2048 samples)\n%>\n%> @retval cKey key string\n% ======================================================================\nfunction [cKey] = ComputeKey (x, f_s, afWindow, iBlockLength, iHopLength)\n\n % set default parameters if necessary\n if (nargin < 5)\n iHopLength = 2048;\n end\n if (nargin < 4)\n iBlockLength = 4096;\n end\n\n if (nargin < 3 || isempty(afWindow))\n afWindow = hann(iBlockLength, 'periodic');\n end\n\n % key names\n cMajor = char ('C Maj','C# Maj','D Maj','D# Maj','E Maj','F Maj',...\n 'F# Maj','G Maj','G# Maj','A Maj','A# Maj','B Maj');\n cMinor = char ('c min','c# min','d min','d# min','e min','f min',...\n 'f# min','g min','g# min','a min','a# min','b min');\n \n % template pitch chroma (Krumhansl major/minor)\n t_pc = [6.35 2.23 3.48 2.33 4.38 4.09 2.52 5.19 2.39 3.66 2.29 2.88\n 6.33 2.68 3.52 5.38 2.60 3.53 2.54 4.75 3.98 2.69 3.34 3.17];\n t_pc = diag(1 ./ sum(t_pc, 2)) * t_pc;\n \n % compute FFT window function\n if (length(afWindow) ~= iBlockLength)\n error('window length mismatch');\n end \n\n % extract audio pitch chroma\n [v_pc, t] = computeFeature(\"SpectralPitchChroma\", x, f_s, afWindow, iBlockLength, iHopLength);\n\n % average pitch chroma\n v_pc = mean(v_pc, 2);\n \n % compute manhattan distances for major and minor\n d = zeros(2,12);\n for (i = 0:11)\n d(:,i+1)= sum(abs(repmat(v_pc', 2, 1)-circshift(t_pc, [0 i])), 2);\n end\n [dist,iKeyIdx] = min(d,[],2);\n if (dist(1) < dist(2))\n cKey = deblank(cMajor(iKeyIdx(1), :));\n else\n cKey = deblank(cMinor(iKeyIdx(2), :));\n end \nend\n", "meta": {"author": "alexanderlerch", "repo": "ACA-Code", "sha": "85d7258d5fcee1ca52bac52f651d26b665717687", "save_path": "github-repos/MATLAB/alexanderlerch-ACA-Code", "path": "github-repos/MATLAB/alexanderlerch-ACA-Code/ACA-Code-85d7258d5fcee1ca52bac52f651d26b665717687/ComputeKey.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49483244050971187}} {"text": "clear all\nsyms a b c x\n % Rezolvarea primei ecuatii\nsol1=solve(a*x^2+b*x+c)\npretty(sol1)\n % Rezolvarea ecuatiei a doua\nsol2=solve('cos(2*x)+sin(x)=1')\n % Transformarea solutiei simbolice in numerica\nnumsol2=double(sol2)\n % Reprezentarea grafica a functiei pe intervalul dat\nezplot('cos(2*x)+sin(x)-1',[0, 2*pi])\nhold on\ngrid\n % Marcarea solutiilor obtinute pe grafic\nplot(numsol2,zeros(size(numsol2)),'rd')", "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/12/Ex_12_13.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.49474391258293576}} {"text": "function [nlZ,dnlZ,post,K_mat,Q] = gplite_core(hyp,gp,compute_nlZ,compute_nlZ_grad)\n%GPLITE_CORE Core kernel computations for lite GP regression.\n\n%% Initialize GP hyperparameters\n \n[N,D] = size(gp.X); % Number of training points and dimension\n\nNcov = gp.Ncov;\nNnoise = gp.Nnoise;\nNmean = gp.Nmean;\n\n% Output warping\noutwarp_flag = isfield(gp,'outwarpfun') && ~isempty(gp.outwarpfun);\nif outwarp_flag\n Noutwarp = gp.Noutwarp;\n hyp_outwarp = hyp(Ncov+Nnoise+Nmean+1:Ncov+Nnoise+Nmean+Noutwarp);\n if compute_nlZ_grad\n [y,dwarp_dt,dwarp_dtheta,d2warp_dthetadt] = gp.outwarpfun(hyp_outwarp,gp.y);\n else\n [y,dwarp_dt] = gp.outwarpfun(hyp_outwarp,gp.y);\n end\n if ~isempty(gp.s2)\n s2 = gp.s2 .* dwarp_dt.^2; % Warped noise\n else\n s2 = [];\n end\nelse\n y = gp.y;\n s2 = gp.s2;\nend\n\n% Evaluate observation noise on training inputs\nhyp_noise = hyp(Ncov+1:Ncov+Nnoise); % Get noise hyperparameters\nif compute_nlZ_grad\n [sn2,dsn2] = gplite_noisefun(hyp_noise,gp.X,gp.noisefun,gp.y,s2);\nelse\n sn2 = gplite_noisefun(hyp_noise,gp.X,gp.noisefun,gp.y,s2);\nend\nsn2_mult = 1; % Effective noise variance multiplier\n\n% Evaluate mean function on training inputs\nhyp_mean = hyp(Ncov+Nnoise+1:Ncov+Nnoise+Nmean); % Get mean function hyperparameters\nif compute_nlZ_grad\n [m,dm] = gplite_meanfun(hyp_mean,gp.X,gp.meanfun,[],gp.meanfun_extras);\nelse\n m = gplite_meanfun(hyp_mean,gp.X,gp.meanfun,[],gp.meanfun_extras);\nend\n\n%% Observed covariance matrix inversion\n\n% Compute kernel matrix K_mat\nif gp.covfun(1) == 1\n ell = exp(hyp(1:D));\n sf2 = exp(2*hyp(D+1));\n K_mat = sq_dist(bsxfun(@rdivide,gp.X',ell));\n K_mat = sf2 * exp(-K_mat/2);\nelse\n hyp_cov = hyp(1:Ncov); % Get covariance function hyperparameters\n if compute_nlZ_grad\n [K_mat,dK_mat] = gplite_covfun(hyp_cov,gp.X,gp.covfun,[]);\n else\n K_mat = gplite_covfun(hyp_cov,gp.X,gp.covfun,[]); \n end\nend\n\n% Use Cholesky representation of posterior for non-small noise\nLchol = min(sn2) >= 1e-6;\n\nif Lchol\n if isscalar(sn2)\n sn2div = sn2;\n sn2_mat = eye(N);\n else\n sn2div = min(sn2);\n sn2_mat = diag(sn2/sn2div);\n end\n \n for iter = 1:10\n [L,p] = chol(K_mat/(sn2div*sn2_mult)+sn2_mat);\n if p > 0; sn2_mult = sn2_mult*10; else; break; end\n end\n sl = sn2div*sn2_mult;\n if nargout > 2\n pL = L; % L = chol(eye(n)+sW*sW'.*K)\n end\nelse\n if isscalar(sn2)\n sn2_mat = sn2*eye(N);\n else\n sn2_mat = diag(sn2);\n end\n for iter = 1:10 % Cholesky decomposition until it works\n [L,p] = chol(K_mat+sn2_mult*sn2_mat);\n if p > 0; sn2_mult = sn2_mult*10; else; break; end\n end\n sl = 1;\n if nargout > 2\n pL = -L\\(L'\\eye(N)); % L = -inv(K+inv(sW^2))\n end\nend\n\nalpha = L\\(L'\\(y-m)) / sl; % alpha = inv(K_mat + diag(sn2)) * (y - m) I\n\n%% Integrated basis functions\n\nif gp.intmeanfun > 0 \n bb = gp.intmeanfun_mean(:);\n BB = gp.intmeanfun_var(:);\n \n H = gplite_intmeanfun(gp.X,gp.intmeanfun);\n plus_idx = (BB > 0); % Non-delta parameters\n betabar = zeros(1,size(H,1));\n if any(~plus_idx)\n T_plus = diag(1./BB(plus_idx)) + H(plus_idx,:)*(L\\(L'\\H(plus_idx,:)')/sl);\n T_chol = chol(T_plus);\n betabar(plus_idx) = T_chol \\ (T_chol' \\ (bb(plus_idx)./BB(plus_idx) + H(plus_idx,:)*alpha));\n betabar(~plus_idx) = bb(~plus_idx);\n else\n T_plus = diag(1./BB) + H*(L\\(L'\\H')/sl);\n T_chol = chol(T_plus);\n% betabar(:) = T_plus \\ (bb./BB + H*alpha);\n betabar(:) = T_chol \\ (T_chol' \\ (bb./BB + H*alpha));\n end\nend\n\n\n%% Negative log marginal likelihood computation\nnlZ = []; dnlZ = []; Q = [];\n\nif compute_nlZ\n Nhyp = size(hyp,1); \n \n if gp.intmeanfun > 0\n % Negative log marginal likelihood with integrated basis functions\n prec_idx = BB > 0 & isfinite(BB);\n inf_idx = isinf(BB);\n \n vagueall_flag = all(inf_idx); % Vague prior on *all* basis functions?\n vagueany_flag = any(inf_idx); % Some vague priors?\n precany_flag = any(prec_idx); % Some precise priors?\n \n % Compute first quadratic term\n nu = y-m - H'*bb;\n if vagueall_flag\n nlZ_1 = nu'*alpha/2;\n else\n if precany_flag\n HBH_prec = H(prec_idx,:)'*bsxfun(@times,BB(prec_idx),H(prec_idx,:));\n N_mat = L'*L*sl + HBH_prec;\n N_chol = chol(N_mat); \n % Ninv = N_mat\\eye(N);\n Ninv = N_chol\\(N_chol'\\eye(N));\n nlZ_1 = nu'*(Ninv*nu)/2;\n else\n nlZ_1 = nu'*(L\\(L'\\nu))/sl/2;\n end\n end\n \n % Compute second quadratic term (vague prior contribution)\n if vagueany_flag\n if ~precany_flag\n W = chol(H*(L\\(L'\\H'))/sl); \n % A = H'*((H*Kinv*H')\\H);\n A_mat = H'*(W\\(W'\\H));\n nlZ_v = -nu'*(L\\(L'\\(A_mat*(L\\(L'\\nu)))))/sl^2/2;\n else\n Hinf = H(inf_idx,:);\n W = chol(Hinf*Ninv*Hinf');\n % A = Hinf'*((Hinf*Ninv*Hinf')\\Hinf);\n A_mat = Hinf'*(W\\(W'\\Hinf));\n C = Ninv*A_mat*Ninv; \n nlZ_v = -nu'*C*nu/2;\n end\n else\n nlZ_v = 0;\n end\n \n % Compute determinants\n nldet = sum(log(diag(L))); % First component\n if precany_flag % Precise priors\n nldet = nldet + sum(log(BB(prec_idx)))/2;\n Tprec_idx = isfinite(BB(BB > 0));\n nldet = nldet + log(det(T_plus(Tprec_idx,Tprec_idx)))/2;\n end\n if vagueany_flag\n nldet = nldet + sum(log(diag(W)));\n end\n \n nlZ = nlZ_1 + nlZ_v + nldet + N*log(2*pi*sl)/2 - sum(inf_idx)*log(2*pi)/2; \n \n else\n % Compute negative log marginal likelihood\n nlZ = (y-m)'*alpha/2 + sum(log(diag(L))) + N*log(2*pi*sl)/2;\n end\n \n if outwarp_flag % Jacobian correction for output warping\n nlZ = nlZ - sum(log(abs(dwarp_dt)));\n end\n\n if compute_nlZ_grad\n % Compute gradient of negative log marginal likelihood\n\n dnlZ = zeros(Nhyp,1); % allocate space for derivatives\n \n if gp.intmeanfun > 0\n % Gradient with integrated basis functions\n Kinv = L\\(L'\\eye(N))/sl;\n if ~precany_flag; Ninv = Kinv; end\n chi = Ninv*nu;\n Q = Kinv - chi*chi';\n if vagueany_flag\n phi = Ninv*A_mat*chi;\n Q = Q - phi*phi' + 2*chi*phi';\n if ~precany_flag\n Q = Q - Kinv*A_mat*Kinv; \n else\n Q = Q - Ninv*A_mat*Ninv;\n end\n else\n phi = 0; \n end\n if precany_flag\n Q = Q - Kinv*H(prec_idx,:)'*(T_plus(Tprec_idx,Tprec_idx)\\(H(prec_idx,:)*Kinv));\n end \n else \n Q = L\\(L'\\eye(N))/sl - alpha*alpha';\n end\n \n if gp.covfun(1) == 1\n for i = 1:D % Grad of cov length scales\n K_temp = K_mat .* sq_dist(gp.X(:,i)'/ell(i));\n dnlZ(i) = sum(sum(Q.*K_temp))/2;\n end\n dnlZ(D+1) = sum(sum(Q.*(2*K_mat)))/2; % Grad of cov output scale\n else \n for i = 1:Ncov % Grad of cov hyperparameters\n dnlZ(i) = sum(sum(Q.*dK_mat(:,:,i)))/2;\n end\n end\n\n % Gradient of GP likelihood\n if isscalar(sn2)\n trQ = trace(Q);\n for i = 1:Nnoise; dnlZ(Ncov+i) = 0.5*sn2_mult*dsn2(i)*trQ; end\n else\n dgQ = diag(Q);\n for i = 1:Nnoise; dnlZ(Ncov+i) = 0.5*sn2_mult*sum(dsn2(:,i).*dgQ); end\n if outwarp_flag\n error('Input-dependent noise not supported with output warping yet.');\n end\n end\n\n % Gradient of mean function\n if Nmean > 0\n if gp.intmeanfun > 0\n % Mean function gradient with integrated basis functions\n dnlZ(Ncov+Nnoise+(1:Nmean)) = -dm'*(chi - phi); \n else\n dnlZ(Ncov+Nnoise+(1:Nmean)) = -dm'*alpha;\n end\n end\n \n % Gradient of output warping function\n if outwarp_flag && Noutwarp > 0\n if gp.intmeanfun > 0\n error('Integrated basis functions are not supported with output warping yet.');\n end\n for i = 1:Noutwarp\n dnlZ(Ncov+Nnoise+Nmean+i) = dwarp_dtheta(:,i)'*alpha ...\n - sum(d2warp_dthetadt(:,i)./dwarp_dt);\n end\n end\n\n end\nend\n\n%% Output posterior struct if requested\nif nargout > 2\n post.hyp = hyp;\n post.alpha = alpha;\n post.sW = ones(N,1)./sqrt(min(sn2)*sn2_mult); % sqrt of noise precision vector\n post.L = pL;\n post.sn2_mult = sn2_mult;\n post.Lchol = Lchol;\n if gp.intmeanfun > 0\n post.intmean.HKinv = H*(L\\(L'\\eye(N))/sl);\n % Inverse reduced T (only positive variances)\n post.intmean.Tplusinv = T_chol \\ (T_chol' \\eye(size(T_chol)));\n post.intmean.betabar = betabar;\n end\nend\n\n\nend", "meta": {"author": "acerbilab", "repo": "vbmc", "sha": "54ba2cdd6c11d2595b9613557da14573abbb7b92", "save_path": "github-repos/MATLAB/acerbilab-vbmc", "path": "github-repos/MATLAB/acerbilab-vbmc/vbmc-54ba2cdd6c11d2595b9613557da14573abbb7b92/gplite/private/gplite_core.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.4945674141335993}} {"text": "function song = sing(str, bpm)\n%SING A basic keyboard for MATLAB using CHEBFUNs.\n% S = SING('STR1 STR2 STR3 ...') creates a CHEBFUN F corresponding to the\n% musical notes in each of the STR which vaguely correspond to Helmholtz pitch\n% notation (http://en.wikipedia.org/wiki/Helmholtz_pitch_notation).\n%\n% S = SING('STR1 ...', BPM) alters the temp of the tune (in beats per minute).\n% The default value is 60bpm.\n%\n% For example, S = SING('A'), produces a function corresponding to the note\n% A, S = SING('B') produces a B, and so on.\n%\n% Basic chords are provided, for example S = SING('CEG') will produce a major\n% triad (http://en.wikipedia.org/wiki/Major_chord). The convention is for the\n% kth note to have 1/k times the amplitude of the first.\n%\n% Empty spaces correspond to pause of a sixteenth note (semiquaver), and\n% commas separate notes without a pause.\n%\n% If STR is in uppercase, it will last for a quarter note (crotchet), and\n% lower case notes for a sixteenth note (semiquaver).\n%\n% The SING keyboard has three octaves (in A to G). S = SING('C-') produces a\n% low C, S = SING('C') produces a middle C, and S = SING('C+') produces a\n% high C.\n%\n% Sharps are supported by using '#', but there is currently no notation for\n% flats.\n%\n% Examples:\n% 1. Ode to Joy:\n% S = SING('BG- BG- CA DB DB CA BG- AD- G-B G-B AD- BG- BG- AD- AD-');\n% 2. God Save The Queen\n% S = SING('CG CG DG BG CG DG EC EC FC EC DG CG DG CG BG CG',30);\n%\n% CHEBFUNs for these examples may be generated with SING(1) and SING(2),\n% respectively.\n%\n% See also SOUND, CHEBTUNE.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Set up basic frequencies.\ns0 = 2^(1/12);\nf0 = 440*pi;\nfp1 = 2*f0;\nfm1 = .5*f0;\n\n% Set tempo.\nif ( nargin < 2 )\n bpm = 60;\n t0 = 1/4;\nelse\n t0 = 60/bpm/4;\nend\n\nq = chebfun('x', [0 t0]); % Quarter note.\ns = chebfun('x', [0 t0/4]); % Sixteenth note.\n\n%% Middle\n\n% Quarter notes\nA = sin(f0*q);\nAs = sin(f0*s0*q);\nB = sin(f0*s0^2*q);\nC = sin(f0*s0^3*q);\nCs = sin(f0*s0^4*q);\nD = sin(f0*s0^5*q);\nDs = sin(f0*s0^6*q);\nE = sin(f0*s0^7*q);\nF = sin(f0*s0^8*q);\nFs = sin(f0*s0^9*q);\nG = sin(f0*s0^10*q);\nGs = sin(f0*s0^11*q);\n\n% Sixteenth notes\na = sin(f0*s);\nas = sin(f0*s0*s);\nb = sin(f0*s0^2*s);\nc = sin(f0*s0^3*s);\ncs = sin(f0*s0^4*s);\nd = sin(f0*s0^5*s);\nds = sin(f0*s0^6*s);\ne = sin(f0*s0^7*s);\nf = sin(f0*s0^8*s);\nfs = sin(f0*s0^9*s);\ng = sin(f0*s0^10*s);\ngs = sin(f0*s0^11*s);\n\n%% -\n\n% Quarter notes\nAm = sin(fm1*q);\nAms = sin(fm1*s0*q);\nBm = sin(fm1*s0^2*q);\nCm = sin(fm1*s0^3*q);\nCms = sin(fm1*s0^4*q);\nDm = sin(fm1*s0^5*q);\nDms = sin(fm1*s0^6*q);\nEm = sin(fm1*s0^7*q);\nFm = sin(fm1*s0^8*q);\nFms = sin(fm1*s0^9*q);\nGm = sin(fm1*s0^10*q);\nGms = sin(fm1*s0^11*q);\n\n% Sixteenth notes\nam = sin(fm1*s);\nams = sin(fm1*s0*s);\nbm = sin(fm1*s0^2*s);\ncm = sin(fm1*s0^3*s);\ncms = sin(fm1*s0^4*s);\ndm = sin(fm1*s0^5*s);\ndms = sin(fm1*s0^6*s);\nem = sin(fm1*s0^7*s);\nfm = sin(fm1*s0^8*s);\nfms = sin(fm1*s0^9*s);\ngm = sin(fm1*s0^10*s);\ngms = sin(fm1*s0^11*s);\n\n%% +\n\n% Quarter notes\nAp = sin(fp1*q);\nAps = sin(fp1*s0*q);\nBp = sin(fp1*s0^2*q);\nCp = sin(fp1*s0^3*q);\nCps = sin(fp1*s0^4*q);\nDp = sin(fp1*s0^5*q);\nDps = sin(fp1*s0^6*q);\nEp = sin(fp1*s0^7*q);\nFp = sin(fp1*s0^8*q);\nFps = sin(fp1*s0^9*q);\nGp = sin(fp1*s0^10*q);\nGps = sin(fp1*s0^11*q);\n\n% Sixteenth notes\nap = sin(fp1*s);\naps = sin(fp1*s0*s);\nbp = sin(fp1*s0^2*s);\ncp = sin(fp1*s0^3*s);\ncps = sin(fp1*s0^4*s);\ndp = sin(fp1*s0^5*s);\ndps = sin(fp1*s0^6*s);\nep = sin(fp1*s0^7*s);\nfp = sin(fp1*s0^8*s);\nfps = sin(fp1*s0^9*s);\ngp = sin(fp1*s0^10*s);\ngps = sin(fp1*s0^11*s);\n\n%%\n\n% Easy access to example tunes.\nif ( (nargin == 0) || isnumeric(str) )\n if ( nargin == 0 )\n str = 1;\n end\n\n switch str\n case 1 % Ode to Joy\n str = 'BG- BG- CA DB DB CA BG- AD- G-B G-B AD- BG- BG- AD- AD-';\n case 2 % God Save The Queen\n str = 'CG CG DG BG CG DG EC EC FC EC DG CG DG CG BG CG';\n end\nend\n\n% Build the CHEBFUN from the string of notes for the tune.\nsong = chebfun;\nl = 0;\nwhile ( ~isempty(str) )\n l = l + 1;\n k = 0;\n\n % Get the string for the next chord.\n for j = 1:numel(str)\n k = k + 1;\n if ( strcmp(str(k), ' ') || strcmp(str(k), ',') )\n break\n end\n end\n\n strk = str(1:k);\n str(1:k) = [];\n\n % Quarter note or sixteenth note?\n if ( isstrprop(strk(1), 'upper') )\n strk = upper(strk);\n songtmp = 0*A;\n else\n strk = lower(strk);\n songtmp = 0*a;\n end\n\n % Assemble the chord from its constituent notes.\n j = 0;\n while ( ~isempty(strk) )\n % Parse out one note from the chord.\n if ( (length(strk) > 1) && any(strcmpi(strk(2), {'+' '-' '#' '*'})) )\n if ( (length(strk) > 2) && any(strcmpi(strk(3), {'#' '*'})) )\n strjk = strk(1:3);\n strk(1:3) = [];\n else\n strjk = strk(1:2);\n strk(1:2) = [];\n end\n else\n strjk = strk(1);\n strk(1) = [];\n end\n\n % Set the amplitude of this note in the chord.\n j = j + 1;\n amp = .4/j;\n\n % Decode and add in the note.\n if ( strcmp(strjk, 'r') || strcmp(strjk, ' ') ) % Sixteenth rest.\n songtmp = join(songtmp, 0*s);\n break\n elseif ( strcmp(strjk, 'R') ) % Quarter rest.\n songtmp = join(songtmp, 0*q);\n break\n else % Actual note.\n songtmp = songtmp + amp*getNote(strjk);\n end\n end\n\n % Tack the chord onto the end of the song.\n song = join(song, songtmp);\nend\n\n % Nested function for mapping note strings to note CHEBFUNs defined above.\n function note = getNote(s)\n switch (s)\n case 'A', note = A;\n case 'B', note = B;\n case 'C', note = C;\n case 'D', note = D;\n case 'E', note = E;\n case 'F', note = F;\n case 'G', note = G;\n\n case 'a', note = a;\n case 'b', note = b;\n case 'c', note = c;\n case 'd', note = d;\n case 'e', note = e;\n case 'f', note = f;\n case 'g', note = g;\n\n case 'A-', note = Am;\n case 'B-', note = Bm;\n case 'C-', note = Cm;\n case 'D-', note = Dm;\n case 'E-', note = Em;\n case 'F-', note = Fm;\n case 'G-', note = Gm;\n\n case 'a-', note = am;\n case 'b-', note = bm;\n case 'c-', note = cm;\n case 'd-', note = dm;\n case 'e-', note = em;\n case 'f-', note = fm;\n case 'g-', note = gm;\n\n case 'A+', note = Ap;\n case 'B+', note = Bp;\n case 'C+', note = Cp;\n case 'D+', note = Dp;\n case 'E+', note = Ep;\n case 'F+', note = Fp;\n case 'G+', note = Gp;\n\n case 'a+', note = ap;\n case 'b+', note = bp;\n case 'c+', note = cp;\n case 'd+', note = dp;\n case 'e+', note = ep;\n case 'f+', note = fp;\n case 'g+', note = gp;\n\n case 'a#', note = as;\n case 'c#', note = cs;\n case 'd#', note = ds;\n case 'f#', note = fs;\n case 'g#', note = gs;\n\n case 'A#', note = As;\n case 'C#', note = Cs;\n case 'D#', note = Ds;\n case 'F#', note = Fs;\n case 'G#', note = Gs;\n\n case 'a+#', note = aps;\n case 'c+#', note = cps;\n case 'd+#', note = dps;\n case 'f+#', note = fps;\n case 'g+#', note = gps;\n\n case 'A+#', note = Aps;\n case 'C+#', note = Cps;\n case 'D+#', note = Dps;\n case 'F+#', note = Fps;\n case 'G+#', note = Gps;\n\n case 'a-#', note = ams;\n case 'c-#', note = cms;\n case 'd-#', note = dms;\n case 'f-#', note = fms;\n case 'g-#', note = gms;\n\n case 'A-#', note = Ams;\n case 'C-#', note = Cms;\n case 'D-#', note = Dms;\n case 'F-#', note = Fms;\n case 'G-#', note = Gms;\n end\n end\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/sing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.629774621301746, "lm_q1q2_score": 0.494567407804815}} {"text": "function [coord,R]=calcgrip(Tr,Tc)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%EN FUNCION DE DONDE ESTE LA CAJA Y DONDE ESTE EL ROBOT,\n%CALCULA QUE LADO DE LA CAJA ESTA A MENOS DISTANCIA DE LA \n%POSICION ACTUAL, Y DEVUELVE POR DONDE TIENE QUE COGER LA CAJA\n%Y CON QUE ORIENTACION\n\n Tc(3,4)=Tc(3,4)+0.05;\n Tc1=Tc(1:3,4);\n Tc2=Tc(1:3,4);\n Tc3=Tc(1:3,4);\n Tc4=Tc(1:3,4);\n Tc1(1,4)=Tc(1,4)+0.14;\n dist(1,1)=norm(Tc1-Tr(1:3,4));\n Tc2(1,4)=Tc(1,4)-0.14;\n dist(2,1)=norm(Tc2-Tr(1:3,4));\n Tc3(1,4)=Tc(2,4)+0.10;\n dist(3,1)=norm(Tc3-Tr(1:3,4));\n Tc4(1,4)=Tc(2,4)-0.10;\n dist(4,1)=norm(Tc4-Tr(1:3,4));\n [M,I]=min(dist);\n if I==1\n coord=[0.14;0;0.05];\n R=[0 0 1 ;0 1 0;1 0 0];\n end\n if I==2\n coord=[-0.14;0;0.05];\n \n R=[0 0 -1 ;0 1 0;-1 0 0];\n end\n if I==3\n coord=[0;0.10;0.05];\n R=[0 -1 0 ;0 0 1; -1 0 0];\n \n end\n if I==4\n coord=[0;-0.10;0.05];\n R=[0 1 0 ;0 0 -1; 1 0 0];\n end\n \n \nend\n \n \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/demos/projects/two_robots_and_a_fruit_box/calcgrip.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.49447196392186177}} {"text": "classdef DOC8 < PROBLEM\n% \n% Benchmark MOP with constraints in both decision and objective spaces\n\n%------------------------------- Reference --------------------------------\n% Z. Liu and Y. Wang, Handling constrained multiobjective optimization\n% problems with constraints in both the decision and objective spaces. IEEE\n% Transactions on Evolutionary Computation, 2019, 23(5): 870-884.\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 methods\n %% Default settings of the problem\n function Setting(obj)\n obj.M = 3;\n obj.D = 10;\n obj.lower = [0 0 500 1000 5000 100 100 100 100 100];\n obj.upper = [1 1 1000 2000 6000 500 500 500 500 500];\n obj.encoding = ones(1,obj.D);\n end\n %% Calculate objective values and constraint violations\n function Population = Evaluation(obj,varargin)\n X = varargin{1};\n X = max(min(X,repmat(obj.upper,size(X,1),1)),repmat(obj.lower,size(X,1),1));\n g_temp = X(:, 3) + X(:, 4) + X(:, 5);\n g = g_temp-7049.2480205286 +1;\n PopObj(:,1) = (X(:,1).*X(:,2)).*g;\n PopObj(:,2) = (X(:,1).*(1 - X(:,2))).*g;\n PopObj(:,3) = (1-X(:,1)).*g;\n % Constraints in objective space\n c(:,1) = max( - (PopObj(:,3) - 0.4).*(PopObj(:,3) - 0.6), 0);\n % Constraints in decision space\n c(:,2) = -1 + 0.0025 * (X(:, 6) + X(:, 8));\n c(:,3) = -1 + 0.0025 * (X(:, 7) + X(:, 9) - X(:, 6));\n c(:,4) = -1 + 0.01 * (X(:, 10) - X(:, 7));\n c(:,5) = -X(:, 3).* X(:, 8) + 833.33252 * X(:, 6) + 100 * X(:, 3) - 83333.333;\n c(:,6) = -X(:, 4).* X(:, 9) + 1250 * X(:, 7) + X(:, 4).* X(:, 6) - 1250 * X(:, 6);\n c(:,7) = -X(:, 5).* X(:, 10) + 1250000 + X(:, 5).* X(:, 7) - 2500 * X(:, 7);\n Population = SOLUTION(X,PopObj,c,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,3);\n R(0.4 = real(u'*v).\n%\n% If transposed is set to true (it is false by default), then the matrices\n% are transposed: a point Y on the manifold is a matrix of size m x n and\n% each row has unit 2-norm. It is the same geometry, just a different\n% representation.\n%\n% In transposed form, a point Y is such that Y*Y' is a Hermitian, positive\n% semidefinite matrix of size m and of rank at most n, such that all the\n% diagonal entries are equal to 1.\n%\n% Note: obliquecomplexfactory(1, n, true) is equivalent to (but potentially\n% slower than) complexcirclefactory(n).\n%\n% See also: spherecomplexfactory complexcirclefactory obliquefactory\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, Sep. 3, 2014.\n% Contributors:\n% Change log:\n%\n% Oct. 21, 2016 (NB)\n% Formatted for inclusion in Manopt release.\n%\n% July 20, 2017 (NB)\n% Distance function is now accurate for close-by points. See notes\n% inside the spherefactory file for details. Also improves distances\n% computation as part of the log function.\n\n\n if ~exist('transposed', 'var') || isempty(transposed)\n transposed = false;\n end\n\n if transposed\n trnsp = @(X) X.';\n else\n trnsp = @(X) X;\n end\n\n M.name = @() sprintf('Complex oblique manifold COB(%d, %d)', n, m);\n\n M.dim = @() (2*n-1)*m;\n\n M.inner = @(x, d1, d2) real(d1(:)'*d2(:));\n\n M.norm = @(x, d) norm(d(:));\n\n M.dist = @(x, y) norm(real(2*asin(.5*sqrt(sum(trnsp(abs(x - y).^2), 1)))));\n\n M.typicaldist = @() pi*sqrt(m);\n\n M.proj = @(X, U) trnsp(projection(trnsp(X), trnsp(U)));\n\n M.tangent = M.proj;\n\n % For Riemannian submanifolds, converting a Euclidean gradient into a\n % Riemannian gradient amounts to an orthogonal projection.\n M.egrad2rgrad = M.proj;\n\n M.ehess2rhess = @ehess2rhess;\n function rhess = ehess2rhess(X, egrad, ehess, U)\n X = trnsp(X);\n egrad = trnsp(egrad);\n ehess = trnsp(ehess);\n U = trnsp(U);\n\n PXehess = projection(X, ehess);\n inners = sum(real(conj(X).*egrad), 1);\n rhess = PXehess - bsxfun(@times, U, inners);\n\n rhess = trnsp(rhess);\n end\n\n M.exp = @exponential;\n % Exponential on the complex oblique manifold\n function y = exponential(x, d, t)\n x = trnsp(x);\n d = trnsp(d);\n\n if nargin == 2\n % t = 1;\n td = d;\n else\n td = t*d;\n end\n\n nrm_td = sqrt(sum(real(td).^2 + imag(td).^2, 1));\n\n y = bsxfun(@times, x, cos(nrm_td)) + ...\n bsxfun(@times, td, sinxoverx(nrm_td));\n\n y = trnsp(y);\n end\n\n M.log = @logarithm;\n function v = logarithm(x1, x2)\n x1 = trnsp(x1);\n x2 = trnsp(x2);\n\n v = projection(x1, x2 - x1);\n dists = real(2*asin(.5*sqrt(sum(trnsp(abs(x2 - x1).^2), 1))));\n norms = sqrt(sum(real(v).^2 + imag(v).^2, 1));\n factors = dists./norms;\n % For very close points, dists is almost equal to norms, but\n % because they are both almost zero, the division above can return\n % NaN's. To avoid that, we force those ratios to 1.\n factors(dists <= 1e-10) = 1;\n v = bsxfun(@times, v, factors);\n\n v = trnsp(v);\n end\n\n M.retr = @retraction;\n % Retraction on the oblique manifold\n function y = retraction(x, d, t)\n x = trnsp(x);\n d = trnsp(d);\n\n if nargin < 3\n td = d;\n else\n td = t*d;\n end\n\n y = normalize_columns(x + td);\n\n y = trnsp(y);\n end\n\n M.hash = @(x) ['z' hashmd5([real(x(:)) ; imag(x(:))])];\n\n M.rand = @() trnsp(random(n, m));\n\n M.randvec = @(x) trnsp(randomvec(n, m, trnsp(x)));\n\n M.lincomb = @matrixlincomb;\n\n M.zerovec = @(x) trnsp(zeros(n, m));\n\n M.transp = @(x1, x2, d) M.proj(x2, d);\n\n M.pairmean = @pairmean;\n function y = pairmean(x1, x2)\n y = trnsp(x1+x2);\n y = normalize_columns(y);\n y = trnsp(y);\n end\n\n % vec returns a vector representation of an input tangent vector which\n % is represented as a matrix. mat returns the original matrix\n % representation of the input vector representation of a tangent\n % vector. vec and mat are thus inverse of each other. They are\n % furthermore isometries between a subspace of R^2nm and the tangent\n % space at x.\n vect = @(X) X(:);\n M.vec = @(x, u_mat) [vect(real(trnsp(u_mat))) ; ...\n vect(imag(trnsp(u_mat)))];\n M.mat = @(x, u_vec) trnsp(reshape(u_vec(1:(n*m)), [n, m])) + ...\n 1i*trnsp(reshape(u_vec((n*m+1):end), [n, m]));\n M.vecmatareisometries = @() true;\n\nend\n\n% Given a matrix X, returns the same matrix but with each column scaled so\n% that they have unit 2-norm.\nfunction X = normalize_columns(X)\n norms = sqrt(sum(real(X).^2 + imag(X).^2, 1));\n X = bsxfun(@times, X, 1./norms);\nend\n\n% Orthogonal projection of the ambient vector H onto the tangent space at X\nfunction PXH = projection(X, H)\n\n % Compute the inner product between each vector H(:, i) with its root\n % point X(:, i), that is, real(X(:, i)' * H(:, i)).\n % Returns a row vector.\n inners = real(sum(conj(X).*H, 1));\n\n % Subtract from H the components of the H(:, i)'s that are parallel to\n % the root points X(:, i).\n PXH = H - bsxfun(@times, X, inners);\n\nend\n\n% Uniform random sampling on the sphere.\nfunction x = random(n, m)\n\n x = normalize_columns(randn(n, m) + 1i*randn(n, m));\n\nend\n\n% Random normalized tangent vector at x.\nfunction d = randomvec(n, m, x)\n\n d = randn(n, m) + 1i*randn(n, m);\n d = projection(x, d);\n d = d / norm(d(:));\n\nend\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/oblique/obliquecomplexfactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7279754371026368, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.4944254056756969}} {"text": "% cmbglobl.m : cmb globals : physical constants that are used through all files\n% are given a value here\n%\n% D Vangheluwe 28 jan 2005, see cmbaccur.m anc cmbacc1.m as the main files\n\nglobal GL_cmb_c GL_cmb_h0 GL_cmb_t0 GL_cmb_T0 GL_cmb_rv GL_cmb_fv GL_cmb_kg1 GL_cmb_ka1 ...\n GL_cmb_yp GL_cmb_ncr GL_cmb_cr GL_cmb_pcm GL_cmb_dha;\n \n% velocity of light in m/s\nGL_cmb_c = 2.998e8;\n% the Hubble constant at present in (h Mpc^-1), see my notes p71\nGL_cmb_h0 = 1e5/GL_cmb_c;\n% the present temperature of the CMB in degr Kelvin and in eV\nGL_cmb_t0 = 2.725;\nGL_cmb_T0 = GL_cmb_t0/11605;\n% ratio of radiation density/critical density, see Dodelson (2.87)\n%fv = 0.405;\nGL_cmb_rv = (21/8) * (4/11)^(4/3);\nGL_cmb_fv = GL_cmb_rv/(1 + GL_cmb_rv);\nGL_cmb_kg1 = 2.47e-5;\nGL_cmb_ka1 = GL_cmb_kg1/(1 - GL_cmb_fv);\n%ka1 = 4.15e-5;\n% the primordial helium mass fraction\nGL_cmb_yp = 0.24;\n% critical density in m^-3\nGL_cmb_ncr = 11.23;\n%ncr = 10.8;\n% Compton cross section in m^2, see Dodelson p 72\nGL_cmb_cr = 0.665e-28;\n% conversion of Parsec to meters\nGL_cmb_pcm = 3.0856e22;\n% amplitude of the primordial density perturbation at the horizon, see Dodelson (8.76)\nGL_cmb_dha = 4.47e-5;\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/8491-cmbaccur/cmbglobl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4944065764670011}} {"text": "function [F,sE,sC] = VBA_spm_log_evidence(varargin)\n% Return the log-evidence of a reduced model (under Laplace approximation)\n% FORMAT [F,sE,sC] = spm_log_evidence(qE,qC,pE,pC,rE,rC)\n% FORMAT [F,sE,sC] = spm_log_evidence(qE,qC,pE,pC,priorfun,varargin)\n% FORMAT [F,sE,sC] = spm_log_evidence(qE,qC,pE,pC)\n%\n% qE,qC - posterior expectation and covariance of full model\n% pE,pC - prior expectation and covariance of full model\n% rE,rC - prior expectation and covariance of reduced model\n% or \n% priorfun - inline function that returns prior moments\n% {rE rC} = priorfun(varargin{:})\n%\n% or (if omitted) rE = 0 and rC = 0;\n%\n% F - reduced log-evidence: ln p(y|reduced model) - ln p(y|full model)\n% [sE,sC] - posterior expectation and covariance of reduced model\n%\n%--------------------------------------------------------------------------\n% This routine assumes the reduced model is nested within a full model and\n% that the posteriors (and priors) are Gaussian. Nested here means that the\n% prior precision of the reduced model, minus the prior precision of the\n% full model is positive definite. We additionally assume that the prior\n% means are unchanged. The two input argument formats are for use with\n% spm_argmax.\n%__________________________________________________________________________\n% Copyright (C) 2005 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: spm_log_evidence.m 4281 2011-03-31 19:49:57Z karl $\n \n% Compute reduced log-evidence\n%==========================================================================\n \n% check to see if priors are specified by a function\n%--------------------------------------------------------------------------\nqE = varargin{1};\nqC = varargin{2};\npE = varargin{3};\npC = varargin{4};\ntry\n priors = varargin{5}(varargin{6:end});\n rE = priors{1};\n rC = priors{2};\ncatch\n try\n rE = varargin{5};\n rC = varargin{6};\n catch\n n = size(qC,1);\n rE = sparse(n,1);\n rC = sparse(n,n);\n end\nend\n \n% reduced subspace \n%--------------------------------------------------------------------------\nqE = VBA_spm_vec(qE);\npE = VBA_spm_vec(pE);\nrE = VBA_spm_vec(rE);\n \nif nargout < 2\n dE = pE - rE;\n dC = pC - rC;\n k = find(dE | any(dC,2));\n if ~isempty(k)\n qE = qE(k);\n pE = pE(k);\n rE = rE(k);\n qC = qC(k,k);\n pC = pC(k,k);\n rC = rC(k,k);\n else\n \n % the reduced and full models are the same\n %------------------------------------------------------------------\n F = 0;\n return\n end\nend\n\n% fix tolerance for matrix inversions\n%--------------------------------------------------------------------------\nTOL = exp(-16);\n\n% remove fixed parameters under full model\n%--------------------------------------------------------------------------\ni = find(diag(pC));\n\n% preliminaries\n%--------------------------------------------------------------------------\nqP = VBA_spm_inv(qC(i,i),TOL);\npP = VBA_spm_inv(pC(i,i),TOL);\nrP = VBA_spm_inv(rC(i,i),TOL);\nsP = qP + rP - pP;\nsC = VBA_spm_inv(sP,TOL);\nsE = qP*qE(i) + rP*rE(i) - pP*pE(i);\n\n% log-evidence\n%--------------------------------------------------------------------------\nF = VBA_spm_logdet(rP*qP*sC*pC(i,i)) ...\n - (qE(i)'*qP*qE(i) + rE(i)'*rP*rE(i) - pE(i)'*pP*pE(i) - sE'*sC*sE);\nF = F/2;\n \n% restore full conditional density\n%--------------------------------------------------------------------------\nif nargout > 1\n rE(i) = sC*sE;\n rC(i,i) = sC;\n sE = VBA_spm_unvec(rE,varargin{1});\n sC = rC;\nend\n", "meta": {"author": "MBB-team", "repo": "VBA-toolbox", "sha": "01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414", "save_path": "github-repos/MATLAB/MBB-team-VBA-toolbox", "path": "github-repos/MATLAB/MBB-team-VBA-toolbox/VBA-toolbox-01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414/thrid-party/spm/VBA_spm_log_evidence.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138366, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4942500664159858}} {"text": "function [OffDec,OffVel] = LCSA_CoefficientSMPSOOperator(Particle,Pbest,Gbest,xlower,xupper)\n% ----------------------------------------------------------------------- \n% Copyright (C) 2020 Heiner Zille\n%\n% This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 \n% International License. (CC BY-NC-SA 4.0). To view a copy of this license, \n% visit http://creativecommons.org/licenses/by-nc-sa/4.0/ or see the \n% pdf-file \"License-CC-BY-NC-SA-4.0.pdf\" that came with this code. \n%\n% You are free to: \n% * Share ? copy and redistribute the material in any medium or format\n% * Adapt ? remix, transform, and build upon the material \n% Under the following terms:\n% * Attribution ? You must give appropriate credit, provide a link to the \n% license, and indicate if changes were made. You may do so in any reasonable \n% manner, but not in any way that suggests the licensor endorses you or your use.\n% * NonCommercial ? You may not use the material for commercial purposes.\n% * ShareAlike ? If you remix, transform, or build upon the material, you must \n% distribute your contributions under the same license as the original.\n% * No additional restrictions ? You may not apply legal terms or technological \n% measures that legally restrict others from doing anything the license permits.\n% \n% Author of this Code: \n% Heiner Zille or \n%\n% This code is based on the following publications:\n%\n% 1) Heiner Zille \n% \"Large-scale Multi-objective Optimisation: New Approaches and a Classification of the State-of-the-Art\" \n% PhD Thesis, Otto von Guericke University Magdeburg, 2019 \n% http://dx.doi.org/10.25673/32063 \n% \n% 2) Heiner Zille and Sanaz Mostaghim\n% \"Linear Search Mechanism for Multi- and Many-Objective Optimisation\"\n% 10th International Conference on Evolutionary Multi-Criterion Optimization (EMO 2019), \n% Lecture Notes in Computer Science, vol 11411. \n% Deb K. et al. (eds), Springer, Cham, East Lansing, Michigan, USA, March 2019 \n% https://doi.org/10.1007/978-3-030-12598-1_32.\n%\n% This file is intended to work with the PlatEMO framework version 2.5. \n% Date of publication of this code: 06.04.2020 \n% Last Update of this code: 06.04.2020\n% A newer version of this algorithm may be available. Please contact the author \n% or see http://www.ci.ovgu.de/Research/Codes.html. \n%\n% The files may have been modified in Feb 2021 by the authors of the Platemo framework to work with the Platemo 3.0 release. \n% ----------------------------------------------------------------------- \n% This file is derived from its original version containied in the PlatEMO \n% framework.\n% ----------------------------------------------------------------------- \n\n %% Parameter setting \n [ParticleDec,ParticleVel] = unpackDecAndVel(Particle.adds); \n [PbestDec,~] = unpackDecAndVel(Pbest.adds);\n [GbestDec,~] = unpackDecAndVel(Gbest.adds);\n [N,D] = size(ParticleDec);\n\n %% Particle swarm optimization\n W = repmat(unifrnd(0.1,0.5,N,1),1,D);\n r1 = repmat(rand(N,1),1,D);\n r2 = repmat(rand(N,1),1,D);\n C1 = repmat(unifrnd(1.5,2.5,N,1),1,D);\n C2 = repmat(unifrnd(1.5,2.5,N,1),1,D);\n OffVel = W.*ParticleVel + C1.*r1.*(PbestDec-ParticleDec) + C2.*r2.*(GbestDec-ParticleDec);\n phi = max(4,C1+C2);\n OffVel = OffVel.*2./abs(2-phi-sqrt(phi.^2-4*phi));\n delta = repmat((xupper-xlower)/2,N,1);\n OffVel = max(min(OffVel,delta),-delta);\n OffDec = ParticleDec + OffVel;\n \n %% Deterministic back\n Lower = repmat(xlower,N,1);\n Upper = repmat(xupper,N,1);\n repair = OffDec < Lower | OffDec > Upper;\n OffVel(repair) = 0.001*OffVel(repair);\n OffDec = max(min(OffDec,Upper),Lower);\n \n %% Polynomial mutation\n disM = 20;\n Site1 = repmat(rand(N,1)<0.15,1,D);\n Site2 = rand(N,D) < 1/D;\n mu = rand(N,D);\n temp = Site1 & Site2 & mu<=0.5;\n OffDec(temp) = OffDec(temp)+(Upper(temp)-Lower(temp)).*((2.*mu(temp)+(1-2.*mu(temp)).*...\n (1-(OffDec(temp)-Lower(temp))./(Upper(temp)-Lower(temp))).^(disM+1)).^(1/(disM+1))-1);\n temp = Site1 & Site2 & mu>0.5; \n OffDec(temp) = OffDec(temp)+(Upper(temp)-Lower(temp)).*(1-(2.*(1-mu(temp))+2.*(mu(temp)-0.5).*...\n (1-(Upper(temp)-OffDec(temp))./(Upper(temp)-Lower(temp))).^(disM+1)).^(1/(disM+1)));\nend\n\nfunction [positions, velocities] = unpackDecAndVel(pack)\n noOfSolutions = size(pack,1);\n P = arrayfun(@(K) pack(K).xDecs, 1:noOfSolutions, 'UniformOutput',0);\n positions = cell2mat(transpose(P));\n V = arrayfun(@(K) pack(K).xDecs, 1:noOfSolutions, 'UniformOutput',0);\n velocities = cell2mat(transpose(V));\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Algorithms/Multi-objective optimization/LCSA/LCSA_CoefficientSMPSOOperator.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4940377275761946}} {"text": "function h11=derotated_dtcwt(n,Yh)\n%FUNCTION to perform a derotated DT_CWT\n\n% n -> No. of levels of wavelet decomposition\n% Yh -> A cell array containing the 6 complex highpass subimages for\n% each level.\n% h11 ->detotated Yh\nh11{n}=Yh{n};\nfor k=n:-1:2\n for m=1:6\n xp=imresize(Yh{k}(:,:,m),2);%\n argxp=angle(xp);\n argx=angle(Yh{k-1}(:,:,m));\n argx=argx-2.*argxp;\n absx=abs(Yh{k-1}(:,:,m));\n xa=absx.*cos(argx);\n xb=absx.*sin(argx);\n h11{k-1}(:,:,m)=complex(xa,xb);\n end\nend\n%figure;\n%cimage5(h11{1}(:,:,4));\n%figure;\n%cimage5(h1{1}(:,:,4));\n%figure;\n%cimage5(h11{2}(:,:,4));\n%figure;\n%cimage5(h1{2}(:,:,4));", "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/derotated_dtcwt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080671950640463, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4940377162725263}} {"text": "function [loss, fchg, tchg, dloss_dV, dchg_dVm] = get_losses(baseMVA, bus, branch)\n%GET_LOSSES Returns series losses (and reactive injections) per branch.\n%\n% LOSS = GET_LOSSES(RESULTS)\n% LOSS = GET_LOSSES(BASEMVA, BUS, BRANCH)\n%\n% [LOSS, CHG] = GET_LOSSES(RESULTS)\n% [LOSS, FCHG, TCHG] = GET_LOSSES(RESULTS)\n% [LOSS, FCHG, TCHG, DLOSS_DV] = GET_LOSSES(RESULTS)\n% [LOSS, FCHG, TCHG, DLOSS_DV, DCHG_DVM] = GET_LOSSES(RESULTS)\n%\n% Computes branch series losses, and optionally reactive injections from\n% line charging, as functions of bus voltages and branch parameters, using the\n% following formulae:\n%\n% loss = abs( Vf / tau - Vt ) ^ 2 / (Rs - j Xs)\n% fchg = abs( Vf / tau ) ^ 2 * Bc / 2\n% tchg = abs( Vt ) ^ 2 * Bc / 2\n%\n% Optionally, computes the partial derivatives of the line losses with\n% respect to voltage angles and magnitudes.\n%\n% Input:\n% RESULTS - a MATPOWER case struct with bus voltages corresponding to\n% a valid power flow solution.\n% (Can optionally be specified as individual fields BASEMVA,\n% BUS, and BRANCH.)\n%\n% Output(s):\n% LOSS - complex NL x 1 vector of losses (in MW), where NL is the number\n% of branches in the system, representing only the losses in the\n% series impedance element of the PI model for each branch.\n% CHG - NL x 1 vector of total reactive injection for each line\n% (in MVAr), representing the line charging injections of both\n% of the shunt elements of PI model for each branch.\n% FCHG - Same as CHG, but for the element at the \"from\" end of the\n% branch only.\n% TCHG - Same as CHG, but for the element at the \"to\" end of the branch.\n% DLOSS_DV - Struct with partial derivatives of LOSS with respect to bus\n% voltages, with fields:\n% .a - Partial with respect to bus voltage angles.\n% .m - Partial with respect to bus voltage magnitudes.\n% DCHG_DVM - Struct with partial derivatives of FCHG and TCHG with\n% respect to bus voltage magnitudes, with fields:\n% .f - Partial of FCHG with respect to bus voltage magnitudes.\n% .t - Partial of TCHG with respect to bus voltage magnitudes.\n%\n% Example:\n% results = runpf(mycase);\n% [loss, chg] = get_losses(results);\n% total_system_real_losses = sum(real(loss));\n% total_system_reac_losses = sum(imag(loss)) - sum(chg);\n%\n% [loss, fchg, tchg, dloss_dV] = get_losses(results);\n\n% MATPOWER\n% Copyright (c) 1996-2017, Power Systems Engineering Research Center (PSERC)\n% by Ray Zimmerman, PSERC Cornell\n%\n% This file is part of MATPOWER.\n% Covered by the 3-clause BSD License (see LICENSE file for details).\n% See https://matpower.org for more info.\n\n%% default arguments\nif isstruct(baseMVA)\n mpc = baseMVA;\n [baseMVA, bus, branch] = deal(mpc.baseMVA, mpc.bus, mpc.branch);\nend\n\n%% define named indices into bus, gen, branch matrices\n[PQ, PV, REF, NONE, BUS_I, BUS_TYPE, PD, QD, GS, BS, BUS_AREA, VM, ...\n VA, BASE_KV, ZONE, VMAX, VMIN, LAM_P, LAM_Q, MU_VMAX, MU_VMIN] = idx_bus;\n[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%% create map of external bus numbers to bus indices\ni2e = bus(:, BUS_I);\ne2i = sparse(max(i2e), 1);\ne2i(i2e) = (1:size(bus, 1))';\nout = find(branch(:, BR_STATUS) == 0); %% out-of-service branches\n\n%% sizes of things\nnb = size(bus, 1); %% number of buses\nnl = size(branch, 1); %% number of branches\n\n%% construct complex bus voltage vector\nV = bus(:, VM) .* exp(1j * pi/180 * bus(:, VA));\n\n%% parameters\nCf = sparse(1:nl, e2i(branch(:, F_BUS)), branch(:, BR_STATUS), nl, nb);\nCt = sparse(1:nl, e2i(branch(:, T_BUS)), branch(:, BR_STATUS), nl, nb);\ntap = ones(nl, 1); %% default tap ratio = 1 for lines\nxfmr = find(branch(:, TAP)); %% indices of transformers\ntap(xfmr) = branch(xfmr, TAP); %% include transformer tap ratios\ntap = tap .* exp(1j*pi/180 * branch(:, SHIFT)); %% add phase shifters\nA = spdiags(1 ./ tap, 0, nl, nl) * Cf - Ct;\nYsc = 1 ./ (branch(:, BR_R) - 1j * branch(:, BR_X));\nVdrop = A * V; %% vector of voltage drop across series impedance element\nloss = baseMVA * Ysc .* Vdrop .* conj(Vdrop);\n% loss = baseMVA * abs(V(e2i(branch(:, F_BUS))) ./ tap - V(e2i(branch(:, T_BUS)))) .^ 2 ./ ...\n% (branch(:, BR_R) - 1j * branch(:, BR_X));\n% loss(out) = 0;\n\nif nargout > 1\n Vf = Cf * V;\n Vt = Ct * V;\n fchg = real(baseMVA / 2 * branch(:, BR_B) .* Vf .* conj(Vf) ./ (tap .* conj(tap)));\n tchg = real(baseMVA / 2 * branch(:, BR_B) .* Vt .* conj(Vt));\n% fchg = abs(V(e2i(branch(:, F_BUS))) ./ tap) .^ 2 .* branch(:, BR_B) * baseMVA / 2;\n% tchg = abs(V(e2i(branch(:, T_BUS))) ) .^ 2 .* branch(:, BR_B) * baseMVA / 2;\n fchg(out) = 0;\n tchg(out) = 0;\n\n if nargout == 2\n fchg = fchg + tchg;\n end\nend\n\nif nargout > 3\n B = spdiags(A * V, 0, nl, nl) * conj(A) * spdiags(conj(V), 0, nb, nb);\n dYsc = spdiags(Ysc, 0, nl, nl);\n dloss_dV = struct(...\n 'a', -1j * baseMVA * dYsc * (B - conj(B)), ...\n 'm', baseMVA * dYsc * (B + conj(B)) * spdiags(1 ./ abs(V), 0, nb, nb) ...\n );\n if nargout > 4\n Bc = spdiags(branch(:, BR_B), 0, nl, nl);\n tt = spdiags(1 ./ (tap .* conj(tap)), 0, nl, nl);\n dchg_dVm = struct(...\n 'f', baseMVA * Bc * tt * spdiags(Cf * bus(:, VM), 0, nl, nl) * Cf, ...\n 't', baseMVA * Bc * spdiags(Ct * bus(:, VM), 0, nl, nl) * Ct ...\n );\n end\nend\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/get_losses.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49402245380361515}} {"text": "function g = findBestGammaAsCRF(img0, img1, exposure0, exposure1)\n%\n% g = findBestGammaAsCRF(img0, img1, exposure0, exposure1)\n%\n% This function computes the best gamma paramters for RGB that approximate\n% the camera response function.\n%\n% Input:\n% -img0: an SDR image\n% -img1: an SDR image\n% -exposure0: the shutter speed of img0\n% -exposure1: the shutter speed of img1\n%\n% Output:\n% -lin_fun: the inverse CRF\n% -max_lin_fun: maximum value of the inverse CRF\n%\n% Copyright (C) 2014-15 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\ndelta_exposure = exposure1 / exposure0;\nmask = ones(size(img0));\nmask(img0>0.95) = 0.0;\nmask(img1>0.95) = 0.0;\nmask(img0<0.05) = 0.0;\nmask(img1<0.05) = 0.0;\n\n function err = residualFunction(p)\n err = 0.0;\n for i=1:3\n gt = p(i);\n img0_lin(:,:,i) = (img0(:,:,i).^gt);\n img0_re(:,:,i) = img0_lin(:,:,i) * delta_exposure;\n img0_re(:,:,i) = img0_re(:,:,i).^(1.0/gt);\n \n delta = abs(img0_re(:,:,i) - img1(:,:,i)) .* mask(:,:,i);\n err = err + mean(delta(:));\n end\n end\n\n opts = optimset('Display', 'iter', 'TolFun', 1e-12, 'TolX', 1e-12, 'MaxIter', 1000);\n gi = 2.2 * ones(1,3);\n g = fminsearch(@residualFunction, gi, opts);\n for i=1:3\n img0_lin(:,:,i) = (img0(:,:,i).^g(i));\n img0_re(:,:,i) = img0_lin(:,:,i) * delta_exposure;\n img0_re(:,:,i) = img0_re(:,:,i).^(1.0/g(i));\n end \n \n imshow([img0, img0_re, img1]);\n \nend", "meta": {"author": "banterle", "repo": "HDR_Toolbox", "sha": "a2b45dc48b7169192fb633097a83879e71a0c0f2", "save_path": "github-repos/MATLAB/banterle-HDR_Toolbox", "path": "github-repos/MATLAB/banterle-HDR_Toolbox/HDR_Toolbox-a2b45dc48b7169192fb633097a83879e71a0c0f2/demos/FindBestGamma.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4940224422121135}} {"text": "%% FUNCTION Least_SRMTL\n% Sparse Structure-Regularized Learning with Least Squares Loss.\n%\n%% OBJECTIVE\n% argmin_W { sum_i^t (0.5 * norm (Y{i} - X{i}' * W(:, i))^2)\n% + rho1 * norm(W*R, 'fro')^2 + rho2 * \\|W\\|_1}\n%\n%% R encodes structure relationship\n% 1)Structure order is given by using [1 -1 0 ...; 0 1 -1 ...; ...]\n% e.g.: R=zeros(t,t-1);R(1:(t+1):end)=1;R(2:(t+1):end)=-1;\n% 2)Ridge penalty term by setting: R = eye(t)\n% 3)All related regularized: R = eye (t) - ones (t) / t\n%\n%% INPUT\n% X: {n * d} * t - input matrix\n% Y: {n * 1} * t - output matrix\n% R: regularization structure\n% rho1: structure regularization parameter\n% rho2: sparsity controlling parameter\n%\n%% OUTPUT\n% W: model: d * t\n% funcVal: function value vector.\n%\n%% LICENSE\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% Copyright (C) 2011 - 2012 Jiayu Zhou and Jieping Ye\n%\n% You are suggested to first read the Manual.\n% For any problem, please contact with Jiayu Zhou via jiayu.zhou@asu.edu\n%\n% Last modified on June 3, 2012.\n%\n%% RELATED PAPERS\n%\n% [1] Evgeniou, T. and Pontil, M. Regularized multi-task learning, KDD 2004\n% [2] Zhou, J. Technical Report. http://www.public.asu.edu/~jzhou29/Software/SRMTL/CrisisEventProjectReport.pdf\n%\n%% RELATED FUNCTIONS\n% Logistic_SRMTL, init_opts\n\n%% Code starts here\nfunction [W, funcVal] = Least_SRMTL(X, Y, R, rho1, rho2, opts)\n\nif nargin <5\n error('\\n Inputs: X, Y, R, rho1, and rho2 should be specified!\\n');\nend\nX = multi_transpose(X);\n\nif nargin <6\n opts = [];\nend\n\n% initialize options.\nopts=init_opts(opts);\n\nif isfield(opts, 'rho_L2')\n rho_L2 = opts.rho_L2;\nelse\n rho_L2 = 0;\nend\n\n\ntask_num = length (X);\ndimension = size(X{1}, 1);\nfuncVal = [];\n\n% precomputation.\nRRt = R * R';\nXY = cell(task_num, 1);\nW0_prep = [];\nfor t_idx = 1: task_num\n XY{t_idx} = X{t_idx}*Y{t_idx};\n W0_prep = cat(2, W0_prep, XY{t_idx});\nend\n\n% initialize a starting point\nif opts.init==2\n W0 = zeros(dimension, task_num);\nelseif opts.init == 0\n W0 = W0_prep;\nelse\n if isfield(opts,'W0')\n W0=opts.W0;\n if (nnz(size(W0)-[dimension, task_num]))\n error('\\n Check the input .W0');\n end\n else\n W0=W0_prep;\n end\nend\n\n\nbFlag=0; % this flag tests whether the gradient step only changes a little\n\nWz= W0;\nWz_old = W0;\n\nt = 1;\nt_old = 0;\n\n\niter = 0;\ngamma = 1;\ngamma_inc = 2;\n\nwhile iter < opts.maxIter\n alpha = (t_old - 1) /t;\n \n Ws = (1 + alpha) * Wz - alpha * Wz_old;\n \n % compute function value and gradients of the search point\n gWs = gradVal_eval(Ws, rho1);\n Fs = funVal_eval (Ws, rho1);\n \n while true\n [Wzp l1c_wzp] = l1_projection(Ws - gWs/gamma, 2 * rho2 / gamma);\n Fzp = funVal_eval (Wzp, rho1);\n \n delta_Wzp = Wzp - Ws;\n r_sum = norm(delta_Wzp, 'fro')^2;\n Fzp_gamma = Fs + trace(delta_Wzp' * gWs) + gamma/2 * norm(delta_Wzp, 'fro')^2;\n \n if (r_sum <=1e-20)\n bFlag=1; % this shows that, the gradient step makes little improvement\n break;\n end\n \n if (Fzp <= Fzp_gamma)\n break;\n else\n gamma = gamma * gamma_inc;\n end\n end\n \n Wz_old = Wz;\n Wz = Wzp;\n \n funcVal = cat(1, funcVal, Fzp + rho2 * l1c_wzp);\n \n if (bFlag)\n % fprintf('\\n The program terminates as the gradient step changes the solution very small.');\n break;\n end\n \n % test stop condition.\n switch(opts.tFlag)\n case 0\n if iter>=2\n if (abs( funcVal(end) - funcVal(end-1) ) <= opts.tol)\n break;\n end\n end\n case 1\n if iter>=2\n if (abs( funcVal(end) - funcVal(end-1) ) <=...\n opts.tol* funcVal(end-1))\n break;\n end\n end\n case 2\n if ( funcVal(end)<= opts.tol)\n break;\n end\n case 3\n if iter>=opts.maxIter\n break;\n end\n end\n \n iter = iter + 1;\n t_old = t;\n t = 0.5 * (1 + (1+ 4 * t^2)^0.5);\n \nend\n\nW = Wzp;\n\n\n% private functions\n\n function [z l1_comp_val] = l1_projection (v, beta)\n % this projection calculates\n % argmin_z = \\|z-v\\|_2^2 + beta \\|z\\|_1\n % z: solution\n % l1_comp_val: value of l1 component (\\|z\\|_1)\n \n z = zeros(size(v));\n vp = v - beta/2;\n z (v> beta/2) = vp(v> beta/2);\n vn = v + beta/2;\n z (v< -beta/2) = vn(v< -beta/2);\n \n \n l1_comp_val = sum(sum(abs(z)));\n end\n\n function [grad_W] = gradVal_eval(W, rho1)\n \n if opts.pFlag\n grad_W = zeros(size(W));\n parfor t_ii = 1:task_num\n XWi = X{t_ii}' * W(:,t_ii);\n XTXWi = X{t_ii}* XWi;\n grad_W(:, t_ii) = XTXWi - XY{t_ii};\n %grad_W = cat(2, grad_W, X{t_ii}*(X{t_ii}' * W(:,t_ii)-Y{t_ii}) );\n end\n else\n grad_W = [];\n for t_ii = 1:task_num\n XWi = X{t_ii}' * W(:,t_ii);\n XTXWi = X{t_ii}* XWi;\n grad_W = cat(2, grad_W, XTXWi - XY{t_ii});\n %grad_W = cat(2, grad_W, X{t_ii}*(X{t_ii}' * W(:,t_ii)-Y{t_ii}) );\n end\n end\n grad_W = grad_W + rho1 * 2 * W * RRt...\n + rho_L2 * 2 * W;\n end\n\n function [funcVal] = funVal_eval (W, rho1)\n funcVal = 0;\n if opts.pFlag\n parfor i = 1: task_num\n funcVal = funcVal + 0.5 * norm (Y{i} - X{i}' * W(:, i))^2;\n end\n else\n for i = 1: task_num\n funcVal = funcVal + 0.5 * norm (Y{i} - X{i}' * W(:, i))^2;\n end\n end\n funcVal = funcVal + rho1 * norm(W*R, 'fro')^2 ...\n + rho_L2 * norm(W, 'fro')^2;\n end\n\nend", "meta": {"author": "jiayuzhou", "repo": "MALSAR", "sha": "fb9751594983df020ddc4f7e4a40520ee7c37989", "save_path": "github-repos/MATLAB/jiayuzhou-MALSAR", "path": "github-repos/MATLAB/jiayuzhou-MALSAR/MALSAR-fb9751594983df020ddc4f7e4a40520ee7c37989/MALSAR/functions/SRMTL/Least_SRMTL.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4939495365202421}} {"text": "function varargout=bss_decomp_filt(varargin)\n\n% decompose an estimated source into target/interference/noise/artefacts components, assuming the admissible distortion is a pure time-invariant filter.\n% components, assuming the admissible distortion is a pure time-invariant\n% filter.\n%\n% Usage:\n%\n% [s_target,e_interf[,e_noise],e_artif]=bss_decomp_filt(se,index,S[,N],L)\n%\n% Input:\n% - se: row vector of length T containing the estimated source,\n% - index: points which component of S se has to be compared to,\n% - S: n x T matrix containing the original sources,\n% - N: m x T matrix containing the noise on the observations (if any).\n% - L: the number of lags of the allowed filter\n%\n% Output:\n% - s_target: row vector of length T containing the target source(s)\n% contribution,\n% - e_interf: row vector of length T containing the interferences\n% contribution,\n% - e_noise: row vector of length T containing the noise contribution (if\n% any),\n% - e_artif: row vector of length T containing the artifacts\n% contribution.\n%\n% Developers: - Cedric Fevotte (fevotte@tsi.enst.fr) - Emmanuel Vincent\n% (emmanuel.vincent@irisa.fr) - Remi Gribonval (remi.gribonval@irisa.fr)\n\nse=varargin{1}; index=varargin{2}; S=varargin{3};\n \nswitch nargin\n case 4\n N=[];\n L=varargin{4};\n case 5\n N=varargin{4};\n L=varargin{5};\n otherwise\n disp('Wrong number of arguments.')\nend\n \n[ne,Te]=size(se);\n[n,T]=size(S);\n\n%%%%%%%%%% WARNINGS %%%%%%%%%%%%%\nswitch isempty(N)\n case 1\n if n>T | ne>Te, disp('Watch out: signals must be in rows.'), return; end \n if ne~=1, disp('Watch out: se must contain only one row.'), return; end\n if T~=Te, disp('Watch out: se and S have different lengths.'), return; end \n case 0\n [m,Tm]=size(N); \n if n>T | ne>Te | m>Tm, disp('Watch out: signals must be in rows.'), return; end \n if ne~=1, disp('Watch out: se must contain only one row.'), return; end\n if T~=Te, disp('Watch out: S and Se have different lengths.'), return; end \n if T~=Tm, disp('Watch out: N, S and Se have different lengths.'), return; end \nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Create the space of target source(s)\ntarget_space=bss_make_lags(S(index,:),L); \n% Create the space of sources\nsources_space=bss_make_lags(S,L);\n% Create the noise space\nnoise_space=bss_make_lags(N,L);\n\ns_target=zeros(1,T);\ne_interf=zeros(1,T);\ne_artif=zeros(1,T);\nif isempty(noise_space)==0, e_noise=zeros(1,T); end\n\n%%% Target source(s) contribution %%%\ns_target = bss_proj(se,target_space);\n\n%%% Interferences contribution %%%\nP_S_se = bss_proj(se,sources_space);\ne_interf = P_S_se - s_target;\n\nswitch isempty(noise_space)\n case 1 % No noise\n %%% Artifacts contribution %%%\n e_artif= se - P_S_se;\n \n %%% Output %%%\n varargout{1}=s_target;\n varargout{2}=e_interf;\n varargout{3}=e_artif;\n \n case 0 % Noise\n %%% Noise contribution %%%\n P_SN_se= bss_proj(se,[sources_space;noise_space]);\n e_noise=P_SN_se-P_S_se;\n \n %%% Artifacts contribution %%% \n e_artif=se-P_SN_se;\n \n %%% Output %%%\n varargout{1}=s_target;\n varargout{2}=e_interf;\n varargout{3}=e_noise;\n varargout{4}=e_artif; \nend \n", "meta": {"author": "posenhuang", "repo": "deeplearningsourceseparation", "sha": "6a6e54d9234756e9624507f66d9e8fcd0b868dc7", "save_path": "github-repos/MATLAB/posenhuang-deeplearningsourceseparation", "path": "github-repos/MATLAB/posenhuang-deeplearningsourceseparation/deeplearningsourceseparation-6a6e54d9234756e9624507f66d9e8fcd0b868dc7/tools/bss_eval_2.1/bss_decomp_filt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4939495255012386}} {"text": "function ActiveImportanceSampling = activeimportancesampling_vbmc(vp,gp,acqfun,acqinfo,options)\n%ACTIVEIMPORTANCESAMPLING_VBMC Setup importance sampling acquisition functions\n\n% This function samples from the base importance sampling (IS) density in\n% three steps:\n% 1) Use importance sampling-resampling (ISR) to sample from the\n% base IS density based on a proposal distribuion which is a mixture of\n% a smoothed variational posterior and on box-uniform mixture centered \n% around the current training points\n% 2) Optionally use MCMC initialized with the ISR samples to sample from \n% the base IS density\n% 3) Compute IS statistics and book-keeping\n\n% Does the importance sampling step use the variational posterior?\nisamplevp_flag = isfield(acqinfo,'importance_sampling_vp') ...\n && acqinfo.importance_sampling_vp;\n\n% Do we simply sample from the variational posterior?\nonlyvp_flag = isfield(acqinfo,'variational_importance_sampling') ...\n && acqinfo.variational_importance_sampling;\n\nD = size(gp.X,2);\n\nNs_gp = numel(gp.post); % # GP hyperparameter samples\n\n% Input space bounds and typical scales (for MCMC only)\nwidths = std(gp.X,[],1);\nMaxBnd = 0.5;\ndiam = max(gp.X) - min(gp.X);\nLB = min(gp.X) - MaxBnd*diam;\nUB = max(gp.X) + MaxBnd*diam;\n\nActiveImportanceSampling.lnw = [];\nActiveImportanceSampling.Xa = [];\nActiveImportanceSampling.fs2a = [];\n\nif onlyvp_flag\n %% Step 0: Simply sample from the variational posterior\n \n if ischar(options.ActiveImportanceSamplingMCMCSamples)\n K = vp.K;\n nvars = D;\n Na = ceil(eval(options.ActiveImportanceSamplingMCMCSamples));\n elseif isscalar(options.ActiveImportanceSamplingMCMCSamples)\n Na = ceil(options.ActiveImportanceSamplingMCMCSamples);\n else\n Na = 0;\n end\n \n if ~isfinite(Na) || ~isscalar(Na) || Na <= 0\n error('OPTIONS.ActiveImportanceSamplingMCMCSamples should be (or evaluate to) a positive integer.');\n end\n \n Xa = vbmc_rnd(vp,Na,0);\n [~,~,fmu,fs2] = gplite_pred(gp,Xa,[],[],1,0); \n \n if isfield(acqinfo,'mcmc_importance_sampling') && acqinfo.mcmc_importance_sampling\n \n % Compute fractional effective sample size (ESS)\n fESS = fess_vbmc(vp,fmu,Xa);\n \n % If fESS is less than thresh ==> major mismatch, do MCMC\n if fESS < options.ActiveImportanceSamplingfESSThresh\n Xa_old = Xa; \n \n if isamplevp_flag\n logpfun = @(x) log_isbasefun(x,acqfun,gp,vp);\n else\n logpfun = @(x) log_isbasefun(x,acqfun,gp,[]);\n end\n \n % Get MCMC options\n Nmcmc_samples = Na*options.ActiveImportanceSamplingMCMCThin;\n thin = 1;\n burnin = 0;\n sampleopts = get_mcmcopts([],thin,burnin);\n logPfuns = logpfun;\n W = Na; % # walkers\n\n % Perform a single MCMC step for all samples\n Xa = eissample_lite(logPfuns,Xa,Nmcmc_samples,W,widths,LB,UB,sampleopts);\n Xa = Xa(end-Na+1:end,:);\n [~,~,fmu,fs2] = gplite_pred(gp,Xa,[],[],1,0); \n \n if 0\n hold off;\n scatter(Xa_old(:,1),Xa_old(:,2),'b'); hold on;\n scatter(Xa(:,1),Xa(:,2),'k'); hold on;\n drawnow;\n end\n end\n end\n \n if isamplevp_flag\n vlnpdf = max(vbmc_pdf(vp,Xa,0,1),log(realmin));\n lny = acqfun('islogf1',vlnpdf,[],[],fmu,fs2);\n else\n lny = acqfun('islogf1',[],[],[],fmu,fs2);\n end\n\n ActiveImportanceSampling.fs2a = fs2;\n ActiveImportanceSampling.lnw = lny';\n ActiveImportanceSampling.Xa = Xa;\n \nelse\n %% Step 1: Importance sampling-resampling\n\n Nvp_samples = options.ActiveImportanceSamplingVPSamples;\n Nbox_samples = options.ActiveImportanceSamplingBoxSamples;\n w_vp = Nvp_samples/(Nvp_samples + Nbox_samples);\n\n rect_delta = 2*std(gp.X);\n\n % Smoothed posterior for importance sampling-resampling\n if Nvp_samples > 0 \n scale_vec = [0.05,0.2,1];\n %scale = sqrt(mean(var(gp.X,[],1)));\n\n vp_is = vp;\n for ii = 1:numel(scale_vec)\n vp_is.K = vp_is.K + vp.K;\n vp_is.w = [vp_is.w, vp.w];\n vp_is.mu = [vp_is.mu, vp.mu];\n vp_is.sigma = [vp_is.sigma, sqrt(vp.sigma.^2 + scale_vec(ii)^2)];\n end\n vp_is.w = vp_is.w/sum(vp_is.w);\n\n % Sample from smoothed posterior\n Xa_vp = vbmc_rnd(vp_is,Nvp_samples,0,0);\n [lnw,fs2a_vp] = activesample_proposalpdf(Xa_vp,gp,vp_is,w_vp,rect_delta,acqfun,vp,isamplevp_flag);\n ActiveImportanceSampling.lnw = [ActiveImportanceSampling.lnw, lnw'];\n ActiveImportanceSampling.Xa = [ActiveImportanceSampling.Xa; Xa_vp];\n ActiveImportanceSampling.fs2a = [ActiveImportanceSampling.fs2a; fs2a_vp];\n else\n vp_is = [];\n end\n\n % Box-uniform sampling around training inputs\n if Nbox_samples > 0\n jj = randi(size(gp.X,1),[1,Nbox_samples]);\n Xa_box = gp.X(jj,:) + bsxfun(@times,2*rand(numel(jj),D)-1,rect_delta);\n [lnw,fs2a_box] = activesample_proposalpdf(Xa_box,gp,vp_is,w_vp,rect_delta,acqfun,vp,isamplevp_flag);\n ActiveImportanceSampling.lnw = [ActiveImportanceSampling.lnw, lnw'];\n ActiveImportanceSampling.Xa = [ActiveImportanceSampling.Xa; Xa_box];\n ActiveImportanceSampling.fs2a = [ActiveImportanceSampling.fs2a; fs2a_box];\n end\n\n ActiveImportanceSampling.lnw(~isfinite(ActiveImportanceSampling.lnw)) = -Inf;\n % optimState.w = exp(optimState.lnw - max(optimState.lnw))';\n % optimState.w = optimState.w / sum(optimState.w);\n % 1./sum(optimState.w.^2)\n\n %% Step 2 (optional): MCMC sample\n\n Nmcmc_samples = options.ActiveImportanceSamplingMCMCSamples;\n \n if Nmcmc_samples > 0\n \n ActiveImportanceSampling_old = ActiveImportanceSampling; \n \n ActiveImportanceSampling.lnw = zeros(Ns_gp,Nmcmc_samples);\n ActiveImportanceSampling.Xa = zeros(Nmcmc_samples,D,Ns_gp);\n ActiveImportanceSampling.fs2a = zeros(Nmcmc_samples,Ns_gp); \n \n\n gp1 = gp; % Consider only one GP sample at a time\n \n for s = 1:Ns_gp\n \n gp1.post = []; % Assign current GP sample\n gp1.post = gp.post(s);\n \n if D == 2 && 0\n % We could use a quasi-random grid for D <= 2, but not implemented\n Xa = rand(Na,D).*(UB - LB) + LB;\n [~,~,fmu,optimState.fs2a] = gplite_pred(gp1,Xa,[],[],1,0); \n optimState.lnw = mean(fmu,2)';\n optimState.Xa = Xa; \n else\n if isamplevp_flag\n logpfun = @(x) log_isbasefun(x,acqfun,gp1,vp);\n else\n logpfun = @(x) log_isbasefun(x,acqfun,gp1,[]);\n end\n\n % Get MCMC options\n thin = options.ActiveImportanceSamplingMCMCThin;\n burnin = ceil(thin*Nmcmc_samples/2);\n sampleopts = get_mcmcopts(Nmcmc_samples,thin,burnin);\n \n logPfuns = logpfun;\n % sampleopts.TransitionOperators = {'transSliceSampleRD'};\n W = 2*(D+1); % # walkers\n\n if 0\n % Take starting points from high posterior density region\n hpd_frac = 0.5;\n N = numel(gp1.y);\n N_hpd = min(N,max(W,round(hpd_frac*N)));\n [~,ord] = sort(gp1.y,'descend');\n X_hpd = gp1.X(ord(1:N_hpd),:);\n x0 = X_hpd(randperm(N_hpd,min(W,N_hpd)),:);\n x0 = bsxfun(@min,bsxfun(@max,x0,LB),UB);\n else\n % Use importance sampling-resampling\n [~,~,fmu,fs2] = gplite_pred(gp1,ActiveImportanceSampling_old.Xa,[],[],1,0); \n lnw = ActiveImportanceSampling_old.lnw(s,:) + acqfun('islogf2',[],[],[],fmu,fs2)';\n w = exp(bsxfun(@minus,lnw,max(lnw,[],2)));\n x0 = zeros(W,D);\n for ii = 1:W\n idx = catrnd(w,1);\n w(idx) = 0;\n x0(ii,:) = ActiveImportanceSampling_old.Xa(idx,:);\n end\n end\n\n [Xa,logp] = eissample_lite(logPfuns,x0,Nmcmc_samples,W,widths,LB,UB,sampleopts);\n [~,~,fmu,fs2] = gplite_pred(gp1,Xa,[],[],1,0); \n\n % Fixed log weight for importance sampling (log fixed integrand)\n if isamplevp_flag\n vlnpdf = max(vbmc_pdf(vp,Xa,0,1),log(realmin)); \n lny = acqfun('islogf1',vlnpdf,[],[],fmu,fs2);\n else\n lny = acqfun('islogf1',[],[],[],fmu,fs2);\n end\n % lny = lny - warpvars_vbmc(Xa,'logp',vp.trinfo);\n\n ActiveImportanceSampling.fs2a(:,s) = fs2;\n ActiveImportanceSampling.lnw(s,:) = bsxfun(@minus,lny',logp');\n ActiveImportanceSampling.Xa(:,:,s) = Xa;\n end\n\n end\n end\nend\n\nif 0\n hold off;\n scatter(ActiveImportanceSampling.Xa(:,1),ActiveImportanceSampling.Xa(:,2)); hold on;\n % scatter(x0(:,1),x0(:,2),'ro','MarkerFaceColor','r')\n xlim([-2,2]);\n ylim([-2,2]);\n drawnow;\nend\n\n%% Step 3: Pre-compute quantities for importance sampling calculations\n\n% Precompute cross-kernel matrix on importance points\nKax_mat = zeros(size(ActiveImportanceSampling.Xa,1),size(gp.X,1),Ns_gp);\nCtmp_mat = zeros(size(gp.X,1),size(ActiveImportanceSampling.Xa,1),Ns_gp);\nfor s = 1:Ns_gp\n if size(ActiveImportanceSampling.Xa,3) == 1\n Xa = ActiveImportanceSampling.Xa;\n else\n Xa(:,:) = ActiveImportanceSampling.Xa(:,:,s);\n end\n hyp = gp.post(s).hyp;\n L = gp.post(s).L;\n Lchol = gp.post(s).Lchol;\n sn2_eff = 1/gp.post(s).sW(1)^2;\n if gp.covfun(1) == 1 % Hard-coded SE-ard for speed\n ell = exp(hyp(1:D))';\n sf2 = exp(2*hyp(D+1)); \n Kax_tmp = sq_dist(Xa*diag(1./ell),gp.X*diag(1./ell));\n Kax_mat(:,:,s) = sf2 * exp(-Kax_tmp/2); \n else\n error('Other covariance functions not supported yet.');\n end\n \n if Lchol\n Ctmp_mat(:,:,s) = (L\\(L'\\Kax_mat(:,:,s)'))/sn2_eff;\n else\n Ctmp_mat(:,:,s) = (L*Kax_mat(:,:,s)'); \n end \nend\nActiveImportanceSampling.Kax_mat = Kax_mat;\nActiveImportanceSampling.Ctmp_mat = Ctmp_mat;\n\n% Precompute integrated mean basis function on importance points\nif isfield(gp,'intmeanfun') && gp.intmeanfun > 0\n plus_idx = gp.intmeanfun_var > 0; \n if size(ActiveImportanceSampling.Xa,3) == 1\n Ha = gplite_intmeanfun(ActiveImportanceSampling.Xa,gp.intmeanfun);\n ActiveImportanceSampling.Ha = Ha(plus_idx,:);\n else\n for s = 1:Ns_gp\n Ha = gplite_intmeanfun(ActiveImportanceSampling.Xa(:,:,s),gp.intmeanfun);\n ActiveImportanceSampling.Ha(:,:,s) = Ha(plus_idx,:);\n end\n end\nend\n\n\nend\n\n%--------------------------------------------------------------------------\nfunction [lnw,fs2] = activesample_proposalpdf(Xa,gp,vp_is,w_vp,rect_delta,acqfun,vp,isamplevp_flag)\n%ACTIVESAMPLE_PROPOSALPDF Compute importance weights for proposal pdf\n\n[N,D] = size(gp.X);\nNa = size(Xa,1);\n\n[~,~,fmu,fs2] = gplite_pred(gp,Xa,[],[],1,0);\n\nNtot = 1 + N; % Total number of mixture elements\n\nif w_vp < 1; templpdf = zeros(Na,Ntot); end\n\n% Mixture of variational posteriors\nif w_vp > 0\n logflag = true;\n templpdf(:,1) = vbmc_pdf(vp_is,Xa,0,logflag) + log(w_vp);\nelse\n templpdf(:,1) = -Inf;\nend\n\n% Fixed log weight for importance sampling (log fixed integrand)\nif isamplevp_flag\n vlnpdf = max(vbmc_pdf(vp,Xa,0,1),log(realmin));\n lny = acqfun('islogf1',vlnpdf,[],[],fmu,fs2);\nelse\n lny = acqfun('islogf1',[],[],[],fmu,fs2);\nend\n% lny = lny - warpvars_vbmc(Xa,'logp',vp.trinfo);\n\n% Mixture of box-uniforms\nif w_vp < 1\n VV = prod(2*rect_delta);\n\n for ii = 1:N\n templpdf(:,ii+1) = log(all(abs(bsxfun(@minus,Xa,gp.X(ii,:))) < rect_delta,2) / VV / N * (1 - w_vp));\n end\n\n mmax = max(templpdf,[],2);\n lpdf = log(sum(exp(templpdf - mmax),2));\n lnw = bsxfun(@minus,lny,lpdf + mmax);\nelse\n lnw = bsxfun(@minus,lny,templpdf);\nend\n\nend\n\n%--------------------------------------------------------------------------\nfunction y = log_isbasefun(x,acqfun,gp,vp)\n%LOG_ISBASEFUN Base importance sampling proposal log pdf\n\n[fmu,fs2] = gplite_pred(gp,x);\nif isempty(vp)\n y = acqfun('islogf',[],[],[],fmu,fs2);\nelse\n vlnpdf = max(vbmc_pdf(vp,x,0,1),log(realmin));\n y = acqfun('islogf',vlnpdf,[],[],fmu,fs2);\nend\n\nend\n\n\n%--------------------------------------------------------------------------\n%SQ_DIST Compute matrix of all pairwise squared distances between two sets \n% of vectors, stored in the columns of the two matrices, a (of size n-by-D) \n% and b (of size m-by-D).\nfunction C = sq_dist(a,b)\n\nn = size(a,1);\nm = size(b,1);\nmu = (m/(n+m))*mean(b,1) + (n/(n+m))*mean(a,1);\na = bsxfun(@minus,a,mu); b = bsxfun(@minus,b,mu);\nC = bsxfun(@plus,sum(a.*a,2),bsxfun(@minus,sum(b.*b,2)',2*a*b'));\nC = max(C,0);\n\nend\n\n%--------------------------------------------------------------------------\nfunction sampleopts = get_mcmcopts(Ns,thin,burnin)\n%GET_MCMCOPTS Get standard MCMC options.\n\nif nargin < 2 || isempty(thin); thin = 1; end\nif nargin < 3; burnin = []; end\n\nsampleopts.Thin = thin;\nif isempty(burnin)\n sampleopts.Burnin = ceil(sampleopts.Thin*Ns/2);\nelse\n sampleopts.Burnin = burnin;\nend\nsampleopts.Display = 'off';\nsampleopts.Diagnostics = false;\nsampleopts.VarTransform = false;\nsampleopts.InversionSample = false;\nsampleopts.FitGMM = false;\n\nend\n\n%--------------------------------------------------------------------------\nfunction x = catrnd(p,n)\n%CATRND Sample from categorical distribution.\n\nmaxel = 1e6;\nNel = n*numel(p);\nstride = ceil(maxel/numel(p));\n\ncdf(1,:) = cumsum(p);\nu = rand(n,1)*cdf(end);\n\n% Split for memory reasons\nif Nel <= maxel\n x = sum(bsxfun(@lt, cdf, u),2) + 1;\nelse\n x = zeros(n,1);\n idx_min = 1;\n while idx_min <= n\n idx_max = min(idx_min+stride-1,n);\n idx = idx_min:idx_max;\n x(idx) = sum(bsxfun(@lt, cdf, u(idx)),2) + 1;\n idx_min = idx_max+1;\n end\nend\n\nend\n", "meta": {"author": "acerbilab", "repo": "vbmc", "sha": "54ba2cdd6c11d2595b9613557da14573abbb7b92", "save_path": "github-repos/MATLAB/acerbilab-vbmc", "path": "github-repos/MATLAB/acerbilab-vbmc/vbmc-54ba2cdd6c11d2595b9613557da14573abbb7b92/private/activeimportancesampling_vbmc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.49390236647948293}} {"text": "function [V, converged, i] = newtonpf_I_cart(Ybus, Sbus, V0, ref, pv, pq, mpopt)\n%NEWTONPF_I_CART Solves power flow using full Newton's method (current/cartesian)\n% [V, CONVERGED, I] = NEWTONPF_I_CART(YBUS, SBUS, V0, REF, PV, PQ, MPOPT)\n%\n% Solves for bus voltages using a full Newton-Raphson method, using nodal\n% current balance equations and cartesian coordinate representation of\n% voltages, given the following inputs:\n% YBUS - full system admittance matrix (for all buses)\n% SBUS - handle to function that returns the complex bus power\n% injection vector (for all buses), given the bus voltage\n% magnitude vector (for all buses)\n% V0 - initial vector of complex bus voltages\n% REF - bus index of reference bus (voltage ang reference & gen slack)\n% PV - vector of bus indices for PV buses\n% PQ - vector of bus indices for PQ buses\n% MPOPT - (optional) MATPOWER option struct, used to set the\n% termination tolerance, maximum number of iterations, and\n% output options (see MPOPTION for details).\n%\n% The bus voltage vector contains the set point for generator\n% (including ref bus) buses, and the reference angle of the swing\n% bus, as well as an initial guess for remaining magnitudes and\n% angles.\n%\n% Returns the final complex voltages, a flag which indicates whether it\n% converged or not, and the number of iterations performed.\n%\n% See also RUNPF, NEWTONPF, NEWTONPF_S_CART, NEWTONPF_I_POLAR.\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%% default arguments\nif nargin < 7\n mpopt = mpoption;\nend\n\n%% options\ntol = mpopt.pf.tol;\nmax_it = mpopt.pf.nr.max_it;\nlin_solver = mpopt.pf.nr.lin_solver;\n\n%% initialize\nconverged = 0;\ni = 0;\nV = V0;\nVm = abs(V);\nVmpv = Vm(pv);\nn = length(V0);\n\n%% set up indexing for updating V\nnpv = length(pv);\nnpq = length(pq);\nj1 = 1; j2 = npv; %% j1:j2 - Q of pv buses\nj3 = j2 + 1; j4 = j2 + npq; %% j3:j4 - Vr of pq buses\nj5 = j4 + 1; j6 = j4 + npv; %% j5:j6 - Vr of pv buses\nj7 = j6 + 1; j8 = j6 + npq; %% j7:j8 - Vi of pq buses\nj9 = j8 + 1; j10= j8 + npv; %% j9:j10- Vi of pv buses\n\n%% evaluate F(x0)\nSb = Sbus(Vm);\nSb(pv) = real(Sb(pv)) + 1j * imag(V(pv) .* conj(Ybus(pv, :) * V));\nmis = Ybus * V - conj(Sb ./ V);\nF = [ real(mis([pv; pq]));\n imag(mis([pv; pq]));\n V(pv) .* conj(V(pv)) - Vmpv.^2 ];\n\n%% check tolerance\nnormF = norm(F, inf);\nif mpopt.verbose > 1\n fprintf('\\n it max Ir & Ii mismatch (p.u.)');\n fprintf('\\n---- ---------------------------');\n fprintf('\\n%3d %10.3e', i, normF);\nend\nif normF < tol\n converged = 1;\n if mpopt.verbose > 1\n fprintf('\\nConverged!\\n');\n end\nend\n\n%% attempt to pick fastest linear solver, if not specified\nif isempty(lin_solver)\n nx = length(F);\n if nx <= 10 || have_feature('octave')\n lin_solver = '\\'; %% default \\ operator\n else %% MATLAB and nx > 10 or Octave and nx > 2000\n lin_solver = 'LU3'; %% LU decomp with 3 output args, AMD ordering\n end\nend\n\n%% do Newton iterations\nwhile (~converged && i < max_it)\n %% update iteration counter\n i = i + 1;\n\n %% evaluate Jacobian\n dImis_dQ = sparse(pv, pv, 1j./conj(V(pv)), n, n);\n dV2_dVr = sparse(1:npv, npq+(1:npv), 2*real(V(pv)), npv, npv+npq);\n dV2_dVi = sparse(1:npv, npq+(1:npv), 2*imag(V(pv)), npv, npv+npq);\n [dImis_dVr, dImis_dVi] = dImis_dV(Sb, Ybus, V, 1);\n\n %% handling of derivatives for voltage dependent loads\n %% (not yet implemented) goes here\n\n j11 = real(dImis_dQ([pv; pq], pv));\n j12 = real(dImis_dVr([pv; pq], [pq; pv]));\n j13 = real(dImis_dVi([pv; pq], [pq; pv]));\n j21 = imag(dImis_dQ([pv; pq], pv));\n j22 = imag(dImis_dVr([pv; pq], [pq; pv]));\n j23 = imag(dImis_dVi([pv; pq], [pq; pv]));\n j31 = sparse(npv, npv);\n j32 = dV2_dVr;\n j33 = dV2_dVi;\n\n J = [ j11 j12 j13;\n j21 j22 j23;\n j31 j32 j33; ];\n\n %% compute update step\n dx = mplinsolve(J, -F, lin_solver);\n\n %% update voltage\n if npv\n V(pv) = V(pv) + dx(j5:j6) + 1j * dx(j9:j10);\n Sb(pv) = real(Sb(pv)) + 1j * (imag(Sb(pv)) + dx(j1:j2));\n end\n if npq\n V(pq) = V(pq) + dx(j3:j4) + 1j * dx(j7:j8);\n end\n\n %% evalute F(x)\n mis = Ybus * V - conj(Sb ./ V);\n F = [ real(mis([pv; pq]));\n imag(mis([pv; pq]));\n V(pv) .* conj(V(pv)) - Vmpv.^2 ];\n\n %% check for convergence\n normF = norm(F, inf);\n if mpopt.verbose > 1\n fprintf('\\n%3d %10.3e', i, normF);\n end\n if normF < tol\n converged = 1;\n if mpopt.verbose\n fprintf('\\nNewton''s method power flow (current balance, cartesian) converged in %d iterations.\\n', i);\n end\n end\nend\n\nif mpopt.verbose\n if ~converged\n fprintf('\\nNewton''s method power flow (current balance, cartesian) did not converge in %d iterations.\\n', i);\n end\nend\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/newtonpf_I_cart.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4939023664794828}} {"text": "% Zhou, Zongwei, et al. \"Fine-tuning convolutional neural networks for biomedical image analysis: actively and incrementally.\" \n% IEEE conference on computer vision and pattern recognition, Hawaii. 2017.\n\n% Author: [Zongwei Zhou](http://www.zongweiz.com)\n% Email: zongweiz@asu.edu\n% Last modified: Jan.26.2017\n\n%% Table 1. examples of seven different patterns\n% Relationships among seven prediction patterns and six AIFT methods in active candidate selection. We assume that\n% a candidate has 11 patches, and their probabilities predicted by the current CNN are listed in Column 2. AIFT Entropyα,\n% Diversityα, and (Entropy+Diversity)α operate on the top or bottom α percent of the candidate’s patches based on the majority\n% prediction as described in Sec. 3.3. In this illustration, we choose α to be 1/4, meaning that the selection criterion (Eq. 3) is\n% computed based on 3 patches within each candidate. The first choice of each method is highlighted in yellow and the second\n% choice is in light yellow.\n\nfunction Alg_Analysis()\n\nclose all; clear; clc;\n\n\n% A, B, C, D, E, F represents outputs from CNN after Softmax Layer belong to one candidate.\nA = [0.4 0.4 0.4 0.5 0.5 0.5 0.5 0.5 0.5 0.6 0.6];\nB = [0.0 0.1 0.2 0.3 0.4 0.4 0.6 0.7 0.8 1.0 1.0];\nC = [0.0 0.0 0.0 0.1 0.1 0.9 0.9 1.0 1.0 1.0 1.0];\nD = [1.0 1.0 1.0 1.0 1.0 1.0 1.0 0.9 0.9 0.9 0.9];\nE = [0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.1 0.1 0.1 0.1];\nF = [0.0 0.0 0.1 0.1 0.1 0.1 0.2 0.2 0.3 0.9 1.0];\nG = [0.0 0.1 0.7 0.8 0.8 0.9 0.9 0.9 0.9 1.0 1.0];\n\n%% Produce values in Table 1 by row pattern A\ndisp('Table 1. pattern A');\ndisp(['Entropy_A = ', num2str(roundn(compute_matrix(A, 1, 0, 1), -2))]);\ndisp(['Entropy^1/4_A = ', num2str(roundn(compute_matrix(A, 1, 0, 0.25), -2))]);\ndisp(['Diversity_A = ', num2str(roundn(compute_matrix(A, 0, 1, 1), -2))]);\ndisp(['Diversity^1/4_A = ', num2str(roundn(compute_matrix(A, 0, 1, 0.25), -2))]);\ndisp(['(Entropy+Diversity)_A = ', num2str(roundn(compute_matrix(A, 1, 1, 1), -2))]);\ndisp(['(Entropy+Diversity)^1/4_A = ', num2str(roundn(compute_matrix(A, 1, 1, 0.25), -2))]);\ndisp(' ');\n\n%% Produce values in Table 1 by row pattern B\ndisp('Table 1. pattern B');\ndisp(['Entropy_B = ', num2str(roundn(compute_matrix(B, 1, 0, 1), -2))]);\ndisp(['Entropy^1/4_B = ', num2str(roundn(compute_matrix(B, 1, 0, 0.25), -2))]);\ndisp(['Diversity_B = ', num2str(roundn(compute_matrix(B, 0, 1, 1), -2))]);\ndisp(['Diversity^1/4_B = ', num2str(roundn(compute_matrix(B, 0, 1, 0.25), -2))]);\ndisp(['(Entropy+Diversity)_B = ', num2str(roundn(compute_matrix(B, 1, 1, 1), -2))]);\ndisp(['(Entropy+Diversity)^1/4_B = ', num2str(roundn(compute_matrix(B, 1, 1, 0.25), -2))]);\ndisp(' ');\n\n%% Produce values in Table 1 by row pattern C\ndisp('Table 1. pattern C');\ndisp(['Entropy_C = ', num2str(roundn(compute_matrix(C, 1, 0, 1), -2))]);\ndisp(['Entropy^1/4_C = ', num2str(roundn(compute_matrix(C, 1, 0, 0.25), -2))]);\ndisp(['Diversity_C = ', num2str(roundn(compute_matrix(C, 0, 1, 1), -2))]);\ndisp(['Diversity^1/4_C = ', num2str(roundn(compute_matrix(C, 0, 1, 0.25), -2))]);\ndisp(['(Entropy+Diversity)_C = ', num2str(roundn(compute_matrix(C, 1, 1, 1), -2))]);\ndisp(['(Entropy+Diversity)^1/4_C = ', num2str(roundn(compute_matrix(C, 1, 1, 0.25), -2))]);\ndisp(' ');\n\n%% Produce values in Table 1 by row pattern D\ndisp('Table 1. pattern D');\ndisp(['Entropy_D = ', num2str(roundn(compute_matrix(D, 1, 0, 1), -2))]);\ndisp(['Entropy^1/4_D = ', num2str(roundn(compute_matrix(D, 1, 0, 0.25), -2))]);\ndisp(['Diversity_D = ', num2str(roundn(compute_matrix(D, 0, 1, 1), -2))]);\ndisp(['Diversity^1/4_D = ', num2str(roundn(compute_matrix(D, 0, 1, 0.25), -2))]);\ndisp(['(Entropy+Diversity)_D = ', num2str(roundn(compute_matrix(D, 1, 1, 1), -2))]);\ndisp(['(Entropy+Diversity)^1/4_D = ', num2str(roundn(compute_matrix(D, 1, 1, 0.25), -2))]);\ndisp(' ');\n\n%% Produce values in Table 1 by row pattern E\ndisp('Table 1. pattern E');\ndisp(['Entropy_E = ', num2str(roundn(compute_matrix(E, 1, 0, 1), -2))]);\ndisp(['Entropy^1/4_E = ', num2str(roundn(compute_matrix(E, 1, 0, 0.25), -2))]);\ndisp(['Diversity_E = ', num2str(roundn(compute_matrix(E, 0, 1, 1), -2))]);\ndisp(['Diversity^1/4_E = ', num2str(roundn(compute_matrix(E, 0, 1, 0.25), -2))]);\ndisp(['(Entropy+Diversity)_E = ', num2str(roundn(compute_matrix(E, 1, 1, 1), -2))]);\ndisp(['(Entropy+Diversity)^1/4_E = ', num2str(roundn(compute_matrix(E, 1, 1, 0.25), -2))]);\ndisp(' ');\n\n%% Produce values in Table 1 by row pattern F\ndisp('Table 1. pattern F');\ndisp(['Entropy_F = ', num2str(roundn(compute_matrix(F, 1, 0, 1), -2))]);\ndisp(['Entropy^1/4_F = ', num2str(roundn(compute_matrix(F, 1, 0, 0.25), -2))]);\ndisp(['Diversity_F = ', num2str(roundn(compute_matrix(F, 0, 1, 1), -2))]);\ndisp(['Diversity^1/4_F = ', num2str(roundn(compute_matrix(F, 0, 1, 0.25), -2))]);\ndisp(['(Entropy+Diversity)_F = ', num2str(roundn(compute_matrix(F, 1, 1, 1), -2))]);\ndisp(['(Entropy+Diversity)^1/4_F = ', num2str(roundn(compute_matrix(F, 1, 1, 0.25), -2))]);\ndisp(' ');\n\n%% Produce values in Table 1 by row pattern G\ndisp('Table 1. pattern G');\ndisp(['Entropy_G = ', num2str(roundn(compute_matrix(G, 1, 0, 1), -2))]);\ndisp(['Entropy^1/4_G = ', num2str(roundn(compute_matrix(G, 1, 0, 0.25), -2))]);\ndisp(['Diversity_G = ', num2str(roundn(compute_matrix(G, 0, 1, 1), -2))]);\ndisp(['Diversity^1/4_G = ', num2str(roundn(compute_matrix(G, 0, 1, 0.25), -2))]);\ndisp(['(Entropy+Diversity)_G = ', num2str(roundn(compute_matrix(G, 1, 1, 1), -2))]);\ndisp(['(Entropy+Diversity)^1/4_G = ', num2str(roundn(compute_matrix(G, 1, 1, 0.25), -2))]);\ndisp(' ');\n\n\n% %% Visualize the diversity equation\n% x = 0:0.01:1;\n% y = 0:0.01:1;\n% [x,y] = meshgrid(x,y);\n% div = (x-y).*log(x./(y+eps))+(y-x).*log((1-x)./(1-y+eps));\n% mesh(x,y,div)\n\nend\n\n%% Compute matrix R (Eq. 3 in the paper)\nfunction [S] = compute_matrix(p, lamda_1, lamda_2, alpha)\n\n% lamda_1 and lamda_2 are trade-offs between entropy and diversity\n% lamda_1: turn on/off entropy (1 or 0)\n% lamda_2: turn on/off diversity (1 or 0)\n\n\n% Handling noisy labels via majority selection (see Sec 3.3)\ntop = round(length(p) * alpha);\np = Majority(p,top);\n\n% Initialize the R matrix\nR = zeros(length(p));\nfor i = 1:length(p)\n for j = 1:i\n if i == j % entropy computed for diagonal of R\n R(i,i) = - lamda_1 * (p(i)*log(p(i)+eps)+(1-p(i))*log(1-p(i)+eps));\n else % diversity computed for rest of R\n R(i,j) = lamda_2 * ((p(i)-p(j)) * log((p(i)+eps)/(p(j)+eps)) + ...\n (1-p(i)-1+p(j)) * log((1-p(i)+eps)/(1-p(j)+eps)));\n R(j,i) = R(i,j);\n end\n end\nend\n\n% Compute active selecting value from matrix R for this candidate\n% by numerical sum of R (see Alg 1 line 11)\nS = sum(R(:));\n\n\nend\n\n\n%% Sec 3.3. Handling noisy labels via majority selection\n% eq. 4, calculate the mean and sort based on dominate predictions.\nfunction [p] = Majority(p,top)\n\nm = mean(p);\nif m > 0.5\n p = sort(p,'descend');\nelse\n p = sort(p,'ascend');\nend\np = p(1:top);\n\nend", "meta": {"author": "MrGiovanni", "repo": "Active-Learning", "sha": "9f15638cbeadd98b6056318405d01ec0dcc4aa49", "save_path": "github-repos/MATLAB/MrGiovanni-Active-Learning", "path": "github-repos/MATLAB/MrGiovanni-Active-Learning/Active-Learning-9f15638cbeadd98b6056318405d01ec0dcc4aa49/active_select_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208004, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.49388648050002043}} {"text": "load('table_T.mat')\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Params for UAV\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%% UAV == Zagi\n% p_drone.mass = 1.56;\n% p_drone.Jx = 0.1147;\n% p_drone.Jy = 0.0576;\n% p_drone.Jz = 0.1712;\n% p_drone.Jxz = 0.0015;\n\n\n%%% UAV == Aerosonde\np_drone.mass = 13.5;\np_drone.Jx = 0.8244;\np_drone.Jy = 1.135;\np_drone.Jz = 1.759;\np_drone.Jxz = .1204;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Compute gammas\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\np_drone.gamma = p_drone.Jx*p_drone.Jz - p_drone.Jxz^2;\np_drone.gamma1 = p_drone.Jxz*(p_drone.Jx-p_drone.Jy+p_drone.Jz)/p_drone.gamma;\np_drone.gamma2 = (p_drone.Jz*(p_drone.Jz-p_drone.Jy)+p_drone.Jxz^2)/p_drone.gamma;\np_drone.gamma3 = p_drone.Jz/p_drone.gamma;\np_drone.gamma4 = p_drone.Jxz/p_drone.gamma;\np_drone.gamma5 = (p_drone.Jz-p_drone.Jx)/p_drone.Jy;\np_drone.gamma6 = p_drone.Jxz/p_drone.Jy;\np_drone.gamma7 = ((p_drone.Jx-p_drone.Jy)*p_drone.Jx+p_drone.Jxz^2)/p_drone.gamma;\np_drone.gamma8 = p_drone.Jx/p_drone.gamma;\n\n% Aerodynamic coefficients\np_drone.S_wing = 0.55; % Surface of the plane\np_drone.b = 2.8956;\np_drone.c = 0.18994;\np_drone.S_prop = 0.2027; % Surface of the propeller\np_drone.k_motor = 80; % k motor\np_drone.k_TP = 0;\np_drone.k_omega = 0;\np_drone.e = 0.9;\n\np_drone.kb = @(Va) 0.5*p_drone.b/Va;\np_drone.kc = @(Va) 0.5*p_drone.c/Va;\n\n% Longitudinal dynamics:\n% lift and drag (F_L, F_D)\np_drone.CL0 = 0.28; % C_L_0\np_drone.CL_alpha = 3.45; % C_L_alpha\np_drone.CL_q = 0.0; % C_L_q\np_drone.CL_de = -0.36; % C_L_delta_e\np_drone.CD0 = 0.03; % C_D_0\np_drone.CD_alpha = 0.30; % C_D_alpha\np_drone.CD_p = 0.0437; % C_D_p\np_drone.CD_q = 0.0; % C_D_q\np_drone.CD_de = 0.0; % C_D_delta_e\n\n% moment around y (m)\np_drone.Cm0 = -0.02338; % C_m_0\np_drone.Cm_alpha = -0.38; % C_m_alpha\np_drone.Cm_q = -3.6; % C_m_q\np_drone.Cm_de = -0.5; % C_m_delta_e\n\n% Lateral dynamics\n% F_y\np_drone.CY0 = 0.0;\np_drone.CY_beta = -0.98;\np_drone.CY_p = 0.0;\np_drone.CY_r = 0.0; % C_Y_r\np_drone.CY_da = 0.0; % C_Y_delta_a\np_drone.CY_dr = -0.17; % C_Y_delta_r\n\n% moment around x (l) and z (n)\np_drone.Cl0 = 0.0; % C_l_0\np_drone.Cl_beta = -0.12; % Cl_beta\np_drone.Cl_p = -0.26; % C_l_p\np_drone.Cl_r = 0.14; % C_l_r\np_drone.Cl_da = 0.08; % C_l_delta_aileron\np_drone.Cl_dr = 0.105; % C_l_delta_rudder\np_drone.Cn0 = 0.0; % C_n_0\np_drone.Cn_beta = 0.25; % C_n_beta\np_drone.Cn_p = 0.022; % C_n_p\np_drone.Cn_r = -0.35; % C_n_r\np_drone.Cn_da = 0.06; % C_n_delta_a\np_drone.Cn_dr = -0.032; % C_n_delta_r\n\n\np_drone.C_prop = 1.0; % propeller proportional coeff fx=Sprop*Cprop*dp\np_drone.M = 50;\np_drone.epsilon = 0.1592;\np_drone.alpha0 = 0.4712;\n\np_drone.Cp0 = p_drone.gamma3 * p_drone.Cl0 + p_drone.gamma4 * p_drone.Cn0;\np_drone.Cp_beta = p_drone.gamma3 * p_drone.Cl_beta + p_drone.gamma4 * p_drone.Cn_beta;\np_drone.Cp_p = p_drone.gamma3 * p_drone.Cl_p + p_drone.gamma4 * p_drone.Cn_p;\np_drone.Cp_r = p_drone.gamma3 * p_drone.Cl_r + p_drone.gamma4 * p_drone.Cn_r;\np_drone.Cp_da = p_drone.gamma3 * p_drone.Cl_da + p_drone.gamma4 * p_drone.Cn_da;\np_drone.Cp_dr = p_drone.gamma3 * p_drone.Cl_dr + p_drone.gamma4 * p_drone.Cn_dr;\np_drone.Cr0 = p_drone.gamma4 * p_drone.Cl0 + p_drone.gamma8 * p_drone.Cn0;\np_drone.Cr_b = p_drone.gamma4 * p_drone.Cl_beta + p_drone.gamma8 * p_drone.Cn_beta;\np_drone.Cr_p = p_drone.gamma4 * p_drone.Cl_p + p_drone.gamma8 * p_drone.Cn_p;\np_drone.Cr_r = p_drone.gamma4 * p_drone.Cl_r + p_drone.gamma8 * p_drone.Cn_r;\np_drone.Cr_da = p_drone.gamma4 * p_drone.Cl_da + p_drone.gamma8 * p_drone.Cn_da;\np_drone.Cr_dr = p_drone.gamma4 * p_drone.Cl_dr + p_drone.gamma8 * p_drone.Cn_dr;\n\n\n% first cut at initial conditions\n% p_drone.pn_T = xyu_T(1); % initial North position\n% p_drone.pe_T = xyu_T(2); % initial East position\n% p_drone.pd_T = xyu_T(3); % initial Down position (negative altitude)\n% p_drone.vx_T = xyu_T(4); % initial velocity along body x-axis\n% p_drone.vy_T = xyu_T(5); % initial velocity along body y-axis\n% p_drone.vz_T = xyu_T(6); % initial velocity along body z-axis\n% p_drone.phi_T = xyu_T(7); % initial roll angle\n% p_drone.theta_T = xyu_T(8); % initial pitch angle\n% p_drone.psi_T = xyu_T(9); % initial yaw angle\n% p_drone.p_T = xyu_T(10); % initial body frame roll rate\n% p_drone.q_T = xyu_T(11); % initial body frame pitch rate\n% p_drone.r_T = xyu_T(12); % initial body frame yaw rate\n\n% p_drone.Va_T = xyu_T(13);\n% p_drone.alpha_T = xyu_T(14);\n% p_drone.beta_T = xyu_T(15);\n\n% p_drone.de_T = xyu_T(16);\n% p_drone.da_T = xyu_T(17);\n% p_drone.dr_T = xyu_T(18);\n% p_drone.dt_T = xyu_T(19);\n\n% Values for the Aerosonde UAV\np_drone.Va0 = 35; % m/s (~85 mph)\n\n% Trim conditions used for static PID tuning\nVa_Td = 35;\ngamma_Td = deg2rad(0);\nR_Td = Inf;\n\nTd = [Va_Td, gamma_Td, R_Td];\n\n% Compute PID control\n% p_drone.C = compute_pid_controller(Td, P)\n[Va_idx, gamma_idx, R_idx] = Td2idx(Td);\nxyu_T = table_T(:,Va_idx, gamma_idx, R_idx);\np_drone.phi_T = 0; % initial roll angle\np_drone.theta_T = 0; % initial pitch angle\np_drone.psi_T = 0; % initial yaw angle\np_drone.Va_T = 35;\n[a,TF] = compute_tf_model(xyu_T, p_drone, p_physics);\n% PVa_T = xyu_T(13); % Extract trimmed state\n\n\n% Altitude state machine parameters\np_drone.altitude_take_off_zone = 40;\np_drone.h_theta_hold_zone = 10;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Tuning PID loops\n\n% Lateral dynamics\n% Roll_aileron-hold\nephi_max = deg2rad(15);\np_drone.kp_phi = p_drone.da_max / ephi_max;\nksi_phi = KSI_OPT;\nwn_phi = sqrt(p_drone.kp_phi * a.phi2);\np_drone.kd_phi = (2*ksi_phi*wn_phi - a.phi1) / a.phi2;\n\np_drone.tau_phi = 0.05; % [seconds] <=> 1 autopilot loop\n\n% Course_roll-hold\nW_chi_phi = 10; % Bandwith separation factor\n% Between 5 and 10. Safety corresponds to 10.\nwn_chi = wn_phi / W_chi_phi; %[rad/sec]\nksi_chi = KSI_OPT;\np_drone.kp_chi = 2*ksi_chi*wn_chi*p_drone.Va_T/p_physics.gravity;\np_drone.ki_chi = wn_chi^2*p_drone.Va_T/p_physics.gravity;\n\n% Sideslip_rudder-hold\n%TODO\n\n% Longitudinal dynamics\n% Pitch_elevator-hold\netheta_max = deg2rad(10);\np_drone.kp_theta = p_drone.de_max / etheta_max * sign(a.theta3);\nwn_theta = sqrt(a.theta2 + p_drone.kp_theta*a.theta3);\nksi_theta = KSI_OPT;\nif isfinite(a.theta3)\n p_drone.kd_theta = (2*ksi_theta*wn_theta - a.theta1) / a.theta3;\nelse\n p_drone.kd_theta = 0;\n disp(\"kd_theta is null!\");\nend\np_drone.tau_theta = 0.1; % [seconds] <=> 10 autopilot loops\n\n% Altitude_pitch-hold\n% Scale factor between theta_c and theta\nK_theta_DC = p_drone.kp_theta*a.theta3/(a.theta2+p_drone.kp_theta*a.theta3);\nW_h_theta = 10; % Between 5 and 15. Safety corresponds to 15.\nwn_h = wn_theta / W_h_theta; % [rad/sec]\nksi_h = 1;\np_drone.kp_h = 2*ksi_h*wn_h/(K_theta_DC*p_drone.Va_T);\np_drone.ki_h = wn_h^2 / (K_theta_DC*p_drone.Va_T);\n\n% Airspeed_thrust-hold\nwn_va_dt = 10; % [rad/sec] Need to be tuned.\nksi_va_dt = 1;\np_drone.kp_va_dt = (2*ksi_va_dt*wn_va_dt - a.va1)/a.va2;\np_drone.ki_va_dt = wn_va_dt^2/a.va2;\n\n% Airspeed_pitch-hold\nW_va_theta = 7; % [rad/sec] 10 by default, can be lower.\nwn_va_theta = wn_theta / W_va_theta;\nksi_va_theta = KSI_OPT;\np_drone.kp_va_theta = (a.va1 - 2*ksi_va_theta*wn_va_theta)/(K_theta_DC*p_physics.gravity);\np_drone.ki_va_theta = -wn_va_theta^2/(K_theta_DC*p_physics.gravity);\n\n% first cut at initial conditions\np_drone.pn_T = xyu_T(1); % initial North position\np_drone.pe_T = xyu_T(2); % initial East position\np_drone.pd_T = xyu_T(3)-200; % initial Down position (negative altitude)\np_drone.vx_T = xyu_T(4); % initial velocity along body x-axis\np_drone.vy_T = xyu_T(5); % initial velocity along body y-axis\np_drone.vz_T = xyu_T(6); % initial velocity along body z-axis\np_drone.phi_T = xyu_T(7); % initial roll angle\np_drone.theta_T = xyu_T(8); % initial pitch angle\np_drone.psi_T = xyu_T(9); % initial yaw angle\np_drone.p_T = xyu_T(10); % initial body frame roll rate\np_drone.q_T = xyu_T(11); % initial body frame pitch rate\np_drone.r_T = xyu_T(12); % initial body frame yaw rate\n\np_drone.Va_T = xyu_T(13);\np_drone.alpha_T = xyu_T(14);\np_drone.beta_T = xyu_T(15);\n\np_drone.de_T = xyu_T(16);\np_drone.da_T = xyu_T(17);\np_drone.dr_T = xyu_T(18);\np_drone.dt_T = xyu_T(19);\n\nrun('param_sensors')", "meta": {"author": "lis-epfl", "repo": "swarmlab", "sha": "3574deddd2e4fdcc5696d08f93d6e888f45c8ecc", "save_path": "github-repos/MATLAB/lis-epfl-swarmlab", "path": "github-repos/MATLAB/lis-epfl-swarmlab/swarmlab-3574deddd2e4fdcc5696d08f93d6e888f45c8ecc/parameters/param_drone/param_fixed_wing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024556, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.49376399393685183}} {"text": "function rhs = globNedRHSVIFE3D(fun, mesh, fem, femI, dind, vind)\n\n%% USAGE: generate global load vector on a tetrahedral mesh\n%\n% INPUTS:\n% fun --- the load function from PDE (pde.f)\n% mesh --- a struct data contains mesh information.\n% fem --- global DoF for test function space\n% dind --- derivative info for test function\n% d = [0,0,0]: function value\n% d = [1,0,0]: Dx value\n% d = [0,1,0]: Dy value\n% d = [0,0,1]: Dz value\n%\n% OUTPUTS:\n% rhs --- global rhs vector\n\n% Last Modified: 08/07/2020 by Xu Zhang\n\n%% 1. RHS on non-interface elements\ndof = size(fem.g2ldof,2); nloc = dof;\nntID = find(mesh.tLoc > 0); ntN = length(ntID);\nAN = fem.area(ntID); gw = fem.gw;\ngxN = fem.gx(ntID,:); gyN = fem.gy(ntID,:); gzN = fem.gz(ntID,:); \nX = zeros(nloc*ntN, 1);\n\nfeEvalBas = @EvalNed1Bas3D;\nIfeEvalBas = @evalNed1IFEBas3D;\n\nfN = feval(fun,gxN,gyN,gzN);\nind = 0;\nI = reshape(femI.g2ldof(ntID,1:6),nloc*ntN,1);\nfor i = 1:dof\n ibas = feEvalBas(fem.bas, ntID, gxN, gyN, gzN, i, dind, vind);\n X(ind+1:ind+ntN) = AN.*sum((ibas.*fN).*gw',2).*fem.t_e_orit(ntID,i);\n ind = ind + ntN;\nend\nrhsN = sparse(I,1,X,length(femI.gdof),1);\n\n%% 2. RHS on interface elements\nAI1 = femI.area1; gw = femI.gw; gxI1 = femI.gx1; gyI1 = femI.gy1; gzI1 = femI.gz1;\nntI1 = size(femI.tType1,1); % not number of interface element, but quadrature element\nnloc1 = 12; X1 = zeros(nloc1*ntI1, 1);\nfI1 = feval(fun,gxI1,gyI1,gzI1);\nind = 0;\nI1 = reshape(femI.tType1,nloc1*ntI1,1);\nfor i = 1:nloc1\n ibas = femI.basUType1(:,vind,i);\n X1(ind+1:ind+ntI1) = AI1.*sum((ibas.*fI1).*gw',2);\n ind = ind + ntI1;\nend\nrhsI1 = sparse(I1,1,X1,size(femI.gdof,1),1);\n\n\n\nAI2 = femI.area2; gw = femI.gw; gxI2 = femI.gx2; gyI2 = femI.gy2; gzI2 = femI.gz2;\nntI2 = size(femI.tType2,1); % not number of interface element, but quadrature element\nnloc2 = 14; X2 = zeros(nloc2*ntI2, 1);\nfI2 = feval(fun,gxI2,gyI2,gzI2);\nind = 0;\nI2 = reshape(femI.tType2,nloc2*ntI2,1);\nfor i = 1:nloc2\n ibas = femI.basUType2(:,vind,i);\n X2(ind+1:ind+ntI2) = AI2.*sum((ibas.*fI2).*gw',2);\n ind = ind + ntI2;\nend\nrhsI2 = sparse(I2,1,X2,size(femI.gdof,1),1);\n\n\nrhs = rhsN + rhsI1 + rhsI2;\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/IVEM/globNedRHSVIFE3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4937592633528588}} {"text": "function [ar,arp,aru,g]=v_lpcrf2ar(rf)\n%V_LPCRF2AR Convert reflection coefs to autoregressive coefs [AR,ARP,ARU,G]=(RF)\n%\n% Input: RF(:,p+1) gives reflection coefficients of one or more p-section lossless tubes \n% Ouputs: G is the gain of the all-pole AR filter\n% AR/G is the transfer function from U_in to the glottal input wave, U_g.\n% AR(:,1)=1 always.\n% ARP*K is the transfer function from U_in to the pressure just after the glottis\n% where K = rho*c/Alips: rho = air density 1.23 kg/m^3, c=sound speed 340 m/s, \n% Alips = effective area of free space beyond the lips.\n% ARU is the transfer function from U_in to the total volume velocity through the glottis\n% \n% where U_in=z^(p/2)*U_lips is the time-advanced volume velocity at the lips\n%\n% Energy into the vcal tract is equal to K*filter(ARP,1,Ulips).*filter(ARU,1,Ulips)\n% reverse glottal flows divided by 1-r0 where r0 is the glottal reflection coefficient.\n% The scale factor is included to avoid a zero answer when the glottis is closed giving r0=1.\n%\n% The transfer functions have ar(:,1)=art(:,1)=1\n% They should both be multiplied by z^(p/2)/prod(1+rf) to correct the absolute\n% gain and to compensate for the delay of p/2 samples along the length of the tube.\n%\n% The energy into the vocal tract is given by ars(speech) * are(speech)\n%\n% Ref: D. M. Brookes and H. P. Loke. \"Modelling energy flow in the vocal tract with\n% applications to glottal closure and opening detection.\" In Proc ICASSP'99, pages 213-216, Mar 1999.\n\n\n% Copyright (C) Mike Brookes 1997\n% Version: $Id: v_lpcrf2ar.m 10865 2018-09-21 17:22:45Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[nf,p1]=size(rf);\np2=p1+1;\np=p1-1;\npm=p-1;\narf=[ones(nf,1) zeros(nf,p)];\narr=[zeros(nf,p) rf(:,p1)];\ncr=zeros(nf,p);\nfor k=1:p-1\n rk=rf(:,(p1-k)*ones(1,k));\n cr(:,1:k)=arr(:,p2-k:p1);\n arr(:,p1-k:p)=arr(:,p1-k:p)+rk.*arf(:,1:k);\n arf(:,2:k+1)=arf(:,2:k+1)+rk.*cr(:,1:k);\nend\nr1=rf(:,1);\nar=arf+r1(:,ones(1,p1)).*arr;\nif nargout>1\n kp=prod(1-rf(:,2:p1),2);\n arp=(arf-arr)./kp(:,ones(1,p1));\n if nargout>2\n g=prod(1+rf(:,2:p1),2);\n aru=(arf+arr)./g(:,ones(1,p1));\n if nargout>3\n g=g.*(1+rf(:,1));\n end\n end\nend\n\n\n", "meta": {"author": "ImperialCollegeLondon", "repo": "sap-voicebox", "sha": "28f2654b7584f724277ec81de533debe28ff51ac", "save_path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox", "path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox/sap-voicebox-28f2654b7584f724277ec81de533debe28ff51ac/voicebox/v_lpcrf2ar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.493759252615167}} {"text": "function [b, dev, stat] = glm_multilevel(D, Yvarname, Xvarnames, wh_keep)\n% Predict Y from X using GLM\n%\n% :Usage:\n% ::\n%\n% [b, dev, stat] = glm_multilevel(D, Yvarname, Xvarnames, wh_keep)\n%\n% ..\n% Author and copyright information:\n%\n% Copyright (C) 2013 Tor Wager\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n% ..\n%\n% :Inputs:\n%\n% **D:**\n% a canlab_dataset object\n%\n% **Yvarname:**\n% the name of a variable to predict. must be event level\n%\n% **Xvarnames:**\n% the name(s) of predictor variables. if multiple, put in\n% cell array. must be event level\n%\n% **wh_keep:**\n% a logical vector of 1/0 values\n%\n% :Outputs:\n% **b:**\n% a vector of coefficient estimates (same as for glmfit())\n%\n% **dev:**\n% the deviance of the fit (same as for glmfit())\n%\n% **stat:**\n% structure containing stats fields (see glmfit() documentation)\n%\n\n[Y, ~, levelY] = get_var(D, Yvarname, wh_keep);\nY = Y';\n\n%% MUST IMPLEMENT GET_VAR FOR MULTIPLE VARS AT AN EVENT LEVEL. RETURNS A CELL ARRAY FOR EACH PERSON. DAT BECOMES WARNING STRING, DATCELL IS OF INTEREST.\n\n[X, ~, levelX] = get_var(D, Xvarnames, wh_keep); \n\nif levelY ~= 2 || levelX ~= 2, error('Vars must be event level'); end\n\n\n\nn=size(Y,2);\nX1 = cell(1,n);\nX2 = mean(Y)'; % matrix of 2nd level preds\n\n%{\nif isstruct(varargin{1}) % the \"alternative format\" described above\n xstruct = varargin{1};\n fields = varargin{2};\n for i = 1:n % each subject\n clear myX\n for j = 1:length(fields) %all the fields\n myX(:, j) = xstruct.(fields{j}){i};\n X1{i} = myX;\n end\n getvif(X1{i})\n end\n\nelse\n%}\n for i = 1:n % each subject\n clear myX\n for j = 1:length(varargin)\n myX(:, j) = varargin{j}{i};\n X1{i} = myX;\n end\n end\n%end\n\n\nstats = glmfit_multilevel(Y, X1, scale(X2, 1), 'weighted', 'noplots', ...\n 'names', {'Intrcpt' names{2:end}}, 'beta_names', {'Avg within-ss relationship' ['Effect of Avg. ' names{1}]});\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/@canlab_dataset/glm_multilevel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.49375924724632086}} {"text": "%\tBloch simulator using mex file\n% [mx,my,mz] = blochCim(b1,gr,tp,T1,T2,freq,pr,mode,sens,mx0,my0,mz0);\n%\n%\tBloch simulation of rotations due to B1, gradient and\n%\toff-resonance, including relaxation effects. At each time\n%\tpoint, the rotation matrix and decay matrix are calculated.\n%\tSimulation can simulate the steady-state if the sequence\n%\tis applied repeatedly.This code can also simulate the parallel transmit.\n%\n% INPUT:\n% b1 = (ntime * ncoil) RF pulse, complex number in (Gauss).\n% gr = (ntime * 3) gradient in (Gauss/cm).\n% tp = (ntime * 1) time duration of each b1 and gr point, in (sec),\n%\t\t\t\tor (1 * 1) time step if constant for all points\n%\t\t\t\tor monotonically INCREASING endtime of each\n%\t\t\t\tinterval..\n% T1, T2 = (1 * 1) relaxation time in (sec)\n% freq = (nx * ny * nz) or (npos * 1) off-resonance freq. in (Hz)\n% pr = (npos * 3) array of spatial positions in (cm)\n% mode= Bitmask simulation mode: (default 0)\n%\t\tBit 0: 0-Simulate from start, 1-Steady State\n%\t\tBit 1: 1-Record m at time points. 0-just end time.%\n% Bit 2: 0-display simulation information. 1-only print out warnings.\n% \n%\n% (OPTIONAL)\n% sens = (ncoils * npos or ncoils * nx*ny*nz) sensitivities matrix.\n% default is 1 for all position. Set to default if you put 1 here. \n% mx0,my0,mz0 = (npos * 1) initial magnetization\n% default is (0,0,1) for all position\n%\n%\tOUTPUT:\n%\t\tmx,my,mz = npos x 1 arrays of the resulting magnetization\n%\t\t\t\tcomponents at each position.\n%\n%\tThe code is originally downloaded from Brian Hargreaves's website.\n% \n% Hao Sun made the following main changes:\n% (1)match field map with position\n% (2)correct the minus sign error in the 'b1imag' in the blochsimfz sub\n% function in Brian's code\n% (3)add parallel simulation function\n% \n%\n% Hao Sun, the University of Michigan, Jul 22,2012\n\n\n\n\n\n\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/mri-rf/sun-bloch/blochCim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.6224593171945417, "lm_q1q2_score": 0.4936761827490508}} {"text": "function [cg,theta] = cgmo(im,radius,norient,varargin)\n% function [cg] = cgmo(im,radius,norient,...)\n%\n% Compute the color gradient at a single scale and multiple\n% orientations.\n%\n% INPUT\n%\tim\t\tGrayscale or RGB image, values in [0,1].\n%\tradius\t\tRadius of disc for cg.\n%\tnorient\t\tNumber of orientations for cg.\n%\t'nbins'\t\tNumber of bins; should be > 1/sigmaSim.\n%\t'sigmaSim'\tFor color similarity function.\n%\t'gamma'\t\tGamma correction for LAB [2.5].\n%\t'smooth'\tSmoothing method, one of \n%\t\t\t{'gaussian','savgol','none'}, default 'none'.\n%\t'sigmaSmo'\tSigma for smoothing, default to radius.\n%\n% OUTPUT\n%\tcg\t\tSize [h,w,d,norient] array of cg images,\n%\t\t\twhere d is the dimensionality of the image.\n%\n% The input parameters {radius,nbins,sigmaSim,sigmaSmo} should be\n% scalars when the input image is grayscale, and can be either scalars\n% or 3-element vectors when the image is RGB.\n%\n% See also cgmo.\n%\n% David R. Martin \n% April 2003\n\n% process options\nnbins = 32;\nsigmaSim = 0.1;\ngamma = 2.5;\nsmooth = 'none';\nsigmaSmo = radius;\nfor i = 1:2:numel(varargin),\n opt = varargin{i};\n if ~ischar(opt), error('option names not a string'); end\n if i==numel(varargin), error(sprintf('option ''%s'' has no value',opt)); end\n val = varargin{i+1};\n switch opt,\n case 'nbins', nbins=val;\n case 'sigmaSim', sigmaSim=val;\n case 'gamma', gamma=val;\n case 'smooth',\n switch val,\n case {'none','gaussian','savgol'}, smooth=val;\n otherwise, error(sprintf('invalid option smooth=''%s''',val));\n end\n case 'sigmaSmo', sigmaSmo=val;\n otherwise, error(sprintf('invalid option ''%s''',opt));\n end\nend\n\n% check arguments\nif ndims(im)==2, % grayscale image\n if numel(radius)~=1, error('radius should have 1 element'); end\n if numel(nbins)~=1, error('nbins should have 1 element'); end\n if numel(sigmaSim)~=1, error('sigmaSim should have 1 element'); end\n if numel(sigmaSmo)~=1, error('sigmaSim should have 1 element'); end\nelseif ndims(im)==3, % RGB image\n if numel(radius)==1, radius = radius*ones(3,1); end\n if numel(nbins)==1, nbins = nbins*ones(3,1); end\n if numel(sigmaSim)==1, sigmaSim = sigmaSim*ones(3,1); end\n if numel(sigmaSmo)==1, sigmaSmo = sigmaSmo*ones(3,1); end\n if numel(radius)~=3, error('radius should have 1 or 3 elements'); end\n if numel(nbins)~=3, error('nbins should have 1 or 3 elements'); end\n if numel(sigmaSim)~=3, error('sigmaSim should have 1 or 3 elements'); end\n if numel(sigmaSmo)~=3, error('sigmaSmo should have 1 or 3 elements'); end\n radius = radius(:);\n nbins = nbins(:);\n sigmaSim = sigmaSim(:);\n sigmaSmo = sigmaSmo(:);\nelse\n error('image not of valid dimension');\nend\nnorient = max(1,norient);\nnbins = max(1,nbins);\n\n% min and max values for a,b channels of LAB\n% used to scale values into the unit interval\nabmin = -73;\nabmax = 95;\n\n% make sure nbins is large enough with respect to sigmaSim\nif any( nbins < 1./sigmaSim ),\n warning('nbins < 1/sigmaSim is suspect');\nend\n\n% check pixel valies\nif min(im(:)) < 0 | max(im(:))>1, \n error('pixel values out of range [0,1]');\nend\n\nif ndims(im)==2, % grayscale image\n\n % compute cg from gray values\n cmap = max(1,ceil(im*nbins));\n csim = colorsim(nbins,sigmaSim);\n [cg,theta] = tgmo(...\n cmap,nbins,radius,norient,...\n 'tsim',csim,'smooth',smooth,'sigma',sigmaSmo);\n\nelse, % RGB image\n\n % convert gamma-corrected image to LAB and scale values into [0,1]\n lab = RGB2Lab(im.^gamma);\n lab(:,:,1) = lab(:,:,1) ./ 100;\n lab(:,:,2) = (lab(:,:,2) - abmin) ./ (abmax-abmin);\n lab(:,:,3) = (lab(:,:,3) - abmin) ./ (abmax-abmin);\n lab(:,:,2) = max(0,min(1,lab(:,:,2)));\n lab(:,:,3) = max(0,min(1,lab(:,:,3)));\n\n % compute cg from LAB values\n cg = zeros([size(im) norient]);\n for i = 1:3,\n cmap = max(1,ceil(lab(:,:,i)*nbins(i)));\n csim = colorsim(nbins(i),sigmaSim(i));\n [cg(:,:,i,:),theta] = tgmo(...\n cmap,nbins(i),radius(i),norient,...\n 'tsim',csim,'smooth',smooth,'sigma',sigmaSmo(i));\n end\n\nend\n\n% compute color similarity matrix assuming colors are in [0,1]\nfunction m = colorsim(nbins,sigma)\nbc = ((1:nbins)-0.5)/nbins; % bin centers\n[x,y] = meshgrid(bc,bc);\nm = 1.0 - exp(-abs(x-y).^2./(2*sigma.^2));\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/external/segbench/lib/matlab/cgmo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4936656038168805}} {"text": "function [x,f,fulltraining_instances,exitflag,output] = minFunc(funObj,x0,options,...\n params, allSNum, labels, cat_size, dictionary_length,freq_train, func, func_prime,We2,...\n varargin)\n% minFunc(funObj,x0,options,varargin)\n%\n% Unconstrained optimizer using a line search strategy\n%\n% Uses an interface very similar to fminunc\n% (it doesn't support all of the optimization toolbox options,\n% but supports many other options).\n%\n% It computes descent directions using one of ('Method'):\n% - 'sd': Steepest Descent\n% (no previous information used, not recommended)\n% - 'csd': Cyclic Steepest Descent\n% (uses previous step length for a fixed length cycle)\n% - 'bb': Barzilai and Borwein Gradient\n% (uses only previous step)\n% - 'cg': Non-Linear Conjugate Gradient\n% (uses only previous step and a vector beta)\n% - 'scg': Scaled Non-Linear Conjugate Gradient\n% (uses previous step and a vector beta, \n% and Hessian-vector products to initialize line search)\n% - 'pcg': Preconditionined Non-Linear Conjugate Gradient\n% (uses only previous step and a vector beta, preconditioned version)\n% - 'lbfgs': Quasi-Newton with Limited-Memory BFGS Updating\n% (default: uses a predetermined nunber of previous steps to form a \n% low-rank Hessian approximation)\n% - 'newton0': Hessian-Free Newton\n% (numerically computes Hessian-Vector products)\n% - 'pnewton0': Preconditioned Hessian-Free Newton \n% (numerically computes Hessian-Vector products, preconditioned\n% version)\n% - 'qnewton': Quasi-Newton Hessian approximation\n% (uses dense Hessian approximation)\n% - 'mnewton': Newton's method with Hessian calculation after every\n% user-specified number of iterations\n% (needs user-supplied Hessian matrix)\n% - 'newton': Newton's method with Hessian calculation every iteration\n% (needs user-supplied Hessian matrix)\n% - 'tensor': Tensor\n% (needs user-supplied Hessian matrix and Tensor of 3rd partial derivatives)\n%\n% Several line search strategies are available for finding a step length satisfying\n% the termination criteria ('LS'):\n% - 0: Backtrack w/ Step Size Halving\n% - 1: Backtrack w/ Quadratic/Cubic Interpolation from new function values\n% - 2: Backtrack w/ Cubic Interpolation from new function + gradient\n% values (default for 'bb' and 'sd')\n% - 3: Bracketing w/ Step Size Doubling and Bisection\n% - 4: Bracketing w/ Cubic Interpolation/Extrapolation with function +\n% gradient values (default for all except 'bb' and 'sd')\n% - 5: Bracketing w/ Mixed Quadratic/Cubic Interpolation/Extrapolation\n% - 6: Use Matlab Optimization Toolbox's line search\n% (requires Matlab's linesearch.m to be added to the path)\n%\n% Above, the first three find a point satisfying the Armijo conditions,\n% while the last four search for find a point satisfying the Wolfe\n% conditions. If the objective function overflows, it is recommended\n% to use one of the first 3.\n% The first three can be used to perform a non-monotone\n% linesearch by changing the option 'Fref'.\n%\n% Several strategies for choosing the initial step size are avaiable ('LS_init'):\n% - 0: Always try an initial step length of 1 (default for all except 'cg' and 'sd')\n% (t = 1)\n% - 1: Use a step similar to the previous step (default for 'cg' and 'sd')\n% (t = t_old*min(2,g'd/g_old'd_old))\n% - 2: Quadratic Initialization using previous function value and new\n% function value/gradient (use this if steps tend to be very long)\n% (t = min(1,2*(f-f_old)/g))\n% - 3: The minimum between 1 and twice the previous step length\n% (t = min(1,2*t)\n% - 4: The scaled conjugate gradient step length (may accelerate\n% conjugate gradient methods, but requires a Hessian-vector product)\n% (t = g'd/d'Hd)\n%\n% Inputs:\n% funObj is a function handle\n% x0 is a starting vector;\n% options is a struct containing parameters\n% (defaults are used for non-existent or blank fields)\n% all other arguments are passed to funObj\n%\n% Outputs:\n% x is the minimum value found\n% f is the function value at the minimum found\n% exitflag returns an exit condition\n% output returns a structure with other information\n%\n% Supported Input Options\n% Display - Level of display [ off | final | (iter) | full | excessive ]\n% MaxFunEvals - Maximum number of function evaluations allowed (1000)\n% MaxIter - Maximum number of iterations allowed (500)\n% TolFun - Termination tolerance on the first-order optimality (1e-5)\n% TolX - Termination tolerance on progress in terms of function/parameter changes (1e-9)\n% Method - [ sd | csd | bb | cg | scg | pcg | {lbfgs} | newton0 | pnewton0 |\n% qnewton | mnewton | newton | tensor ]\n% c1 - Sufficient Decrease for Armijo condition (1e-4)\n% c2 - Curvature Decrease for Wolfe conditions (.2 for cg methods, .9 otherwise)\n% LS_init - Line Search Initialization -see above (2 for cg/sd, 4 for scg, 0 otherwise)\n% LS - Line Search type -see above (2 for bb, 4 otherwise)\n% Fref - Setting this to a positive integer greater than 1\n% will use non-monotone Armijo objective in the line search.\n% (20 for bb, 10 for csd, 1 for all others)\n% numDiff - compute derivative numerically\n% (default: 0) (this option has a different effect for 'newton', see below)\n% useComplex - if 1, use complex differentials when computing numerical derivatives\n% to get very accurate values (default: 0)\n% DerivativeCheck - if 'on', computes derivatives numerically at initial\n% point and compares to user-supplied derivative (default: 'off')\n% outputFcn - function to run after each iteration (default: []). It\n% should have the following interface:\n% outputFcn(x,infoStruct,state,varargin{:})\n% useMex - where applicable, use mex files to speed things up (default: 1)\n%\n% Method-specific input options:\n% newton:\n% HessianModify - type of Hessian modification for direct solvers to\n% use if the Hessian is not positive definite (default: 0)\n% 0: Minimum Euclidean norm s.t. eigenvalues sufficiently large\n% (requires eigenvalues on iterations where matrix is not pd)\n% 1: Start with (1/2)*||A||_F and increment until Cholesky succeeds\n% (an approximation to method 0, does not require eigenvalues)\n% 2: Modified LDL factorization\n% (only 1 generalized Cholesky factorization done and no eigenvalues required)\n% 3: Modified Spectral Decomposition\n% (requires eigenvalues)\n% 4: Modified Symmetric Indefinite Factorization\n% 5: Uses the eigenvector of the smallest eigenvalue as negative\n% curvature direction\n% cgSolve - use conjugate gradient instead of direct solver (default: 0)\n% 0: Direct Solver\n% 1: Conjugate Gradient\n% 2: Conjugate Gradient with Diagonal Preconditioner\n% 3: Conjugate Gradient with LBFGS Preconditioner\n% x: Conjugate Graident with Symmetric Successive Over Relaxation\n% Preconditioner with parameter x\n% (where x is a real number in the range [0,2])\n% x: Conjugate Gradient with Incomplete Cholesky Preconditioner\n% with drop tolerance -x\n% (where x is a real negative number)\n% numDiff - compute Hessian numerically\n% (default: 0, done with complex differentials if useComplex = 1)\n% LS_saveHessiancomp - when on, only computes the Hessian at the\n% first and last iteration of the line search (default: 1)\n% mnewton:\n% HessianIter - number of iterations to use same Hessian (default: 5)\n% qnewton:\n% initialHessType - scale initial Hessian approximation (default: 1)\n% qnUpdate - type of quasi-Newton update (default: 3):\n% 0: BFGS\n% 1: SR1 (when it is positive-definite, otherwise BFGS)\n% 2: Hoshino\n% 3: Self-Scaling BFGS\n% 4: Oren's Self-Scaling Variable Metric method \n% 5: McCormick-Huang asymmetric update\n% Damped - use damped BFGS update (default: 1)\n% newton0/pnewton0:\n% HvFunc - user-supplied function that returns Hessian-vector products\n% (by default, these are computed numerically using autoHv)\n% HvFunc should have the following interface: HvFunc(v,x,varargin{:})\n% useComplex - use a complex perturbation to get high accuracy\n% Hessian-vector products (default: 0)\n% (the increased accuracy can make the method much more efficient,\n% but gradient code must properly support complex inputs)\n% useNegCurv - a negative curvature direction is used as the descent\n% direction if one is encountered during the cg iterations\n% (default: 1)\n% precFunc (for pnewton0 only) - user-supplied preconditioner\n% (by default, an L-BFGS preconditioner is used)\n% precFunc should have the following interfact:\n% precFunc(v,x,varargin{:})\n% lbfgs:\n% Corr - number of corrections to store in memory (default: 100)\n% (higher numbers converge faster but use more memory)\n% Damped - use damped update (default: 0)\n% pcg:\n% cgUpdate - type of update (default: 2)\n% cg/scg/pcg:\n% cgUpdate - type of update (default for cg/scg: 2, default for pcg: 1)\n% 0: Fletcher Reeves\n% 1: Polak-Ribiere\n% 2: Hestenes-Stiefel (not supported for pcg)\n% 3: Gilbert-Nocedal\n% HvFunc (for scg only)- user-supplied function that returns Hessian-vector \n% products\n% (by default, these are computed numerically using autoHv)\n% HvFunc should have the following interface:\n% HvFunc(v,x,varargin{:})\n% precFunc (for pcg only) - user-supplied preconditioner\n% (by default, an L-BFGS preconditioner is used)\n% precFunc should have the following interfact:\n% precFunc(v,x,varargin{:})\n% bb:\n% bbType - type of bb step (default: 1)\n% 0: min_alpha ||delta_x - alpha delta_g||_2\n% 1: min_alpha ||alpha delta_x - delta_g||_2\n% 2: Conic BB\n% 3: Gradient method with retards\n% csd:\n% cycle - length of cycle (default: 3)\n%\n% Supported Output Options\n% iterations - number of iterations taken\n% funcCount - number of function evaluations\n% algorithm - algorithm used\n% firstorderopt - first-order optimality\n% message - exit message\n% trace.funccount - function evaluations after each iteration\n% trace.fval - function value after each iteration\n%\n% Author: Mark Schmidt (2006)\n% Web: http://www.cs.ubc.ca/~schmidtm\n%\n% Sources (in order of how much the source material contributes):\n% J. Nocedal and S.J. Wright. 1999. \"Numerical Optimization\". Springer Verlag.\n% R. Fletcher. 1987. \"Practical Methods of Optimization\". Wiley.\n% J. Demmel. 1997. \"Applied Linear Algebra. SIAM.\n% R. Barret, M. Berry, T. Chan, J. Demmel, J. Dongarra, V. Eijkhout, R.\n% Pozo, C. Romine, and H. Van der Vost. 1994. \"Templates for the Solution of\n% Linear Systems: Building Blocks for Iterative Methods\". SIAM.\n% J. More and D. Thuente. \"Line search algorithms with guaranteed\n% sufficient decrease\". ACM Trans. Math. Softw. vol 20, 286-307, 1994.\n% M. Raydan. \"The Barzilai and Borwein gradient method for the large\n% scale unconstrained minimization problem\". SIAM J. Optim., 7, 26-33,\n% (1997).\n% \"Mathematical Optimization\". The Computational Science Education\n% Project. 1995.\n% C. Kelley. 1999. \"Iterative Methods for Optimization\". Frontiers in\n% Applied Mathematics. SIAM.\n\nif nargin < 3\n options = [];\nend\n\n% Get Parameters\n[verbose,verboseI,debug,doPlot,maxFunEvals,maxIter,tolFun,tolX,method,...\n corrections,c1,c2,LS_init,LS,cgSolve,qnUpdate,cgUpdate,initialHessType,...\n HessianModify,Fref,useComplex,numDiff,LS_saveHessianComp,...\n DerivativeCheck,Damped,HvFunc,bbType,cycle,...\n HessianIter,outputFcn,useMex,useNegCurv,precFunc] = ...\n minFunc_processInputOptions(options);\n\nif isfield(options, 'logfile')\n logfile = options.logfile;\nelse\n logfile = [];\nend\n\n% Constants\nSD = 0;\nCSD = 1;\nBB = 2;\nCG = 3;\nPCG = 4;\nLBFGS = 5;\nQNEWTON = 6;\nNEWTON0 = 7;\nNEWTON = 8;\nTENSOR = 9;\n\n% Initialize\np = length(x0);\nd = zeros(p,1);\nx = x0;\nt = 1;\n\n% If necessary, form numerical differentiation functions\nfunEvalMultiplier = 1;\nif numDiff && method ~= TENSOR\n varargin(3:end+2) = varargin(1:end);\n varargin{1} = useComplex;\n varargin{2} = funObj;\n if method ~= NEWTON\n if debug\n if useComplex\n fprintf('Using complex differentials for gradient computation\\n');\n else\n fprintf('Using finite differences for gradient computation\\n');\n end\n end\n funObj = @autoGrad;\n else\n if debug\n if useComplex\n fprintf('Using complex differentials for gradient computation\\n');\n else\n fprintf('Using finite differences for gradient computation\\n');\n end\n end\n funObj = @autoHess;\n end\n\n if method == NEWTON0 && useComplex == 1\n if debug\n fprintf('Turning off the use of complex differentials\\n');\n end\n useComplex = 0;\n end\n\n if useComplex\n funEvalMultiplier = p;\n else\n funEvalMultiplier = p+1;\n end\nend\n\n% Evaluate Initial Point\nif method < NEWTON\n [f,g] = feval(funObj, x, varargin{:});\nelse\n [f,g,H] = feval(funObj, x, varargin{:});\n computeHessian = 1;\nend\nfunEvals = 1;\n\nif strcmp(DerivativeCheck,'on')\n if numDiff\n fprintf('Can not do derivative checking when numDiff is 1\\n');\n end\n % Check provided gradient/hessian function using numerical derivatives\n fprintf('Checking Gradient:\\n');\n [f2,g2] = autoGrad(x,useComplex,funObj,varargin{:});\n\n fprintf('Max difference between user and numerical gradient: %f\\n',max(abs(g-g2)));\n if max(abs(g-g2)) > 1e-4\n fprintf('User NumDif:\\n');\n [g g2]\n diff = abs(g-g2)\n pause;\n end\n\n if method >= NEWTON\n fprintf('Check Hessian:\\n');\n [f2,g2,H2] = autoHess(x,useComplex,funObj,varargin{:});\n\n fprintf('Max difference between user and numerical hessian: %f\\n',max(abs(H(:)-H2(:))));\n if max(abs(H(:)-H2(:))) > 1e-4\n H\n H2\n diff = abs(H-H2)\n pause;\n end\n end\nend\n\n% Output Log\nif verboseI\n fprintf('%10s %10s %15s %15s %15s\\n','Iteration','FunEvals','Step Length','Function Val','Opt Cond');\nend\n\nif logfile\n fid = fopen(logfile, 'a');\n if (fid > 0)\n fprintf(fid, '-- %10s %10s %15s %15s %15s\\n','Iteration','FunEvals','Step Length','Function Val','Opt Cond');\n fclose(fid);\n end\nend\n\n% Output Function\nif ~isempty(outputFcn)\n callOutput(outputFcn,x,'init',0,funEvals,f,[],[],g,[],sum(abs(g)),varargin{:});\nend\n\n% Initialize Trace\ntrace.fval = f;\ntrace.funcCount = funEvals;\n\n% Check optimality of initial point\nif sum(abs(g)) <= tolFun\n exitflag=1;\n msg = 'Optimality Condition below TolFun';\n if verbose\n fprintf('%s\\n',msg);\n end\n if nargout > 3\n output = struct('iterations',0,'funcCount',1,...\n 'algorithm',method,'firstorderopt',sum(abs(g)),'message',msg,'trace',trace);\n end\n return;\nend\nindex=0;\n% Perform up to a maximum of 'maxIter' descent steps:\nfor i = 1:maxIter\n\n % ****************** COMPUTE DESCENT DIRECTION *****************\n\n switch method\n case SD % Steepest Descent\n d = -g;\n\n case CSD % Cyclic Steepest Descent\n\n if mod(i,cycle) == 1 % Use Steepest Descent\n alpha = 1;\n LS_init = 2;\n LS = 4; % Precise Line Search\n elseif mod(i,cycle) == mod(1+1,cycle) % Use Previous Step\n alpha = t;\n LS_init = 0;\n LS = 2; % Non-monotonic line search\n end\n d = -alpha*g;\n\n case BB % Steepest Descent with Barzilai and Borwein Step Length\n\n if i == 1\n d = -g;\n else\n y = g-g_old;\n s = t*d;\n if bbType == 0\n yy = y'*y;\n alpha = (s'*y)/(yy);\n if alpha <= 1e-10 || alpha > 1e10\n alpha = 1;\n end\n elseif bbType == 1\n sy = s'*y;\n alpha = (s'*s)/sy;\n if alpha <= 1e-10 || alpha > 1e10\n alpha = 1;\n end\n elseif bbType == 2 % Conic Interpolation ('Modified BB')\n sy = s'*y;\n ss = s'*s;\n alpha = ss/sy;\n if alpha <= 1e-10 || alpha > 1e10\n alpha = 1;\n end\n alphaConic = ss/(6*(myF_old - f) + 4*g'*s + 2*g_old'*s);\n if alphaConic > .001*alpha && alphaConic < 1000*alpha\n alpha = alphaConic;\n end\n elseif bbType == 3 % Gradient Method with retards (bb type 1, random selection of previous step)\n sy = s'*y;\n alpha = (s'*s)/sy;\n if alpha <= 1e-10 || alpha > 1e10\n alpha = 1;\n end\n v(1+mod(i-2,5)) = alpha;\n alpha = v(ceil(rand*length(v)));\n end\n d = -alpha*g;\n end\n g_old = g;\n myF_old = f;\n\n\n case CG % Non-Linear Conjugate Gradient\n\n if i == 1\n d = -g; % Initially use steepest descent direction\n else\n gtgo = g'*g_old;\n gotgo = g_old'*g_old;\n\n if cgUpdate == 0\n % Fletcher-Reeves\n beta = (g'*g)/(gotgo);\n elseif cgUpdate == 1\n % Polak-Ribiere\n beta = (g'*(g-g_old)) /(gotgo);\n elseif cgUpdate == 2\n % Hestenes-Stiefel\n beta = (g'*(g-g_old))/((g-g_old)'*d);\n else\n % Gilbert-Nocedal\n beta_FR = (g'*(g-g_old)) /(gotgo);\n beta_PR = (g'*g-gtgo)/(gotgo);\n beta = max(-beta_FR,min(beta_PR,beta_FR));\n end\n\n d = -g + beta*d;\n\n % Restart if not a direction of sufficient descent\n if g'*d > -tolX\n if debug\n fprintf('Restarting CG\\n');\n end\n beta = 0;\n d = -g;\n end\n\n % Old restart rule:\n %if beta < 0 || abs(gtgo)/(gotgo) >= 0.1 || g'*d >= 0\n\n end\n g_old = g;\n\n case PCG % Preconditioned Non-Linear Conjugate Gradient\n\n % Apply preconditioner to negative gradient\n if isempty(precFunc)\n % Use L-BFGS Preconditioner\n if i == 1\n old_dirs = zeros(length(g),0);\n old_stps = zeros(length(g),0);\n Hdiag = 1;\n s = -g;\n else\n [old_dirs,old_stps,Hdiag] = lbfgsUpdate(g-g_old,t*d,corrections,debug,old_dirs,old_stps,Hdiag);\n\n if useMex\n s = lbfgsC(-g,old_dirs,old_stps,Hdiag);\n else\n s = lbfgs(-g,old_dirs,old_stps,Hdiag);\n end\n end\n else % User-supplied preconditioner\n s = precFunc(-g,x,varargin{:});\n end\n\n if i == 1\n d = s;\n else\n\n if cgUpdate == 0\n % Preconditioned Fletcher-Reeves\n beta = (g'*s)/(g_old'*s_old);\n elseif cgUpdate < 3\n % Preconditioned Polak-Ribiere\n beta = (g'*(s-s_old))/(g_old'*s_old);\n else\n % Preconditioned Gilbert-Nocedal\n beta_FR = (g'*s)/(g_old'*s_old);\n beta_PR = (g'*(s-s_old))/(g_old'*s_old);\n beta = max(-beta_FR,min(beta_PR,beta_FR));\n end\n d = s + beta*d;\n\n if g'*d > -tolX\n if debug\n fprintf('Restarting CG\\n');\n end\n beta = 0;\n d = s;\n end\n\n end\n g_old = g;\n s_old = s;\n case LBFGS % L-BFGS\n\n % Update the direction and step sizes\n\n if i == 1\n d = -g; % Initially use steepest descent direction\n old_dirs = zeros(length(g),0);\n old_stps = zeros(length(d),0);\n Hdiag = 1;\n else\n if Damped\n [old_dirs,old_stps,Hdiag] = dampedUpdate(g-g_old,t*d,corrections,debug,old_dirs,old_stps,Hdiag);\n else\n [old_dirs,old_stps,Hdiag] = lbfgsUpdate(g-g_old,t*d,corrections,debug,old_dirs,old_stps,Hdiag);\n end\n\n if useMex\n d = lbfgsC(-g,old_dirs,old_stps,Hdiag);\n else\n d = lbfgs(-g,old_dirs,old_stps,Hdiag);\n end\n end\n g_old = g;\n\n case QNEWTON % Use quasi-Newton Hessian approximation\n\n if i == 1\n d = -g;\n else\n % Compute difference vectors\n y = g-g_old;\n s = t*d;\n\n if i == 2\n % Make initial Hessian approximation\n if initialHessType == 0\n % Identity\n if qnUpdate <= 1\n R = eye(length(g));\n else\n H = eye(length(g));\n end\n else\n % Scaled Identity\n if debug\n fprintf('Scaling Initial Hessian Approximation\\n');\n end\n if qnUpdate <= 1\n % Use Cholesky of Hessian approximation\n R = sqrt((y'*y)/(y'*s))*eye(length(g));\n else\n % Use Inverse of Hessian approximation\n H = eye(length(g))*(y'*s)/(y'*y);\n end\n end\n end\n\n if qnUpdate == 0 % Use BFGS updates\n Bs = R'*(R*s);\n if Damped\n eta = .02;\n if y'*s < eta*s'*Bs\n if debug\n fprintf('Damped Update\\n');\n end\n theta = min(max(0,((1-eta)*s'*Bs)/(s'*Bs - y'*s)),1);\n y = theta*y + (1-theta)*Bs;\n end\n R = cholupdate(cholupdate(R,y/sqrt(y'*s)),Bs/sqrt(s'*Bs),'-');\n else\n if y'*s > 1e-10\n R = cholupdate(cholupdate(R,y/sqrt(y'*s)),Bs/sqrt(s'*Bs),'-');\n else\n if debug\n fprintf('Skipping Update\\n');\n end\n end\n end\n elseif qnUpdate == 1 % Perform SR1 Update if it maintains positive-definiteness\n\n Bs = R'*(R*s);\n ymBs = y-Bs;\n if abs(s'*ymBs) >= norm(s)*norm(ymBs)*1e-8 && (s-((R\\(R'\\y))))'*y > 1e-10\n R = cholupdate(R,-ymBs/sqrt(ymBs'*s),'-');\n else\n if debug\n fprintf('SR1 not positive-definite, doing BFGS Update\\n');\n end\n if Damped\n eta = .02;\n if y'*s < eta*s'*Bs\n if debug\n fprintf('Damped Update\\n');\n end\n theta = min(max(0,((1-eta)*s'*Bs)/(s'*Bs - y'*s)),1);\n y = theta*y + (1-theta)*Bs;\n end\n R = cholupdate(cholupdate(R,y/sqrt(y'*s)),Bs/sqrt(s'*Bs),'-');\n else\n if y'*s > 1e-10\n R = cholupdate(cholupdate(R,y/sqrt(y'*s)),Bs/sqrt(s'*Bs),'-');\n else\n if debug\n fprintf('Skipping Update\\n');\n end\n end\n end\n end\n elseif qnUpdate == 2 % Use Hoshino update\n v = sqrt(y'*H*y)*(s/(s'*y) - (H*y)/(y'*H*y));\n phi = 1/(1 + (y'*H*y)/(s'*y));\n H = H + (s*s')/(s'*y) - (H*y*y'*H)/(y'*H*y) + phi*v*v';\n\n elseif qnUpdate == 3 % Self-Scaling BFGS update\n ys = y'*s;\n Hy = H*y;\n yHy = y'*Hy;\n gamma = ys/yHy;\n v = sqrt(yHy)*(s/ys - Hy/yHy);\n H = gamma*(H - Hy*Hy'/yHy + v*v') + (s*s')/ys;\n elseif qnUpdate == 4 % Oren's Self-Scaling Variable Metric update\n\n % Oren's method\n if (s'*y)/(y'*H*y) > 1\n phi = 1; % BFGS\n omega = 0;\n elseif (s'*(H\\s))/(s'*y) < 1\n phi = 0; % DFP\n omega = 1;\n else\n phi = (s'*y)*(y'*H*y-s'*y)/((s'*(H\\s))*(y'*H*y)-(s'*y)^2);\n omega = phi;\n end\n\n gamma = (1-omega)*(s'*y)/(y'*H*y) + omega*(s'*(H\\s))/(s'*y);\n v = sqrt(y'*H*y)*(s/(s'*y) - (H*y)/(y'*H*y));\n H = gamma*(H - (H*y*y'*H)/(y'*H*y) + phi*v*v') + (s*s')/(s'*y);\n\n elseif qnUpdate == 5 % McCormick-Huang asymmetric update\n theta = 1;\n phi = 0;\n psi = 1;\n omega = 0;\n t1 = s*(theta*s + phi*H'*y)';\n t2 = (theta*s + phi*H'*y)'*y;\n t3 = H*y*(psi*s + omega*H'*y)';\n t4 = (psi*s + omega*H'*y)'*y;\n H = H + t1/t2 - t3/t4;\n end\n\n if qnUpdate <= 1\n d = -R\\(R'\\g);\n else\n d = -H*g;\n end\n\n end\n g_old = g;\n\n case NEWTON0 % Hessian-Free Newton\n\n cgMaxIter = min(p,maxFunEvals-funEvals);\n cgForce = min(0.5,sqrt(norm(g)))*norm(g);\n\n % Set-up preconditioner\n precondFunc = [];\n precondArgs = [];\n if cgSolve == 1\n if isempty(precFunc) % Apply L-BFGS preconditioner\n if i == 1\n old_dirs = zeros(length(g),0);\n old_stps = zeros(length(g),0);\n Hdiag = 1;\n else\n [old_dirs,old_stps,Hdiag] = lbfgsUpdate(g-g_old,t*d,corrections,debug,old_dirs,old_stps,Hdiag);\n if useMex\n precondFunc = @lbfgsC;\n else\n precondFunc = @lbfgs;\n end\n precondArgs = {old_dirs,old_stps,Hdiag};\n end\n g_old = g;\n else\n % Apply user-defined preconditioner\n precondFunc = precFunc;\n precondArgs = {x,varargin{:}};\n end\n end\n\n % Solve Newton system using cg and hessian-vector products\n if isempty(HvFunc)\n % No user-supplied Hessian-vector function,\n % use automatic differentiation\n HvFun = @autoHv;\n HvArgs = {x,g,useComplex,funObj,varargin{:}};\n else\n % Use user-supplid Hessian-vector function\n HvFun = HvFunc;\n HvArgs = {x,varargin{:}};\n end\n \n if useNegCurv\n [d,cgIter,cgRes,negCurv] = conjGrad([],-g,cgForce,cgMaxIter,debug,precondFunc,precondArgs,HvFun,HvArgs);\n else\n [d,cgIter,cgRes] = conjGrad([],-g,cgForce,cgMaxIter,debug,precondFunc,precondArgs,HvFun,HvArgs);\n end\n\n funEvals = funEvals+cgIter;\n if debug\n fprintf('newtonCG stopped on iteration %d w/ residual %.5e\\n',cgIter,cgRes);\n\n end\n\n if useNegCurv\n if ~isempty(negCurv)\n %if debug\n fprintf('Using negative curvature direction\\n');\n %end\n d = negCurv/norm(negCurv);\n d = d/sum(abs(g));\n end\n end\n\n case NEWTON % Newton search direction\n\n if cgSolve == 0\n if HessianModify == 0\n % Attempt to perform a Cholesky factorization of the Hessian\n [R,posDef] = chol(H);\n\n % If the Cholesky factorization was successful, then the Hessian is\n % positive definite, solve the system\n if posDef == 0\n d = -R\\(R'\\g);\n\n else\n % otherwise, adjust the Hessian to be positive definite based on the\n % minimum eigenvalue, and solve with QR\n % (expensive, we don't want to do this very much)\n if debug\n fprintf('Adjusting Hessian\\n');\n end\n H = H + eye(length(g)) * max(0,1e-12 - min(real(eig(H))));\n d = -H\\g;\n end\n elseif HessianModify == 1\n % Modified Incomplete Cholesky\n R = mcholinc(H,debug);\n d = -R\\(R'\\g);\n elseif HessianModify == 2\n % Modified Generalized Cholesky\n if useMex\n [L D perm] = mcholC(H);\n else\n [L D perm] = mchol(H);\n end\n d(perm) = -L' \\ ((D.^-1).*(L \\ g(perm)));\n\n elseif HessianModify == 3\n % Modified Spectral Decomposition\n [V,D] = eig((H+H')/2);\n D = diag(D);\n D = max(abs(D),max(max(abs(D)),1)*1e-12);\n d = -V*((V'*g)./D);\n elseif HessianModify == 4\n % Modified Symmetric Indefinite Factorization\n [L,D,perm] = ldl(H,'vector');\n [blockPos junk] = find(triu(D,1));\n for diagInd = setdiff(setdiff(1:p,blockPos),blockPos+1)\n if D(diagInd,diagInd) < 1e-12\n D(diagInd,diagInd) = 1e-12;\n end\n end\n for blockInd = blockPos'\n block = D(blockInd:blockInd+1,blockInd:blockInd+1);\n block_a = block(1);\n block_b = block(2);\n block_d = block(4);\n lambda = (block_a+block_d)/2 - sqrt(4*block_b^2 + (block_a - block_d)^2)/2;\n D(blockInd:blockInd+1,blockInd:blockInd+1) = block+eye(2)*(lambda+1e-12);\n end\n d(perm) = -L' \\ (D \\ (L \\ g(perm)));\n else\n % Take Newton step if Hessian is pd,\n % otherwise take a step with negative curvature\n [R,posDef] = chol(H);\n if posDef == 0\n d = -R\\(R'\\g);\n else\n if debug\n fprintf('Taking Direction of Negative Curvature\\n');\n end\n [V,D] = eig(H);\n u = V(:,1);\n d = -sign(u'*g)*u;\n end\n end\n\n else\n % Solve with Conjugate Gradient\n cgMaxIter = p;\n cgForce = min(0.5,sqrt(norm(g)))*norm(g);\n\n % Select Preconditioner\n if cgSolve == 1\n % No preconditioner\n precondFunc = [];\n precondArgs = [];\n elseif cgSolve == 2\n % Diagonal preconditioner\n precDiag = diag(H);\n precDiag(precDiag < 1e-12) = 1e-12 - min(precDiag);\n precondFunc = @precondDiag;\n precondArgs = {precDiag.^-1};\n elseif cgSolve == 3\n % L-BFGS preconditioner\n if i == 1\n old_dirs = zeros(length(g),0);\n old_stps = zeros(length(g),0);\n Hdiag = 1;\n else\n [old_dirs,old_stps,Hdiag] = lbfgsUpdate(g-g_old,t*d,corrections,debug,old_dirs,old_stps,Hdiag);\n end\n g_old = g;\n if useMex\n precondFunc = @lbfgsC;\n else\n precondFunc = @lbfgs;\n end\n precondArgs = {old_dirs,old_stps,Hdiag};\n elseif cgSolve > 0\n % Symmetric Successive Overelaxation Preconditioner\n omega = cgSolve;\n D = diag(H);\n D(D < 1e-12) = 1e-12 - min(D);\n precDiag = (omega/(2-omega))*D.^-1;\n precTriu = diag(D/omega) + triu(H,1);\n precondFunc = @precondTriuDiag;\n precondArgs = {precTriu,precDiag.^-1};\n else\n % Incomplete Cholesky Preconditioner\n opts.droptol = -cgSolve;\n opts.rdiag = 1;\n R = cholinc(sparse(H),opts);\n if min(diag(R)) < 1e-12\n R = cholinc(sparse(H + eye*(1e-12 - min(diag(R)))),opts);\n end\n precondFunc = @precondTriu;\n precondArgs = {R};\n end\n\n % Run cg with the appropriate preconditioner\n if isempty(HvFunc)\n % No user-supplied Hessian-vector function\n [d,cgIter,cgRes] = conjGrad(H,-g,cgForce,cgMaxIter,debug,precondFunc,precondArgs);\n else\n % Use user-supplied Hessian-vector function\n [d,cgIter,cgRes] = conjGrad(H,-g,cgForce,cgMaxIter,debug,precondFunc,precondArgs,HvFunc,{x,varargin{:}});\n end\n if debug\n fprintf('CG stopped after %d iterations w/ residual %.5e\\n',cgIter,cgRes);\n %funEvals = funEvals + cgIter;\n end\n end\n\n case TENSOR % Tensor Method\n\n if numDiff\n % Compute 3rd-order Tensor Numerically\n [junk1 junk2 junk3 T] = autoTensor(x,useComplex,funObj,varargin{:});\n else\n % Use user-supplied 3rd-derivative Tensor\n [junk1 junk2 junk3 T] = feval(funObj, x, varargin{:});\n end\n options_sub.Method = 'newton';\n options_sub.Display = 'none';\n options_sub.TolX = tolX;\n options_sub.TolFun = tolFun;\n d = minFunc(@taylorModel,zeros(p,1),options_sub,f,g,H,T);\n\n if any(abs(d) > 1e5) || all(abs(d) < 1e-5) || g'*d > -tolX\n if debug\n fprintf('Using 2nd-Order Step\\n');\n end\n [V,D] = eig((H+H')/2);\n D = diag(D);\n D = max(abs(D),max(max(abs(D)),1)*1e-12);\n d = -V*((V'*g)./D);\n else\n if debug\n fprintf('Using 3rd-Order Step\\n');\n end\n end\n end\n\n if ~isLegal(d)\n fprintf('Step direction is illegal!\\n');\n pause;\n return\n end\n\n % ****************** COMPUTE STEP LENGTH ************************\n\n % Directional Derivative\n gtd = g'*d;\n\n % Check that progress can be made along direction\n if gtd > -tolX\n exitflag=2;\n msg = 'Directional Derivative below TolX';\n break;\n end\n\n % Select Initial Guess\n if i == 1\n if method < NEWTON0\n t = min(1,1/sum(abs(g)));\n else\n t = 1;\n end\n else\n if LS_init == 0\n % Newton step\n t = 1;\n elseif LS_init == 1\n % Close to previous step length\n t = t*min(2,(gtd_old)/(gtd));\n elseif LS_init == 2\n % Quadratic Initialization based on {f,g} and previous f\n t = min(1,2*(f-f_old)/(gtd));\n elseif LS_init == 3\n % Double previous step length\n t = min(1,t*2);\n elseif LS_init == 4\n % Scaled step length if possible\n if isempty(HvFunc)\n % No user-supplied Hessian-vector function,\n % use automatic differentiation\n dHd = d'*autoHv(d,x,g,0,funObj,varargin{:});\n else\n % Use user-supplid Hessian-vector function\n dHd = d'*HvFunc(d,x,varargin{:});\n end\n\n funEvals = funEvals + 1;\n if dHd > 0\n t = -gtd/(dHd);\n else\n t = min(1,2*(f-f_old)/(gtd));\n end\n end\n\n if t <= 0\n t = 1;\n end\n end\n f_old = f;\n gtd_old = gtd;\n\n % Compute reference fr if using non-monotone objective\n if Fref == 1\n fr = f;\n else\n if i == 1\n old_fvals = repmat(-inf,[Fref 1]);\n end\n\n if i <= Fref\n old_fvals(i) = f;\n else\n old_fvals = [old_fvals(2:end);f];\n end\n fr = max(old_fvals);\n end\n\n computeHessian = 0;\n if method >= NEWTON\n if HessianIter == 1\n computeHessian = 1;\n elseif i > 1 && mod(i-1,HessianIter) == 0\n computeHessian = 1;\n end\n end\n\n % Line Search\n f_old = f;\n if LS < 3 % Use Armijo Bactracking\n % Perform Backtracking line search\n if computeHessian\n [t,x,f,g,LSfunEvals,H] = ArmijoBacktrack(x,t,d,f,fr,g,gtd,c1,LS,tolX,debug,doPlot,LS_saveHessianComp,funObj,varargin{:});\n else\n [t,x,f,g,LSfunEvals] = ArmijoBacktrack(x,t,d,f,fr,g,gtd,c1,LS,tolX,debug,doPlot,1,funObj,varargin{:});\n end\n funEvals = funEvals + LSfunEvals;\n\n elseif LS < 6\n % Find Point satisfying Wolfe\n\n if computeHessian\n [t,f,g,LSfunEvals,H] = WolfeLineSearch(x,t,d,f,g,gtd,c1,c2,LS,25,tolX,debug,doPlot,LS_saveHessianComp,funObj,varargin{:});\n else\n [t,f,g,LSfunEvals] = WolfeLineSearch(x,t,d,f,g,gtd,c1,c2,LS,25,tolX,debug,doPlot,1,funObj,varargin{:});\n end\n funEvals = funEvals + LSfunEvals;\n x = x + t*d;\n\n else\n % Use Matlab optim toolbox line search\n [t,f_new,fPrime_new,g_new,LSexitFlag,LSiter]=...\n lineSearch({'fungrad',[],funObj},x,p,1,p,d,f,gtd,t,c1,c2,-inf,maxFunEvals-funEvals,...\n tolX,[],[],[],varargin{:});\n funEvals = funEvals + LSiter;\n if isempty(t)\n exitflag = -2;\n msg = 'Matlab LineSearch failed';\n break;\n end\n\n if method >= NEWTON\n [f_new,g_new,H] = funObj(x + t*d,varargin{:});\n funEvals = funEvals + 1;\n end\n x = x + t*d;\n f = f_new;\n g = g_new;\n end\n\n % Output iteration information\n if verboseI\n fprintf('%10d %10d %15.5e %15.5e %15.5e\\n',i,funEvals*funEvalMultiplier,t,f,sum(abs(g)));\n end\n\n if logfile\n fid = fopen(logfile, 'a');\n if (fid > 0)\n fprintf(fid, '-- %10d %10d %15.5e %15.5e %15.5e\\n',i,funEvals*funEvalMultiplier,t,f,sum(abs(g)));\n fclose(fid);\n end\n end\n\n \n % Output Function\n if ~isempty(outputFcn)\n callOutput(outputFcn,x,'iter',i,funEvals,f,t,gtd,g,d,sum(abs(g)),varargin{:});\n end\n\n % Update Trace\n trace.fval(end+1,1) = f;\n trace.funcCount(end+1,1) = funEvals;\n\n \n %% Fetch the features\n [W1, W2, W3, W4, b1, b2, b3, Wcat,bcat, We] = getW(1, x, params.embedding_size, cat_size, dictionary_length);\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n disp('Get features by forward propagating and finding structure for all train and test sentences...')\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % in this setting, we take the top node's vector and the average of all vectors in the tree as a concatenated feature vector\n fulltraining_instances = getFeatures(allSNum,0,...\n We,We2,W1,W2,W3,W4,b1,b2,b3,Wcat,bcat,params.alpha_cat,params.embedding_size, ...\n labels, freq_train, func, func_prime, params.trainModel);\n\n % Check Optimality Condition\n if sum(abs(g)) <= tolFun\n exitflag=1;\n msg = 'Optimality Condition below TolFun';\n break;\n end\n\n % ******************* Check for lack of progress *******************\n\n if sum(abs(t*d)) <= tolX\n exitflag=2;\n msg = 'Step Size below TolX';\n break;\n end\n\n\n if abs(f-f_old) < tolX\n exitflag=2;\n msg = 'Function Value changing by less than TolX';\n break;\n end\n\n % ******** Check for going over iteration/evaluation limit *******************\n\n if funEvals*funEvalMultiplier > maxFunEvals\n exitflag = 0;\n msg = 'Exceeded Maximum Number of Function Evaluations';\n break;\n end\n\n if i == maxIter\n exitflag = 0;\n msg='Exceeded Maximum Number of Iterations';\n break;\n end\n\nend\n\nif verbose\n fprintf('%s\\n',msg);\nend\nif nargout > 3\n output = struct('iterations',i,'funcCount',funEvals*funEvalMultiplier,...\n 'algorithm',method,'firstorderopt',sum(abs(g)),'message',msg,'trace',trace);\nend\n\n% Output Function\nif ~isempty(outputFcn)\n callOutput(outputFcn,x,'done',i,funEvals,f,t,gtd,g,d,sum(abs(g)),varargin{:});\nend\n\nend\n\n", "meta": {"author": "jacoxu", "repo": "STC2", "sha": "34a28c5a8cf2d6e1db300d32f271f6522db3bde5", "save_path": "github-repos/MATLAB/jacoxu-STC2", "path": "github-repos/MATLAB/jacoxu-STC2/STC2-34a28c5a8cf2d6e1db300d32f271f6522db3bde5/software/RecNN/tools/minFunc/minFunc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.49359306752937965}} {"text": "function [ev,ee,ebound,xyp] = q1q1grid(x,y,xy,mv,bound,mbound);\n%q1q1grid Q1-Q1 element grid generator\n% [ev,ee,ebound,xyp] = q1q1grid(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%%\nxyp=xy;\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-Q1 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/q1q1grid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.4935930501462912}} {"text": "function lambda = kershaw_eigenvalues ( )\n\n%*****************************************************************************80\n%\n%% KERSHAW_EIGENVALUES returns the eigenvalues of the KERSHAW matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% David Kershaw,\n% The Incomplete Cholesky-Conjugate Gradient Method for the Iterative\n% Solution of Systems of Linear Equations,\n% Journal of Computational Physics,\n% Volume 26, Number 1, January 1978, pages 43-65.\n%\n% Parameters:\n%\n% Output, real LAMBDA(4,1), the eigenvalues of the matrix.\n%\n lambda(1:4,1) = [ ...\n 5.828427124746192, ...\n 5.828427124746188, ...\n 0.171572875253810, ...\n 0.171572875253810 ];\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_mat/kershaw_eigenvalues.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.4935718289214937}} {"text": "function jac = p00_jac ( problem, option, nvar, x )\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% 14 October 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer PROBLEM, the problem index.\n%\n% Input, integer OPTION, the option index.\n%\n% Input, integer NVAR, the number of variables.\n%\n% Input, real X(NVAR), the argument of the jacobian.\n%\n% Output, real JAC(NVAR-1,NVAR), the jacobian matrix evaluated\n% at X. The NVAR-th row is not set by this routine.\n%\n if ( problem == 1 )\n jac = p01_jac ( option, nvar, x );\n elseif ( problem == 2 )\n jac = p02_jac ( option, nvar, x );\n elseif ( problem == 3 )\n jac = p03_jac ( option, nvar, x );\n elseif ( problem == 4 )\n jac = p04_jac ( option, nvar, x );\n elseif ( problem == 5 )\n jac = p05_jac ( option, nvar, x );\n elseif ( problem == 6 )\n jac = p06_jac ( option, nvar, x );\n elseif ( problem == 7 )\n jac = p07_jac ( option, nvar, x );\n elseif ( problem == 8 )\n jac = p08_jac ( option, nvar, x );\n elseif ( problem == 9 )\n jac = p09_jac ( option, nvar, x );\n elseif ( problem == 10 )\n jac = p10_jac ( option, nvar, x );\n elseif ( problem == 11 )\n jac = p11_jac ( option, nvar, x );\n elseif ( problem == 12 )\n jac = p12_jac ( option, nvar, x );\n elseif ( problem == 13 )\n jac = p13_jac ( option, nvar, x );\n elseif ( problem == 14 )\n jac = p14_jac ( option, nvar, x );\n elseif ( problem == 15 )\n jac = p15_jac ( option, nvar, x );\n elseif ( problem == 16 )\n jac = p16_jac ( option, nvar, x );\n elseif ( problem == 17 )\n jac = p17_jac ( option, nvar, x );\n elseif ( problem == 18 )\n jac = p18_jac ( option, nvar, x );\n elseif ( problem == 19 )\n jac = p19_jac ( option, nvar, x );\n elseif ( problem == 20 )\n jac = p20_jac ( option, nvar, x );\n else\n jac = [];\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'P00_JAC - Fatal error!\\n' );\n fprintf ( 1, ' Unrecognized problem number = %d\\n', problem );\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_con/p00_jac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514778, "lm_q2_score": 0.7025300449389325, "lm_q1q2_score": 0.49354848154371006}} {"text": "% THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION IS RELEASED \"AS IS.\" THE U.S. GOVERNMENT MAKES NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, CONCERNING THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL THE U.S. GOVERNMENT BE LIABLE FOR ANY DAMAGES, INCLUDING ANY LOST PROFITS, LOST SAVINGS OR OTHER INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE, OR INABILITY TO USE, THIS SOFTWARE OR ANY ACCOMPANYING DOCUMENTATION, EVEN IF INFORMED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.\n%\n% file: rate_ci.m\n% computes confidence interval estimate rates.\n% x = number of events (numerator of r_hat)\n% A = test area (denominator of p_hat) - the CI will be in the same units as the rate,\n% which is in the same units as 1/A.\n% alpha = probability that the true value will fall outside the confidence interval\n% method = \n% 1 for 1-sided confidence interval, \n% note that you get both the lower 1-sided and the upper 1-sided when method = 1.\n% 2 for 2-sided, minimum length interval (default)\n% 3 for 2-sided, symmetrical about the estimate (except when either end of the interval would fall outside the acceptable range [0,1]\n% 4 for 2-sided, equal tail masses\n% 5 for 2-sided, MatLab implementation\n% 6 for 2-sided, Normal approximation\n% ci = (r_hat, lower bound of confidence interval, upper bound of confidence interval)\n% note that you get both the lower 1-sided and the upper 1-sided when sides = 1.\n%\n% 010129 tdr created from interval_est_r and prob_ci to simply input parameters\n% 010315 tdr added method options > 2 and verbose.\n% 010326 tdr added x=0 fix for Method 5\n% 010412 tdr added method to verbose output\n% 030110 tdr added warnings for extremes x's and alpha's\n% 031223 tdr added test for NaN in inputs\n\nfunction metrics = rate_ci(x,A,alpha,method, verbose)\n\n% ------------------------------------------------------------\n% start checking inputs\n\nif nargin == 4, \n verbose = 0;\nend\n\nif nargin == 3, \n verbose = 0;\n method = 2;\nend\n\nif (nargin ~= 3) & (nargin ~= 4) & (nargin ~= 5), \n error('Requires 3, 4, or 5 input arguments x, A, alpha, method(default=2), verbose(default=0)');\nend\n \n% inputs must all be scalars\nif (max(max([size(x); size(A); size(alpha)])) ~= 1)\n error('Non-scalar input'); \nend;\n\nif isnan(x) | isnan(A) | isnan(alpha)\n warning('NaN input')\n metrics = [NaN, NaN, NaN];\n return\nend;\n \n% x must be integer\nif (round(x) ~= x)\n x = round(x);\n warning('Non-integer input x'); \nend;\n\n% A must be > 0\nif (A <= 0),\n metrics = [ NaN NaN NaN];\n warning('A <= 0');\n return;\nend;\n\n% x must be >= 0\nif ( x < 0),\n metrics = [ NaN NaN NaN];\n warning('x < 0');\n return;\nend;\n\n% results may be inaccurate for x too large or alpha too small\nif ( x > 1e6), warning('x > 1e6, results may not be accurate.'); end;\nif ( alpha < 1e-5), warning('alpha < 1e-5, results may not be accurate.'); end;\n\n% alpha must be > 0.0 and < 1.0\nif ( alpha < 0 | alpha > 1),\n metrics = [ NaN NaN NaN];\n warning('alpha < 0 or alpha > 1');\n return;\nend;\n\n% end checking inputs\n% ------------------------------------------------------------\n\n% call interval estimator with best method\ntic;\nswitch method\ncase 1,\n ci = interval_est_r(x,A,alpha,'cs1_1s');\ncase 2,\n ci = interval_est_r(x,A,alpha,'ml');\ncase 3,\n ci = interval_est_r(x,A,alpha,'cs1');\ncase 4,\n ci = interval_est_r(x,A,alpha/2,'cs1_1s');\ncase 5,\n [lambda ci_tmp] = poissfit(x,alpha);\n ci = [lambda ci_tmp(1) ci_tmp(2)]/A;\n if (x == 0) ci(2) = 0; end;\ncase 6,\n ci = interval_est_r(x,A,alpha,'na');\notherwise\n error('Not a valid method: 1 (1-sided), 2 (min length), 3 (symm.), 4 (equal tail), 5 (MatLab-poissfit), 6 (Normal Approx)');\nend;\nrt = toc;\n\nif verbose\n max_lambda = max(1000, x*1000);\n length = ci(3)-ci(2);\n lower_tail = integrate_poisspdf(x,0,A*ci(2));\n upper_tail = integrate_poisspdf(x,A*ci(3),max_lambda);\n if (method == 1)\n actual_alpha = (lower_tail + upper_tail)/2;\n else\n actual_alpha = lower_tail + upper_tail;\n end;\n if (abs(actual_alpha - alpha) > 0.00005) % close_enough is 0.00001 throughout, but spec is 0.0001.\n warning('Interval not to spec: abs(desired_alpha - actual_alpha) < 0.00005)');\n warning_stats = [alpha actual_alpha alpha-actual_alpha]\n end;\n disp('r_hat, Lower CI Bound, Upper CI Bound, x, A, Desired alpha, Method, Length, Lower Tail, Upper Tail, Actual alpha, Delta alpha, Run Time')\n metrics = [ci x A alpha method length lower_tail upper_tail actual_alpha (alpha - actual_alpha) rt];\n disp(sprintf('%8.4g, %8.4g, %8.4g, %d, %8.4g, %8.6g, %d, %8.4g, %8.6g, %8.6g, %8.6g, %8.6g, %8.2g',metrics));\nelse\n metrics = ci;\nend;\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/3031-accurate-confidence-intervals/ci_tool/rate_ci.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7057850154599562, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.49352329237739856}} {"text": "function F_BBHEwVEDg_gray = BBHEwVEDg_gray( F )\n\n% clear all;\n% close all;\n% clc;\n%x0=imread('eswar.jpg');\nx0=F;\n%x0=imread('11.bmp');\n% x0=imread('12.bmp');\n%y0=rgb2ycbcr(x0);\nluma=x0;%(:,:,1);\n[m,n]=size(luma);\n% cb=y0(:,:,2);\n% cr=y0(:,:,3);\nk=mean(mean(luma));\nr=round(k);\nl=length(luma(luma<=r));\n listindex=find(luma<=r);\n k1=reshape(luma(listindex),l,1);%obtained below fist mean values put it into an arry\n k2=mean(k1);%find mean of mean in first half\n k3=round(k2);%round to nearest integer to find pdf and cdf till first quarter\n sum=0;\n l1=length(luma(luma<=k3));%find all values in luma falls below fist mean\n listindex1=find(luma<=k3);%all values in luma falls below fist mean given in their locations\n k4=reshape(luma(listindex1),l1,1);%arrange all fist mean values in a vector\n xpdf=hist(k4,[0:k3]);%pdf from 0:r\n xpdf=xpdf/l1;%normalized pdf to get nk/n,l=sum of xpdf,total no of pixels form 0 to r.\n% plot(xpdf);\n% xlabel('gray levels up to mean');\n% ylabel('pdf up to mean');\n% title('histogram for half an image up to mean');\n sk=xpdf*triu(ones(k3+1));\n% figure(2);\n% plot(sk);\n% xlabel('gray levels upto 1st mean');\n% ylabel('cdf upto mean');\n% title('cdf for half of an image up to ist mean');\n alpha=0.6;\n for l2=0:k3\n list1=find(k4==l2);%find value in an vector i.e converted from matrix\n list(list1)=alpha*sk(l2+1)*(k3+1)+(1-alpha)*(k3+1);\n %list(list1)=sk(l2+1)*(k3+1);%map dont disturb to get bhe as\n %it is 13/3/2011\n ert(l2+1)=alpha*sk(l2+1)*(k3+1)+(1-alpha)*(k3+1);\n end\n p=zeros(m,n); \n p(listindex1)= list;\n% figure(3);\n% imshow(p);\n% xlabel('gray levels up to first mean');\n% ylabel('luma component equilized image up to first mean');\n% title('processed luma image up to first mean');\n k=mean(mean(luma));\nr=round(k);\nl=length(luma(luma<=r));\n listindex=find(luma<=r);\n k1=reshape(luma(listindex),l,1);%obtained below fist mean values put it into an arry\n k2=mean(k1);%find mean of mean in first half\n k3=round(k2);%round to nearest integer to find pdf and cdf till first quarter\n% sum=0;\n b=k3;\n% l2=length(luma(luma>k3));%find all values in luma falls below fist mean\n listindex2=find((luma>k3)&(luma<=r));%all values in luma falls below fist mean given in their locations\n l2=length(listindex2);\n k5=reshape(luma(listindex2),l2,1);%arrange all fist mean values in a vector\n x2pdf=hist(k5,[k3+1:r]);%pdf from 0:r\n x2pdf=x2pdf/l2;%normalized pdf to get nk/n,l=sum of xpdf,total no of pixels form 0 to r.\n% figure(4);\n% plot(x2pdf);\n% xlabel('gray levels 2nd mean');\n% ylabel('pdf of 2nd mean');\n% title('histogram for 2nd mean');\n sk2=x2pdf*triu(ones(r-k3));\n% figure(5);\n% plot(sk2);\n% xlabel('gray levels of 2nd mean');\n% ylabel('cdf upto mean');\n% title('cdf for half of an image of 2nd mean');\n k2u=1;\n for l3=k3+1:r\n list2=find(k5==l3);%find value in an vector i.e converted from matrix\n list1(list2)=alpha*sk2(k2u)*(r-k3)+(1-alpha)*(k3+1);\n %list1(list2)=(k3+1)+(sk2(k2u))*(r-k3);%map dont disturb to\n %get BHE 13/3/2011\n ert(l3)=alpha*sk2(k2u)*(r-k3)+(1-alpha)*(k3+1);\n k2u=k2u+1;\n end\n p1=zeros(m,n); \n p1(listindex2)= list1;\n% figure(6);\n% imshow(p1);\n% xlabel('gray levels up to first 2nd mean');\n% ylabel('luma component equilized image 2nd mean');\n% title('processed luma image up to 2nd mean');\n %lupper30=length(luma(luma>r);\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n lupper30=length(luma(luma>r));\n%for i=0:r\n %if(luma(luma<=r))\n listindexupper3=find(luma>r);\n % end\n%end\n k1upper=reshape(luma(listindexupper3),lupper30,1);\n mean3=mean(k1upper);\n r3=round(mean3);\n %length30=length((luma<=r3)&(luma>r));\n listindexupper30=find((luma>r)&(luma<=r3));\n length30=length(listindexupper30);\n k30upper=reshape(luma(listindexupper30),length30,1);\n \n %length30=length((luma<=r3)&(luma>r));\n% sum=0;\n xpdfupper30=hist(k30upper,[r+1:r3]);%pdf from r+1:r3\n xpdfupper30=xpdfupper30/length30;%normalized pdf to get nk/n,l=sum of xpdf,total no of pixels form r+1 to 255.\n% figure(7);\n% plot(xpdfupper30);\n% xlabel('gray levels 3rd mean');\n% ylabel('pdf of 3rd mean');\n% title('histogram for upper half an image 3rd mean');\n skupper30=xpdfupper30*triu(ones(r3-r));\n% figure(8);\n% plot(skupper30);\n% xlabel('gray levels after mean');\n% ylabel('cdf after mean');\n% title('cdf for upper half of an image after mean');\n k3u=1;\n for k3upper=(r+1):r3\n list1upper30=find(k30upper==k3upper);%find value in an vector i.e converted from matrix\n listnew(list1upper30)=(r+1)+skupper30(k3u)*(r3-r);%map\n ert(k3upper)=(r+1)+skupper30(k3u)*(r3-r);\n k3u=k3u+1;\n end\n \n p2=zeros(m,n);\n \n p2(listindexupper30)= listnew;\n% figure(9);\n% imshow(p2);\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n listindexupper40=find(luma>r3);\n lupper40=length(listindexupper40);\n % end\n%end\n k1upper40=reshape(luma(listindexupper40),lupper40,1);\n %sum=0;\n %for i=0:r\n xpdfupper40=hist(k1upper40,[r3+1:255]);%pdf from r+1:255\n xpdfupper40=xpdfupper40/lupper40;%normalized pdf to get nk/n,l=sum of xpdf,total no of pixels form r+1 to 255.\n% figure(10);\n% plot(xpdfupper40);\n% xlabel('gray levels after 4mean');\n% ylabel('pdf after 4mean');\n% title('histogram for upper half an image after 4mean');\n skupper40=xpdfupper40*triu(ones(255-r3));\n% figure(11);\n% plot(skupper40);\n% xlabel('gray levels after 4mean');\n% ylabel('cdf after 4mean');\n% title('cdf for upper half of an image after 4mean');\n k4u=1;\n for k4upper=(r3+1):255\n %if(xpdfupper(k2upper)>r)\n list1upper40=find(k1upper40==k4upper);%find value in an vector i.e converted from matrix\n %for k2u=1:58\n listnew4(list1upper40)=(r3+1+skupper40(k4u)*(255-r3));%map\n %end\n ert(k4upper)=(r3+1+skupper40(k4u)*(255-r3));\n k4u=k4u+1;\n end\n \n% for i=0:l-1\n p3=zeros(m,n);\n% if (p(listindex))\n% p(:)=list;\n% end\n% end\n \n p3(listindexupper40)= listnew4;\n% figure(12);\n% imshow(p3);\n% xlabel('gray levels after 4mean');\n% ylabel('luma component equilized image after 4mean');\n% title('processed luma image after 4mean');\n om=p+p1+p2+p3;\n F_BBHEwVEDg_gray=om;\n %ommmmm=p1+p;\n% figure(13);\n% imshow(uint8(om));\n % colormap('gray');\n% xlabel('gray level');\n% ylabel('combined lower and upper half luma component equilized image');\n% title('combined luma image');\n% figure(8);\n %image(om);\n% for j1=0:255\n% count=0;\n% for i1=0:m*n-1\n% if om(i1+1)==j1\n% count=count+1;\n% end\n% end\n% prob(j1+1)=count/m*n;\n% end\n% figure(16);\n% plot(prob);\n% \n% for j2=0:255\n% count1=0;\n% for i2=0:m*n-1\n% if luma(i2+1)==j2\n% count1=count1+1;\n% end\n% end\n% prob2(j2+1)=count1/m*n;\n% end\n% figure(17);\n% plot(prob2); \n% xlabel('gray levels after mean');\n% ylabel('luma component equilized image after mean');\n% title('processed luma image after mean');\n% ommmmm=p1+p;\n% figure(7);\n% colormap('gray');\n% xlabel('gray level');\n% ylabel('combined lower and upper half luma component equilized image');\n% title('combined luma image');\n% image(ommmmm);\n% cat1=cat(3,om,cb,cr);\n% figure(14);\n% imshow(cat1);\n% % xlabel('gray level(ycbcr)');\n% % ylabel('combined lower and upper half luma,cromablue,croma red component equilized image');\n% % title('luma croma b and r color processed image');\n% catconversion=ycbcr2rgb(cat1);\n% figure(15);\n% imshow(catconversion);\n% xlabel('gray level(rgb)');\n% ylabel('combined lower and upper half RGB component equilized image');\n% title('converted from ycbcr2rgb color(RGB) processed image');\n\n", "meta": {"author": "xingchenzhang", "repo": "VIFB", "sha": "7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa", "save_path": "github-repos/MATLAB/xingchenzhang-VIFB", "path": "github-repos/MATLAB/xingchenzhang-VIFB/VIFB-7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa/methods/MGFF/BBHEwVEDg_gray.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4934683557094477}} {"text": "function [M_low]=voxelate(M,reduction_factor)\n\n% function [M_low]=voxelate(M,reduction_factor)\n% ------------------------------------------------------------------------\n% This function lowers the resulution of a 3D image based on\n% 'reduction_factor'.\n%\n% Kevin Mattheus Moerman\n% kevinmoerman@hotmail.com\n% 25/05/2008\n% ------------------------------------------------------------------------\n\n%%\nnum_dims=ndims(M);\n\nswitch num_dims\n \n case 2\n %Setting up cell shape\n cell_shape_1=reduction_factor*ones(size(M,1)/reduction_factor,1);\n cell_shape_2=reduction_factor*ones(size(M,2)/reduction_factor,1);\n \n %Converting matrix to cell\n M_cell=mat2cell(M, cell_shape_1, cell_shape_2);\n \n %Calculating average for each cell\n M_cell=cellfun(@mean, cellfun(@mean, M_cell, 'UniformOutput',0), 'UniformOutput',0);\n \n case 3\n %Setting up cell shape\n cell_shape_1=reduction_factor*ones(size(M,1)/reduction_factor,1);\n cell_shape_2=reduction_factor*ones(size(M,2)/reduction_factor,1);\n cell_shape_3=reduction_factor*ones(size(M,3)/reduction_factor,1);\n \n %Converting matrix to cell\n M_cell=mat2cell(M, cell_shape_1, cell_shape_2, cell_shape_3);\n \n %Calculating average for each cell\n M_cell=cellfun(@mean, cellfun(@mean, cellfun(@mean, M_cell, 'UniformOutput',0), 'UniformOutput',0), 'UniformOutput',0);\n \nend\n\n\n%Converting cell to matrix\nM_low=cell2mat(M_cell);\n%% OLD VERSION\n%\n% % Setting field of view FOV size\n% FOV=[size(M,1)*voxeldim_high, size(M,2)*voxeldim_high, size(M,3)*voxeldim_high];\n% no_elements=FOV(1)/voxeldim_low;\n%\n% reduction_factor=size(M,1)/no_elements;\n% cell_shape=reduction_factor*ones(size(M,1)/reduction_factor,1);\n%\n% for k=1:size(M,3)\n% M_slice=M(:,:,k);\n% cell_slice=mat2cell(M_slice, cell_shape, cell_shape);\n% column_means = cellfun(@mean, cell_slice, 'UniformOutput',0);\n% total_means = cellfun(@mean, column_means, 'UniformOutput',0);\n% M_means(:,:,k)=cell2mat(total_means);\n% end\n%\n% i=1;\n% for k=1:size(M,3)/reduction_factor\n% M_low(:,:,k)=sum(M_means(:,:,(i:(i+reduction_factor-1))),3) /reduction_factor;\n% i=i+reduction_factor;\n% end\n%\n% %% END\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/voxelate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.4934477641024686}} {"text": "function F = metoffice_experiment_gpfa_gpkron2(datanum, anomalies)\n\n% DEBUGGING!!\ndebug = false;\nif debug\n maxiter = 1;\n N_samples = 2;\nelse\n maxiter = 1000;\n N_samples = 1000;\nend\n\n\n\n\n%\n% Load the data\n%\n\n\n[data,dataset,folder,maskfile] = metoffice_getdata(datanum, anomalies);\nfolder = [folder '/gpfa_gpkron2'];\nmkdir(folder);\ndate = datestr(now,'yyyymmdd');\n\nif anomalies\n disp('Model anomalies')\n comps = [0 10 0]; \n comps_spatial = [0 10 0];\nelse\n disp('Don''t remove climatological averages')\n comps = [5 10 0]; \n comps_spatial = [2 13 0];\nend\n% Number of components\nD = sum(comps);\n\n% Form the data matrix\nY = data.data;\n[M,N] = size(Y);\nObs = ~isnan(Y);\nweights = repmat(data.gridsize, [1, N]);\n\nif false\n gpfafile = ['/share/work/jluttine/metoffice/rectest/gpfa_gpkron2/' ...\n 'results_rectest_hadsst2d1_gpfa_D=6_anomalies=0_20110318'];\n D = 6;\nelse\n gpfafile = [];\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% GPFA inference\n%\n\nif isempty(gpfafile)\n \n %\n % Model for temporal X\n %\n\n covfunc_x = cell(D,1);\n theta_x = cell(D,1);\n is_pseudos_x = false(D,1);\n\n\n % Inputs (assume uniformly spaced time instances which is not exactly correct)\n in_x = linspace(data.time(1), data.time(end), length(data.time));\n pseudo_x = in_x(1:10:end);\n\n % Squared distances for covariance functions\n D2_pp = sq_dist(pseudo_x);\n D2_px = sq_dist(pseudo_x, in_x);\n d2_x = zeros(size(in_x,2),1); %diag(D2_xx);\n D_pp = sqrt(D2_pp);\n D_px = sqrt(D2_px);\n d_x = sqrt(d2_x);\n\n % Distance matrices for covariance functions\n d_xx = sqrt(sq_dist(in_x(:,1),in_x));\n\n ind = 0;\n\n % Periodic components (1 year period) with decay (rational quadratic)\n% $$$ ind = 1:min(D,comps(1));\n% $$$ fprintf('%d periodic components for X\\n', length(ind));\n% $$$ covfunc = @(D,D2) gp_cov_product(gp_cov_periodic(D, 'wavelength', 365), ...\n% $$$ gp_cov_rq(D2));\n% $$$ covfunc_x(ind) = {gp_cov_pseudo(gp_cov_jitter(covfunc(D_pp,D2_pp), 1e-6), ...\n% $$$ covfunc(D_px,D2_px), ...\n% $$$ covfunc(d_x,d2_x))};\n% $$$ theta_x(ind) = columns_to_cells(...\n% $$$ [linspace(1,1,length(ind)) % smoothness of the period\n% $$$ 365*linspace(20,1,length(ind)) % lengthscale of the decay (RQ)\n% $$$ ones(1,length(ind))]); % alpha (RQ)\n% $$$ is_pseudos_x(ind) = true;\n% Periodic components (1 year period) WITHOUT decay\n if comps(1) > 0\n ind = 1:min(D,comps(1));\n fprintf('%d periodic components for X\\n', length(ind));\n covfunc = @(D) gp_cov_periodic(D, 'wavelength', 365);\n covfunc_x(ind) = {gp_cov_pseudo(gp_cov_jitter(covfunc(D_pp), 1e-6), ...\n covfunc(D_px), ...\n covfunc(d_x))};\n theta_x(ind) = columns_to_cells(...\n [linspace(1,0.1,length(ind))]); % smoothness of the period\n is_pseudos_x(ind) = true;\n end\n\n % Slow components (1-20 years): rational quadratic using pseudo inputs\n if comps(2) > 0\n ind = ind(end) + (1:min(D-ind(end),comps(2)));\n fprintf('%d slow components for X\\n', length(ind));\n% $$$ covfunc = @(D2) gp_cov_se(D2); % SE\n covfunc = @(D2) gp_cov_rq(D2); % RQ\n covfunc_x(ind) = {gp_cov_pseudo(gp_cov_jitter(covfunc(D2_pp), 1e-3), ...\n covfunc(D2_px), ...\n covfunc(d2_x))};\n% $$$ theta_x(ind) = columns_to_cells(...\n% $$$ [365*linspace(20,1,length(ind))]); % lengthscale for SE\n theta_x(ind) = columns_to_cells(...\n [365*linspace(4,1,length(ind)) % lengthscale for RQ\n ones(1,length(ind))]); % alpha for RQ\n is_pseudos_x(ind) = true;\n end\n\n % Fast components (4-18 months): piecewise polynomial in 1-D\n % Take advantage of the Toeplitz structure of the covariance matrix\n if comps(3) > 0\n ind = (ind(end)+1):D;\n fprintf('%d fast components for X\\n', length(ind));\n covfunc_x(ind) = {gp_cov_jitter(gp_cov_toeplitz(gp_cov_pp(d_xx,1)))};\n theta_x(ind) = columns_to_cells(...\n [30*linspace(12,4,length(ind))]); % lengthscale or cut-off\n is_pseudos_x(ind) = false;\n end\n\n %\n % Model for spatial W\n %\n\n covfunc_w = cell(D,1);\n theta_w = cell(D,1);\n is_pseudos_w = false(D,1);\n\n % Remove land area grid points\n in_w = data.coordinates;\n\n %% Smooth components (using pseudo inputs)\n\n % Pseudo inputs (uniformly with respect to area size)\n pseudo_w = points_on_sphere(18); % uniform points by number of latitudes\n % Remove pseudo inputs that are on land (the nearest grid point is land)\n ind_pseudo_w = mohsst5_points_to_grid_index(pseudo_w);\n mask = metoffice_get_mask(maskfile);\n pseudo_w(:,~mask(ind_pseudo_w)) = [];\n% $$$ % This code shows the pseudo inputs on the map\n% $$$ figure\n% $$$ map_projection('global-ellipse');\n% $$$ map_plot(pseudo_w,'r+');\n% $$$ map_coast()\n% $$$ map_grid()\n% $$$ return\n\n % Transform inputs to 3-D Euclidean coordinates\n in_w = geographic_to_euclidean(in_w);\n pseudo_w = geographic_to_euclidean(pseudo_w);\n\n % Squared distance matrices for the covariance functions\n D2_ww = sq_dist(in_w);\n D2_pp = sq_dist(pseudo_w);\n D2_pw = sq_dist(pseudo_w, in_w);\n d2_w = diag(D2_ww);\n \n ind = 0;\n \n if comps_spatial(1) > 0\n ind = ind(end) + (1:comps_spatial(1));\n fprintf('%d iid components for W\\n', length(ind));\n \n covfunc_w(ind) = {gp_cov_scale(gp_cov_delta(size(in_w,2)))};\n theta_w(ind) = columns_to_cells(...\n [linspace(1,0.1,length(ind))]); % magnitudes\n end\n\n if comps_spatial(2) > 0\n ind = ind(end) + (1:comps_spatial(2));\n fprintf('%d slow components for W (using %d pseudo inputs)\\n', length(ind), ...\n size(pseudo_w,2));\n\n % Covariance function (scaled squared exponential) with pseudo inputs\n covfunc = @(D2) gp_cov_se(D2);\n covfunc_w(ind) = {gp_cov_pseudo(...\n gp_cov_scale(gp_cov_jitter(covfunc(D2_pp), 1e-3)), ...\n gp_cov_scale(covfunc(D2_pw)), ...\n gp_cov_scale(covfunc(d2_w)))};\n\n % Hyperparameters for the covariance functions\n theta_w(ind) = columns_to_cells(...\n [linspace(1,0.1,length(ind)); % magnitudes\n linspace(4000,1000,length(ind))]); % lengthscales\n is_pseudos_w(ind) = true;\n end\n\n %\n % Process data\n %\n\n % Filename for saving the results\n filename = sprintf('%s/results_rectest_%s_gpfa_D=%d_anomalies=%d_%s', ...\n folder, ...\n dataset, ...\n D, ...\n anomalies, ...\n date);\n\n % Component-wise factorization for X\n X_module = factor_module_gp_factorized(N, covfunc_x, theta_x, ...\n 'update_hyperparameters', [5 10:10:100 100:100:2000], ...\n 'maxiter_hyperparameters', 5, ...\n 'is_pseudo', is_pseudos_x, ...\n 'init', zeros(D,N));\n\n % Component-wise factorization for W\n W_module = factor_module_gp_factorized(M, covfunc_w, theta_w, ...\n 'update_hyperparameters', [5 10:10:100 100:100:2000], ...\n 'maxiter_hyperparameters', 5, ...\n 'is_pseudo', is_pseudos_w);\n\n % Isotropic noise (precisions weighted proportionally to grid size)\n% $$$ figure\n% $$$ mohsst5_mapplot(metoffice_add_land(weights(:,1)));\n% $$$ return\n noise_module = noise_module_isotropic(M, N, 1e-3, 1e-3, ...\n 'init', 10, ...\n 'weights', weights);\n\n % Run GPFA\n Q = gpfa(D, Y, W_module, X_module, noise_module, ...\n 'maxiter', maxiter, ...\n 'rotate', 1:100, ... %[1:50 60:10:2000], ...\n 'autosavefile', filename, ...\n 'autosave', [10:100:2000]);\n\n Yh = Q.W'*Q.X;\n\n % Some performance measures\n fprintf('Weighted training RMSE of the reconstruction: %f\\n', ...\n rmsew(Y(Obs)-Yh(Obs),weights(Obs)));\n\n % Save the results\n save(filename, '-struct', 'Q');\n fprintf('Saved GPFA results to %s\\n', filename);\n\nelse\n \n Q = load(gpfafile);\n \n fprintf('Loaded GPFA results from %s\\n', gpfafile);\n \nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Short-scale GP inference for the residuals\n%\n\n% Reconstruct\nif debug\n Yh = zeros(size(Y));\nelse\n Yh = Q.W'*Q.X;\nend\nYres = Y - Yh;\nclear Q;\n\n%\n% Temporal covariance function (assume uniformly spaced time instances)\n%\n\nd = abs(1-(1:length(data.time)));\ncovfunc1 = gp_cov_toeplitz(gp_cov_pp(d,1));\ntheta_temporal = [7];\n% $$$ covfunc1 = gp_cov_toeplitz(gp_cov_sum(gp_cov_pp(d,1), ...\n% $$$ gp_cov_scale(gp_cov_pp(d,1))));\n% $$$ theta_temporal = [7; % length scale 1\n% $$$ 1.0; % magnitude 2\n% $$$ 3]; % length scale 2\n\n%\n% Spatial covariance function\n%\n\n[LON,LAT] = meshgrid(data.lon,data.lat);\n\nX = geographic_to_euclidean([LON(:)';LAT(:)']);\n\n% Use block-Toeplitz structure for the covariance function\n[lat,lon0] = meshgrid(data.lat,data.lon(1));\nX0 = geographic_to_euclidean([lon0(:)';lat(:)']);\nD = sqrt(sq_dist(X0,X));\ncovfunc2 = gp_cov_jitter(gp_cov_toeplitz_block(gp_cov_pp(D,3)), 1e-3);\ntheta_spatial = nan;\nif datanum <= 4\n % 5x5 SST\n theta_spatial = [3000]; % length scale\nelseif datanum == 5\n % 1x1 sea ice\n theta_spatial = [50];\nelse\n error('Unknown datanum');\nend\n\n% Select sea areas\nsea = metoffice_get_mask(maskfile);\ncovfunc2 = gp_cov_select(covfunc2, sea);\n\n% $$$ % DEBUG: Test solver stuff\n% $$$ K2 = covfunc2(theta_spatial);\n% $$$ S = solver_ldlchol();\n% $$$ R = S.decompose(K2);\n% $$$ L = S.squareroot(R);\n% $$$ K2h = L*L';\n% $$$ norm_err = sqrt(mean((K2(:)-K2h(:)).^2))\n% $$$ L = lchol(K2);\n% $$$ x = randn(length(K2),1);\n% $$$ y = K2 * x;\n% $$$ xh = S.linsolve(R, y);\n% $$$ x_err = sqrt(mean((xh-x).^2))\n% $$$ return\n\n\n\n%\n% Inference\n%\n\nburnin = floor(N_samples/2);\nfolder_samples = sprintf('%s/samples_rectest_%s_gpkron2_%s', ...\n folder, ...\n dataset, ...\n date);\nmkdir(folder_samples);\nfilename = sprintf('%s/results_rectest_%s_gpkron2_D=%d_anomalies=%d_%s', ...\n folder, ...\n dataset, ...\n sum(comps), ...\n anomalies, ...\n date);\nfilename_samples = sprintf('%s/samples_rectest_%s_gpkron2_D=%d_anomalies=%d_%s', ...\n folder_samples, ...\n dataset, ...\n sum(comps), ...\n anomalies, ...\n date);\n\na = 1e-3;\nb = 1e-3;\nlogprior_theta = @(theta) sum(gamma_logpdf(theta, a, b));\ndlogprior_theta = @(theta) gamma_dlogpdf(theta, a, b);\n\n% Initial guess for covariance parameters\ntheta_init = [0.5; ... % total magnitude\n theta_temporal(:); ... % temporal parameters\n 0.5; ... % temporal noise magnitude\n theta_spatial(:); ... % spatial parameters\n 0.5]'; % spatial noise magnitude\n\nsamplefunc = get_sample_function2(numel(theta_init), N_samples, burnin, ...\n filename, filename_samples);\n\n% Weights for the noise levels using the respective grid size\nw = 1./sqrt(cosd(LAT));\nw = w(sea);\n%W = repmat(w(sea), [1,size(Y,2)]);\n\n[get_logpdf, get_dlogpdf, get_rand_model, func_theta] = ...\n gp_init_kron1(covfunc1, ...\n solver_ldlchol(), ...\n covfunc2, ...\n solver_ldlchol(), ...\n logprior_theta, ...\n dlogprior_theta, ...\n samplefunc, ...\n 'noise_scale2', w);\n\n% Transform to log-scale\nfunc_theta = @(logtheta, varargin) func_theta_transformed(logtheta, ...\n exp(logtheta), ...\n func_theta, ...\n varargin{:});\nget_logpdf = @(f_theta) get_logpdf_transformed(f_theta, ...\n get_logpdf, ...\n sum(f_theta.theta_transformed));\nget_dlogpdf = @(df_theta) get_dlogpdf_transformed(df_theta, ...\n get_dlogpdf, ...\n diag(exp(df_theta.theta_transformed)), ...\n ones(size(df_theta.theta_transformed)));\ntheta_init = log(theta_init);\n\n[rand_theta, f_theta] = mcmc_init_slicesampling(theta_init, ...\n get_logpdf, ...\n 'fx', func_theta);\n\nrand_model = get_rand_model(rand_theta, f_theta);\n\n\n\n\n% Gibbs sampling\ntic\ngibbs(Yres,~Obs, N_samples, rand_model);\ntoc\n\n% Check the results\nres = samplefunc();\n\nsave(filename, '-struct', 'res');\ndisp(['Saved short-scale GP results to ', filename]);\n\n% Mean reconstruction\nF = Yh + res.F;\n\nfilename = sprintf('%s/results_rectest_%s_gpfa_gpkron2_D=%d_anomalies=%d_%s', ...\n folder, ...\n dataset, ...\n sum(comps), ...\n anomalies, ...\n date);\nsave(filename, 'F');\ndisp(['Saved total reconstruction to ', filename]);\n\nfprintf('Weighted training RMSE of the reconstruction: %f\\n', ...\n rmsew(Y(Obs)-F(Obs),weights(Obs)));\n\nif nargout < 1\n clear F;\nend\n\nend\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction S = solver_ldlchol()\n\nS.decompose = @decompose;\nS.linsolve = @linsolve;\nS.logdet = @logdet;\nS.inv = @inv;\nS.squareroot = @squareroot;\n \n function S = decompose(K)\n [S.LD,p,S.q] = ldlchol(K);\n if p>0\n error('Matrix must be positive definite');\n end\n end\n \n function x = linsolve(S, y)\n x(S.q,:) = linsolve_ldlchol(S.LD,y(S.q,:));\n end\n \n function ldet = logdet(S)\n ldet = logdet_ldlchol(S.LD);\n end\n \n function A = inv(S)\n %A(S.q,S.q) = spinv_ldlchol(S.LD);\n N = length(S.q);\n R = sparse(1:N,S.q,ones(N,1));\n L = R'*spinv_ldlchol(S.LD)*R;\n end\n \n function L = squareroot(S)\n % WARNING/TODO: This permutation might take A LOT of time..\n % L(S.q,S.q) = ldlchol2lchol(S.LD);\n % Try instead:\n N = length(S.q);\n R = sparse(1:N,S.q,ones(N,1));\n L = R'*ldlchol2lchol(S.LD)*R;\n end\n\nend\n\n\nfunction [f_theta, df_theta] = func_theta_transformed(theta_transformed, ...\n theta, func_theta, varargin)\nif nargout <= 1\n f_theta = func_theta(theta, varargin{:});\n f_theta.theta_transformed = theta_transformed;\nelse\n [f_theta, df_theta] = func_theta(theta, varargin{:});\n f_theta.theta_transformed = theta_transformed;\n df_theta.theta_transformed = theta_transformed;\nend\nend\n\nfunction logpdf_y = get_logpdf_transformed(fy, get_logpdf, logjacobian)\nlogpdf = get_logpdf(fy);\nlogpdf_y = @logpdf_transformed;\n function lpdf = logpdf_transformed(varargin)\n lpdf = logpdf(varargin{:}) + logjacobian;\n end\nend\n\nfunction dlogpdf_y = get_dlogpdf_transformed(dfy, get_dlogpdf, Jacobian, ...\n dlogjacobian)\ndlogpdf = get_dlogpdf(dfy);\ndlogpdf_y = @dlogpdf_transformed;\n function dlpdf = dlogpdf_transformed(varargin)\n dlpdf = dlogpdf(varargin{:});\n dlpdf = Jacobian*dlpdf + dlogjacobian;\n end\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction samplefunc = get_sample_function2(D_theta, N, burnin, filename, filename_samples)\nresults.Y = [];\nresults.F = 0;\nresults.FF = 0;\nresults.theta = zeros(D_theta, N);\nsamplefunc = @process_sample;\nn = 1;\n function res = process_sample(Y, F, theta)\n if nargin >= 1\n % Store results\n results.Y = Y;\n if true && n > burnin\n results.F = (F + (n-burnin-1)*results.F) / (n-burnin);\n end\n if true && n > burnin\n results.FF = (F.*F + (n-burnin-1)*results.FF) / (n-burnin);\n end\n results.theta(:,n) = theta(:);\n % Save results\n fprintf('Saving results to %s..', filename)\n save(filename, '-struct', 'results');\n save(sprintf('%s_F%d',filename_samples,n), 'F');\n fprintf(' done.\\n')\n n = n + 1;\n end\n if nargout >= 1\n % Return results\n res = results;\n end\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction gibbs(Y, Imv, N, rand_model, samplefunc)\n\nY(Imv) = 0;\n\nfor n=1:N\n \n t = cputime();\n Y = rand_model(Y,Imv);\n dt = cputime() - t;\n fprintf('Iteration step %d done. (%f seconds)\\n', n, dt)\n \nend\n\nend\n\n\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/datasets/metoffice/metoffice_experiment_gpfa_gpkron2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.49334277158442075}} {"text": "function result = neg_sampling_objective(head_embedding, tail_embedding, head, tail, weights, a, b, negative_sample_rate, same_embedding)\n%NEG_SAMPLING_OBJECTIVE Given a low-dimensional embedding and weights of\n% 1-simplices of a high-dimensional simplicial complex, compute the\n% associated negative sampling objective. This is the quantity that the\n% original Python UMAP implementation is attempting to minimize by using\n% the negative sampling technique during stochastic gradient descent (SGD).\n% Note that this value is distinct from cross entropy as presented in the\n% original UMAP paper.\n% This calculation uses the modified smooth formula Phi for\n% low-dimensional weight that is used in SGD.\n% Because the computation time is O(n^2), we recommend only using this when\n% n1*n2 <= 1e8.\n%\n% result = neg_sampling_objective(head_embedding, tail_embedding, head, tail, weights, a, b, negative_sample_rate, same_embedding)\n%\n% Parameters\n% ----------\n% n_neighbors: double (optional, default 15)\n% The size of local neighborhood (in terms of number of neighboring\n% sample points) used for manifold approximation. Larger values result\n% in more global views of the manifold, while smaller values result in\n% more local data being preserved. In general values should be in the\n% range 2 to 100.\n% \n% n_components: integer (optional, default 2)\n% The dimension of the space to embed into. This defaults to 2 to\n% provide easy visualization, but can reasonably be set to any integer\n% value in the range 2 to 100.\n% \n% metric: string or function (optional, default 'euclidean')\n% The metric to use to compute distances in high dimensional space. If\n% a string is passed, it must match a valid predefined metric. For now,\n% valid string metrics include:\n% * euclidean (or l2)\n% * manhattan (or l1)\n% * chebyshev (or linf)\n% * correlation\n% * cosine\n% * hamming\n% * jaccard\n% * mahalanobis\n% * minkowski\n% * seuclidean\n% \n% n_epochs: integer (optional)\n% The number of training epochs to be used in optimizing the low\n% dimensional embedding. Larger values result in more accurate\n% embeddings. If 0, a value will be selected based on the size of the\n% input dataset (200 for large datasets, 500 for small).\n% \n% learning_rate: double (optional, default 1)\n% The initial learning rate for the embedding optimization.\n% \n% init: string (optional, default 'spectral')\n% How to initialize the low dimensional embedding. Options are:\n% * 'spectral': use a spectral embedding of the fuzzy 1-skeleton\n% * 'random': assign initial embedding positions at random.\n% * An array of initial embedding positions.\n% \n% min_dist: double (optional, default 0.1)\n% The effective minimum distance between embedded points. Smaller\n% values will result in a more clustered/clumped embedding where nearby\n% points on the manifold are drawn closer together, while larger values\n% will result on a more even dispersal of points. The value should be\n% set relative to the \"spread\" value, which determines the scale at\n% which embedded points will be spread out.\n% \n% spread: double (optional, default 1)\n% The effective scale of embedded points. In combination with\n% \"min_dist\" this determines how clustered/clumped the embedded points\n% are.\n% \n% set_op_mix_ratio: double (optional, default 1)\n% Interpolate between (fuzzy) union and intersection as the set\n% operation used to combine local fuzzy simplicial sets to obtain a\n% global fuzzy simplicial sets. Both fuzzy set operations use the\n% product t-norm. The value of this parameter should be between 0 and\n% 1; a value of 1 will use a pure fuzzy union, while 0 will use a pure\n% fuzzy intersection.\n% \n% local_connectivity: integer (optional, default 1)\n% The local connectivity required -- i.e. the number of nearest\n% neighbors that should be assumed to be connected at a local level.\n% The higher this value the more connected the manifold becomes\n% locally. In practice this should be not more than the local intrinsic\n% dimension of the manifold.\n% \n% repulsion_strength: double (optional, default 1)\n% Weighting applied to negative samples in low dimensional embedding\n% optimization. Values higher than one will result in greater weight\n% being given to negative samples.\n% \n% negative_sample_rate: integer (optional, default 5)\n% The number of negative samples to select per positive sample in the\n% optimization process. Increasing this value will result in greater\n% repulsive force being applied, greater optimization cost, but\n% slightly more accuracy.\n% \n% transform_queue_size: double (optional, default 4)\n% For transform operations (embedding new points using a trained model)\n% this will control how aggressively to search for nearest neighbors.\n% Larger values will result in slower performance but more accurate\n% nearest neighbor evaluation.\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.ad\n% \n% Returns\n% -------\n% result: double\n% The value of the negative sampling objective.\n%\n% See also: CROSS_ENTROPY\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 if n1*n2 > 1e8\n error('HALTED: MATLAB usually freezes for embeddings this large.');\n end\n \n n_other_points = n2;\n if same_embedding\n n_other_points = n_other_points - 1;\n end\n\n full_dists = pdist2(head_embedding, tail_embedding);\n\n Phi = ones(size(full_dists))./(1 + a*(full_dists.^(2*b)));\n if same_embedding\n Phi = Phi - diag(diag(Phi));\n end\n gap_part = sum(log(1 - Phi), 2);\n\n Phi_summands = weights.*(log(Phi(sub2ind(size(Phi), head, tail))) + negative_sample_rate/n_other_points*gap_part(head));\n\n result = -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/neg_sampling_objective.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.4933427543544138}} {"text": "function A01 = synA01min(A11, A00, cmax)\n%-----------------------------------------------------------------------------\n%\n% For each point of colour 01 this function assigns the minimum value at the\n% neighbouring gridpoints of colours 11 and 00.\n%\n% Design and implementation by:\n% Dr. Paul M. de Zeeuw http://homepages.cwi.nl/~pauldz/\n% Last Revision: December 7, 2001.\n% (c) 1998-2002 Stichting CWI, Amsterdam\n%-----------------------------------------------------------------------------\n[n00, m00]=size(A00);\n[n11, m11]=size(A11);\n%[n01, m01]=size(A01);\nn01=n00;\nm01=m11;\nif m01 == m00\n S=min(stripL(extR(A00,cmax)), A00);\nelseif m01 == m00-1 \n S=min(stripL(A00), stripR(A00));\nelse\n disp([' size A11 = ' int2str(size(A11)) ' size A00 = ' int2str(size(A00))]);\n error(' synA01min - A11 and A00 do not match ');\nend\nif n01 == n11\n T=min(A11, stripD(extU(A11, cmax)));\nelseif n01 == n11+1 \n T=min(extD(A11, cmax), extU(A11, cmax));\nelse\n disp([' size A11 = ' int2str(size(A11)) ' size A00 = ' int2str(size(A00))]);\n error(' synA01min - A11 and A00 do not match ');\nend\n%Note: all(size(S) == size(T)) & all(size(S) == [n01 m01]) always holds.\nA01=min(S, T);\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/13507-lisq-a-toolbox-for-the-lifting-scheme-on-2d-quincunx-grids/LISQ/synA01min.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.4933219210052535}} {"text": "function [alpha, beta, gamma, loglik, xi_summed, gamma2] = fwdback(init_state_distrib, ...\n transmat, obslik, varargin)\n% FWDBACK Compute the posterior probs. in an HMM using the forwards backwards algo.\n%\n% [alpha, beta, gamma, loglik, xi, gamma2] = fwdback(init_state_distrib, transmat, obslik, ...)\n%\n% Notation:\n% Y(t) = observation, Q(t) = hidden state, M(t) = mixture variable (for MOG outputs)\n% A(t) = discrete input (action) (for POMDP models)\n%\n% INPUT:\n% init_state_distrib(i) = Pr(Q(1) = i)\n% transmat(i,j) = Pr(Q(t) = j | Q(t-1)=i)\n% or transmat{a}(i,j) = Pr(Q(t) = j | Q(t-1)=i, A(t-1)=a) if there are discrete inputs\n% obslik(i,t) = Pr(Y(t)| Q(t)=i)\n% (Compute obslik using eval_pdf_xxx on your data sequence first.)\n%\n% Optional parameters may be passed as 'param_name', param_value pairs.\n% Parameter names are shown below; default values in [] - if none, argument is mandatory.\n%\n% For HMMs with MOG outputs: if you want to compute gamma2, you must specify\n% 'obslik2' - obslik(i,j,t) = Pr(Y(t)| Q(t)=i,M(t)=j) []\n% 'mixmat' - mixmat(i,j) = Pr(M(t) = j | Q(t)=i) []\n%\n% For HMMs with discrete inputs:\n% 'act' - act(t) = action performed at step t\n%\n% Optional arguments:\n% 'fwd_only' - if 1, only do a forwards pass and set beta=[], gamma2=[] [0]\n% 'scaled' - if 1, normalize alphas and betas to prevent underflow [1]\n% 'maximize' - if 1, use max-product instead of sum-product [0]\n%\n% OUTPUTS:\n% alpha(i,t) = p(Q(t)=i | y(1:t)) (or p(Q(t)=i, y(1:t)) if scaled=0)\n% beta(i,t) = p(y(t+1:T) | Q(t)=i)*p(y(t+1:T)|y(1:t)) (or p(y(t+1:T) | Q(t)=i) if scaled=0)\n% gamma(i,t) = p(Q(t)=i | y(1:T))\n% loglik = log p(y(1:T))\n% xi(i,j,t-1) = p(Q(t-1)=i, Q(t)=j | y(1:T)) - NO LONGER COMPUTED\n% xi_summed(i,j) = sum_{t=}^{T-1} xi(i,j,t) - changed made by Herbert Jaeger\n% gamma2(j,k,t) = p(Q(t)=j, M(t)=k | y(1:T)) (only for MOG outputs)\n%\n% If fwd_only = 1, these become\n% alpha(i,t) = p(Q(t)=i | y(1:t))\n% beta = []\n% gamma(i,t) = p(Q(t)=i | y(1:t))\n% xi(i,j,t-1) = p(Q(t-1)=i, Q(t)=j | y(1:t))\n% gamma2 = []\n%\n% Note: we only compute xi if it is requested as a return argument, since it can be very large.\n% Similarly, we only compute gamma2 on request (and if using MOG outputs).\n%\n% Examples:\n%\n% [alpha, beta, gamma, loglik] = fwdback(pi, A, multinomial_prob(sequence, B));\n%\n% [B, B2] = mixgauss_prob(data, mu, Sigma, mixmat);\n% [alpha, beta, gamma, loglik, xi, gamma2] = fwdback(pi, A, B, 'obslik2', B2, 'mixmat', mixmat);\n\nif nargout >= 5, compute_xi = 1; else compute_xi = 0; end\nif nargout >= 6, compute_gamma2 = 1; else compute_gamma2 = 0; end\n\n[obslik2, mixmat, fwd_only, scaled, act, maximize, compute_xi, compute_gamma2] = ...\n process_options(varargin, ...\n 'obslik2', [], 'mixmat', [], ...\n 'fwd_only', 0, 'scaled', 1, 'act', [], 'maximize', 0, ...\n 'compute_xi', compute_xi, 'compute_gamma2', compute_gamma2);\n\n[Q T] = size(obslik);\n\nif isempty(obslik2)\n compute_gamma2 = 0;\nend\n\nif isempty(act)\n act = ones(1,T);\n transmat = { transmat } ;\nend\n\nscale = ones(1,T);\n\n% scale(t) = Pr(O(t) | O(1:t-1)) = 1/c(t) as defined by Rabiner (1989).\n% Hence prod_t scale(t) = Pr(O(1)) Pr(O(2)|O(1)) Pr(O(3) | O(1:2)) ... = Pr(O(1), ... ,O(T))\n% or log P = sum_t log scale(t).\n% Rabiner suggests multiplying beta(t) by scale(t), but we can instead\n% normalise beta(t) - the constants will cancel when we compute gamma.\n\nloglik = 0;\n\nalpha = zeros(Q,T);\ngamma = zeros(Q,T);\nif compute_xi\n xi_summed = zeros(Q,Q);\nelse\n xi_summed = [];\nend\n\n%%%%%%%%% Forwards %%%%%%%%%%\n\nt = 1;\nalpha(:,1) = init_state_distrib(:) .* obslik(:,t);\nif scaled\n %[alpha(:,t), scale(t)] = normaliseC(alpha(:,t));\n [alpha(:,t), scale(t)] = normalise(alpha(:,t));\nend\nassert(approxeq(sum(alpha(:,t)),1))\nfor t=2:T\n %trans = transmat(:,:,act(t-1))';\n trans = transmat{act(t-1)};\n if maximize\n m = max_mult(trans', alpha(:,t-1));\n %A = repmat(alpha(:,t-1), [1 Q]);\n %m = max(trans .* A, [], 1);\n else\n m = trans' * alpha(:,t-1);\n end\n alpha(:,t) = m(:) .* obslik(:,t);\n if scaled\n %[alpha(:,t), scale(t)] = normaliseC(alpha(:,t));\n [alpha(:,t), scale(t)] = normalise(alpha(:,t));\n end\n if compute_xi & fwd_only % useful for online EM\n %xi(:,:,t-1) = normaliseC((alpha(:,t-1) * obslik(:,t)') .* trans);\n xi_summed = xi_summed + normalise((alpha(:,t-1) * obslik(:,t)') .* trans);\n end\n assert(approxeq(sum(alpha(:,t)),1))\nend\nif scaled\n if any(scale==0)\n loglik = -inf;\n else\n loglik = sum(log(scale));\n end\nelse\n loglik = log(sum(alpha(:,T)));\nend\n\nif fwd_only\n gamma = alpha;\n beta = [];\n gamma2 = [];\n return;\nend\n\n%%%%%%%%% Backwards %%%%%%%%%%\n\nbeta = zeros(Q,T);\nif compute_gamma2\n M = size(mixmat, 2);\n gamma2 = zeros(Q,M,T);\nelse\n gamma2 = [];\nend\n\nbeta(:,T) = ones(Q,1);\n%gamma(:,T) = normaliseC(alpha(:,T) .* beta(:,T));\ngamma(:,T) = normalise(alpha(:,T) .* beta(:,T));\nt=T;\nif compute_gamma2\n denom = obslik(:,t) + (obslik(:,t)==0); % replace 0s with 1s before dividing\n gamma2(:,:,t) = obslik2(:,:,t) .* mixmat .* repmat(gamma(:,t), [1 M]) ./ repmat(denom, [1 M]);\n %gamma2(:,:,t) = normaliseC(obslik2(:,:,t) .* mixmat .* repmat(gamma(:,t), [1 M])); % wrong!\nend\nfor t=T-1:-1:1\n b = beta(:,t+1) .* obslik(:,t+1);\n %trans = transmat(:,:,act(t));\n trans = transmat{act(t)};\n if maximize\n B = repmat(b(:)', Q, 1);\n beta(:,t) = max(trans .* B, [], 2);\n else\n beta(:,t) = trans * b;\n end\n if scaled\n %beta(:,t) = normaliseC(beta(:,t));\n beta(:,t) = normalise(beta(:,t));\n end\n %gamma(:,t) = normaliseC(alpha(:,t) .* beta(:,t));\n gamma(:,t) = normalise(alpha(:,t) .* beta(:,t));\n if compute_xi\n %xi(:,:,t) = normaliseC((trans .* (alpha(:,t) * b')));\n xi_summed = xi_summed + normalise((trans .* (alpha(:,t) * b')));\n end\n if compute_gamma2\n denom = obslik(:,t) + (obslik(:,t)==0); % replace 0s with 1s before dividing\n gamma2(:,:,t) = obslik2(:,:,t) .* mixmat .* repmat(gamma(:,t), [1 M]) ./ repmat(denom, [1 M]);\n %gamma2(:,:,t) = normaliseC(obslik2(:,:,t) .* mixmat .* repmat(gamma(:,t), [1 M]));\n end\nend\n\n% We now explain the equation for gamma2\n% Let zt=y(1:t-1,t+1:T) be all observations except y(t)\n% gamma2(Q,M,t) = P(Qt,Mt|yt,zt) = P(yt|Qt,Mt,zt) P(Qt,Mt|zt) / P(yt|zt)\n% = P(yt|Qt,Mt) P(Mt|Qt) P(Qt|zt) / P(yt|zt)\n% Now gamma(Q,t) = P(Qt|yt,zt) = P(yt|Qt) P(Qt|zt) / P(yt|zt)\n% hence\n% P(Qt,Mt|yt,zt) = P(yt|Qt,Mt) P(Mt|Qt) [P(Qt|yt,zt) P(yt|zt) / P(yt|Qt)] / P(yt|zt)\n% = P(yt|Qt,Mt) P(Mt|Qt) P(Qt|yt,zt) / P(yt|Qt)\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/HMM/fwdback.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.4933219119676129}} {"text": "function [jac,err] = jacobianest(fun,x0)\n% gradest: estimate of the Jacobian matrix of a vector valued function of n variables\n% usage: [jac,err] = jacobianest(fun,x0)\n%\n%\n% arguments: (input)\n% fun - (vector valued) analytical function to differentiate.\n% fun must be a function of the vector or array x0.\n%\n% x0 - vector location at which to differentiate fun\n% If x0 is an nxm array, then fun is assumed to be\n% a function of n*m variables.\n%\n%\n% arguments: (output)\n% jac - array of first partial derivatives of fun.\n% Assuming that x0 is a vector of length p\n% and fun returns a vector of length n, then\n% jac will be an array of size (n,p)\n%\n% err - vector of error estimates corresponding to\n% each partial derivative in jac.\n%\n%\n% Example: (nonlinear least squares)\n% xdata = (0:.1:1)';\n% ydata = 1+2*exp(0.75*xdata);\n% fun = @(c) ((c(1)+c(2)*exp(c(3)*xdata)) - ydata).^2;\n%\n% [jac,err] = jacobianest(fun,[1 1 1])\n%\n% jac =\n% -2 -2 0\n% -2.1012 -2.3222 -0.23222\n% -2.2045 -2.6926 -0.53852\n% -2.3096 -3.1176 -0.93528\n% -2.4158 -3.6039 -1.4416\n% -2.5225 -4.1589 -2.0795\n% -2.629 -4.7904 -2.8742\n% -2.7343 -5.5063 -3.8544\n% -2.8374 -6.3147 -5.0518\n% -2.9369 -7.2237 -6.5013\n% -3.0314 -8.2403 -8.2403\n%\n% err =\n% 5.0134e-15 5.0134e-15 0\n% 5.0134e-15 0 2.8211e-14\n% 5.0134e-15 8.6834e-15 1.5804e-14\n% 0 7.09e-15 3.8227e-13\n% 5.0134e-15 5.0134e-15 7.5201e-15\n% 5.0134e-15 1.0027e-14 2.9233e-14\n% 5.0134e-15 0 6.0585e-13\n% 5.0134e-15 1.0027e-14 7.2673e-13\n% 5.0134e-15 1.0027e-14 3.0495e-13\n% 5.0134e-15 1.0027e-14 3.1707e-14\n% 5.0134e-15 2.0053e-14 1.4013e-12\n%\n% (At [1 2 0.75], jac should be numerically zero)\n%\n%\n% See also: derivest, gradient, gradest\n%\n%\n% Author: John D'Errico\n% e-mail: woodchips@rochester.rr.com\n% Release: 1.0\n% Release date: 3/6/2007\n\n% get the length of x0 for the size of jac\nnx = numel(x0);\n\nMaxStep = 100;\nStepRatio = 2.0000001;\n\n% was a string supplied?\nif ischar(fun)\n fun = str2func(fun);\nend\n\n% get fun at the center point\nf0 = fun(x0);\nf0 = f0(:);\nn = length(f0);\nif n==0\n % empty begets empty\n jac = zeros(0,nx);\n err = jac;\n return\nend\n\nrelativedelta = MaxStep*StepRatio .^(0:-1:-25);\nnsteps = length(relativedelta);\n\n% total number of derivatives we will need to take\njac = zeros(n,nx);\nerr = jac;\nfor i = 1:nx\n x0_i = x0(i);\n if x0_i ~= 0\n delta = x0_i*relativedelta;\n else\n delta = relativedelta;\n end\n\n % evaluate at each step, centered around x0_i\n % difference to give a second order estimate\n fdel = zeros(n,nsteps);\n for j = 1:nsteps\n fdif = fun(swapelement(x0,i,x0_i + delta(j))) - ...\n fun(swapelement(x0,i,x0_i - delta(j)));\n\n fdel(:,j) = fdif(:);\n end\n\n % these are pure second order estimates of the\n % first derivative, for each trial delta.\n derest = fdel.*repmat(0.5 ./ delta,n,1);\n\n % The error term on these estimates has a second order\n % component, but also some 4th and 6th order terms in it.\n % Use Romberg exrapolation to improve the estimates to\n % 6th order, as well as to provide the error estimate.\n\n % loop here, as rombextrap coupled with the trimming\n % will get complicated otherwise.\n for j = 1:n\n [der_romb,errest] = rombextrap(StepRatio,derest(j,:),[2 4]);\n\n % trim off 3 estimates at each end of the scale\n nest = length(der_romb);\n trim = [1:3, nest+(-2:0)];\n [der_romb,tags] = sort(der_romb);\n der_romb(trim) = [];\n tags(trim) = [];\n\n errest = errest(tags);\n\n % now pick the estimate with the lowest predicted error\n [err(j,i),ind] = min(errest);\n jac(j,i) = der_romb(ind);\n end\nend\n\nend % mainline function end\n\n% =======================================\n% sub-functions\n% =======================================\nfunction vec = swapelement(vec,ind,val)\n% swaps val as element ind, into the vector vec\nvec(ind) = val;\n\nend % sub-function end\n\n% ============================================\n% subfunction - romberg extrapolation\n% ============================================\nfunction [der_romb,errest] = rombextrap(StepRatio,der_init,rombexpon)\n% do romberg extrapolation for each estimate\n%\n% StepRatio - Ratio decrease in step\n% der_init - initial derivative estimates\n% rombexpon - higher order terms to cancel using the romberg step\n%\n% der_romb - derivative estimates returned\n% errest - error estimates\n% amp - noise amplification factor due to the romberg step\n\nsrinv = 1/StepRatio;\n\n% do nothing if no romberg terms\nnexpon = length(rombexpon);\nrmat = ones(nexpon+2,nexpon+1);\n% two romberg terms\nrmat(2,2:3) = srinv.^rombexpon;\nrmat(3,2:3) = srinv.^(2*rombexpon);\nrmat(4,2:3) = srinv.^(3*rombexpon);\n\n% qr factorization used for the extrapolation as well\n% as the uncertainty estimates\n[qromb,rromb] = qr(rmat,0);\n\n% the noise amplification is further amplified by the Romberg step.\n% amp = cond(rromb);\n\n% this does the extrapolation to a zero step size.\nne = length(der_init);\nrhs = vec2mat(der_init,nexpon+2,ne - (nexpon+2));\nrombcoefs = rromb\\(qromb'*rhs);\nder_romb = rombcoefs(1,:)';\n\n% uncertainty estimate of derivative prediction\ns = sqrt(sum((rhs - rmat*rombcoefs).^2,1));\nrinv = rromb\\eye(nexpon+1);\ncov1 = sum(rinv.^2,2); % 1 spare dof\nerrest = s'*12.7062047361747*sqrt(cov1(1));\n\nend % rombextrap\n\n\n% ============================================\n% subfunction - vec2mat\n% ============================================\nfunction mat = vec2mat(vec,n,m)\n% forms the matrix M, such that M(i,j) = vec(i+j-1)\n[i,j] = ndgrid(1:n,0:m-1);\nind = i+j;\nmat = vec(ind);\nif n==1\n mat = mat';\nend\n\nend % vec2mat", "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/DERIVESTsuite/jacobianest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175139669998, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.49321213691533333}} {"text": "function A10 = synA10max(A11, A00, cmin)\n%-----------------------------------------------------------------------------\n%\n% For each point of colour 10 this function assigns the maximum value at the\n% neighbouring gridpoints of colours 11 and 00.\n%\n% Design and implementation by:\n% Dr. Paul M. de Zeeuw http://homepages.cwi.nl/~pauldz/\n% Last Revision: December 7, 2001.\n% (c) 1998-2002 Stichting CWI, Amsterdam\n%-----------------------------------------------------------------------------\n[n00, m00]=size(A00);\n[n11, m11]=size(A11);\nn10=n11;\nm10=m00;\n%[n10, m10]=size(A10);\nif m10 == m11\n S=max(A11, stripR(extL(A11, cmin)));\nelseif m10 == m11+1 \n S=max(extL(A11, cmin), extR(A11, cmin));\nelse\n disp([' size A11 = ' int2str(size(A11)) ' size A00 = ' int2str(size(A00))]);\n error(' synA10max - A11 and A00 do not match ');\nend\nif n10 == n00\n T=max(A00, stripU(extD(A00, cmin)));\nelseif n10 == n00-1 \n T=max(stripD(A00), stripU(A00));\nelse\n disp([' size A11 = ' int2str(size(A11)) ' size A00 = ' int2str(size(A00))]);\n error(' synA10max - A11 and A00 do not match ');\nend\n%Note: all(size(S) == size(T)) & all(size(S) == [n10 m10]) always holds.\nA10=max(S, T);\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/13507-lisq-a-toolbox-for-the-lifting-scheme-on-2d-quincunx-grids/LISQ/synA10max.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6893056040203136, "lm_q1q2_score": 0.49314576954415335}} {"text": "function Fu = computeFu(m,B,I)\n Fu = [ 0 0;...\n 0 0;...\n 0 0;...\n (1/m) (1/m);...\n 0 0;...\n (-B/I) (B/I)];\nend", "meta": {"author": "ccalas", "repo": "mpc", "sha": "2b30095dc94efb7799e861eb5acc6fe02110a328", "save_path": "github-repos/MATLAB/ccalas-mpc", "path": "github-repos/MATLAB/ccalas-mpc/mpc-2b30095dc94efb7799e861eb5acc6fe02110a328/computeFu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4930783112987464}} {"text": "function risultati = fhme(net, nodes_info, data, n)\n%HMEFWD\tForward propagation through an HME model\n%\n% Each row of the (n x class_num) matrix 'risultati' containes the estimated class posterior prob.\n%\n% ----------------------------------------------------------------------------------------------------\n% -> pierpaolo_b@hotmail.com or -> pampo@interfree.it\n% ----------------------------------------------------------------------------------------------------\n%\nns=net.node_sizes;\nif nargin==3\n ndata=n;\nelse\n ndata=size(data, 1);\nend\naltezza=size(ns,2);\ncoeff=cell(altezza-1,1);\nfor m=1:ndata\n %- i=2 --------------------------------------------------------------------------------------\n s=struct(net.CPD{2}); \n if nodes_info(1,2)==0,\n mu=[]; W=[]; predict=[];\n mu=s.mean(:,:);\n W=s.weights(:,:,:);\n predict=mu(:,:)+W(:,:,:)*data(m,:)'; \n coeff{1,1}=predict'; \n elseif nodes_info(1,2)==1,\n coeff{1,1}=fglm(s.glim{1}, data(m,:));\n else,\n coeff{1,1}=fmlp(s.mlp{1}, data(m,:));\n end\n %----------------------------------------------------------------------------------------------\n if altezza>3,\n for i=3:altezza-1,\n s=[]; f=[]; dpsz=[];\n f=family(net.dag,i); f=f(2:end-1); dpsz=prod(ns(f));\n s=struct(net.CPD{i});\n for j=1:dpsz,\n if nodes_info(1,i)==1,\n coeff{i-1,1}(j,:)=coeff{i-2,1}(1,j)*fglm(s.glim{j}, data(m,:));\n else\n coeff{i-1,1}(j,:)=coeff{i-2,1}(1,j)*fmlp(s.mlp{j}, data(m,:));\n end\n end \n app=cat(2, coeff{i-1,1}(:)); coeff{i-1,1}=app'; clear app;\n end\n end\n %- i=altezza ----------------------------------------------------------------------------------\n if altezza>2,\n i=altezza;\n s=[]; f=[]; dpsz=[];\n f=family(net.dag,i); f=f(2:end-1); dpsz=prod(ns(f));\n s=struct(net.CPD{i});\n if nodes_info(1,i)==0, \n mu=[]; W=[];\n mu=s.mean(:,:);\n W=s.weights(:,:,:);\n end\n for j=1:dpsz,\n if nodes_info(1,i)==0, \n predict=[];\n predict=mu(:,j)+W(:,:,j)*data(m,:)'; \n coeff{i-1,1}(j,:)=coeff{i-2,1}(1,j)*predict'; \n elseif nodes_info(1,i)==1,\n coeff{i-1,1}(j,:)=coeff{i-2,1}(1,j)*fglm(s.glim{j}, data(m,:));\n else\n coeff{i-1,1}(j,:)=coeff{i-2,1}(1,j)*fmlp(s.mlp{j}, data(m,:));\n end\n end\n end\n %----------------------------------------------------------------------------------------------\n risultati(m,:)=sum(coeff{altezza-1,1},1);\n clear coeff; coeff=cell(altezza-1,1);\nend\nreturn\n\n%-------------------------------------------------------------------\n\nfunction [y, a] = fglm(net, x)\n%GLMFWD\tForward propagation through 1-layer net->GLM statistical model\n\nndata = size(x, 1);\n\na = x*net.w1 + ones(ndata, 1)*net.b1;\n\nnout = size(a,2);\n% Ensure that sum(exp(a), 2) does not overflow\nmaxcut = log(realmax) - log(nout);\n% Ensure that exp(a) > 0\nmincut = log(realmin);\na = min(a, maxcut);\na = max(a, mincut);\ntemp = exp(a);\ny = temp./(sum(temp, 2)*ones(1,nout));\n\n%-------------------------------------------------------------------\n\nfunction [y, z, a] = fmlp(net, x)\n%MLPFWD\tForward propagation through 2-layer network.\n\nndata = size(x, 1);\n\nz = tanh(x*net.w1 + ones(ndata, 1)*net.b1);\na = z*net.w2 + ones(ndata, 1)*net.b2; \ntemp = exp(a);\nnout = size(a,2);\ny = temp./(sum(temp,2)*ones(1,nout));\n\n%-------------------------------------------------------------------\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/examples/static/HME/fhme.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4927741868094583}} {"text": "% \n% LibQPEP: A Library for Globally Optimal Solving Quadratic Pose Estimation Problems (QPEPs),\n% It also gives highly accurate uncertainty description of the solutions.\n%\n%\n% Article: \n% Wu, J., Zheng, Y., Gao, Z., Jiang, Y., Hu, X., Zhu, Y., Jiao, J., Liu, M. (2020)\n% Quadratic Pose Estimation Problems: Globally Optimal Solutions, \n% Solvability/Observability Analysis and Uncertainty Description.\n% IEEE Transactions on Robotics.\n% https://doi.org/10.1109/TRO.2022.3155880\n%\n%\n% Authors: Jin Wu and Ming Liu\n% Affiliation: Hong Kong University of Science and Technology (HKUST)\n% Emails: jin_wu_uestc@hotmail.com; eelium@ust.hk\n% Websites: https://zarathustr.github.io\n% https://ram-lab.com\n%\n%\n% test_stewart.m: The QPEP illustration of forwart kinematics of hexapod\n% Stewart platform\n\n\nclear all\nclose all\nclc\n\nif(verLessThan('matlab', '8.0.0'))\n error('The MATLAB version is too old to be supported.'); \nend\n\nformat long g\n\naddpath('func_files');\naddpath('solvers');\naddpath('utils');\naddpath('homotopy');\n\nR0 = angle2dcm(-8 * pi / 180, 12 * pi / 180, -15 * pi / 180, 'XYZ');\nq0 = dcm2quat(R0).';\nif(q0(1) < 0)\n q0 = - q0;\nend\nt0 = 1e-2 * randn(3, 1);\nX0 = inv([R0, t0;\n zeros(1, 3), 1]);\n \nbase = [\n 0.1448888739433600, 1, 0.0388228567653781;\n -0.0388228567653781, 1, 0.1448888739433600;\n -0.1060660171779820, 1, 0.1060660171779820;\n -0.1060660171779820, 1, -0.1060660171779820;\n -0.0388228567653781, 1, -0.1448888739433600;\n 0.1448888739433600, 1, -0.0388228567653781;\n ].';\nplat = [\n 0.0707106781186548, 1, 0.07071067811865480;\n 0.0258819045102521, 1, 0.09659258262890680;\n -0.0965925826289068, 1, 0.02588190451025210;\n -0.0965925826289068, 1, -0.0258819045102521;\n 0.0258819045102521, 1, -0.0965925826289068;\n 0.0707106781186548, 1, -0.0707106781186548;\n ].';\n\n\n\nconv = [\n 1, 0, 0;\n 0, 0, 1;\n 0, -1, 0;\n ];\nheight = 0.15;\nbase = conv * base;\nplat = conv * plat;\nplat(3, :) = plat(3, :) + height;\nplat00 = plat;\nbase00 = base;\n\n\n\nleg0 = zeros(6, 1);\nplat0 = zeros(3, 6);\nfor i = 1 : 6\n plat0(:, i) = R0 * plat(:, i) + t0;\n res = base(:, i) - plat0(:, i);\n leg0(i) = sqrt(res.' * res);\nend\ncolors = linspecer(8);\n\nfigure(1);\nsubplot(1, 2, 1);\nplot3(base(1, :), base(2, :), base(3, :), 'LineStyle', 'None', 'Marker', '.', 'MarkerSize', 10); hold on\nplot3(base(1, 1 : 6), base(2, 1 : 6), base(3, 1 : 6), 'LineStyle', '-', 'LineWidth', 2, 'Marker', 'None'); hold on\nplot3([base(1, 1), base(1, 6)], [base(2, 1), base(2, 6)], [base(3, 1), base(3, 6)], 'LineStyle', '-', 'LineWidth', 2, 'Marker', 'None'); hold on\nplot3(plat0(1, :), plat0(2, :), plat0(3, :), 'LineStyle', 'None', 'Marker', '.', 'MarkerSize', 10); hold on\nplot3(plat0(1, 1 : 6), plat0(2, 1 : 6), plat0(3, 1 : 6), 'LineStyle', '-', 'LineWidth', 2, 'Marker', 'None'); hold on\nplot3([plat0(1, 1), plat0(1, 6)], [plat0(2, 1), plat0(2, 6)], [plat0(3, 1), plat0(3, 6)], 'LineStyle', '-', 'LineWidth', 2, 'Marker', 'None'); hold on\nfor i = 1 : 6\n plot3([base(1, i), plat0(1, i)], [base(2, i), plat0(2, i)], [base(3, i), plat0(3, i)], 'LineStyle', '-', 'LineWidth', 4, 'Marker', 'None'); hold on\nend\nhold on\nfill3(base(1, :), base(2, :), base(3, :), colors(8, :)); hold on\nfill3(plat0(1, :), plat0(2, :), plat0(3, :), colors(5, :)); hold off\ngrid on\ngrid minor\ntitle('Reference Result', 'Interpreter', 'LaTeX', 'FontSize', 14);\n\n\nbase_ = base.';\nplat_ = plat.';\ncounter = 1;\nbase = [];\nplat = [];\nfor i = 1 : 6\n base = [base; base_(i, :)];\n plat = [plat; plat_(i, :)];\n if(i < 6)\n tmp = (base_(i, :) + base_(i + 1, :)) / 2;\n base = [base; tmp];\n \n tmp = (plat_(i, :) + plat_(i + 1, :)) / 2;\n plat = [plat; tmp];\n end\n \nend\nbase = base.';\nplat = plat.';\nlen = size(base, 2);\n\n\nleg0 = zeros(len, 1);\nplat0 = zeros(3, len);\nfor i = 1 : len\n plat0(:, i) = R0 * plat(:, i) + t0;\n res = base(:, i) - plat0(:, i);\n leg0(i) = sqrt(res.' * res);\nend\n\n\nsyms q0 q1 q2 q3\nq = [q0; q1; q2; q3];\nsyms t1 t2 t3;\nt = [t1; t2; t3];\nR = q2R(q);\nsyms r1 r2 r3 r4\nr = [r1; r2; r3; r4];\nrr = r(1 : 3);\neqs = sym(zeros(len + 3, 1));\nfor i = 1 : len\n eqs(i) = base(:, i).' * base(:, i) - 2 * plat(:, i).' * R.' * base(:, i) + ...\n plat(:, i).' * plat(:, i) - 2 * base(:, i).' * t + 2 * plat(:, i).' * rr + r4 - leg0(i)^2;\nend\neqs(len + 1) = q.' * q - 1;\neqs(len + 2) = rr.' * rr - r4;\neqs(len + 3) = t.' * t - r4;\neqs = expand(eqs);\nx = [q; t; r];\nH = expand(jacobian(eqs, x).' * eqs);\nassumeAlso(q.' * q == 1);\nassumeAlso(rr.' * rr - r4 == 0);\nassumeAlso(t.' * t - r4 == 0);\neq = vpa(expand(simplify(H)), 32);\n\neq_ = eq(1 : 4);\nG = jacobian(eq(5 : 11), [t; r]);\nss = - pinv(G) * (eq(5 : 11) - G * [t; r]);\nss = neglect_tiny_terms(ss, 32);\nss = ss.';\neq_ = eq(1 : 4);\neq_ = subs(eq_, t1, ss(1));\neq_ = subs(eq_, t2, ss(2));\neq_ = subs(eq_, t3, ss(3));\neq_ = subs(eq_, r1, ss(4));\neq_ = subs(eq_, r2, ss(5));\neq_ = subs(eq_, r3, ss(6));\neq_ = subs(eq_, r4, ss(7));\nt_func = matlabFunction([ss(1); ss(2); ss(3)], 'Vars', {q});\nr_func = matlabFunction([ss(4); ss(5); ss(6)], 'Vars', {q});\nr4_func = matlabFunction(ss(7), 'Vars', {q});\neq_ = vpa(expand(eval(eq_)), 32);\nsyms lambda\neq_ = [\n neglect_tiny_terms(eq_, 32).';\n q.' * q - 1;\n ]\n\neqs = [\n eq_(1 : 4) + lambda * q;\n eq_(5);\n ];\nstr = '';\nfor i = 1 : length(eqs)\n str = strcat(str, sprintf(' PP{%d} = char(vpa(%%s, 32));', i));\nend\n \nstr_ = sprintf(str, char(eqs(1)), ...\n char(eqs(2)), ...\n char(eqs(3)), ...\n char(eqs(4)), ...\n char(eqs(5)));\neval(str_);\n[S, vars] = psolve(PP);\nS = S.';\nSS = S;\nfor i = 1 : length(vars)\n if(strcmp(vars{i}, 'q0'))\n SS(:, 1) = S(:, i);\n elseif(strcmp(vars{i}, 'q1'))\n SS(:, 2) = S(:, i);\n elseif(strcmp(vars{i}, 'q2'))\n SS(:, 3) = S(:, i);\n elseif(strcmp(vars{i}, 'q3'))\n SS(:, 4) = S(:, i);\n elseif(strcmp(vars{i}, 'lambda'))\n SS(:, 5) = S(:, i);\n end\nend\nS = real(SS);\nxs_ = S;\nsols = SS.';\n \nnum = size(sols, 2);\nsol = zeros(4, num);\nts = zeros(3, num);\nLs = 1e50 * ones(num, 1);\nq_true = dcm2quat(R0).';\nif(q_true(1) < 0)\n q_true = - q_true;\nend\nfor i = 1 : num\n sol(:, i) = real(sols(1 : 4, i));\n sol(:, i) = sol(:, i) ./ norm(sol(:, i));\n if(sol(1, i) < 0)\n sol(:, i) = - sol(:, i);\n end\n C = q2R(sol(:, i));\n t = t_func(sol(:, i));\n r4 = r4_func(sol(:, i));\n ts(:, i) = t;\n res = abs(q_true - sol(:, i));\n loss = res.' * res;\n Ls(i) = loss;\nend\n[~, idx] = sort(Ls);\n\nq_ = sol(:, idx(1)).'\nq_true_ = q_true.'\n\n\nR_ = quat2dcm(sol(:, idx(1)).');\nt_ = t0;\nplat0 = zeros(3, 6);\nfor i = 1 : 6\n plat0(:, i) = R_ * plat00(:, i) + t_;\nend\nbase = base00;\n\n\n\nsubplot(1, 2, 2);\nplot3(base(1, :), base(2, :), base(3, :), 'LineStyle', 'None', 'Marker', '.', 'MarkerSize', 10); hold on\nplot3(base(1, 1 : 6), base(2, 1 : 6), base(3, 1 : 6), 'LineStyle', '-', 'LineWidth', 2, 'Marker', 'None'); hold on\nplot3([base(1, 1), base(1, 6)], [base(2, 1), base(2, 6)], [base(3, 1), base(3, 6)], 'LineStyle', '-', 'LineWidth', 2, 'Marker', 'None'); hold on\nplot3(plat0(1, :), plat0(2, :), plat0(3, :), 'LineStyle', 'None', 'Marker', '.', 'MarkerSize', 10); hold on\nplot3(plat0(1, 1 : 6), plat0(2, 1 : 6), plat0(3, 1 : 6), 'LineStyle', '-', 'LineWidth', 2, 'Marker', 'None'); hold on\nplot3([plat0(1, 1), plat0(1, 6)], [plat0(2, 1), plat0(2, 6)], [plat0(3, 1), plat0(3, 6)], 'LineStyle', '-', 'LineWidth', 2, 'Marker', 'None'); hold on\nfor i = 1 : 6\n plot3([base(1, i), plat0(1, i)], [base(2, i), plat0(2, i)], [base(3, i), plat0(3, i)], 'LineStyle', '-', 'LineWidth', 4, 'Marker', 'None'); hold on\nend\nhold on\nfill3(base(1, :), base(2, :), base(3, :), colors(8, :)); hold on\nfill3(plat0(1, :), plat0(2, :), plat0(3, :), colors(5, :)); hold off\ngrid on\ngrid minor\ntitle('QPEP Result', 'Interpreter', 'LaTeX', 'FontSize', 14);\n\nif(~ispc())\n set(gcf, 'Position', [634 780 1159 320])\nend\n\n\n\n\n\n\n\n\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/test_stewart.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.49274814949026274}} {"text": "function [ a, det, inert ] = chidi ( a, lda, n, ipvt, job )\n\n%*****************************************************************************80\n%\n%% CHIDI computes the determinant and inverse of a matrix factored by CHIFA.\n%\n% Discussion:\n%\n% CHIDI computes the determinant, inertia (number of positive, zero,\n% and negative eigenvalues) and inverse of a complex hermitian matrix\n% using the factors from CHIFA.\n%\n% A division by zero may occur if the inverse is requested\n% and CHICO has set RCOND == 0.0 or CHIFA has set INFO /= 0.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 May 2007\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Reference:\n%\n% Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart,\n% LINPACK User's Guide,\n% SIAM, 1979,\n% ISBN13: 978-0-898711-72-1,\n% LC: QA214.L56.\n%\n% Parameters:\n%\n% Input, complex A(LDA,N); the factored matrix from CHIFA. \n%\n% Input, integer LDA, the leading dimension of A.\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, integer IPVT(N), the pivot vector from CHIFA.\n%\n% Input, integer JOB, has the decimal expansion ABC where:\n% if C /= 0, the inverse is computed,\n% if B /= 0, the determinant is computed,\n% if A /= 0, the inertia is computed.\n% For example, JOB = 111 gives all three.\n%\n% Output, complex A(LDA,N); if the inverse was requested, A contains\n% the inverse matrix. The strict lower triangle of A is never\n% referenced.\n%\n% Output, real DET(2), the determinant of the original matrix.\n% Determinant = DET(1) * 10.0**DET(2) with 1.0 <= abs ( DET(1) ) < 10.0\n% or DET(1) = 0.0.\n%\n% Output, integer INERT(3), the inertia of the original matrix.\n% INERT(1) = number of positive eigenvalues.\n% INERT(2) = number of negative eigenvalues.\n% INERT(3) = number of zero eigenvalues.\n%\n inert = [];\n det = [];\n\n noinv = floor ( mod ( job, 10 ) ) == 0;\n nodet = floor ( mod ( job, 100 ) / 10 ) == 0;\n noert = floor ( mod ( job, 1000 ) / 100 ) == 0;\n\n if ( ~nodet || ~noert )\n\n if ( ~noert )\n inert(1:3) = 0;\n end\n\n if ( ~nodet )\n det(1) = 1.0;\n det(2) = 0.0;\n end\n\n t = 0.0;\n\n for k = 1 : n\n\n d = real ( a(k,k) );\n%\n% Check if 1 by 1.\n%\n if ( ipvt(k) <= 0 )\n%\n% 2 by 2 block\n% Use DET = ( D / T * C - T ) * T, T = abs ( S )\n% to avoid underflow/overflow troubles.\n% Take two passes through scaling. Use T for flag.\n%\n if ( t == 0.0 )\n t = abs ( a(k,k+1) );\n d = ( d / t ) * real ( a(k+1,k+1) ) - t;\n else\n d = t;\n t = 0.0;\n end\n\n end\n\n if ( ~noert )\n if ( 0.0 < d )\n inert(1) = inert(1) + 1;\n elseif ( d < 0.0 )\n inert(2) = inert(2) + 1;\n elseif ( d == 0.0 )\n inert(3) = inert(3) + 1;\n end\n end\n\n if ( ~nodet )\n\n det(1) = det(1) * d;\n\n if ( det(1) ~= 0.0 )\n\n while ( abs ( det(1) ) < 1.0 )\n det(1) = det(1) * 10.0;\n det(2) = det(2) - 1.0;\n end\n\n while ( 10.0 <= abs ( det(1) ) )\n det(1) = det(1) / 10.0;\n det(2) = det(2) + 1.0;\n end\n\n end\n\n end\n\n end\n\n end\n%\n% Compute inverse(A).\n%\n if ( ~noinv )\n\n k = 1;\n\n while ( k <= n )\n\n km1 = k - 1;\n\n if ( 0 <= ipvt(k) )\n%\n% 1 by 1\n%\n a(k,k) = 1.0 / real ( a(k,k) );\n\n if ( 1 <= km1 )\n\n work(1:km1) = a(1:km1,k);\n\n for j = 1 : km1\n a(j,k) = work(1:j) * conj ( a(1:j,j) );\n a(1:j-1,k) = a(1:j-1,k) + work(j) * a(1:j-1,j);\n end\n\n a(k,k) = a(k,k) + real ( conj ( work(1:km1) ) * a(1:km1,k) );\n\n end\n\n kstep = 1;\n\n else\n%\n% 2 by 2\n%\n t = abs ( a(k,k+1) );\n ak = real ( a(k,k) ) / t;\n akp1 = real ( a(k+1,k+1) ) / t;\n akkp1 = a(k,k+1) / t;\n d = t * ( ak * akp1 - 1.0 );\n a(k,k) = akp1 / d;\n a(k+1,k+1) = ak / d;\n a(k,k+1) = -akkp1 / d;\n\n if ( 1 <= km1 )\n\n work(1:km1) = a(1:km1,k+1);\n\n for j = 1 : km1\n a(j,k+1) = work(1:j) * conj ( a(1:j,j) );\n a(1:j-1,k+1) = a(1:j-1,k+1) + work(j) * a(1:j-1,j);\n end\n\n a(k+1,k+1) = a(k+1,k+1) + ...\n real ( conj ( work(1:km1) ) * a(1:km1,k+1) );\n\n a(k,k+1) = a(k,k+1) ...\n + transpose ( conj ( a(1:km1,k) ) ) * a(1:km1,k+1);\n\n work(1:km1) = a(1:km1,k);\n\n for j = 1 : km1\n a(j,k) = work(1:j) * conj ( a(1:j,j) );\n a(1:j-1,k) = a(1:j-1,k) + work(j) * a(1:j-1,j);\n end\n\n a(k,k) = a(k,k) + real ( conj ( work(1:km1) ) * a(1:km1,k) );\n\n end\n\n kstep = 2;\n\n end\n%\n% Swap\n%\n ks = abs ( ipvt(k) );\n\n if ( ks ~= k )\n\n temp = a(1:ks,ks);\n a(1:ks,ks) = a(1:ks,k);\n a(1:ks,k) = temp;\n\n for j = k : -1 : ks\n temp = conj ( a(j,k) );\n a(j,k) = conj ( a(ks,j) );\n a(ks,j) = temp;\n end\n\n if ( kstep ~= 1 )\n temp = a(ks,k+1);\n a(ks,k+1) = a(k,k+1);\n a(k,k+1) = temp;\n end\n\n end\n\n k = k + kstep;\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/linpack_c/chidi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.4927481424605538}} {"text": "function u = tan(a)\n%TAN Slope tangent tan(a)\n%\n\n% written 12/06/98 S.M. Rump\n% modified 04/04/04 S.M. Rump set round to nearest for safety\n% modified 04/06/05 S.M. Rump rounding unchanged\n% modified 09/28/08 S.M. Rump check for rounding to nearest improved\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 INTLAB_SLOPE = getappdata(0,'INTLAB_SLOPE');\n\n u = a;\n\n u.r = tan(a.r);\n indexc = 1:INTLAB_SLOPE.NUMVAR;\n indexr = 2:INTLAB_SLOPE.NUMVAR+1;\n Xxs = hull(a.r(:,indexc),a.r(:,indexr));\n u.s = a.s ./ sqr(cos(Xxs));\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/slope/@slope/tan.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4925907292074087}} {"text": "function [W, a, train_err] = train_foe(images, basis, no_experts, a)\n%TRAIN_FOE Trains a Field of Experts model on a collection of images\n%\n% [W, a, train_err] = train_foe(images, basis, no_experts)\n% [W, a, train_err] = train_foe(images, basis, W, a)\n%\n% Trains a Field of Experts model on a set of (grayscale) images. The\n% potential functions of the MRF are given by the energy function of a\n% product of no_experts Student-t distributions (with parameters W and a).\n% The potential functions are defined over a cliques that are image patches\n% of patch_size x patch_size pixels.\n%\n%\n% (C) Laurens van der Maaten, 2009\n% Delft University of Technology\n\n\n % Initialize parameters\n eta_W = .01;\n eta_a = .1;\n max_iter = 1000;\n no_images = size(images, 1);\n size_im = sqrt(size(images, 2));\n batch_size = min(200, no_images);\n momentum = .9;\n train_err = zeros(max_iter, 1);\n addpath(genpath('netlab'));\n\n % Initialize model\n if exist('a', 'var')\n W = no_experts;\n else\n W = randn(size(basis, 1), no_experts);\n a = repmat(0.01, [no_experts 1]);\n end\n prev_dW = zeros(size(W));\n prev_da = zeros(size(a));\n \n % Perform training of the model\n for iter=1:max_iter\n \n % Create batches\n tic\n ind = randperm(no_images);\n disp(['Iteration ' num2str(iter) '...']);\n \n % Loop over batches\n for b=1:batch_size:no_images\n \n % Get batch and initialize positive and negative data\n batch = images(ind(b:b + batch_size - 1),:); \n pos_W = zeros(size(W)); pos_a = zeros(size(a));\n neg_W = zeros(size(W)); neg_a = zeros(size(a));\n \n % Loop over all training images to compute gradient terms\n for i=1:batch_size\n\n % Get image\n im = reshape(batch(i,:), [size_im size_im]);\n \n% % Check gradients\n% options = zeros(18, 1);\n% options(9) = 1;\n% hmc('foe_energy_w', W(1:end), options, 'foe_energy_grad_w', im, basis, a);\n% hmc('foe_energy_a', a, options, 'foe_energy_grad_a', im, basis, W);\n% hmc('foe_energy', im(1:end), options, 'foe_energy_grad_x', basis, W, a, [size_im size_im 1]);\n\n % Compute positive part of gradient\n pos_W = pos_W + reshape(foe_energy_grad_w(W(1:end), im, basis, a), size(W));\n pos_a = pos_a + foe_energy_grad_a(a, im, basis, W);\n\n % Draw samples from model using hybrid Monte Carlo\n options = zeros(18, 1);\n options(1) = 0; % do not print diagnostics\n options(5) = 0; % do not use momentum persistence\n options(7) = 30; % number of leaps (= steps in leap-frog)\n options(9) = 0; % do not check gradient\n options(14) = 1; % number of samples to return\n options(15) = 0; % number of samples to omit from start\n sample = hmc('foe_energy', batch(i,:), options, 'foe_energy_grad_x', basis, W, a, [size_im size_im 1]);\n \n % Compute negative CD part\n neg_W = neg_W + reshape(foe_energy_grad_w(W(1:end), sample, basis, a), size(W));\n neg_a = neg_a + foe_energy_grad_a(a, sample, basis, W);\n end\n\n % Perform the gradient updates\n prev_dW = eta_W * (momentum * prev_dW + (1 - momentum) * (1 / batch_size) * (pos_W - neg_W));\n prev_da = eta_a * (momentum * prev_da + (1 - momentum) * (1 / batch_size) * (pos_a - neg_a));\n W = W + prev_dW;\n a = exp(log(a) + a .* prev_da);\n end\n \n % Evaluate sum of energies of training data\n sum_E = 0;\n for i=1:no_images\n im = reshape(images(i,:), [size_im size_im]);\n sum_E = sum_E + foe_energy(im, basis, W, a);\n end\n disp([' mean energy of training data is ' num2str(sum_E ./ no_images)]);\n train_err(iter) = sum_E ./ no_images;\n toc\n end\n ", "meta": {"author": "lbasek", "repo": "image-denoising-benchmark", "sha": "9d753198d715b7628c8e7d9259dfa5c219d033ea", "save_path": "github-repos/MATLAB/lbasek-image-denoising-benchmark", "path": "github-repos/MATLAB/lbasek-image-denoising-benchmark/image-denoising-benchmark-9d753198d715b7628c8e7d9259dfa5c219d033ea/algoritms/matlab/FOE/foe/train_foe.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146849, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.49254900315493694}} {"text": "%DEMO_MODELASSESMENT2 Demonstration for model assessment when the observation \n% model is non-Gaussian\n%\n% Description\n% We will consider the classification problem in demo_classific. \n% The analysis is conducted with full Gaussian process using\n% both probit and logit likelihood. The performance of these two\n% models are compared by evaluating the ten-fold\n% cross-validation, leave-one-out cross-validation, WAIC, DIC\n% and the effective number of parameters The inference will be\n% conducted using maximum a posterior (MAP) estimate for the\n% parameters using EP and Laplace approximation, via full Markov\n% chain Monte Carlo (MCMC) and with an integration approximation\n% (IA) for the parameters.\n%\n% This demo is organised in two parts:\n% 1) data analysis with with probit likelihood\n% 2) data analysis with with logit likelihood\n%\n% See also \n% DEMO_CLASSIFIC1, DEMO_MODELASSESMENT1\n\n% Copyright (c) 2009-2010 Jarno Vanhatalo\n% Copyright (c) 2010 Aki Vehtari\n\n% This software is distributed under the GNU General Public \n% License (version 3 or later); please refer to the file \n% License.txt, included with the software, for details.\n\n\n% =====================================\n% 1) data analysis with probit likelihood\n% =====================================\ndisp('Data analysis with probit likelihood')\nS = which('demo_classific');\nL = strrep(S,'demo_classific.m','demodata/synth.tr');\nx=load(L);\ny=x(:,end);\ny = 2.*y-1;\nx(:,end)=[];\n[n, nin] = size(x);\n\nDIC=repmat(NaN,1,8);DIC2=repmat(NaN,1,8);DIC_latent=repmat(NaN,1,8);\np_eff=repmat(NaN,1,8);p_eff2=repmat(NaN,1,8);p_eff_latent=repmat(NaN,1,8);p_eff_latent2=repmat(NaN,1,8);\n\n% Create covariance functions\ngpcf = gpcf_sexp('lengthScale', [0.9 0.9], 'magnSigma2', 2);\n\n% Set the prior for the parameters of covariance functions \npl = prior_logunif();\ngpcf = gpcf_sexp(gpcf, 'lengthScale_prior', pl,'magnSigma2_prior', pl); %\n\n% Create the GP structure\ngp = gp_set('lik', lik_probit, 'cf', gpcf, 'jitterSigma2', 1e-4);\n\n% ------- Laplace approximation --------\ndisp(['Probit with Laplace integration over the latent values '; ...\n 'and MAP estimate for the parameters '])\n\n% Set the approximate inference method\ngp = gp_set(gp, 'latent_method', 'Laplace');\n\nn=length(y);\n\n% Set the options for the optimization\nopt=optimset('TolFun',1e-3,'TolX',1e-3);\n% Optimize with the quasi-Newton method\ngp=gp_optim(gp,x,y,'opt',opt,'optimf',@fminlbfgs);\n\n% Evaluate the effective number of parameters and DIC with focus on\n% latent variables.\nmodels{1} = 'pr_Laplace';\np_eff_latent(1) = gp_peff(gp, x, y);\n[DIC_latent(1), p_eff_latent2(1)] = gp_dic(gp, x, y, 'focus', 'latent');\nWAIC(1) = gp_waic(gp,x,y);\n\n% Evaluate the 10-fold cross-validation results. \ncvres = gp_kfcv(gp, x, y, 'display', 'fold');\nmlpd_cv(1) = cvres.mlpd_cv;\n\n% Evaluate the leave-one-out cross-validation results. \n[Ef,Varf,lpy] = gp_loopred(gp, x, y);\nmlpd_loo(1) = mean(lpy);\n\n% ------- Expectation propagation --------\ndisp(['Probit with EP integration over the latent values and MAP '; ...\n 'estimate for the parameters '])\n\n% Set the approximate inference method\ngp = gp_set(gp, 'latent_method', 'EP');\n\n% Set the options for the optimization\nopt=optimset('TolFun',1e-3,'TolX',1e-3);\n% Optimize with the BFGS quasi-Newton method\ngp=gp_optim(gp,x,y,'opt',opt,'optimf',@fminlbfgs);\n\n% Evaluate the effective number of parameters and DIC with focus on\n% latent variables.\nmodels{2} = 'pr_EP';\np_eff_latent(2) = gp_peff(gp, x, y) ;\n[DIC_latent(2), p_eff_latent2(2)] = gp_dic(gp, x, y, 'focus', 'latent');\nWAIC(2) = gp_waic(gp,x,y);\n\n% Evaluate the 10-fold cross-validation results. \ncvres = gp_kfcv(gp, x, y, 'display', 'fold');\nmlpd_cv(2) = cvres.mlpd_cv;\n\n% Evaluate the leave-one-out cross-validation results. \n[Ef,Varf,lpy] = gp_loopred(gp, x, y);\nmlpd_loo(2) = mean(lpy);\n\n% ------- MCMC ---------------\ndisp(['Probit with MCMC integration over the latent values and '; ...\n 'the parameters '])\n\n% Set the approximate inference method\ngp = gp_set(gp, 'latent_method', 'MCMC');\n\n% Sample\nmcopt.nsamples=220;mcopt.display=20;\n[rgp,gp]=gp_mc(gp, x, y, mcopt);\nrgp=thin(rgp, 21, 2);\n\n% Evaluate the effective number of parameters and DIC with focus on\n% latent variables.\nmodels{3} = 'pr_MCMC';\n[DIC(3), p_eff(3)] = gp_dic(rgp, x, y, 'focus', 'param');\n[DIC2(3), p_eff2(3)] = gp_dic(rgp, x, y, 'focus', 'all');\nWAIC(3) = gp_waic(rgp,x,y);\n\n% Evaluate the 10-fold cross-validation results. \nmcopt.nsamples=50;mcopt.display=20;\ncvres = gp_kfcv(gp, x, y, 'inf_method', 'MCMC', 'opt', mcopt, 'display', 'fold');\nmlpd_cv(3) = cvres.mlpd_cv;\n\n% Evaluate the leave-one-out cross-validation results. \n[Ef,Varf,lpy] = gp_loopred(rgp, x, y);\nmlpd_loo(3) = mean(lpy);\n\n% --- Integration approximation approach ---\ndisp(['Probit with EP integration over the latent values and '; ...\n 'grid integration over the parameters '])\n\n% Use EP\ngp = gp_set(gp, 'latent_method', 'EP');\n\n% Set the options for the optimization\nopt=optimset('TolFun',1e-3,'TolX',1e-3);\n% Optimize with the BFGS quasi-Newton method\ngp=gp_optim(gp,x,y,'opt',opt,'optimf',@fminlbfgs);\n\n% now perform the integration\nclear opt\nopt.int_method = 'grid';\nopt.step_size = 2;\ngp_array = gp_ia(gp, x, y, opt);\n\nmodels{4} = 'pr_IA'; \n[DIC(4), p_eff(4)] = gp_dic(gp_array, x, y, 'focus', 'param');\n[DIC2(4), p_eff2(4)] = gp_dic(gp_array, x, y, 'focus', 'all');\nWAIC(4) = gp_waic(gp_array,x,y);\n\n% Then the 10 fold cross-validation.\ncvres = gp_kfcv(gp, x, y, 'inf_method', 'IA', 'opt', opt, 'display', 'fold');\nmlpd_cv(4) = cvres.mlpd_cv;\n\n% Evaluate the leave-one-out cross-validation results. \n[Ef,Varf,lpy] = gp_loopred(gp_array, x, y);\nmlpd_loo(4) = mean(lpy);\n\n% =====================================\n% 2) data analysis with logit likelihood\n% =====================================\ndisp('Data analysis with logit likelihood')\n\nS = which('demo_classific');\nL = strrep(S,'demo_classific.m','demodata/synth.tr');\nx=load(L);\ny=x(:,end);\ny = 2.*y-1;\nx(:,end)=[];\n[n, nin] = size(x);\n\n% Create covariance functions\ngpcf = gpcf_sexp('lengthScale', [0.9 0.9], 'magnSigma2', 2);\n\n% Set the prior for the parameters of covariance functions \npl = prior_logunif();\ngpcf = gpcf_sexp(gpcf, 'lengthScale_prior', pl,'magnSigma2_prior', pl); %\n\n% Create the likelihood structure\nlik = ('init');\n\n% Create the GP structure\ngp = gp_set('lik', lik_logit, 'cf', gpcf, 'jitterSigma2', 1e-4);\n\n\n% ------- Laplace approximation --------\ndisp(['Logit with Laplace integration over the latent values and '; ...\n 'MAP estimate for the parameters '])\n\n% Set the approximate inference method\ngp = gp_set(gp, 'latent_method', 'Laplace');\n\n% Set the options for the optimization\nopt=optimset('TolFun',1e-3,'TolX',1e-3);\n% Optimize with the BFGS quasi-Newton method\ngp=gp_optim(gp,x,y,'opt',opt,'optimf',@fminlbfgs);\n\n% Evaluate the effective number of parameters and DIC with focus on\n% latent variables.\nmodels{5} = 'lo_Laplace';\np_eff_latent(5) = gp_peff(gp, x, y);\n[DIC_latent(5), p_eff_latent2(5)] = gp_dic(gp, x, y, 'focus', 'latent');\nWAIC(5) = gp_waic(gp,x,y);\n\n% Evaluate the 10-fold cross-validation results. \ncvres = gp_kfcv(gp, x, y, 'display', 'fold');\nmlpd_cv(5) = cvres.mlpd_cv;\n\n% Evaluate the leave-one-out cross-validation results. \n[Ef,Varf,lpy] = gp_loopred(gp, x, y);\nmlpd_loo(5) = mean(lpy);\n\n% ------- Expectation propagation --------\ndisp(['Logit with EP integration over the latent values and MAP'; ...\n 'estimate for the parameters '])\n\n% Set the approximate inference method\ngp = gp_set(gp, 'latent_method', 'EP');\n\n% Set the options for the optimization\nopt=optimset('TolFun',1e-3,'TolX',1e-3);\n% Optimize with the BFGS quasi-Newton method\ngp=gp_optim(gp,x,y,'opt',opt,'optimf',@fminlbfgs);\n\n% Evaluate the effective number of parameters and DIC with focus on\n% latent variables.\nmodels{6} = 'lo_EP';\np_eff_latent(6) = gp_peff(gp, x, y) ;\n[DIC_latent(6), p_eff_latent2(6)] = gp_dic(gp, x, y, 'focus', 'latent');\nWAIC(6) = gp_waic(gp,x,y);\n\n% Evaluate the 10-fold cross-validation results. \ncvres = gp_kfcv(gp, x, y, 'display', 'fold');\nmlpd_cv(6) = cvres.mlpd_cv;\n\n% Evaluate the leave-one-out cross-validation results. \n[Ef,Varf,lpy] = gp_loopred(gp, x, y);\nmlpd_loo(6) = mean(lpy);\n\n% ------- MCMC ---------------\ndisp(['Logit with MCMC integration over the latent values and '; ...\n 'the parameters '])\n\n% Set the approximate inference method\ngp = gp_set(gp, 'latent_method', 'MCMC');\n\n% Sample \nmcopt.nsamples=200;mcopt.display=20;\n[rgp,gp] = gp_mc(gp, x, y, mcopt);\nrgp=thin(rgp, 21, 2);\n\n% Evaluate the effective number of parameters and DIC with focus on latent variables.\nmodels{7} = 'lo_MCMC';\n[DIC(7), p_eff(7)] = gp_dic(rgp, x, y, 'focus', 'param');\n[DIC2(7), p_eff2(7)] = gp_dic(rgp, x, y, 'focus', 'all');\nWAIC(7) = gp_waic(rgp,x,y);\n\n% Evaluate the 10-fold cross-validation results. \nmcopt.nsamples=50;mcopt.display=20;\ncvres = gp_kfcv(gp, x, y, 'inf_method', 'MCMC', 'opt', mcopt, 'display', 'fold');\nmlpd_cv(7) = cvres.mlpd_cv;\n\n% Evaluate the leave-one-out cross-validation results. \n[Ef,Varf,lpy] = gp_loopred(rgp, x, y);\nmlpd_loo(7) = mean(lpy);\n\n% --- Integration approximation approach ---\ndisp(['Logit with EP integration over the latent values and grid '; ...\n 'integration over the parameters '])\n\n% Use EP\ngp = gp_set(gp, 'latent_method', 'EP');\n\n% Set the options for the optimization\nopt=optimset('TolFun',1e-3,'TolX',1e-3);\n% Optimize with the BFGS quasi-Newton method\ngp=gp_optim(gp,x,y,'opt',opt,'optimf',@fminlbfgs);\n\n% now perform the integration\nclear opt\nopt.int_method = 'grid';\nopt.step_size = 2;\ngp_array = gp_ia(gp, x, y, opt);\n\nmodels{8} = 'lo_IA'; \n[DIC(8), p_eff(8)] = gp_dic(gp_array, x, y, 'focus', 'param');\n[DIC2(8), p_eff2(8)] = gp_dic(gp_array, x, y, 'focus', 'all');\nWAIC(8) = gp_waic(gp_array,x,y);\n\n% Then the 10 fold cross-validation.\ncvres = gp_kfcv(gp, x, y, 'inf_method', 'IA', 'opt', opt, 'display', 'fold');\nmlpd_cv(8) = cvres.mlpd_cv;\n\n% Evaluate the leave-one-out cross-validation results. \n[Ef,Varf,lpy] = gp_loopred(gp_array, x, y);\nmlpd_loo(8) = mean(lpy);\n\n%========================================================\n% PART 4 Print the results\n%========================================================\ndisp('Summary of the results')\n\nS = ' ';\nfor i = 1:length(models)\n S = [S ' ' models{i}];\nend\n\nS = sprintf([S '\\n CV-mlpd %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f'], mlpd_cv);\nS = sprintf([S '\\n LOO-mlpd %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f'], mlpd_loo);\nS = sprintf([S '\\n ']);\nS = sprintf([S '\\n WAIC %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f'], WAIC);\nS = sprintf([S '\\n ']);\nS = sprintf([S '\\n DIC_h %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f'], DIC);\nS = sprintf([S '\\n DIC_a %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f'], DIC2);\nS = sprintf([S '\\n DIC_l %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f'], DIC_latent);\nS = sprintf([S '\\n peff_h %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f'], p_eff);\nS = sprintf([S '\\n peff_a %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f'], p_eff2);\nS = sprintf([S '\\n peff_l %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f'], p_eff_latent);\nS = sprintf([S '\\n peff_l2 %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f'], p_eff_latent2);\nS = sprintf([S '\\n ']);\nS = sprintf([S '\\n The notation is as follows:']);\nS = sprintf([S '\\n pr_* = probit likelihood and inference method']);\nS = sprintf([S '\\n lo_* = logit likelihood and inference method']);\nS = sprintf([S '\\n CV-mlpd = mean log predictive density from the 10-fold CV. ']);\nS = sprintf([S '\\n LOO-mlpd = mean log predictive density from the 10-fold CV. ']);\nS = sprintf([S '\\n WAIC = Widely applicable information criterion. ']);\nS = sprintf([S '\\n DIC_h = DIC with focus on parameters. ']);\nS = sprintf([S '\\n DIC_a = DIC with focus on parameters and laten variables (all). ']);\nS = sprintf([S '\\n DIC_l = DIC with focus on latent variables. ']);\nS = sprintf([S '\\n peff_h = effective number of parameters (latent variables marginalized). ']);\nS = sprintf([S '\\n peff_a = effective number of parameters and latent variables. ']);\nS = sprintf([S '\\n peff_l = effective number of latent variables evaluated with gp_peff. ']);\nS = sprintf([S '\\n peff_l2 = effective number of latent variables evaluated with gp_dic. ']);\nS = sprintf([S '\\n '])\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/gp/demo_modelassesment2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6654105454764746, "lm_q1q2_score": 0.49251982599208344}} {"text": "% MATCORR - Find matching rows in two matrices and their corrs.\n% Uses the Hungarian (default), VAM, or maxcorr assignment methods.\n% (Follow with MATPERM to permute and sign x -> y).\n%\n% Usage: >> [corr,indx,indy,corrs] = matcorr(x,y,rmmean,method,weighting);\n%\n% Inputs:\n% x = first input matrix \n% y = matrix with same number of columns as x\n% \n% Optional inputs:\n% rmmean = When present and non-zero, remove row means prior to correlation \n% {default: 0}\n% method = Method used to find assignments.\n% 0= Hungarian Method - maximize sum of abs corrs {default: 2}\n% 1= Vogel's Assignment Method -find pairs in order of max contrast \n% 2= Max Abs Corr Method - find pairs in order of max abs corr \n% Note that the methods 0 and 1 require matrices to be square.\n% weighting = An optional weighting matrix size(weighting) = size(corrs) that \n% weights the corrs matrix before pair assignment {def: 0/[] -> ones}\n% Outputs:\n% corr = a column vector of correlation coefficients between \n% best-correlating rows of matrice x and y\n% indx = a column vector containing the index of the maximum \n% abs-correlated x row in descending order of abs corr \n% (no duplications)\n% indy = a column vector containing the index of the maximum \n% abs-correlated row of y in descending order of abs corr \n% (no duplications)\n% corrs = an optional square matrix of row-correlation coefficients\n% between matrices x and y\n%\n% Note: outputs are sorted by abs(corr)\n%\n% Authors: Scott Makeig & Sigurd Enghoff, SCCN/INC/UCSD, La Jolla, 11-30-96 \n\n% Copyright (C) 11-30-96 Scott Makeig, SCCN/INC/UCSD, scott@sccn.ucsd.edu\n%\n% This file is part of EEGLAB, see http://www.eeglab.org\n% for the documentation and details.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are met:\n%\n% 1. Redistributions of source code must retain the above copyright notice,\n% this list of conditions and the following disclaimer.\n%\n% 2. Redistributions in binary form must reproduce the above copyright notice,\n% this list of conditions and the following disclaimer in the documentation\n% and/or other materials provided with the distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n% THE POSSIBILITY OF SUCH DAMAGE.\n\n% 04-22-99 Re-written using VAM by Sigurd Enghoff, CNL/Salk\n% 04-30-99 Added revision of algorithm loop by SE -sm\n% 05-25-99 Added Hungarian method assignment by SE\n% 06-15-99 Maximum correlation method reinstated by SE\n% 08-02-99 Made order of outputs match help msg -sm\n% 02-16-00 Fixed order of corr output under VAM added method explanations, \n% and returned corr signs in abs max method -sm\n% 01-25-02 reformated help & license, added links -ad \n\n% Uses function hungarian.m\n\nfunction [corr,indx,indy,corrs] = matcorr(x,y,rmmean,method,weighting)\n%\nif nargin < 2 || nargin > 5\n help matcorr\n return\nend\n\nif nargin < 4\n\tmethod = 2; % default: Max Abs Corr - select successive best abs(corr) pairs\nend\n\n[m,n] = size(x);\n[p,q] = size(y);\nm = min(m,p);\n\nif m~=n || p~=q\n if nargin>3 && method~=2\n fprintf('matcorr(): Matrices are not square: using max abs corr method (2).\\n');\n end\n method = 2; % Can accept non-square matrices\nend \n\nif n~=q\n error('Rows in the two input matrices must be the same length.');\nend\n\nif nargin < 3 || isempty(rmmean)\n rmmean = 0;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif rmmean\n x = x - mean(x')'*ones(1,n); % optionally remove means\n y = y - mean(y')'*ones(1,n);\nend\ndx = sum(x'.^2);\ndy = sum(y'.^2);\ndx(find(dx==0)) = 1;\ndy(find(dy==0)) = 1;\ncorrs = x*y'./sqrt(dx'*dy);\n\nif nargin > 4 && ~isempty(weighting) && norm(weighting) > 0,\n if any(size(corrs) ~= size(weighting))\n fprintf('matcorr(): weighting matrix size must match that of corrs\\n.')\n return\n else\n\tcorrs = corrs.*weighting;\n end\nend\n\ncc = abs(corrs);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nswitch method\ncase 0\n\tass = hungarian(-cc); % Performs Hungarian algorithm matching\n\n\tidx1 = sub2ind(size(cc),ass,1:m);\n\t[dummy idx2] = sort(-cc(idx1));\n\tcorr = corrs(idx1);\n\tcorr = corr(idx2)';\n\tindy = [1:m]';\n\tindx = ass(idx2)';\n\tindy = indy(idx2);\n\ncase 1 % Implements the VAM assignment method\n\tindx = zeros(m,1);\n\tindy = zeros(m,1);\n\tcorr = zeros(m,1);\n\n\tfor i=1:m,\n\t\t[sx ix] = sort(cc); % Looks for maximum salience along a row/column\n\t\t[sy iy] = sort(cc'); % rather than maximum correlation.\n\t\t[sxx ixx] = max(sx(end,:)-sx(end-1,:));\n\t\t[syy iyy] = max(sy(end,:)-sy(end-1,:));\n\n\t\tif sxx == syy\n\t\t\tif sxx == 0 && syy == 0\n \t [sxx ixx] = max((sx(end,:)-sx(end-1,:)) .* sx(end,:));\n \t [syy iyy] = max((sy(end,:)-sy(end-1,:)) .* sy(end,:));\n\t\t\telse\n\t\t\t\tsxx = sx(end,ixx); % takes care of identical vectors\n\t\t\t\tsyy = sy(end,iyy); % and zero vectors\n\t\t\tend\n\t\tend\n\n\t\tif sxx > syy\n\t\t\tindx(i) = ix(end,ixx);\n\t\t\tindy(i) = ixx;\n\t\telse\n\t\t\tindx(i) = iyy;\n\t\t\tindy(i) = iy(end,iyy);\n\t\tend\n\t\tcc(indx(i),:) = -1;\n\t\tcc(:,indy(i)) = -1;\n\tend\n\n\ti = sub2ind(size(corrs),indx,indy);\n\tcorr = corrs(i);\n\n\t[tmp j] = sort(-abs(corr)); % re-sort by abs(correlation)\n\tcorr = corr(j);\n\tindx = indx(j);\n\tindy = indy(j);\n\ncase 2 % match successive max(abs(corr)) pairs\n\tindx = zeros(size(cc,1),1);\n\tindy = zeros(size(cc,1),1);\n\tcorr = zeros(size(cc,1),1);\n\n\tfor i = 1:size(cc,1)\n\t\t[tmp j] = max(cc(:));\n\t\t% [corr(i) j] = max(cc(:));\n\t\t[indx(i) indy(i)] = ind2sub(size(cc),j);\n corr(i) = corrs(indx(i),indy(i));\n\t\tcc(indx(i),:) = -1; % remove from contention\n\t\tcc(:,indy(i)) = -1;\n\tend\n\notherwise\n\terror('Unknown method');\nend\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/miscfunc/matcorr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959543, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49249592649806634}} {"text": "function [beta_gibbs,sigma_gibbs,favar,It,Bu]=favar_dogibbs(It,Bu,B,EPS,n,T,lags,data_endo,data_exo,const,favar,ar,arvar,lambda1,lambda3,lambda4,m,p,k,priorexo,Y,X,cband,Tstar)\n\n%% the methodolgy closely follows Bernanke, Boivin, Eliasz (2005) and lends from the FAVAR model of Koop & Korobilis \n\n% function [beta_gibbs sigma_gibbs]=ndgibbs(It,Bu,beta0,omega0,X,Y,y,Bhat,n,T,q)\n% performs the Gibbs algorithm 1.5.2 for the normal-diffuse prior, and returns draws from posterior distribution\n% inputs: - integer 'It': total number of iterations of the Gibbs sampler (defined p 28 of technical guide)\n% - integer 'Bu': number of burn-in iterations of the Gibbs sampler (defined p 28 of technical guide)\n% - vector 'beta0': vector of prior values for beta (defined in 1.3.4)\n% - matrix 'omega0': prior covariance matrix for the VAR coefficients (defined in 1.3.8)\n% - matrix 'X': matrix of regressors for the VAR model (defined in 1.1.8)\n% - matrix 'Y': matrix of regressands for the VAR model (defined in 1.1.8)\n% - vector 'y': vectorised regressands for the VAR model (defined in 1.1.12)\n% - matrix 'Bhat': OLS VAR coefficients, in non vectorised form (defined in 1.1.9)\n% - integer 'n': number of endogenous variables in the BVAR model (defined p 7 of technical guide)\n% - integer 'T': number of sample time periods (defined p 7 of technical guide)\n% - integer 'q': total number of coefficients to estimate for the BVAR model (defined p 7 of technical guide)\n% outputs: - matrix 'beta_gibbs': record of the gibbs sampler draws for the beta vector\n% - matrix'sigma_gibbs': record of the gibbs sampler draws for the sigma matrix (vectorised)\n\n\n%% preliminary tasks\n% initialise variables\nnfactorvar=favar.nfactorvar;\nnumpc=favar.numpc;\nfavarX=favar.X(:,favar.plotX_index);\nonestep=favar.onestep;\nXY=favar.XY;\n\n % initial conditions XZ0~N(XZ0mean,XZ0var)\n favar.XZ0mean=zeros(n*lags,1);\n favar.XZ0var=favar.L0*eye(n*lags); %BBE set-up\n\nL=favar.L;\nSigma=bear.nspd(favar.Sigma);\nif onestep==1\nindexnM=favar.indexnM;\nend\nXZ0mean=favar.XZ0mean;\nXZ0var=favar.XZ0var;\nfavar_X=favar.X;\n% load priors\nL0=favar.L0*eye(n);\na0=favar.a0;\nb0=favar.b0;\nsigmahat=(1/T)*(EPS'*EPS);\n\n% preallocation\nbeta_gibbs=zeros(size(B(:),1),It-Bu);\nsigma_gibbs=zeros(size(sigmahat(:),1),It-Bu);\n% X_gibbs=zeros(size(X(:),1),It-Bu);\n% Y_gibbs=zeros(size(Y(:),1),It-Bu);\n% FY_gibbs=zeros(size(data_endo(:),1),It-Bu);\nL_gibbs=zeros(size(L(:),1),It-Bu);\nR2_gibbs=zeros(size(favarX,2),It-Bu);\n\nif onestep==0 %static factors in this case\n FY=data_endo;\n pbstring='two-step'; %string for the progress bar\nelseif onestep==1\n pbstring='one-step'; %string for the progress bar\nend\n\n% state-space representation\nif onestep==1\nB_ss=[B';eye(n*(lags-1)) zeros(n*(lags-1),n)];\nsigma_ss=[sigmahat zeros(n,n*(lags-1));zeros(n*(lags-1),n*lags)];\nend\n\n% create a progress bar\nhbar = bear.parfor_progressbar(It,['Progress of the Gibbs sampler (',pbstring,').']);\n\n%% start iterations\nfor ii=1:It\n if onestep==1\n % Sample latent factors using Carter and Kohn (1994)\n FY=bear.favar_kfgibbsnv(XY,XZ0mean,XZ0var,L,Sigma,B_ss,sigma_ss,indexnM);\n % demean generated factors\n FY=bear.favar_demean(FY);\n % Sample autoregressive coefficients B,in the twostep procedure FY is static, and we want to use updated B\n [B,~,~,X,~,Y]=bear.olsvar(FY,data_exo,const,lags);\n [arvar]=bear.arloop(FY,const,p,n);\n end\n \n % set 'prior' values (here, the dummy observations)\n [Y,X,Tstar]=bear.doprior(Y,X,n,m,p,Tstar,ar,arvar,lambda1,lambda3,lambda4,priorexo);\n % obtain posterior distribution parameters\n [Bcap,betacap,Scap,alphacap,phicap,alphatop]=bear.dopost(X,Y,Tstar,k,n);\n\n% draw B from a matrix-variate student distribution with location Bcap, scale Scap and phicap and degrees of freedom alphatop\nstationary=0;\nwhile stationary==0\nB=bear.matrixtdraw(Bcap,Scap,phicap,alphatop,k,n);\n [stationary]=bear.checkstable(B(:),n,lags,size(B,1)); %switches stationary to 0, if the draw is not stationary\nend\nif onestep==1\nB_ss(1:n,:)=B';\nend\n\n% then draw sigma from an inverse Wishart distribution with scale matrix Scap and degrees of freedom alphacap (step 3)\nsigma=bear.iwdraw(Scap,alphacap);\nif onestep==1\nsigma_ss(1:n,1:n)=sigma;\nend\n\n%% Sample Sigma and L\n[Sigma,L]=bear.favar_SigmaL(Sigma,L,nfactorvar,numpc,onestep,n,favar_X,FY,a0,b0,T,lags,L0);\n\n%% record the values if the number of burn-in iterations is exceeded\nif ii>Bu\n% values of vector beta\nbeta_gibbs(:,ii-Bu)=B(:);\n% values of sigma (in vectorized form)\nsigma_gibbs(:,ii-Bu)=sigma(:);\n\n% save the factors and loadings\nX_gibbs(:,ii-Bu)=X(:);\nY_gibbs(:,ii-Bu)=Y(:);\nFY_gibbs(:,ii-Bu)=FY(:);\nL_gibbs(:,ii-Bu)=L(:);\n\n% compute R2 (Coefficient of Determination) for plotX variables (can be done after burn-in)\nR2=bear.favar_R2(favarX,FY);\nR2_gibbs(:,ii-Bu)=R2(:);\n\n% compute posterior estimates, this is different here to the other prior \n[beta_median,B_median,beta_std,beta_lbound,beta_ubound,sigma_median]=bear.doestimates(betacap,phicap,Scap,alphacap,alphatop,n,k,cband);\nbeta_median_gibbs(:,:,ii-Bu)=beta_median;\nB_median_gibbs(:,:,ii-Bu)=B_median;\nbeta_std_gibbs(:,:,ii-Bu)=beta_std;\nbeta_lbound_gibbs(:,:,ii-Bu)=beta_lbound;\nbeta_ubound_gibbs(:,:,ii-Bu)=beta_ubound;\nsigma_median_gibbs(:,:,ii-Bu)=sigma_median;\n% if current iteration is still a burn iteration, do not record the result\nelse\nend\n\n% update progress by one iteration\nhbar.iterate(1);\n\n% go for next iteration\nend\n\n% in case we have thinning of the draws,\nthin=abs(round(favar.thin)); % should be a positive integer\nif thin~=1\n beta_gibbs=beta_gibbs(:,thin:thin:end);\n sigma_gibbs=sigma_gibbs(:,thin:thin:end);\n X_gibbs=X_gibbs(:,thin:thin:end);\n Y_gibbs=Y_gibbs(:,thin:thin:end);\n FY_gibbs=FY_gibbs(:,thin:thin:end);\n L_gibbs=L_gibbs(:,thin:thin:end);\n R2_gibbs=R2_gibbs(:,thin:thin:end);\n It=(1/thin)*It;\n Bu=(1/thin)*Bu;\nend\n\n% save in favar structure\nfavar.X_gibbs=X_gibbs;\nfavar.Y_gibbs=Y_gibbs;\nfavar.FY_gibbs=FY_gibbs;\nfavar.L_gibbs=L_gibbs;\nfavar.R2_gibbs=R2_gibbs;\n\n\nfavar.beta_median_gibbs=beta_median_gibbs;\nfavar.B_median_gibbs=B_median_gibbs;\nfavar.beta_std_gibbs=beta_std_gibbs;\nfavar.beta_lbound_gibbs=beta_lbound_gibbs;\nfavar.beta_ubound_gibbs=beta_ubound_gibbs;\nfavar.sigma_median_gibbs=sigma_median_gibbs;\n\n% close progress bar\nclose(hbar);\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/favar_dogibbs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49209044661569323}} {"text": "function [inliers, info] = gnc(problem, f, varargin)\n%GNC - Graduated Non-Convexity\n% Implementation of: \n% - \"Graduated Non-Convexity for Robust Spatial Perception: From Non-Minimal Solvers to Global Outlier Rejection\"\n% Yang, Antonante, Tzoumas, Carlone (2020). IEEE Robotics and Automation Letters (RA-L), 5(2), 1127–1134.\n% https://arxiv.org/pdf/1909.08605.pdf\n% - \"Outlier-Robust Estimation: Hardness, Minimally-Tuned Algorithms, and Applications\" \n% Antonante, Tzoumas, Yang, Carlone (2020).\n% https://arxiv.org/pdf/2007.15109.pdf\n%\n% Syntax: [inliers, info] = gnc(problem, f, ...)\n%\n% Inputs:\n% problem - the stracture representing a generic problem (see EmptyProblem)\n% f - a function_handler of a non-minimal solver for problem\n%\n% Options:\n% - ContinuationFactor: continuation factor for mu\n% - InitialMu: initial mu (default: auto)\n% - NoiseBound: inlier threshold\n% - MaxIterations: maximum number of iterations\n% - FixPriorsWeights: fix priors weights to 1 across all iterations\n% - CostThreshold: if weighted sum of squared residuals is below this value, GNC stops\n% - Debug: whether or not to enable the debug information\n%\n% Outputs:\n% inliers - the indices of the inliers\n% info - structure containing extended information about the xecution\n% \n% Example:\n% problem = linearRegressionProblem(100, 0.8);\n% [inliers, info] = gnc(problem, @leastSquareNorm2, ...\n% 'NoiseBound', chi2inv(0.99, problem.dof)*problem.MeasurementNoiseStd^2);\n\n% Author: Pasquale Antonante\n% email: antonap@mit.edu\n% Date: 2021-01-06\n\nparams = inputParser;\nparams.KeepUnmatched = true;\nparams.addParameter('NoiseBound', 0, @(x) isscalar(x) && x>=0 && isfinite(x));\nparams.parse(varargin{:});\nassert(isProblem(problem), 'The problem doesn''t contain required fields.');\n\nstart_t = now;\nif params.Results.NoiseBound > 0\n [inliers, info] = gnc_vanilla(problem, f, varargin{:});\nelse\n error('You need to set the Noise Bound')\nend\nend_t = now;\ninfo.time = (end_t - start_t) * 24 * 60 * 60; % serial date number to sec\nend\n\nfunction [inliers, info] = gnc_vanilla(problem, f, varargin)\nparams = inputParser;\nparams.KeepUnmatched = true;\nparams.addParameter('ContinuationFactor', 1.4, @(x) isscalar(x) && x>0);\nparams.addParameter('InitialMu', 'auto', @(x) ischar(x) || (isscalar(x) && x>0));\nparams.addParameter('NoiseBound', 0, @(x) isscalar(x) && x>=0 && isfinite(x));\nparams.addParameter('MaxIterations', 1e3, @(x) isscalar(x));\nparams.addParameter('FixPriorsWeights', true, @(x) islogical(x));\nparams.addParameter('CostThreshold', 0, @(x) isscalar(x));\nparams.addParameter('Debug', false, @(x) islogical(x));\nparams.addParameter('init_', 0);\nparams.parse(varargin{:});\n\nmax_iterations = params.Results.MaxIterations;\n\nif params.Results.Debug\n residuals_history = [];\n weights_history = [];\nend\n\nif ismember('init_', params.UsingDefaults)\n try\n [~, f_info] = f(problem);\n catch err\n fprintf('Error message: %s', err.message)\n error(\"Could not run the global solver\")\n end\n assert(isfield(f_info, 'residuals'), 'f should compute residuals');\nelse\n f_info = params.Results.('init_');\nend\nbarc2 = params.Results.NoiseBound;\nweights = ones(1, problem.N);\nif ischar(params.Results.InitialMu) && strcmpi(params.Results.InitialMu, 'auto')\n mu = 1 / (2 * max(f_info.residuals) / barc2 - 1 );\nelseif isnumeric(params.Results.InitialMu)\n mu = params.Results.InitialMu;\nelse\n error('Invalid value for InitialMu')\nend\n \nprev_f_cost = 0;\n\ni = 1;\ninfo.stopping = 'MaxIterations'; % Worst case stopping\ninfo.status = 1; % worst case status: failure\nwhile i < max_iterations\n if params.Results.Debug\n residuals_history(i,:) = f_info.residuals(:)';\n weights_history(i, :) = weights;\n end\n weights = gncWeightsUpdate(weights, mu, f_info.residuals, barc2);\n if params.Results.FixPriorsWeights\n weights(problem.priors) = 1;\n end\n try\n [~, f_info] = f(problem, 'Weights', weights);\n catch err\n fprintf('Error message: %s', err.message)\n error(\"Could not run the global solver\")\n end\n f_cost = sum(f_info.residuals(:) .* weights(:));\n cost_diff = abs(f_cost - prev_f_cost);\n prev_f_cost = f_cost;\n \n if (cost_diff < params.Results.CostThreshold) || areBinaryWeights(weights) \n if params.Results.Debug\n residuals_history(i+1,:) = f_info.residuals(:)';\n weights_history(i+1, :) = weights;\n end\n info.residuals = f_info.residuals(:)';\n info.stopping = 'CostThreshold';\n info.status = 1;\n break \n end\n mu = mu * params.Results.ContinuationFactor;\n i = i + 1;\nend\ninliers = find(weights>1-eps);\ninfo.Iterations = i;\ninfo.params = params.Results;\ninfo.Algorithm = 'GNC';\nif params.Results.Debug\n info.mu = mu;\n info.barc2History = repmat(barc2, i+1, 1);\n info.ResidualsHistory = residuals_history;\n info.WeightsHistory = weights_history;\n info.CostDiff = cost_diff;\n info.AreBinaryWeights = areBinaryWeights(weights);\nend\nend", "meta": {"author": "MIT-SPARK", "repo": "GNC-and-ADAPT", "sha": "dd5fe1f51839a8a43782fc54f0ba9aff24f5402f", "save_path": "github-repos/MATLAB/MIT-SPARK-GNC-and-ADAPT", "path": "github-repos/MATLAB/MIT-SPARK-GNC-and-ADAPT/GNC-and-ADAPT-dd5fe1f51839a8a43782fc54f0ba9aff24f5402f/Algorithms/GNC/gnc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6224593382055109, "lm_q1q2_score": 0.4920729789905174}} {"text": "function [au] = ly2au(ly)\n% Convert length from light years to astronomical units. \n% Chad A. Greene 2012\nau = ly*63241.07708807;", "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/ly2au.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.49191990550048675}} {"text": "function [meshr,Ir] = mshMidpoint(mesh,I)\n%+========================================================================+\n%| |\n%| OPENMSH - LIBRARY FOR MESH MANAGEMENT |\n%| openMsh is part of the GYPSILAB toolbox for Matlab |\n%| |\n%| COPYRIGHT : Matthieu Aussal (c) 2017-2018. |\n%| PROPERTY : Centre de Mathematiques Appliquees, Ecole polytechnique, |\n%| route de Saclay, 91128 Palaiseau, France. All rights reserved. |\n%| LICENCE : This program is free software, distributed in the hope that|\n%| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use, |\n%| redistribute and/or modify it under the terms of the GNU General Public|\n%| License, as published by the Free Software Foundation (version 3 or |\n%| later, http://www.gnu.org/licenses). For private use, dual licencing |\n%| is available, please contact us to activate a \"pay for remove\" option. |\n%| CONTACT : matthieu.aussal@polytechnique.edu |\n%| WEBSITE : www.cmap.polytechnique.fr/~aussal/gypsilab Ā Ā Ā Ā  |\n%| |\n%| Please acknowledge the gypsilab toolbox in programs or publications in |\n%| which you use it. |\n%|________________________________________________________________________|\n%| '&` | |\n%| # | FILE : mshMidpoint.m |\n%| # | VERSION : 0.50 |\n%| _#_ | AUTHOR(S) : Matthieu Aussal |\n%| ( # ) | CREATION : 14.03.2017 |\n%| / 0 \\ | LAST MODIF : 25.11.2018 |\n%| ( === ) | SYNOPSIS : Refine triangular mesh with midpoint algorithm|\n%| `---' | |\n%+========================================================================+\n\n% Check dimenion\nif (size(mesh,2) ~= 3)\n error('mshMidpoint : unavailable case 1')\nend\n\n% Save color and replace by hierarchy\ncol = mesh.col;\nmesh.col = (1:length(mesh))';\n\n% Submeshing (triangle)\nmeshs = mesh.sub(I);\n\n% Edge meshes\nedgs = meshs.edg;\n[edg,Itri] = mesh.edg;\n\n% Interface with edge multiplicity for triangle\n[int,Iedg] = intersect(edg,edgs);\nind = ismember(Itri,Iedg);\nmlt = sum(ind,2);\n\n% Security\ntmp = setdiff(int,edgs);\nif (size(tmp.elt,1) ~= 0)\n error('mshMidpoint.m : unavailable case 2');\nend\n\n% Initialize refined mesh for element without refinement\nmeshr = mesh.sub(mlt==0);\n\n% Subdivision with 1 common edge\ntmp = mesh.sub(mlt==1);\ntmp = mshMidpoint1(tmp,int);\nmeshr = union(meshr,tmp);\n\n% Subdivision with 2 common edges\ntmp = mesh.sub(mlt==2);\ntmp = mshMidpoint2(tmp,int);\nmeshr = union(meshr,tmp);\n\n% Subdivision with 3 common edges\ntmp = mesh.sub(mlt==3);\ntmp = mshMidpoint3(tmp);\nmeshr = union(meshr,tmp);\n\n% Parent indices and replace colours\nIr = meshr.col;\nmeshr.col = col(Ir);\n\n% Security\nif (sum(mesh.ndv)-sum(meshr.ndv))/sum(mesh.ndv) > 1e-15*length(meshr)\n error('mshMidpoint.m : unavailable case 3');\nend\nend\n\n\nfunction mesh = mshMidpoint1(mesh,int)\n% Mesh nodes and edges center\n[nds,ctr] = data(mesh);\n\n% Interface center\nXctr = int.ctr;\n\n% Refined mesh initialization\nNvtx = size(mesh.vtx,1);\nNelt = length(mesh);\ncol = mesh.col;\nmesh = mesh.sub([]);\n\n% Loop over nodes\nfor i = 1:3\n % Neighbours\n ip1 = mod(i,3)+1;\n ip2 = mod(ip1,3)+1; \n\n % Selected center are inside subdivided mesh \n I = find(ismember(single(ctr{i}),single(Xctr),'rows'));\n \n % First elements\n vtx = [nds{i}(I,:) ; nds{ip1}(I,:) ; ctr{i}(I,:)];\n elt = reshape((1:3*length(I))',length(I),3);\n tmp = msh(vtx,elt,col(I));\n mesh = union(mesh,tmp);\n \n % Second elements\n vtx = [nds{i}(I,:) ; ctr{i}(I,:) ; nds{ip2}(I,:)];\n elt = reshape((1:3*length(I))',length(I),3);\n tmp = msh(vtx,elt,col(I));\n mesh = union(mesh,tmp);\n\n % Mesh fusion with previous submeshes\n mesh = union(mesh,tmp);\nend\n\n% Security\nif size(mesh.elt,1) ~= 2*Nelt\n error('mshMidpoint1.m : unavailable case 1')\nend\nif size(mesh.vtx,1) ~= Nvtx+Nelt\n error('mshMidpoint1.m : unavailable case 2')\nend\nend\n\n\nfunction mesh = mshMidpoint2(mesh,int)\n% Mesh nodes and edges center\n[nds,ctr] = data(mesh);\n\n% Interface center\nXctr = int.ctr;\n\n% Refined mesh initialization\nNvtx = size(mesh.vtx,1);\nNelt = length(mesh);\ncol = mesh.col;\nmesh = mesh.sub([]);\n\n% Loop over nodes\nfor i = 1:3\n % Neighbours\n ip1 = mod(i,3)+1;\n ip2 = mod(ip1,3)+1; \n\n % Selected nodes center not inside subdivided mesh \n I = find(~ismember(single(ctr{i}),single(Xctr),'rows'));\n \n % First elements\n vtx = [nds{i}(I,:) ; ctr{ip2}(I,:) ; ctr{ip1}(I,:)];\n elt = reshape((1:3*length(I))',length(I),3);\n tmp = msh(vtx,elt,col(I));\n mesh = union(mesh,tmp);\n \n % Second elements \n vtx = [nds{ip1}(I,:) ; nds{ip2}(I,:) ; ctr{ip1}(I,:)];\n elt = reshape((1:3*length(I))',length(I),3);\n tmp = msh(vtx,elt,col(I));\n mesh = union(mesh,tmp);\n \n % Third elements\n vtx = [nds{ip1}(I,:) ; ctr{ip1}(I,:) ; ctr{ip2}(I,:) ; ];\n elt = reshape((1:3*length(I))',length(I),3);\n tmp = msh(vtx,elt,col(I));\n mesh = union(mesh,tmp);\nend\n\n% Security\nif size(mesh.elt,1) ~= 3*Nelt\n error('mshMidpoint2.m : unavailable case 1')\nend\nif size(mesh.vtx,1) ~= Nvtx+2*Nelt\n error('mshMidpoint2.m : unavailable case 2')\nend\nend\n\n\nfunction mesh = mshMidpoint3(mesh) \n% Mesh nodes and edges center\n[nds,ctr] = data(mesh);\n \n% Refined mesh initialization with centered triangle\nNelt = length(mesh);\nvtx = [ctr{1} ; ctr{2} ; ctr{3}];\nelt = reshape((1:3*Nelt)',Nelt,3);\ncol = mesh.col;\nmesh = msh(vtx,elt,col);\n\n% For each node\nfor i = 1:3\n % Neighbours\n ip1 = mod(i,3)+1;\n ip2 = mod(ip1,3)+1;\n\n % New submesh with nodes triangles\n vtx = [nds{i} ; ctr{ip2} ; ctr{ip1}];\n tmp = msh(vtx,elt,col);\n \n % Mesh fusion with previous submeshes\n mesh = union(mesh,tmp);\nend\n\n% Security\nif size(mesh.elt,1) ~= 4*Nelt\n error('mshMidpoint3.m : unavailable case 1')\nend\nend\n\n\nfunction [nds,ctr] = data(mesh)\n% Triangle nodes\nnds{1} = mesh.vtx(mesh.elt(:,1),:);\nnds{2} = mesh.vtx(mesh.elt(:,2),:);\nnds{3} = mesh.vtx(mesh.elt(:,3),:);\n\n% Edges center\nctr{1} = 0.5 * (nds{2} + nds{3});\nctr{2} = 0.5 * (nds{3} + nds{1});\nctr{3} = 0.5 * (nds{1} + nds{2});\nend\n\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/gypsilabModified/openMsh/mshMidpoint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4918554088763783}} {"text": "%+========================================================================+\n%| |\n%| This script uses the GYPSILAB toolbox for Matlab |\n%| |\n%| COPYRIGHT : Matthieu Aussal (c) 2017-2019. |\n%| PROPERTY : Centre de Mathematiques Appliquees, Ecole polytechnique, |\n%| route de Saclay, 91128 Palaiseau, France. All rights reserved. |\n%| LICENCE : This program is free software, distributed in the hope that|\n%| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use, |\n%| redistribute and/or modify it under the terms of the GNU General Public|\n%| License, as published by the Free Software Foundation (version 3 or |\n%| later, http://www.gnu.org/licenses). For private use, dual licencing |\n%| is available, please contact us to activate a \"pay for remove\" option. |\n%| CONTACT : matthieu.aussal@polytechnique.edu |\n%| WEBSITE : www.cmap.polytechnique.fr/~aussal/gypsilab Ā Ā Ā Ā  |\n%| |\n%| Please acknowledge the gypsilab toolbox in programs or publications in |\n%| which you use it. |\n%|________________________________________________________________________|\n%| '&` | |\n%| # | FILE : nrtOprHelmholtzBWneu.m |\n%| # | VERSION : 0.61 |\n%| _#_ | AUTHOR(S) : Matthieu Aussal |\n%| ( # ) | CREATION : 14.03.2017 |\n%| / 0 \\ | LAST MODIF : 05.09.2019 |\n%| ( === ) | SYNOPSIS : Solve neumann scatering problem with |\n%| `---' | Brackage-Werner formulation |\n%+========================================================================+\n\n% Cleaning\nclear all\nclose all\nclc\n\n% Gypsilab path\nrun('../../addpathGypsilab.m')\n\n% Parameters\nN = 1e3\ntol = 1e-3\ntyp = 'P1'\ngss = 3\nX0 = [0 0 -1]\n\n% Spherical mesh\nsphere = mshSphere(N,1);\nsigma = dom(sphere,gss); \nfigure\nplot(sphere)\naxis equal\n\n% Radiative mesh\nsquare = mshSquare(5*N,[5 5]);\nsquare.vtx = [square.vtx(:,1) zeros(size(square.vtx,1),1) square.vtx(:,2)];\nhold on\nplot(square)\n\n% Frequency adjusted to maximum esge size\nstp = sphere.stp;\nk = 1/stp(2)\nf = (k*340)/(2*pi)\n\n% Incident wave\nPW = @(X) exp(1i*k*X*X0');\ngradxPW{1} = @(X) 1i*k*X0(1) .* PW(X);\ngradxPW{2} = @(X) 1i*k*X0(2) .* PW(X);\ngradxPW{3} = @(X) 1i*k*X0(3) .* PW(X);\n\n% Incident wave representation\nplot(sphere,real(PW(sphere.vtx)))\nplot(square,real(PW(square.vtx)))\ntitle('Incident wave')\nxlabel('X'); ylabel('Y'); zlabel('Z');\nhold off\nview(0,10)\n\n\n%%% PREPARE OPERATORS\ndisp('~~~~~~~~~~~~~ PREPARE OPERATORS ~~~~~~~~~~~~~')\n\n% Green kernel function --> G(x,y) = exp(ik|x-y|)/|x-y| \nGxy = '[exp(ikr)/r]';\ngradxGxy = {'gradx[exp(ikr)/r]1','gradx[exp(ikr)/r]2','gradx[exp(ikr)/r]3'};\ngradyGxy = {'grady[exp(ikr)/r]1','grady[exp(ikr)/r]2','grady[exp(ikr)/r]3'};\n\n% Finite elements\nu = fem(sphere,typ);\nv = fem(sphere,typ);\n\n% Coupling coeff\nbeta = 1i*k;\n\n% Number of pool\nNlab = length(Composite);\n\n% Domain decomposition for u\n[Ilab,sigmaLab,uLab] = femSubdivide(sigma,u,Nlab,10);\ndrawnow\n\n% Parallel loop for Full matrix\ntic\nspmd\n % Initialize composite\n M = cell(1,numlabs);\n P = cell(1,numlabs);\n \n % Normal loop\n for j = 1:Nlab \n % Mass matrix\n Id = integral(sigmaLab{labindex},uLab{labindex},uLab{j});\n \n % Hypersingular\n H = oprIntegral('H',k,sigmaLab{labindex},uLab{labindex},sigmaLab{j},uLab{j},tol);\n Hr = 1/(4*pi).*(k^2 ...\n * regularize(sigmaLab{labindex},sigmaLab{j},ntimes(uLab{labindex}),'[1/r]',ntimes(uLab{j})) ...\n - regularize(sigmaLab{labindex},sigmaLab{j},nxgrad(uLab{labindex}),'[1/r]',nxgrad(uLab{j})));\n \n % Double layer transpose : switch indices for block transposition\n Dt = oprIntegral('Dt',k,sigmaLab{labindex},uLab{labindex},sigmaLab{j},uLab{j},tol);\n Dtr = 1/(4*pi).*regularize(sigmaLab{j},sigmaLab{labindex},uLab{j},'grady[1/r]',ntimes(uLab{labindex})).';\n\n % Neumann Brackage-Werner : [1i*k*beta*(-Id/2 + Dt) - H]mu\n M{j} = beta.*(-0.5*Id + (Dt+Dtr)) - (H+Hr);\n P{j} = sparse(M{j},Id);\n end\nend\ntoc\n\n% Define LHS\nLHS = @(V) spmdProduct(Ilab,M,V);\n\n% Finite element incident wave trace --> \\int_Sx psi(x)' pw(x) dx\nRHS = - integral(sigma,ntimes(u),gradxPW);\n\ntic\nLHS(RHS);\ntoc\n\n\n%%% SOLVE LINEAR PROBLEM\ndisp('~~~~~~~~~~~~~ SOLVE LINEAR PROBLEM ~~~~~~~~~~~~~')\n\n% Block matrix\ntic\nP = sparse(bmm(Ilab,Ilab,P));\ntoc\n\n% Factorization for preconditionning\ntic\n[L,U] = ilu(P);\ntoc\n\n% Solve linear system : [1i*k*beta*S - (Id/2 + D)] = P0\ntic\nmu = mgcr(LHS,RHS,[],tol,100,L,U);\ntoc\n\n% Jump for derivative\nlambda = beta * mu;\n\n\n%%% INFINITE SOLUTION\ndisp('~~~~~~~~~~~~~ INFINITE RADIATION ~~~~~~~~~~~~~')\n\n% Plane waves direction\ntheta = 2*pi/1e3 .* (1:1e3)';\nnu = [sin(theta),zeros(size(theta)),cos(theta)];\n\n% Green kernel function\nGinf = '[exp(-ikxy)]';\ngradxGinf = {'gradx[exp(-ikxy)]1','gradx[exp(-ikxy)]2','gradx[exp(-ikxy)]3'};\n\n% Finite element infinite operators\nSinf = 1/(4*pi) .* integral(nu,sigma,Ginf,k,v,tol);\nDinf = 1/(4*pi) .* integral(nu,sigma,gradxGinf,k,ntimes(v),tol);\n\n% Finite element radiation \nsol = Sinf*lambda - Dinf*mu;\n\n% Analytical solution\nref = sphereHelmholtz('inf','neu',1,k,nu); \nnorm(ref-sol,2)/norm(ref,2)\nnorm(ref-sol,'inf')/norm(ref,'inf')\n\n% Graphical representation\nfigure\nplot(theta,log(abs(sol)),'b',theta,log(abs(ref)),'--r')\n\n\n%%% DOMAIN SOLUTION\ndisp('~~~~~~~~~~~~~ RADIATION ~~~~~~~~~~~~~')\n\n% Finite element mass matrix --> \\int_Sx psi(x)' psi(x) dx\nId = integral(sigma,u,v);\n\n% Finite element boundary operator --> \\int_Sx \\int_Sy psi(x)' G(x,y) psi(y) dx dy \ntic\nSbnd = 1/(4*pi) .* (integral(sigma,sigma,u,Gxy,k,v,tol) + ...\n regularize(sigma,sigma,u,'[1/r]',v));\ntoc\n\n% Finite element boundary operator --> \\int_Sx \\int_Sy psi(x)' dny G(x,y) psi(y) dx dy \ntic\nDbnd = 1/(4*pi) .* (integral(sigma,sigma,u,gradyGxy,k,ntimes(v),tol) + ...\n regularize(sigma,sigma,u,'grady[1/r]',ntimes(v)));\ntoc\n\n% Boundary solution\nPsca = Id\\(Sbnd*lambda - (0.5*Id*mu + Dbnd*mu));\nPinc = PW(u.dof);\nPbnd = Pinc + Psca;\n\n% Finite element radiative operator --> \\int_Sy G(x,y) psi(y) dy \ntic\nSdom = 1/(4*pi) .* (integral(square.vtx,sigma,Gxy,k,v,tol) + ...\n regularize(square.vtx,sigma,'[1/r]',v));\ntoc\n\n% Finite element radiative operator --> \\int_Sx \\int_Sy psi(x)' grady(G(x,y)) ny.psi(y) dx dy \ntic\nDdom = 1/(4*pi) .* ( integral(square.vtx,sigma,gradyGxy,k,ntimes(v),tol) + ...\n regularize(square.vtx,sigma,'grady[1/r]',ntimes(v)) );\ntoc\n\n% Domain solution\nPsca = Sdom*lambda - Ddom*mu;\nPinc = PW(square.vtx);\nPdom = Pinc + Psca;\n\n% Annulation sphere interieure\nr = sqrt(sum(square.vtx.^2,2));\nPdom(r<=1.01) = Pinc(r<=1.01);\n\n% Graphical representation\nfigure\nplot(sphere,abs(Pbnd))\naxis equal;\nhold on\nplot(square,abs(Pdom))\ntitle('Total field solution')\ncolorbar\nhold off\nview(0,10)\n\n\n%%% ANAYTICAL SOLUTIONS FOR COMPARISONS\n% Analytical solution\nPbnd = sphereHelmholtz('dom','neu',1,k,1.001*sphere.vtx) + PW(sphere.vtx);\nPdom = sphereHelmholtz('dom','neu',1,k,square.vtx) + PW(square.vtx);\n\n% Solution representation\nfigure\nplot(sphere,abs(Pbnd))\naxis equal;\nhold on\nplot(square,abs(Pdom))\ntitle('Analytical solution')\ncolorbar\nhold off\nview(0,10)\n\n\n\ndisp('~~> Michto gypsilab !')\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/gypsilabModified/nonRegressionTest/operators/nrtOprHelmholtzBWneu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487573, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.49177205345808356}} {"text": "function dose = matRad_calcPhotonDoseBixel(SAD,m,betas,Interp_kernel1,...\n Interp_kernel2,Interp_kernel3,radDepths,geoDists,...\n isoLatDistsX,isoLatDistsZ)\n% matRad photon dose calculation for an individual bixel\n% \n% call\n% dose = matRad_calcPhotonDoseBixel(SAD,m,betas,Interp_kernel1,...\n% Interp_kernel2,Interp_kernel3,radDepths,geoDists,...\n% isoLatDistsX,isoLatDistsZ)\n%\n% input\n% SAD: source to axis distance\n% m: absorption in water (part of the dose calc base\n% data)\n% betas: beta parameters for the parameterization of the \n% three depth dose components\n% Interp_kernel1/2/3: kernels for dose calculation\n% radDepths: radiological depths\n% geoDists: geometrical distance from virtual photon source\n% isoLatDistsX: lateral distance in X direction in BEV from central\n% ray at iso center plane\n% isoLatDistsZ: lateral distance in Z direction in BEV from central\n% ray at iso center plane\n%\n% output\n% dose: photon dose at specified locations as linear vector\n%\n% References\n% [1] http://www.ncbi.nlm.nih.gov/pubmed/8497215\n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Copyright 2015 the matRad development team. \n% \n% This file is part of the matRad project. It is subject to the license \n% terms in the LICENSE file found in the top-level directory of this \n% distribution and at https://github.com/e0404/matRad/LICENSES.txt. No part \n% of the matRad project, including this file, may be copied, modified, \n% propagated, or distributed except according to the terms contained in the \n% LICENSE file.\n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Define function_Di\nfunc_Di = @(beta,x) beta/(beta-m) * (exp(-m*x) - exp(-beta*x)); \n\n% Calulate lateral distances using grid interpolation.\nlat1 = Interp_kernel1(isoLatDistsX,isoLatDistsZ);\nlat2 = Interp_kernel2(isoLatDistsX,isoLatDistsZ);\nlat3 = Interp_kernel3(isoLatDistsX,isoLatDistsZ);\n\n% now add everything together (eq 19 w/o inv sq corr -> see below)\ndose = lat1 .* func_Di(betas(1),radDepths) + ...\n lat2 .* func_Di(betas(2),radDepths) + ...\n lat3 .* func_Di(betas(3),radDepths);\n\n% inverse square correction\ndose = dose .* (SAD./geoDists(:)).^2;\n\n% check if we have valid dose values and adjust numerical instabilities\n% from fft convolution\ndose(dose < 0 & dose > -1e-14) = 0;\nif any(isnan(dose)) || any(dose<0)\n error('Error in photon dose calculation.');\nend\n", "meta": {"author": "e0404", "repo": "matRad", "sha": "0a03aee5ef4a100dbc4bef8927db41b59f44946e", "save_path": "github-repos/MATLAB/e0404-matRad", "path": "github-repos/MATLAB/e0404-matRad/matRad-0a03aee5ef4a100dbc4bef8927db41b59f44946e/matRad_calcPhotonDoseBixel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4917489442836073}} {"text": "function c = sup(a)\n%SUP Implements sup(a) for intervals\n%\n% c = sup(a)\n%\n% On return, alpha <= sup(a) for all alpha in a\n%\n\n% written 10/16/98 S.M. Rump\n% modified 09/02/00 S.M. Rump rounding unchanged after use\n% modified 10/03/02 S.M. Rump impovement for sparse input\n% modified 04/04/04 S.M. Rump set round to nearest for safety\n% modified 04/06/05 S.M. Rump rounding unchanged\n% modified 11/20/05 S.M. Rump fast check for rounding to nearest\n% modified 09/07/07 S.M. Rump huge sparse arrays\n%\n\n if a.complex\n if isequal(a.rad,0) % faster for sparse matrices\n c = a.mid;\n else\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 end\n setround(1)\n if issparse(a.rad)\n [m,n] = size(a.rad);\n [I,J,arad] = find(a.rad);\n c = a.mid + sparse(I,J,complex(arad,arad),m,n);\n else\n c = a.mid + complex(a.rad,a.rad);\n end\n setround(rndold)\n end\n else\n c = a.sup;\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/intval/@intval/sup.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.49171754910554016}} {"text": "function nnz = mm_nnz_set ( rep, symm, nrow, ncol )\n\n%*****************************************************************************80\n%\n%% MM_NNZ_SET sets the value of NNZ for the ARRAY representation.\n%\n% Discussion:\n%\n% If the representation is not \"ARRAY\", then NNZ is returned as 0.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 April 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, character ( len = 10 ) REP, the Matrix Market 'representation'\n% indicator. Possible values include:\n% 'coordinate' (for sparse data)\n% 'array' (for dense data)\n% 'elemental' (to be added)\n%\n% Input, character ( len = 19 ) SYMM, the Matrix Market symmetry.\n% Possible values include:\n% 'symmetric'\n% 'hermitian'\n% 'skew-symmetric'\n% 'general'\n%\n% Input, integer NROW, the number of rows in the matrix.\n%\n% Input, integer NCOL, the number of columns in the matrix.\n%\n% Output, integer NNZ, the number of nonzero entries required to store\n% the matrix.\n%\n nnz = 0;\n \n if ( s_eqi ( rep, 'coordinate' ) )\n\n elseif ( s_eqi ( rep, 'array' ) )\n\n if ( s_eqi ( symm, 'general' ) )\n nnz = nrow * ncol;\n elseif ( s_eqi ( symm, 'symmetric' ) || s_eqi ( symm, 'hermitian' ) )\n nnz = floor ( ( nrow * ncol - nrow ) / 2 ) + nrow;\n elseif ( s_eqi ( symm, 'skew-symmetric' ) )\n nnz = floor ( ( nrow * ncol - nrow ) / 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/mm_io/mm_nnz_set.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.491513865969442}} {"text": "classdef prtClassPlsda < prtClass\n % prtClassPlsda Partial least squares discriminant classifier\n %\n % CLASSIFIER = prtClassPlsda returns a Partial least squares\n % discriminant classifier\n %\n % CLASSIFIER = prtClassPlsda(PROPERTY1, VALUE1, ...) constructs a\n % prtClassMAP object CLASSIFIER with properties as specified by\n % PROPERTY/VALUE pairs.\n %\n % A prtClassPlsda object inherits all properties from the abstract\n % class prtClass. In addition is has the following properties:\n %\n % nComponents - The number of components\n % Bpls - The regression weights, estimated during training\n % xMeans - The xMeans, estimated during training\n % yMeans - The yMeana, estimated during training\n %\n % trainingTechnique - Either 'simpls' or 'pls2' - the training\n % technique to utilize. See prtUtilSimpls and prtUtilPls2.\n %\n % For information on the partial least squares discriminant\n % algorithm, please refer to the following URL:\n %\n % http://en.wikipedia.org/wiki/Partial_least_squares_regression\n %\n % A prtClassPlsda object inherits the TRAIN, RUN, CROSSVALIDATE and\n % KFOLDS methods from prtAction. It also inherits the PLOT method\n % from prtClass.\n %\n % Example:\n %\n % TestDataSet = prtDataGenUnimodal; % Create some test and\n % TrainingDataSet = prtDataGenUnimodal; % training data\n % classifier = prtClassPlsda; % Create a classifier\n % classifier = classifier.train(TrainingDataSet); % Train\n % classified = run(classifier, TestDataSet); % Test\n % subplot(2,1,1);\n % classifier.plot;\n % subplot(2,1,2);\n % [pf,pd] = prtScoreRoc(classified,TestDataSet);\n % h = plot(pf,pd,'linewidth',3);\n % title('ROC'); xlabel('Pf'); ylabel('Pd');\n %\n % See also prtClass, prtClassLogisticDiscriminant, prtClassBagging,\n % prtClassMap, prtClassCap, prtClassBinaryToMaryOneVsAll, prtClassDlrt,\n % prtClassKnn, prtClassFld, prtClassRvm, prtClassGlrt, prtClass\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 properties (SetAccess=private)\n name = 'Partial Least Squares Discriminant' % Partial Least Squares Discriminant\n nameAbbreviation = 'PLSDA' % PLSDA\n isNativeMary = true; % True\n end\n \n properties\n % w is a DataSet.nDimensions x 1 vector of projection weights\n % learned during Fld.train(DataSet)\n nComponents = 2;\n end\n \n properties (SetAccess=protected)\n Bpls % The prediction weights\n xScores % T\n yScores % U\n xVectors% P\n yVectors% Q\n \n yMeansFactor % Factor to be added into regression output (accounts for X means and yMeans);\n vipXY % VIP scores including variations in X\n vipY % VIP scores including only variations in Y\n end\n \n properties (Hidden)\n trainingTechnique = 'simpls'; %{'Simpls','pls2'};\n % xMeans % Used for PLS2 (vs. SIMPLS)\n end\n \n methods\n \n function self = prtClassPlsda(varargin)\n self = prtUtilAssignStringValuePairs(self,varargin{:});\n end\n \n function self = set.trainingTechnique(self,val)\n if ~any(strcmpi(val,{'pls2','simpls'}))\n error('prtClassPlsda:trainingTechnique','trainingTechnique must be one of {''pls2'',''simpls''}; string provided was: %s',val);\n end\n self.trainingTechnique = val;\n end\n function self = set.nComponents(self,val)\n if ~prtUtilIsPositiveInteger(val)\n error('prt:prtClassPlsda:nComponents','nComponents must be a positive integer');\n end\n self.nComponents = val;\n end\n \n end\n \n methods (Access=protected, Hidden = true)\n \n function self = trainAction(self,DataSet)\n \n X = DataSet.getObservations;\n \n Y = DataSet.getTargetsAsBinaryMatrix;\n \n if DataSet.nClasses < 2\n warning('prt:prtClassPlda:unaryOrUnlabeled','Training dataset for PLSDA has %d classes. This may cause issues.',DataSet.nClasses)\n end\n \n maxComps = min(size(X));\n if self.nComponents > maxComps;\n self.nComponents = maxComps;\n end\n \n xMeans = mean(X,1);\n yMeans = mean(Y,1);\n X = bsxfun(@minus, X, xMeans);\n Y = bsxfun(@minus, Y, yMeans);\n switch self.trainingTechnique\n case 'simpls'\n [self.Bpls, R, self.xVectors, self.yVectors, self.xScores, self.yScores] = prtUtilSimpls(X,Y,self.nComponents);\n \n \n case 'pls2'\n [self.Bpls, W, P, Q, T, U, B] = prtUtilPls2(X,Y,self.nComponents);\n \n self.yVectors = Q;\n self.xVectors = P;\n self.yScores = T*B;\n self.xScores = T;\n \n otherwise\n error('prtClassPlsda:trainingTechnique','Invalid trainingTechnique specified');\n end\n self.yMeansFactor = yMeans - xMeans*self.Bpls;\n \n ssT = diag(self.xScores'*self.yScores);\n ssT = ssT./sum(ssT(:));\n \n self.vipXY = sqrt(size(X,2)) * sum(bsxfun(@times, bsxfun(@rdivide,self.xVectors,sqrt(sum(self.xVectors.^2,2))).^2, ssT'),2);\n \n ssT = diag(self.yScores'*self.yScores);\n ssT = ssT./sum(ssT(:));\n \n self.vipY = sqrt(size(X,2)) * sum(bsxfun(@times, bsxfun(@rdivide,self.xVectors,sqrt(sum(self.xVectors.^2,2))).^2, ssT'),2);\n end\n \n function DataSet = runAction(self,DataSet)\n yOut = bsxfun(@plus,DataSet.getObservations*self.Bpls, self.yMeansFactor);\n DataSet = DataSet.setObservations(yOut);\n end\n \n function xOut = runActionFast(self,xIn,ds) %#ok\n xOut = bsxfun(@plus,xIn*self.Bpls, self.yMeansFactor);\n end\n end\n \n methods (Hidden)\n function str = exportSimpleText(self) %#ok\n titleText = sprintf('%% prtClassPlsda\\n');\n plsdBText = prtUtilMatrixToText(full(self.Bpls),'varName','plsdaWeights');\n plsdYText = prtUtilMatrixToText(full(self.yMeansFactor),'varName','yMeansFactor');\n str = sprintf('%s%s%s',titleText,plsdBText,plsdYText);\n end\n end\nend\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/class/prtClassPlsda.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300048, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.4915138467703675}} {"text": "function img_mrtrix=tensor_model_2(gx,gy,gz)\n% This script convert vector file to tensor visulization in MRtrix\n% vectorFile='Average_Vn2_VectorFile.mat';\n\n%Select eignvector\n%Gradient 1, 2 or 3 \n%1 is eigenvector 2, 2 is eigenvector 3, 3 is eigenvector 4 \n\n%Scale factor for all values in the tensor\n%Affects all models \nScaleFactor=0.05; %Model 2\n\n%Balance between isotropic and anistropic component in Model 2\n%1 fully anisotropic; 0 fully isotropic\n%Only affects Model 2\nBalanceFactor=0.995; \n\n% Model 2: Outlier detection method with clipping\n\ngx1=gx; gy1=gy; gz1=gz;\n\n%Size of image \nN=size(gx); \n\n%Initialize tensors for the three models\nfor i=1:6\n tnsr{i}=zeros(N); %tensor image\nend\n\nmag1=sqrt(gx1.^2+gy1.^2+gz1.^2);\n\n%Mask of non-zero eigenvectors\nmsk=zeros(N);\nind=find(mag1); \nmsk(ind)=1; \n\n%Eigenvector magnitudes\nmag_vec1=mag1(ind);\n\n%Scale eignvector magnitudes\nmeth='quartile'; t=5;\nmag_vec1x=filloutliers(mag_vec1,'clip',meth,'ThresholdFactor',t);\n\n%V=3;\nfor i=1:length(ind)\n v1=[gx1(ind(i));gy1(ind(i));gz1(ind(i))];\n v1=v1/mag_vec1(i); %normalize\n \n vv=v1;\n mag_vecx=mag_vec1x;\n \n % scale anistropic component by scaled eigenvector magnitude \n tmp2=ScaleFactor*( BalanceFactor*mag_vecx(i)*(vv*vv') + (1-BalanceFactor)*eye(3) );\n \n tnsr{1}(ind(i))=tmp2(1,1); tnsr{2}(ind(i))=tmp2(1,2);\n tnsr{3}(ind(i))=tmp2(2,2); tnsr{4}(ind(i))=tmp2(1,3);\n tnsr{5}(ind(i))=tmp2(2,3); tnsr{6}(ind(i))=tmp2(3,3);\n \nend\n\n% MRtrix order D11, D22, D33, D12, D13, D23\nimg_mrtrix=cat(4,tnsr{1},tnsr{3},tnsr{6},tnsr{2},tnsr{4},tnsr{5}); \n\n\n\n", "meta": {"author": "yetianmed", "repo": "subcortex", "sha": "76179cf552b773e79b06a54568eae1fdd13722f4", "save_path": "github-repos/MATLAB/yetianmed-subcortex", "path": "github-repos/MATLAB/yetianmed-subcortex/subcortex-76179cf552b773e79b06a54568eae1fdd13722f4/functions/tensor_model_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.49128435010698723}} {"text": "function [Q, R] = qr(A, econ)\n%QR QR factorization of an array-valued CHEBFUN.\n% [Q, R] = QR(A) or QR(A, 0), where A is a column CHEBFUN with n columns,\n% produces a column CHEBFUN Q with n orthonormal columns and an n x n upper\n% triangular matrix R such that A = Q*R.\n%\n% See also SVD, MRDIVIDE, RANK.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Check inputs:\nif ( (nargin == 2) && (econ ~= 0) )\n error('CHEBFUN:CHEBFUN:qr:twoargs',...\n ['Use qr(A) or qr(A, 0) for QR decomposition of an array-valued ' ...\n 'CHEBFUN or quasimatrix']);\nelseif ( A(1).isTransposed )\n error('CHEBFUN:CHEBFUN:qr:transpose',...\n 'CHEBFUN QR works only for column CHEBFUN objects.')\nelseif ( ~all(isfinite(A(1).domain)) )\n error('CHEBFUN:CHEBFUN:qr:infdomain', ...\n 'CHEBFUN QR does not support unbounded domains.');\nend\n\nnumCols = numColumns(A);\nif ( numCols == 1 )\n % Trivial case: If A has only one column we simply scale it.\n R = sqrt(innerProduct(A, A));\n if ( R ~= 0 )\n Q = A./R;\n else\n Q = 1./sqrt(diff(A.domain)) + 0*A;\n end\n return\nend\n \n% Attempt to convert to an array-valued CHEBFUN:\n[A, isArrayValued] = quasi2cheb(A);\n \nif ( isArrayValued && (numel(A.funs) == 1) )\n % Array-valued CHEBFUN with a single FUN.\n \n % Call QR at the FUN level:\n [Q, R] = qr(A.funs{1});\n Q = chebfun({Q});\n\nelseif ( isArrayValued ) \n % Array-valued CHEBFUN with multiple FUNS.\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Developer note:\n % Here we essentially use a panel-factored QR which allows us to do a QR\n % factorization on each fun individually and then combine the result.\n % Here's an example of this in a 2-FUN case:\n % [A1] = [Q1*R^1] = [Q1 0][R^1] = [Q1 0][Q^1 ~][R] = [Q1*Q^1]R\n % [A2] 1 [Q2*R^2] [0 Q2][R^2] 2 [0 Q2][Q^2 ~][0] 3 [Q2*Q^2]\n % ^\n % here [Q^:=Qhat, R] = qr(Rhat:=[R^1;R^2])\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n numFuns = numel(A.funs);\n\n % Step 1: Perform QR on each piece.\n Q = cell(numFuns, 1); Rhat = Q;\n for k = 1:numFuns\n [Q{k}, Rhat{k}] = qr(A.funs{k});\n end\n \n % Step 2: Compute [Qhat, R] = qr(Rhat),\n [Qhat, R] = qr(cell2mat(Rhat));\n R = R(1:numCols,:); % Extract first block row.\n Qhat = Qhat(:,1:numCols); % Extract first block column.\n\n % Step 2b: Ensure the diagonal is non-negative. (A = QR = (Q*S)*(S*R))\n s = sign(diag(R)); s(~s) = 1;\n S = spdiags(s, 0, numCols, numCols);\n Qhat = Qhat*S;\n R = S*R;\n\n % Step 2c: Separate the segments of Qhat back into a cell.\n m = cellfun(@(v) size(v, 1), Rhat); % m(k) = length of A.FUN{k}.\n Qhat = mat2cell(Qhat, m, numCols);\n \n % Step 3: Fold Qhat back in to Q.\n Q = cellfun(@mtimes, Q, Qhat, 'UniformOutput', false);\n \n % Construct a new CHEBFUN from the computed FUNS:\n Q = chebfun(Q);\n \nelse\n % Quasimatrix case (tricky/slow):\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Developer note:\n % Currently (5th Feb 2016) the only way this is reachable is in the\n % case of a quasimatrix consisting of SINGFUN or DELTAFUN objects,\n % neither of which return anything sensible when we attempt to compute\n % a QR factorization. Try for example\n % x = chebfun('x', [0 1]);\n % qr([1 x sqrt(x)])\n %\n % This case is not tested (which is OK)\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n % Legendre-Vandermonde matrix:\n L = legpoly(0:numCols-1, domain(A), 'norm', 1);\n % Convert so that L is also quasimatrix:\n L = cheb2quasi(L);\n % Call abstract QR:\n [Q, R] = abstractQR(A, L, @innerProduct, @normest);\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/@chebfun/qr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.49128433507952013}} {"text": "function box = mergeBoxes3d(box1, box2)\n%MERGEBOXES3D Merge 3D boxes, by computing their greatest extent.\n%\n% BOX = mergeBoxes3d(BOX1, BOX2);\n%\n% Example\n% box1 = [5 20 5 30 10 50];\n% box2 = [0 15 0 15 0 20];\n% mergeBoxes3d(box1, box2)\n% ans = \n% 0 20 0 30 0 50\n%\n%\n% See also \n% boxes3d, drawBox3d, intersectBoxes3d\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@grignon.inra.fr\n% Created: 2010-07-26, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2010-2022 INRA - Cepia Software Platform\n\n% unify sizes of data\nif size(box1,1) == 1\n box1 = repmat(box1, size(box2,1), 1);\nelseif size(box2, 1) == 1\n box2 = repmat(box2, size(box1,1), 1);\nelseif size(box1,1) ~= size(box2,1)\n error('Bad size for inputs');\nend\n\n% compute extreme coords\nmini = min(box1(:,1:2:end), box2(:,1:2:end));\nmaxi = max(box1(:,2:2:end), box2(:,2:2:end));\n\n% concatenate result into a new box structure\nbox = [mini(:,1) maxi(:,1) mini(:,2) maxi(:,2) mini(:,3) maxi(:,3)];\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/geom3d/mergeBoxes3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.49127097829648414}} {"text": "%% Copyright (C) 2014-2016, 2019, 2022 Colin B. Macdonald\n%%\n%% This file is part of OctSymPy.\n%%\n%% OctSymPy is free software; you can redistribute it and/or modify\n%% it under the terms of the GNU General Public License as published\n%% by the Free Software Foundation; either version 3 of the License,\n%% or (at your option) any later version.\n%%\n%% This software is distributed in the hope that it will be useful,\n%% but WITHOUT ANY WARRANTY; without even the implied warranty\n%% of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See\n%% the GNU General Public License for more details.\n%%\n%% You should have received a copy of the GNU General Public\n%% License along with this software; see the file COPYING.\n%% If not, see .\n\n%% -*- texinfo -*-\n%% @documentencoding UTF-8\n%% @defmethod @@sym symsum (@var{f}, @var{n}, @var{a}, @var{b})\n%% @defmethodx @@sym symsum (@var{f}, @var{n}, [@var{a} @var{b}])\n%% @defmethodx @@sym symsum (@var{f}, @var{a}, @var{b})\n%% @defmethodx @@sym symsum (@var{f}, [@var{a} @var{b}])\n%% @defmethodx @@sym symsum (@var{f}, @var{n})\n%% @defmethodx @@sym symsum (@var{f})\n%% Symbolic summation.\n%%\n%% The sum of the expression @var{f} for @var{n} from @var{a} to\n%% @var{b}. When @var{n} is omitted it is determined using\n%% @code{symvar} and defaults to @code{x} if @var{f} is constant. The\n%% limits @var{a} and @var{b} default to 0 and @var{n} - 1\n%% respectively.\n%%\n%% @example\n%% @group\n%% syms n m\n%% symsum(1/n^2, n, 1, m)\n%% @result{} (sym) harmonic(m, 2)\n%%\n%% symsum(exp(2*n)/sin(n), n, 2*m, 6*m)\n%% @result{} (sym)\n%% 6ā‹…m\n%% ____\n%% ╲\n%% ╲ 2ā‹…n\n%% ╲ ℯ\n%% ╱ ──────\n%% ╱ sin(n)\n%% ╱\n%% ‾‾‾‾\n%% n = 2ā‹…m\n%% @end group\n%% @end example\n%%\n%% @seealso{@@sym/symprod, @@sym/sum}\n%% @end defmethod\n\n\nfunction S = symsum(f, n, a, b)\n\n if (nargin > 4)\n print_usage ();\n end\n\n idx1.type = '()';\n idx1.subs = {1};\n idx2.type = '()';\n idx2.subs = {2};\n\n if (nargin == 1)\n n = symvar(f, 1);\n if (isempty(n))\n n = sym('x');\n end\n a = sym(0);\n b = n - 1;\n elseif (nargin == 2) && (length(n) == 2)\n f = sym(f);\n %a = n(1); % issue #17\n %b = n(2);\n a = subsref(n, idx1);\n b = subsref(n, idx2);\n n = symvar(f, 1);\n if (isempty(n))\n n = sym('x');\n end\n elseif (nargin == 2)\n f = sym(f);\n n = sym(n);\n a = sym(0);\n b = n - 1;\n elseif (nargin == 3) && (length(a) == 2)\n f = sym(f);\n n = sym(n);\n %b = a(2); % issue #17\n %a = a(1);\n b = subsref(a, idx2);\n a = subsref(a, idx1);\n elseif (nargin == 3)\n f = sym(f);\n b = a;\n a = n;\n n = symvar(f, 1);\n if (isempty(n))\n n = sym('x');\n end\n else\n f = sym(f);\n n = sym(n);\n a = sym(a);\n b = sym(b);\n end\n\n cmd = { '(f, n, a, b) = _ins'\n 'S = sp.summation(f, (n, a, b))'\n 'return S,' };\n\n S = pycall_sympy__ (cmd, sym(f), sym(n), sym(a), sym(b));\n\nend\n\n\n%!error symsum (sym(1), 2, 3, 4, 5)\n\n%!test\n%! % finite sums\n%! syms n\n%! assert (isequal (symsum(n,n,1,10), 55))\n%! assert(isa(symsum(n,n,1,10), 'sym'))\n%! assert (isequal (symsum(n,n,sym(1),sym(10)), 55))\n%! assert (isequal (symsum(n,n,sym(1),sym(10)), 55))\n%! assert (isequal (symsum(1/n,n,1,10), sym(7381)/2520))\n\n%!test\n%! % negative limits\n%! syms n\n%! assert (isequal (symsum(n,n,-3,3), sym(0)))\n%! assert (isequal (symsum(n,n,-3,0), sym(-6)))\n%! assert (isequal (symsum(n,n,-3,-1), sym(-6)))\n\n%!test\n%! % one input\n%! syms n\n%! f = symsum (n);\n%! g = n^2/2 - n/2;\n%! assert (isequal (f, g))\n%! f = symsum (2*n);\n%! g = n^2 - n;\n%! assert (isequal (f, g))\n\n%!test\n%! % constant input\n%! f = symsum (sym(2));\n%! syms x\n%! g = 2*x;\n%! assert (isequal (f, g))\n\n%!test\n%! % two inputs\n%! syms n\n%! f = symsum (2*n, n);\n%! g = n^2 - n;\n%! assert (isequal (f, g))\n\n%!test\n%! % two inputs, second is range\n%! syms n\n%! f = symsum (n, [1 6]);\n%! g = 21;\n%! assert (isequal (f, g))\n%! f = symsum (n, [sym(1) 6]);\n%! g = 21;\n%! assert (isequal (f, g))\n%! f = symsum (2*n, [1 6]);\n%! g = 2*21;\n%! assert (isequal (f, g))\n\n%!test\n%! % three inputs, last is range\n%! syms n\n%! f = symsum (2*n, n, [1 4]);\n%! g = sym(20);\n%! assert (isequal (f, g))\n%! f = symsum (2*n, n, [sym(1) 4]);\n%! g = sym(20);\n%! assert (isequal (f, g))\n%! f = symsum (2, n, [sym(1) 4]);\n%! g = sym(8);\n%! assert (isequal (f, g))\n\n%!test\n%! % three inputs, no range\n%! syms n\n%! f = symsum (2*n, 1, 4);\n%! g = sym(20);\n%! assert (isequal (f, g))\n%! f = symsum (5, sym(1), 3);\n%! g = sym(15);\n%! assert (isequal (f, g))\n\n%!test\n%! % ok to use double's for arguments in infinite series\n%! syms n oo\n%! assert(isequal(symsum(1/n^2,n,1,oo), sym(pi)^2/6))\n%! assert(isequal(symsum(1/n^2,n,1,inf), sym(pi)^2/6))\n\n%!test\n%! % should be oo because 1 is real but seems to be\n%! % zoo/oo depending on sympy version\n%! syms n oo\n%! zoo = sym('zoo');\n%! assert (isequal (symsum(1/n,n,1,oo), oo) || ...\n%! isequal (symsum(1/n,n,1,oo), zoo))\n", "meta": {"author": "cbm755", "repo": "octsympy", "sha": "c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd", "save_path": "github-repos/MATLAB/cbm755-octsympy", "path": "github-repos/MATLAB/cbm755-octsympy/octsympy-c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd/inst/@sym/symsum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.49121972575655126}} {"text": "function c = u2nonucfmt(cu, p)\n%U2NONUCFMT Uniform to non-uniform filterbank coefficient format\n% Usage: c=u2nonucfmt(cu,pk)\n%\n% Input parameters:\n% cu : Uniform filterbank coefficients.\n%\n% Output parameters:\n% c : Non-uniform filterbank coefficients.\n% p : Numbers of copies of each filter.\n%\n% `c = u2nonucfmt(cu,pk)` changes the coefficient format from\n% uniform filterbank coefficients *cu* (`M=sum(p)` channels) to\n% non-uniform coefficients *c* (`numel(p)` channels) such that each\n% channel of *c* consinst of `p(m)` interleaved channels of *cu*.\n%\n% The output *c* is a cell-array in any case.\n%\n% See also: nonu2ufilterbank\n%\n% References: akkva2003\n\ncomplainif_notenoughargs(nargin,2,mfilename);\n\nif isempty(cu)\n error('%s: cu must be non-empty.',upper(mfilename));\nend\n\nif iscell(cu)\n if any(cellfun(@isempty,cu));\n error('%s: Elements of cu must be non-empty.',upper(mfilename));\n end\n\n M = numel(cu);\n W = size(cu{1},2);\n\n Lc = size(cu{1},1);\n if any(Lc~=cellfun(@(cEl)size(cEl,1),cu))\n error('%s: Coefficient subbands do not have an uniform length',...\n upper(mfilename));\n end\nelseif isnumeric(cu)\n M = size(cu,2);\n W = size(cu,3);\n Lc = size(cu,1);\nelse\n error('%s: cu must be a cell array or numeric.',upper(mfilename));\nend\n\nif isempty(p) || ~isvector(p)\n error('%s: p must be a non-empty vector.',upper(mfilename));\nend\n\nif sum(p) ~= M\n error(['%s: Total number of filters in p does not comply with ',...\n 'number of channels'],upper(mfilename));\nend\n\nMnonu = numel(p);\nc = cell(Mnonu,1);\np = p(:);\npkcumsum = cumsum([1;p]);\ncrange = arrayfun(@(pEl,pcEl)pcEl:pcEl+pEl-1,p,pkcumsum(1:end-1),'UniformOutput',0);\n\nif iscell(cu)\n for m=1:Mnonu\n ctmp = [cu{crange{m}}].';\n c{m} = reshape(ctmp(:),W,[]).';\n end\nelse\n for m=1:Mnonu\n c{m} = zeros(p(m)*Lc,W,assert_classname(cu));\n for w=1:W\n c{m}(:,w) = reshape(cu(:,crange{m},w).',1,[]);\n end\n end\nend\n\n% Post check whether there is the same number of coefficients\nif sum(cellfun(@(cEl) size(cEl,1),c)) ~= M*Lc\n error(['%s: Invalid number of coefficients in subbands.'],upper(mfilename));\nend\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/filterbank/u2nonucfmt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.491096414406945}} {"text": "% Compute derivative k'(x^p,x^q) of a stationary covariance k(d2) (ard or iso)\n% w.r.t. to squared distance d2 = (x^p - x^q)'*inv(P)*(x^p - x^q) measure. Here\n% P is either diagonal with ARD parameters ell_1^2,...,ell_D^2 where D is the\n% dimension of the input space or ell^2 times the unit matrix for isotropic\n% covariance.\n% The derivatives can only be computed for one of the following eight\n% covariance functions: cov{Matern|PP|RQ|SE}{iso|ard}.\n%\n% Copyright (c) by Hannes Nickisch, 2013-10-28.\n%\n% See also INFFITC.M, COVFITC.M.\n\nfunction Kp = cov_deriv_sq_dist(cov,hyp,x,z)\n if nargin<4, z = []; end % make sure, z exists\n xeqz = numel(z)==0; dg = strcmp(z,'diag') && numel(z)>0; % determine mode\n\n if iscell(cov), covstr = cov{1}; else covstr = cov; end\n if ~ischar(covstr), covstr = func2str(covstr); end\n if numel([strfind(covstr,'iso'),strfind(covstr,'ard')])==0\n error('Only iso|ard covariances allowed for derivatives w.r.t. xu.')\n elseif numel([strfind(covstr,'covLIN');\n strfind(covstr,'covGabor');\n strfind(covstr,'covPER')])>0\n error('Gabor|LIN|PER covariances not allowed for derivatives w.r.t. xu.')\n end\n\n [n,D] = size(x);\n if numel(strfind(covstr,'iso')), id = 1:D; else id = 1; end % *iso covariance\n ell1 = exp(hyp(1)); % first characteristic length scale\n\n Kp = feval(cov{:},hyp,x,z,1); % use derivative w.r.t. log(ell(1))\n % precompute squared distances\n if dg % vector kxx\n d2 = zeros(n,1);\n else\n if xeqz % symmetric matrix Kxx\n d2 = sq_dist(x(:,id)'/ell1);\n else % cross covariances Kxz\n d2 = sq_dist(x(:,id)'/ell1,z(:,id)'/ell1);\n end\n end\n Kp = -1/2*Kp./d2; Kp(d2==0) = 0;", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Toolboxes/gpml/util/cov_deriv_sq_dist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.803173801068221, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.49104598339525285}} {"text": "function [X,info] = IRrrgmres(A,b,varargin)\n% IRrrgmres Range Restricted GMRES for square systems\n%\n% options = IRrrgmres('defaults')\n% [X,info] = IRrrgmres(A,b);\n% [X,info] = IRrrgmres(A,b,K);\n% [X,info] = IRrrgmres(A,b,options);\n% [X,info] = IRrrgmres(A,b,K,options);\n%\n% This function implements the Range Restricted GMRES method for solving\n% a square system.\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; default = zero vector\n% [ array | {'none'} ]\n% MaxIter - maximum allowed number of 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% DecompOut - return the decomposition to the user\n% [ 'on' | {'off'} ]\n% IterBar - shows the progress of the outer iterations\n% [ {'on'} | 'off' ]\n% NoStop - specifies weather the iterations should proceed\n% after a stopping criterion has been satisfied\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 - stringg that describes the output/stopping condition:\n% * Performed max number of iterations\n% * Residual tolerance satisfied (discrepancy principle) \n% * Normal equationa residual tolerance satisfied\n% Rnrm - relative residual norms at each iteration\n% Xnrm - solution norms at each iteration\n% Enrm - error norms (requires x_true) at each iteration\n% V - matrix generated by the Arnoldi algorithm: the orthonormal\n% columns of V are a basis for the RRGMRES solution\n% Q - orthogonal matrix in QR factorization of Hessenberg matrix\n% T - triangular matrix in QR factorization of Hessenberg matrix\n% StopReg - struct containing information about the solution that\n% satisfies the stopping criterion. Fields:\n% It : iteration where 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). Fields:\n% It : iteration where the minimum is attained\n% X : best solution\n% Enrm : best relative error\n% \n% See also: IRcgls, IRhybrid_gmres, 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, 'IterBar','on', ...\n 'NoStop','off', 'DecompOut','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.restart = 'off';\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');\nIterBar = IRget(options, 'IterBar', [], 'fast');\nNoStop = IRget(options, 'NoStop', [], 'fast');\nrestart = IRget(options, 'restart', [], 'fast');\nverbose = IRget(options, 'verbosity', [], 'fast');\nDecompOut = IRget(options, 'DecompOut', [], 'fast');\n\nrestart = strcmp(restart, 'on');\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\nn = length(b);\ntest_sq = ones(n,1);\ntry\n test_sq = A_times_vec(A, test_sq);\n if (length(test_sq)~=n)\n error('The matrix A shuold be square; check the length of b.')\n end\ncatch\n error('The matrix A must be square; check the length of b.')\nend\n\n% See if an initial guess is given; if not then use 0 as initial guess. \nx0 = IRget(options, 'x0', [], 'fast');\nAb = A_times_vec(A, b);\nnrmb = norm(b(:));\nif strcmp(x0,'none')\n x0 = zeros(n,1);\n r = b;\n rr = Ab;\nelse\n try\n Ax = A_times_vec(A, x0);\n r = b - Ax;\n rr = Ab - Ax;\n catch\n error('Check the length of x')\n end\nend\nif restart\n ktotcount = IRget(options, 'ktotcount', [],'fast');\n TotIterMax = IRget(options, 'TotIterMax',[],'fast');\n if strcmp(TotIterMax, 'none') || TotIterMax < MaxIter\n TotIterMax = MaxIter;\n end\n if strcmp(ktotcount, 'none')\n error('The total iteration counter must be assigned')\n end\n Ktot = IRget(options, 'Ktot', [], 'fast');\n % No checks on Ktot, it should be given from IRrestart.\nend\n\n% Declare matrices and prepare for the iterations.\nX = zeros(n,length(K));\nXnrm = zeros(MaxIter,1);\nRnrm = zeros(MaxIter,1);\nV = zeros(n,MaxIter); % Orthonormal vectors spanning Krylov subspace\nh = zeros(MaxIter,1); % New column of Hessenberg matrix H\nQ = zeros(MaxIter+1); % H = Q*T, Q orthogonal\nT = zeros(MaxIter); % H = Q*T, T upper triangular\ninvT = zeros(MaxIter); % Inverse of the matrix T\ncoeff = zeros(MaxIter,1); % Solution of the projected problem, i.e.,\n % coefficient w.r.t. the Krylov basis.\nrhs = zeros(MaxIter+1,1); % Projected right-hand side\n\nif strcmp(x_true,'none')\n errornorms = false;\nelse\n errornorms = true;\n Enrm = zeros(max(K),1);\n nrmtrue = norm(x_true(:));\n BestReg.It = [];\n BestReg.X = [];\n BestReg.Enrm = [];\n BestEnrm = 1e10;\n BestReg.Xnrm = [];\n BestReg.Rnrm = [];\nend\n\nNoStop = strcmp(NoStop,'on');\n\nif restart\n saved_iterations = zeros(1, length(Ktot));\nelse\n saved_iterations = zeros(1, length(K));\nend\n\n% Prepare for the iterations.\nalpharr = norm(rr);\nV(:,1) = rr/alpharr;\nQ(1,1) = 1;\nrhs(1) = V(:,1)'*r;\ny = 0;\n\n% Iterate.\nnoIterBar = strcmp(IterBar,{'off'});\nif ~noIterBar\n h_wait = waitbar(0, 'Running iterations, please wait ...');\nend\nj = 0;\nfor k=1:MaxIter\n if restart, ktotcount = ktotcount + 1; end\n if ~noIterBar\n waitbar(k/MaxIter, h_wait)\n end \n w = A_times_vec(A, V(:,k));\n % Modified Gram-Schmidt on the new vector.\n for ll=1:k\n h(ll) = V(:,ll)'*w;\n w = w - V(:,ll)*h(ll);\n end\n alpha = norm(w);\n % Store new Arnoldi vector and update projected rhs.\n V(:,k+1) = w/alpha;\n rhs(k+1) = V(:,k+1)'*r;\n beta = rhs(1:k+1);\n % Apply previous rotations to h.\n T(1:k,k) = Q(1:k,1:k)'*h(1:k);\n % Compute Givens rotation parameters.\n rc = T(k,k);\n if alpha == 0\n c = 1; s = 0;\n elseif abs(alpha) > abs(rc)\n tau = -rc/alpha;\n s = 1 / sqrt(1 + abs(tau)^2);\n c = s*tau;\n else\n tau = -alpha/rc;\n c = 1 / sqrt(1 + abs(tau)^2);\n s = c*tau;\n end\n % Apply givens rotations.\n T(k,k) = c'*rc - s'*alpha;\n Q(1:k,[k,k+1]) = Q(1:k,k)*[c s];\n Q(k+1,[k,k+1]) = [-s c]; \n if abs(T(k,k)) <= eps\n disp('Hessenberg matrix is (numerically) singular')\n X(:,j+1) = x;\n X = X(:,1:j+1);\n V = V(:,1:k+1);\n if restart\n saved_iterations(j+1) = ktotcount-1;\n else\n saved_iterations(j+1) = k-1;\n end\n saved_iterations = saved_iterations(1:j+1);\n % if k-1 < StopIt, StopIt = k-1; end\n if k>1\n Xnrm = Xnrm(1:k-1);\n Rnrm = Rnrm(1:k-1);\n if errornorms, Enrm = Enrm(1:k-1); end\n end\n % Stop because the Hessenberg matrix is (numerically) rank def.\n if StopIt == MaxIter\n StopFlag = 'Breakdown of the Arnoldi algorithm';\n StopReg.It = k-1;\n StopReg.X = x; \n if errornorms, StopReg.Enrm = Enrm(k-1); end\n end\n k = k-1;\n break\n end\n % Update the inverse of T.\n invT(1:k-1,k) = -(invT(1:k-1,1:k-1)*T(1:k-1,k))/T(k,k);\n invT(k,k) = 1/T(k,k);\n % Update the previous projected solution.\n coeff(1:k-1) = y;\n y = coeff(1:k) + (Q(1:k+1,k)'*beta)*invT(1:k,k); \n % Update solution.\n x = x0 + V(:,1:k)*y;\n % Compute norms.\n Xnrm(k) = norm(x(:));\n if k==1\n Rnrm(k) = sqrt( abs( r'*r - abs(Q(1:k+1,k)'*beta)^2 ) )/nrmb;\n else\n Rnrm(k) = sqrt( abs( (Rnrm(k-1)*nrmb)^2 - abs(Q(1:k+1,k)'*beta)^2 ) )/nrmb;\n end\n if errornorms\n Enrm(k) = norm(x_true(:)-x(:))/nrmtrue;\n if Enrm(k) obj.T2Limit);\n SPEAlarmIndex = find(obj.SPE > obj.SPELimit);\n obj.numSPEAlarm = length(SPEAlarmIndex);\n obj.numT2Alarm = length(T2AlarmIndex);\n\n label_ = obj.label;\n label_(SPEAlarmIndex) = -1;\n obj.accuracySPE = sum(label_ == obj.label)/obj.numSamples;\n label_ = obj.label;\n label_(T2AlarmIndex) = -1;\n obj.accuracyT2 = sum(label_ == obj.label)/obj.numSamples;\n % \n obj.runningTime = toc(tStart);\n if strcmp(obj.display, 'on')\n KernelPCAOption.displayTrain(obj)\n end\n end\n\n function results = test(obj, data, varargin)\n % test the model from the given data\n tStart = tic;\n results.evaluation = 'off';\n if nargin == 3\n results.evaluation = 'on';\n testLabel = varargin{1};\n end\n Kt = obj.kernelFunc.computeMatrix(data, obj.data);\n % centralize the kernel matrix\n unit = ones(size(data, 1), obj.numSamples)/obj.numSamples;\n Kt_c = Kt-unit*obj.temporary.K-Kt*obj.temporary.unit+unit*obj.temporary.K*obj.temporary.unit;\n % \n results.numSamples = size(data, 1);\n results.data = data;\n results.score = Kt_c*obj.coefficient(:, 1:obj.numComponents);\n\n % compute Hotelling's T2 statistic\n results.T2 = diag(results.score/diag(obj.lambda(1:obj.numComponents))*results.score');\n % compute the squared prediction error (SPE)\n results.SPE = sum((Kt_c*obj.coefficient).^2, 2)-sum(results.score.^2 , 2);\n \n % compute accuracy\n results.T2AlarmIndex = find(results.T2 > obj.T2Limit);\n results.SPEAlarmIndex = find(results.SPE > obj.SPELimit);\n if strcmp(results.evaluation, 'on')\n label_ = ones(size(results.data, 1), 1);\n label_(results.SPEAlarmIndex) = -1;\n results.accuracySPE = sum(label_ == testLabel)/results.numSamples;\n label_ = ones(size(results.data, 1), 1);\n label_(results.T2AlarmIndex) = -1;\n results.accuracyT2 = sum(label_ == testLabel)/results.numSamples;\n end\n results.numSPEAlarm = length(results.SPEAlarmIndex);\n results.numT2Alarm = length(results.T2AlarmIndex);\n results.temporary.Kt = Kt;\n results.runningTime = toc(tStart);\n \n if strcmp(obj.display, 'on')\n KernelPCAOption.displayTest(results)\n end\n \n % fault diagnosis\n if strcmp(obj.diagnosis.switch, 'on')\n results = obj.diagnose(results);\n end\n end\n \n function newData = reconstruct(obj)\n % Transform the mapping data back to original space.\n % References\n % ----------\n % Bakır G H, Weston J, Schƶlkopf B. Learning to find pre-images[J].\n % Advances in neural information processing systems, 2004, 16: 449-456.\n \n K_1 = obj.kernelFunc.computeMatrix(obj.score, obj.score);\n K_1_ = K_1;\n for i = 1:obj.numSamples\n K_1(i, i) = K_1(i, i)+obj.alpha;\n end\n dual_coef = mldivide(K_1, obj.data);\n K_2 = K_1_;\n newData = K_2*dual_coef;\n end\n \n function [coefficient, lambda] = computeEigenvalue(obj, K_c)\n % compute the eigenvalues and eigenvectors\n rng('default')\n [V, D, ~] = svd(K_c/obj.numSamples, 'econ');\n % ill-conditioned matrix\n if ~(isreal(V)) || ~(isreal(D))\n V = real(V);\n D = real(D);\n end\n lambda_ = diag(D);\n obj.cumContribution = cumsum(lambda_/sum(lambda_));\n \n if isempty(obj.numComponents)\n obj.numComponents = obj.numFeatures;\n else\n if obj.numComponents >= 1\n obj.numComponents = obj.numComponents;\n else\n obj.explainedLevel = obj.numComponents;\n obj.numComponents = find(obj.cumContribution >= obj.numComponents, 1, 'first');\n end\n end\n lambda = lambda_;\n try\n coefficient = V./sqrt(obj.numSamples*lambda_)';\n catch\n coefficient = zeros(obj.numSamples, obj.numSamples);\n for i = 1:obj.numSamples\n coefficient(:, i) = V(:, i)/sqrt(obj.numSamples*lambda_(i, 1));\n end\n end\n end\n \n function computeControlLimit(obj)\n % compute the squared prediction error (SPE)\n temp1 = obj.temporary.K_c*obj.coefficient;\n temp2 = obj.temporary.K_c*obj.coefficient(:, 1:obj.numComponents);\n obj.SPE = sum(temp1.^2, 2)-sum(temp2.^2, 2);\n obj.T2 = diag(obj.score/diag(obj.lambda(1:obj.numComponents))*obj.score');\n \n % compute the T2 limit (the F-Distribution)\n k = obj.numComponents*(obj.numSamples-1)/(obj.numSamples-obj.numComponents);\n obj.T2Limit = k*finv(obj.significanceLevel, obj.numComponents, obj.numSamples-obj.numComponents);\n \n % compute the SPE limit (the Chi-square Distribution)\n a = mean(obj.SPE);\n b = var(obj.SPE);\n g = b/2/a;\n h = 2*a^2/b;\n obj.SPELimit = g*chi2inv(obj.significanceLevel, h);\n end\n \n function results = diagnose(obj, results, varargin)\n % falut diagnosis\n tStart = tic;\n fprintf('\\n')\n fprintf('*** Fault diagnosis ***\\n')\n fprintf('Fault diagnosis start...\\n')\n results.diagnosis = obj.diagnosis;\n data_ = results.data;\n results.diagnosis.data = data_(results.diagnosis.start:results.diagnosis.end, :);\n % contribution plots of train data\n if ~exist('.\\data', 'dir')\n mkdir data;\n end\n file_ = dir('.\\data\\*.mat');\n name_ = {file_(1:length(file_)).name}';\n if ismember('diagnosis.mat', name_)\n load('.\\data\\diagnosis.mat', 'tmp_')\n tmp__ = KernelPCAOption.saveCheckObj(obj);\n if isequal(tmp__, tmp_)\n load('.\\data\\diagnosis.mat', 'T2CpsTrain', 'SPECpsTrain')\n else\n [T2CpsTrain, SPECpsTrain] = obj.computeContribution(results, 'train');\n tmp_ = KernelPCAOption.saveCheckObj(obj);\n save('.\\data\\diagnosis.mat', 'T2CpsTrain', 'SPECpsTrain', 'tmp_')\n end\n else\n [T2CpsTrain, SPECpsTrain] = obj.computeContribution(results, 'train');\n tmp_ = KernelPCAOption.saveCheckObj(obj);\n save('.\\data\\diagnosis.mat', 'T2CpsTrain', 'SPECpsTrain', 'tmp_')\n end\n \n % contribution plots of test data\n [T2CpsTest, SPECpsTest] = obj.computeContribution(results, 'test');\n % normalize the contribution plots\n T2CpsTrainMu = mean(T2CpsTrain);\n T2CpsTrainStd = std(T2CpsTrain);\n \n try\n T2Cps = bsxfun(@rdivide, bsxfun(@minus, T2CpsTest, T2CpsTrainMu), T2CpsTrainStd);\n catch\n mu_array = repmat(T2CpsTrainMu, size(T2CpsTest,1), 1);\n st_array = repmat(T2CpsTrainStd, size(T2CpsTest,1), 1);\n T2Cps = (T2CpsTest-mu_array)./st_array;\n end\n SPECpsTrainMu = mean(SPECpsTrain);\n SPECpsTrainStd = std(SPECpsTrain);\n try\n SPECps = bsxfun(@rdivide, bsxfun(@minus, SPECpsTest, SPECpsTrainMu), SPECpsTrainStd);\n catch\n mu_array = repmat(SPECpsTrainMu, size(SPECpsTest,1), 1);\n st_array = repmat(SPECpsTrainStd, size(SPECpsTest,1), 1);\n SPECps = (SPECpsTest-mu_array)./st_array;\n end\n \n % store the results\n results.diagnosis.T2Cps = T2Cps;\n results.diagnosis.SPECps = SPECps;\n \n %\n T2Cps_ = mean(abs(T2Cps), 1);\n results.diagnosis.meanT2Cps = T2Cps_/sum(T2Cps_, 2);\n \n SPECps_ = mean(abs(SPECps), 1);\n results.diagnosis.meanSPECps = SPECps_/sum(SPECps_, 2);\n \n %\n [value, index] = sort(results.diagnosis.meanT2Cps, 'descend');\n results.diagnosis.faultVariabeT2.value = value;\n results.diagnosis.faultVariabeT2.index = index;\n\n [value, index] = sort(results.diagnosis.meanSPECps, 'descend');\n results.diagnosis.faultVariabeSPE.value = value;\n results.diagnosis.faultVariabeSPE.index = index;\n \n results.diagnosis.runningTime = toc(tStart); \n if strcmp(obj.display, 'on')\n KernelPCAOption.displayDiagnose(results)\n end\n end\n \n function [T2Cps, SPECps] = computeContribution(obj, result, type)\n \n % Compute the Contribution Plots (CPs)\n %\n % Reference\n % [1] Deng X, Tian X. A new fault isolation method based on unified\n % contribution plots[C]//Proceedings of the 30th Chinese Control\n % Conference. IEEE, 2011: 4280-4285.\n % -------------------------------------------------------------------\n % Thanks for the code provided by Rui.\n % --------------------------------------------------------------------\n \n data_ = obj.data;\n switch type\n case 'train'\n Kt = obj.temporary.K;\n Y = data_;\n case 'test'\n Kt = result.temporary.Kt;\n Y = result.diagnosis.data;\n end\n \n K = obj.temporary.K;\n M = size(data_, 1);\n [Mt, d] = size(Y);\n \n A_T2 = obj.coefficient(:, 1:obj.numComponents)*...\n diag(obj.lambda(1:obj.numComponents))^(-1)*...\n obj.coefficient(:, 1:obj.numComponents)';\n \n A_SPE = obj.coefficient(:, 1:obj.numComponents)*...\n obj.coefficient(:, 1:obj.numComponents)';\n newY = Y*obj.theta;\n \n % initialization\n Knew = zeros(Mt, M);\n Knew_d1 = zeros(1, M);\n Knew_d2 = zeros(Mt, M);\n T2Cps = zeros(Mt, d);\n SPECps = zeros(Mt, d);\n Knew_s = zeros(Mt, M);\n sigma = sqrt(1/2/obj.kernelFunc.gamma);\n \n % compute contribution of statistic\n for i = 1:Mt\n for j = 1:d\n for k = 1:M\n Knew(i, k) = Kt(i, k);\n Knew_d1(k) = Knew(i, k)*2*obj.theta*(newY(i, j)-data_(k, j))/(-sigma^2); % derivative\n Knew_d2(i, k) = -2*Knew_d1(k);\n end\n Knew_d1_s = Knew_d1-ones(1, M)*mean(Knew_d1);\n Knew_s(i, :) = Knew(i, :)-ones(1, M)*K/M-Knew(i, :)*ones(M) ...\n /M+ones(1, M)/M*K*ones(M)/M;\n % contribution of T2\n T2Cps(i, j) = Y(i, j)*(Knew_d1_s*A_T2*Knew_s(i, :)' ...\n +Knew_s(i, :)*A_T2*Knew_d1_s');\n % contribution of SPE\n SPECps(i, j)= Y(i, j)*mean(Knew_d2(i, :))-Y(i, j) ...\n *(Knew_d1_s*A_SPE*Knew_s(i, :)'+Knew_s(i, :)*A_SPE*Knew_d1_s');\n end\n end\n end\n \n function numSamples = get.numSamples(obj)\n numSamples= size(obj.data, 1);\n end\n \n function numFeatures = get.numFeatures(obj)\n numFeatures= size(obj.data, 2);\n end\n end\nend\n", "meta": {"author": "iqiukp", "repo": "KPCA-MATLAB", "sha": "16dd1567d7109f55a7c83d2fe3dcb558cf1a8fbf", "save_path": "github-repos/MATLAB/iqiukp-KPCA-MATLAB", "path": "github-repos/MATLAB/iqiukp-KPCA-MATLAB/KPCA-MATLAB-16dd1567d7109f55a7c83d2fe3dcb558cf1a8fbf/KernelPCA/KernelPCA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.49103268442550435}} {"text": "function [V,Q,QT,QF,QL] = voxel_surface(W,varargin)\n % VOXEL_SURFACE Compute the surface quad mesh of a 3d logical image.\n %\n % [V,Q,QT,QF,QL] = voxel_surface(W,varargin)\n %\n % Inputs:\n % W n by m by k binary matix\n % Optional:\n % 'Centers' followed by n*m*k by 3 list of cell centers\n % Outputs:\n % V (n+1)*(m+1)*(k+1) by 3 list of cell corner positions\n % Q #Q by 4 list of quads indexing V\n % QT n*m*k by 4 list of \"top\" quad faces indexing V\n % QF n*m*k by 4 list of \"front\" quad faces indexing V\n % QL n*m*k by 4 list of \"left\" quad faces indexing V\n %\n % Examples:\n % [V,Q] = voxel_surface(W);\n % [V,IM] = remove_unreferenced(V,Q);\n % Q = IM(Q);\n % trisurf(Q,V(:,1),V(:,2),V(:,3));\n % axis equal;\n %\n % See also: voxelize, voxel_grid\n\n BC = [];\n % default values\n % Map of parameter names to variable names\n params_to_variables = containers.Map( ...\n {'Centers'}, ...\n {'BC'});\n v = 1;\n while v <= numel(varargin)\n param_name = varargin{v};\n if isKey(params_to_variables,param_name)\n assert(v+1<=numel(varargin));\n v = v+1;\n % Trick: use feval on anonymous function to use assignin to this workspace\n feval(@()assignin('caller',params_to_variables(param_name),varargin{v}));\n else\n error('Unsupported parameter: %s',varargin{v});\n end\n v=v+1;\n end\n\n dim = ndims(W);\n\n switch dim\n case 2\n side = [size(W,2) size(W,1)];\n if isempty(BC)\n [X,Y] = meshgrid( ...\n linspace(0,1,side(1)), ...\n linspace(0,1,side(2)));\n % barycenters of cells\n BC = [X(:) Y(:)];\n end\n NV = min(BC);\n XV = max(BC);\n r = (XV-NV)./(side-1);\n [X,Y] = meshgrid( ...\n (NV(1)-0.5*r(1))+linspace(0,1,side(1)+1)*(XV(1)-NV(1)+r(1)), ...\n (NV(2)-0.5*r(2))+linspace(0,1,side(2)+1)*(XV(2)-NV(2)+r(2)));\n\n [Q,V] = surf2patch(X,Y,0*X);\n V = V(:,1:2);\n QT = [Q(:,[3 4]);Q(:,[1 2]);];\n QF = [Q(:,[2 3]); Q(:,[4 1])];\n if ~any(W(:))\n Q = [];\n else\n assert(false,'non trivial W not supported');\n end\n\n case 3\n side = [size(W,2) size(W,1) size(W,3)];\n if isempty(BC)\n [X,Y,Z] = meshgrid( ...\n linspace(0,1,side(1)), ...\n linspace(0,1,side(2)), ...\n linspace(0,1,side(3)));\n % barycenters of cells\n BC = [X(:) Y(:) Z(:)];\n end\n\n NV = min(BC);\n XV = max(BC);\n r = (XV-NV)./(side-1);\n [X,Y,Z] = meshgrid( ...\n (NV(1)-0.5*r(1))+linspace(0,1,side(1)+1)*(XV(1)-NV(1)+r(1)), ...\n (NV(2)-0.5*r(2))+linspace(0,1,side(2)+1)*(XV(2)-NV(2)+r(2)), ...\n (NV(3)-0.5*r(3))+linspace(0,1,side(3)+1)*(XV(3)-NV(3)+r(3)));\n % corners of cells\n V = [X(:) Y(:) Z(:)];\n\n [II,JJ,KK] = ind2sub([side(2) side(1) side(3)]+1,reshape(1:size(V,1),[side(2) side(1) side(3)]+1));\n\n QF = [ ...\n reshape(sub2ind([side(2) side(1) side(3)]+1,II(1:end-1,1:end-1,1:end),JJ(1:end-1,1:end-1,1:end),KK(1:end-1,1:end-1,1:end)),[],1) ...\n reshape(sub2ind([side(2) side(1) side(3)]+1,II( 2:end,1:end-1,1:end),JJ( 2:end,1:end-1,1:end),KK( 2:end,1:end-1,1:end)),[],1) ...\n reshape(sub2ind([side(2) side(1) side(3)]+1,II( 2:end, 2:end,1:end),JJ( 2:end, 2:end,1:end),KK( 2:end, 2:end,1:end)),[],1) ...\n reshape(sub2ind([side(2) side(1) side(3)]+1,II(1:end-1, 2:end,1:end),JJ(1:end-1, 2:end,1:end),KK(1:end-1, 2:end,1:end)),[],1) ...\n ];\n\n QL = fliplr([ ...\n reshape(sub2ind([side(2) side(1) side(3)]+1,II(1:end-1,1:end,1:end-1),JJ(1:end-1,1:end,1:end-1),KK(1:end-1,1:end,1:end-1)),[],1) ...\n reshape(sub2ind([side(2) side(1) side(3)]+1,II( 2:end,1:end,1:end-1),JJ( 2:end,1:end,1:end-1),KK( 2:end,1:end,1:end-1)),[],1) ...\n reshape(sub2ind([side(2) side(1) side(3)]+1,II( 2:end,1:end, 2:end),JJ( 2:end,1:end, 2:end),KK( 2:end,1:end, 2:end)),[],1) ...\n reshape(sub2ind([side(2) side(1) side(3)]+1,II(1:end-1,1:end, 2:end),JJ(1:end-1,1:end, 2:end),KK(1:end-1,1:end, 2:end)),[],1) ...\n ]);\n\n QT = [ ...\n reshape(sub2ind([side(2) side(1) side(3)]+1,II(1:end,1:end-1,1:end-1),JJ(1:end,1:end-1,1:end-1),KK(1:end,1:end-1,1:end-1)),[],1) ...\n reshape(sub2ind([side(2) side(1) side(3)]+1,II(1:end, 2:end,1:end-1),JJ(1:end, 2:end,1:end-1),KK(1:end, 2:end,1:end-1)),[],1) ...\n reshape(sub2ind([side(2) side(1) side(3)]+1,II(1:end, 2:end, 2:end),JJ(1:end, 2:end, 2:end),KK(1:end, 2:end, 2:end)),[],1) ...\n reshape(sub2ind([side(2) side(1) side(3)]+1,II(1:end,1:end-1, 2:end),JJ(1:end,1:end-1, 2:end),KK(1:end,1:end-1, 2:end)),[],1) ...\n ];\n\n if ~any(W(:))\n Q = [];\n else\n Wp = padarray(W,[1 1 1],0);\n Dy = diff(Wp,1,1);\n Dx = diff(Wp,1,2);\n Dz = diff(Wp,1,3);\n Q = [ ...\n QF( Dz(2:end-1,2:end-1,1:end)>0.5,:); ...\n QL( Dx(2:end-1,1:end,2:end-1)>0.5,:); ...\n QT( Dy(1:end,2:end-1,2:end-1)>0.5,:); ...\n fliplr(QF( Dz(2:end-1,2:end-1,1:end)<-0.5,:)); ...\n fliplr(QL( Dx(2:end-1,1:end,2:end-1)<-0.5,:)); ...\n fliplr(QT( Dy(1:end,2:end-1,2:end-1)<-0.5,:)); ...\n ];\n end\n end\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/voxel_surface.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.49103268442550424}} {"text": "% [ wave, f, t, coh, phases, raw, coi, scale, period, scalef ] = getWavelet( x, Fs, fMin, fMax, nbins, graphics )\n%\n% x: \n% vector - wavelet analysis is applied\n% multi-column matrix - wavelet analysis is applied to each column\n% separately\n%\n% two-column matrix - treated as two time series and the csd, coherence is\n% computed\n% 3D array, 3rd dimension is 2 - treated as multiple samples from two time\n% series, coherence etc is computed\n%\n% Fs - sampling frequency\n% fMin, fMax, nbins - parameters for spectral analysis - min/max freqnecy\n% (Hz) and number of frequency bins (Morlet is always used so this is\n% frequency per se and not just scale)\n% graphcis - flag 0/1\n%\n% does: compute the CWT of each segment, then if two signals also compute\n% the cross-spectrum/coherence/phase lag. then average over all segments\n% and plot\n%\n% output:\n% wave - the PSD/CSD\n% f, t - vectors\n% coh - only for 2-channel input\n% phases - either for the 1-channel or the phase-difference (from the CSD,\n% not the smoothed estimate)\n% \n%\n% call: wavelet, smoothwavelet, phaseplot, myjet, colormaps\n\n% 08-oct-12 ES\n\n% revisions\n% 15-nov-12 (1) added single-channel phase; cross-spectrum, coherence, and\n% phase difference estimates\n% (2) local plotting of spectrogram + phasogram (single-channel)\n% or coherogram + phase differences (two-channel)\n\n% to do: organize input / output handling better, plotting etc\n% also compute mean spectra/coherence/phase \n% also - external coherence computation for multiple segments (i.e. average\n% across trials)\n\n%function [ wave, f, t, phases, coi, scale, raw ] = getWavelet( x, Fs, fMin, fMax, nbins )\nfunction [ wave, f, t, coh, phases, raw, coi, scale, period, scalef ] = getWavelet( x, Fs, fMin, fMax, nbins, scaling, graphics )\n\nif isa( x, 'int16' ), x = single( x ); end\n\nif nargin < 6 || isempty( scaling )\n scaling = 'var';\nend\nif nargin < 7 || isempty( graphics )\n if nargout == 0\n graphics = 1;\n else\n graphics = 0;\n end\nend\n\ndt = 1 / Fs; \ns0 = 1 / fMax;\ntMax = 1 / fMin;\ndj = log2( tMax/s0 ) / nbins;\n\nmother = 'MORLET';\n%k0 = 6; \n%fourier_factor = (4*pi)/(k0 + sqrt(2 + k0^2)); % scale->frequency\n\nwave = [];\nf = [];\nt = [];\ncoh = [];\nphases = [];\nraw = [];\ncoi = [];\nscale = [];\nperiod = [];\nscalef = [];\n\ner = 0;\nsx = size( x );\nswitch ndims( x )\n case 2\n switch min( sx )\n case 1\n nsignals = 1;\n nsegments = 1;\n nsamples = max( sx );\n x = x( : );\n case 2\n nsignals = 2;\n nsegments = 1;\n if size( x, 1 ) == 2\n x = x';\n end\n y = x( :, 2 );\n x = x( :, 1 );\n nsamples = max( sx );\n otherwise\n nsignals = 1;\n nsegments = sx( 2 );\n nsamples = sx( 1 );\n end\n case 3\n if size( x, 3 ) ~= 2\n er = 1;\n else\n nsignals = 2;\n nsegments = sx( 2 );\n nsamples = sx( 1 );\n y = x( :, :, 2 );\n x = x( :, :, 1 );\n end\n otherwise\n er = 1;\nend\nif er \n error( 'not supported' )\nend\n\n% parameters\nif isa( scaling, 'char' ) && strcmp( scaling, 'var' )\n switch nsignals\n case 1\n scalef = var( x ); % can be a different number for each segment\n case 2\n scalef = std( x ) .* std( y );\n end\nelseif isa( scaling, 'double' ) && size( scaling, 1 ) == ( nbins + 1 )\n scalef = scaling; % can be a different number for each frequency\n scaling = 'z';\nelse\n scalef = ones( 1, nsegments );\n scaling = 'none';\nend\nflipidx = ( nbins + 1 ) : -1 : 1;\nt = ( 1 : nsamples )' / Fs;\n\n% actually comptue\n%[wave,period,scale,coi] = wavelet(Y,dt,pad,dj,s0,J1,mother,param);\nswitch nsignals\n case 1\n xw = zeros( nbins + 1, nsamples, nsegments );\n for i = 1 : nsegments\n [ xw( :, :, i ), period, scale, coi ] = wavelet( x( :, i ), dt, 1, dj, s0, nbins, mother );\n end\n xw = xw( flipidx, :, : ); % freq, time, segments\n wave = abs( xw ) .^ 2;\n phases = angle( xw );\n raw = xw;\n case 2\n xw = zeros( nbins + 1, nsamples, nsegments );\n yw = xw;\n coh = xw;\n for i = 1 : nsegments\n [ xw( :, :, i ), period, scale, coi ] = wavelet( x( :, i ), dt, 1, dj, s0, nbins, mother );\n [ yw( :, :, i ) ] = wavelet( y( :, i ), dt, 1, dj, s0, nbins, mother );\n % coherence (copied as is from wtc.m):\n sinv=1./(scale');\n X = xw( :, :, i );\n Y = yw( :, :, i );\n wxy = X .* conj( Y ); % complex, single trial\n sX=smoothwavelet(sinv(:,ones(1,nsamples)).*(abs(X).^2),dt,period,dj,scale);\n sY=smoothwavelet(sinv(:,ones(1,nsamples)).*(abs(Y).^2),dt,period,dj,scale);\n sWxy=smoothwavelet(sinv(:,ones(1,nsamples)).*wxy,dt,period,dj,scale);\n Rsq=abs(sWxy).^2./(sX.*sY);\n %phases( :, :, i ) = angle( sWxy );\n coh( :, :, i ) = Rsq( flipidx, : );\n %coh = abs( yo( :, 1, 2 ) .^ 2 ) ./ ( yo( :, 1, 1 ) .* yo( :, 2, 2 ) );\n \n% subplot( 4, 2, 1 ), [ c h ] = contourf( t, f, log2( abs( flipud( X ) ).^2 ), 100 ); set( h, 'linestyle', 'none' );\n% subplot( 4, 2, 3 ), [ c h ] = contourf( t, f, log2( abs( flipud( Y ) ).^2 ), 100 ); set( h, 'linestyle', 'none' );\n% subplot( 4, 2, 5 ), [ c h ] = contourf( t, f, log2( abs( flipud( wxy ) ).^2 ), 100 ); set( h, 'linestyle', 'none' );\n% subplot( 4, 2, 2 ), [ c h ] = contourf( t, f, log2( flipud( sX ) ), 100 ); set( h, 'linestyle', 'none' );\n% subplot( 4, 2, 4 ), [ c h ] = contourf( t, f, log2( flipud( sY ) ), 100 ); set( h, 'linestyle', 'none' );\n% subplot( 4, 2, 6 ), [ c h ] = contourf( t, f, log2( flipud( sWxy ) ), 100 ); set( h, 'linestyle', 'none' );\n% subplot( 4, 2, 7 ), [ c h ] = contourf( t, f, flipud( abs(wxy).^2./(X.*Y) ), 100 ); set( h, 'linestyle', 'none' );\n% subplot( 4, 2, 8 ), [ c h ] = contourf( t, f, flipud( abs(sWxy).^2./(sX.*sY) ), 100 ); set( h, 'linestyle', 'none' );\n% \n% x0 = (abs(X).^2);\n% fmat = sinv(:,ones(1,nsamples));\n% sX=smoothwavelet(fmat.*x0,dt,period,dj,scale);\n \n end\n \n % individual channels\n xw = xw( flipidx, :, : );\n yw = yw( flipidx, :, : );\n raw( :, :, :, 1 ) = xw;\n raw( :, :, :, 2 ) = yw;\n %xwave = abs( xw ) .^ 2;\n %ywave = abs( yw ) .^ 2;\n %xphases = angle( xw );\n %yphases = angle( yw );\n % cross spectrum\n xyw = xw .* conj( yw );\n phases = angle( xyw ); % from the CSD\n wave = abs( xyw );\n % for multiple trials, one can also compute the trial-averaged coherence and phase lag by:\n %cohTA = mean( abs( xyw ) .^ 2, 3 ) ./ ( mean( abs( xw ) .^ 2, 3 ) .* mean( abs( yw ) .^ 2, 3 ) ); \n %phasesTA = mod( atan2( mean( sin( phases ), 3 ), mean( cos( phases ), 3 ) ), 2 * pi );\n\nend\n\n\n\n%xw = flipud( xw );\nf = 1 ./ period( flipidx );\ncoi = 1 ./ coi; % minimum freq to consider at each time point\n%f = fliplr( 1 ./ period ); \n%f = fliplr( 1 ./ scale ); \n%t = ( 1 : length( x ) )' / Fs;\n\nif graphics\n \n % here the scaling is by the signal variance\n \n figure\n \n if nsignals == 1\n nplots = 1; % PSD\n else\n nplots = 4; % [ PSD1 CSD; COH PSD2 ]\n end\n \n for np = 1 : nplots\n end\n \n % scale\n %scalef = mean( scalef );\n %scaleres = 0.25;\n scaleres = 10;\n scalename = '{\\sigma}^2';\n pow = zeros( size( wave ) );\n switch scaling\n case { 'var', 'none' }\n for i = 1 : nsegments\n pow( :, :, i ) = log2( abs( wave( :, :, i ) / scalef( i ) ) );\n end\n case 'z'\n \n for i = 1 : length( f )\n pow( i, :, : ) = ( wave( i, :, : ) - scalef( i, 1 ) ) / scalef( i, 2 );\n end\n end\n pow = mean( pow, 3 ); % average over segments (1 signal)\n levels = min( pow(:) ) : scaleres : max( pow( : ) );\n mphases = mod( atan2( mean( sin( phases ), 3 ), mean( cos( phases ), 3 ) ), 2 * pi );\n %mp = []; for i = 1 : size( phases, 1 ), mp( :, i ) = circ_mean( squeeze( phases( i, :, : ) )' ); end\n \n % plot\n h1 = subplot( 1, 1, 1 ); %subplot( 2, 1, 1 );\n %[ c h ] = contourf( t, f, pow, levels );\n [ c h ] = contourf( t, f, pow, 100 );\n set( h, 'linestyle','none')\n %xlabel( 'Time (sec)' )\n ylabel( 'Frequency (Hz)' )\n title( sprintf( '%d segments, %d signals', nsegments, nsignals ) )\n\n % center color limits around log2(1)=0\n if strcmp( scaling, 'var' )\n clim=get(gca,'clim');\n clim=[-1 1]*max(clim(2),3);\n set(gca,'clim',clim)\n end\n \n % add the cone of influence\n line( t, coi, 'color', [ 0 0 0 ] );\n hold on\n tt=[t([1 1])-dt*.5;t;t([end end])+dt*.5];\n hcoi=fill(tt,1./[period([end 1]) 1./coi period([1 end])],'w');\n %hcoi=fill(tt,[f([end 1]) coi f([1 end])],'w');\n set(hcoi,'alphadatamapping','direct','facealpha',.5)\n hold off\n \n set( h1, 'box', 'off', 'tickdir', 'out' )\n \n % add phase arrows (copied as is from xwt.m)\n if nsignals == 2\n Args.ArrowDensity = [30 30];\n Args.ArrowSize = 1;\n Args.ArrowHeadSize = 1;\n ad=mean(Args.ArrowDensity);\n Args.ArrowSize=Args.ArrowSize*30*.03/ad;\n Args.ArrowHeadSize=Args.ArrowHeadSize*Args.ArrowSize*220;\n phs_dt=round(length(t)/Args.ArrowDensity(1));\n tidx=max(floor(phs_dt/2),1):phs_dt:length(t);\n phs_dp=round(length(period)/Args.ArrowDensity(2));\n pidx=fliplr( max(floor(phs_dp/2),1):phs_dp:length(period) );\n phaseplot(t(tidx),f(pidx),2*pi-mphases(pidx,tidx),Args.ArrowSize,Args.ArrowHeadSize);\n end\n \n % add colorbar\n h = colorbar;\n subplot( h )\n barylbls=rats(2.^(get(h,'ytick')'));\n %barylbls([1 end],:)=' ';\n barylbls(:,all(barylbls==' ',1))=[];\n set(h,'yticklabel',barylbls);\n title( scalename )\n set( h, 'box', 'off', 'tickdir', 'out' )\n\n colormap( h1, myjet ) \n\n if 1\n figure, %h2 = subplot( 2, 1, 2 );\n switch nsignals\n case 1\n % plot phases separately\n [ c h ] = contourf( t, f, mphases, 10 );\n set( h, 'linestyle','none')\n xlabel( 'Time (sec)' )\n ylabel( 'Frequency (Hz)' )\n %colormap( h2, colormaps( myjet ) )\n set( gca, 'clim', [ 0 2*pi ] )\n\n \n % add the cone of influence\n lh = line( t, coi, 'color', [ 0 0 0 ] );\n hold on\n tt=[t([1 1])-dt*.5;t;t([end end])+dt*.5];\n hcoi=fill(tt,1./[period([end 1]) 1./coi period([1 end])],'w');\n set(hcoi,'alphadatamapping','direct','facealpha',.5)\n hold off\n \n h = colorbar;\n subplot( h )\n title( 'Phase (rad)' )\n set( h, 'box', 'off', 'tickdir', 'out' )\n colormap( colormaps( myjet ) )\n\n case 2\n % also plot coherence (without phase arrows)\n % plot\n %h2 = subplot( 2, 1, 2 );\n [ c h ] = contourf( t, f, mean( coh, 3 ), 100 );\n %[ c h ] = contourf( t, f, cohTA, 100 );\n set( h, 'linestyle','none')\n xlabel( 'Time (sec)' )\n ylabel( 'Frequency (Hz)' )\n title( sprintf( '%d segments, %d signals', nsegments, nsignals ) )\n set( gca, 'clim', [ 0 1 ] )\n set( h1, 'box', 'off', 'tickdir', 'out' ) \n \n % add the cone of influence\n lh = line( t, coi, 'color', [ 0 0 0 ] );\n hold on\n tt=[t([1 1])-dt*.5;t;t([end end])+dt*.5];\n hcoi=fill(tt,1./[period([end 1]) 1./coi period([1 end])],'w');\n set(hcoi,'alphadatamapping','direct','facealpha',.5)\n hold off\n \n % add phase plots (only for high coherence values inside the coi)\n aaa=2*pi-mphases;\n aaa(mean( coh, 3 )<.5)=NaN; \n aaa( bsxfun( @lt, f' * ones( 1, nsamples ), coi ) ) = NaN;\n phaseplot(t(tidx),f(pidx),aaa(pidx,tidx),Args.ArrowSize,Args.ArrowHeadSize);\n \n % add colorbar\n h = colorbar;\n subplot( h )\n title( 'Coherence' )\n set( h, 'box', 'off', 'tickdir', 'out' )\n colormap( myjet )\n end\n \n end\n \n %figure, xwt( [t x( :, 1 )],[t y( :, 1 ) ], 'Pad', 1, 'Dj', dj, 'S0', s0, 'J1', nbins );\n %figure, [ Rsq,aWxy ] = waveletCoherence( [t x( :, 1 )],[t y( :, 1 ) ], 'Pad', 1, 'Dj', dj, 'S0', s0, 'J1', nbins, 'mcc', 0, 'MakeFigure', 1 ); title( 'COH' )\n %figure, [ Wxy ] = xwt( [t x( :, i )],[t y( :, i ) ], 'Pad', 1, 'Dj', log2( fMax/fMin ) / nbins, 'S0', 1/fMax, 'MaxScale', 1/fMin, 'MakeFigure', 1 ); title( 'CSD' )\n\nend\n\n%t = [ 0 : 1 : length( x ) - 1 ]' / Fs;\n%[ rawwave, period, scale, coi sig95 ] = wt( [ t x ], 'Pad', 1, 'dj', dj, 's0', s0, 'j1', nbins, 'mother', mother, 'MakeFigure', 1 ); \n\nreturn\n\n% notes:\n% (1) it is clear what the frequencies are (nbins, log-spaced between fMin and\n% fMax), but the amp is unclear to me DONE\n% (2) should use a similar approach to filter the signal at various\n% frequency ranges and calculate the spiking rate frequency/phase maps\n\n% to do:\n% (1) adjust the scale properly DONE\n% (2) get the multi-segment version working; basically use the same call to\n% wavelet.m, but concatenate the segments (with intervening portions), then\n% call once with the first segment to get the proper coi. DONE\n% (3) get the plotting of phases working on this diagram DONE\n% (4) 2-signal version: compute the coherence as in Torrence and Compo\n% (smoothing in time- and frequency-domains each of the spectra and the\n% cross-spectrum) and add the phase DONE\n\n% OK now (15nov12), but not super elegant:\n% should partition into two function - getWavelet and plotWavelet,\n% the first should only compute, the second should plot with options:\n% single signal: just power,power + phase plots.\n% e.g. [ 1 1 ] would make two plots, whereas [ 1 0 ] just on\n% two signals: power/phase for each signal; csd/coh/phase for the joint\n% i.e. if only power, plots 2x2 - [ s1 s12_csd; s12_coh; s2 ]\n% if also phase, cuts each plot into two and adds the phase\n\ngetWavelet( [ x0( :, 1 ) y0( :, 1 ) ], Fs, Fmin, Fmax, nBins );\ngetWavelet( [ x0( :, 1 ) ], Fs, Fmin, Fmax, nBins );\ngetWavelet( [ x0( :, 1 : 10 ) ], Fs, Fmin, Fmax, nBins );\nxy = [];\nxy( :, :, 1 ) = x0( :, 1 : 10 );\nxy( :, :, 2 ) = y0( :, 1 : 10 );\ngetWavelet( xy, Fs, Fmin, Fmax, nBins );\n\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/analysis/spikes/cellTypeClassification/BrendonClassificationFromStark2013/getWavelet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49095499342114274}} {"text": "function soln = rungeKutta(problem)\n% soln = rungeKutta(problem)\n%\n% This function transcribes a trajectory optimization problem using the\n% multiple shooting, with 4th-order Runge Kutta integration\n%\n% See Bett's book for details on the method\n%\n% For details on the input and output, see the help file for optimTraj.m\n%\n% Method specific parameters:\n%\n% problem.options.method = 'rungeKutta'\n% problem.options.rungeKutta = struct with method parameters:\n% .nSegment = number of trajectory segments\n% .nSubStep = number of sub-steps to use in each segment\n% .adaptiveDerivativeCheck = 'off' by default. Set to 'on' to enable\n% numerical checks on the analytic gradients, computed using the\n% derivest package, rather than fmincon's internal checks.\n% Derivest is slower, but more accurate than fmincon. Derivest\n% can be downloaded from the Mathworks File Exchange, file id of\n% 13490 - Adaptive Robust Numerical Differentation, John D-Errico\n%\n%\n% NOTES:\n%\n% Code for computing analyic gradients of the Runge Kutta method was\n% contributed by Will Wehner.\n%\n% If analytic gradients are used, then the sparsity pattern is returned\n% in the struct: soln.info.sparsityPattern. View it using spy().\n%\n%\n\n%To make code more readable\nG = problem.guess;\nB = problem.bounds;\nF = problem.func;\nOpt = problem.options;\n\n% Figure out grid size:\nnSegment = Opt.rungeKutta.nSegment;\nnSubStep = Opt.rungeKutta.nSubStep;\nnGridControl = 2*nSegment*nSubStep + 1;\nnGridState = nSegment + 1;\n\n% Print out some solver info if desired:\nif Opt.verbose > 0\n fprintf(' -> Transcription via 4th-order Runge-Kutta method \\n');\n fprintf(' nSegments = %d \\n', nSegment);\n fprintf(' nSubSteps = %d \\n', nSubStep);\nend\n\n% Interpolate the guess at the transcription grid points for initial guess:\nguess.tSpan = G.time([1,end]);\nguess.tState = linspace(guess.tSpan(1), guess.tSpan(2), nGridState);\nguess.tControl = linspace(guess.tSpan(1), guess.tSpan(2), nGridControl);\nguess.state = interp1(G.time', G.state', guess.tState')';\nguess.control = interp1(G.time', G.control', guess.tControl')';\n[zGuess, pack] = packDecVar(guess.tSpan, guess.state, guess.control);\n\n% Unpack all bounds:\ntLow = [B.initialTime.low, B.finalTime.low];\nxLow = [B.initialState.low, B.state.low*ones(1,nGridState-2), B.finalState.low];\nuLow = B.control.low*ones(1,nGridControl);\nzLow = packDecVar(tLow,xLow,uLow);\n\ntUpp = [B.initialTime.upp, B.finalTime.upp];\nxUpp = [B.initialState.upp, B.state.upp*ones(1,nGridState-2), B.finalState.upp];\nuUpp = B.control.upp*ones(1,nGridControl);\nzUpp = packDecVar(tUpp,xUpp,uUpp);\n\n%%%% Set up problem for fmincon:\nflagGradObj = strcmp(Opt.nlpOpt.GradObj,'on');\nflagGradCst = strcmp(Opt.nlpOpt.GradConstr,'on');\nif flagGradObj || flagGradCst\n gradInfo = grad_computeInfo(pack);\nend\nif flagGradObj\n P.objective = @(z)( ...\n myObjGrad(z, pack, F.dynamics, F.pathObj, F.bndObj, gradInfo) ); %Analytic gradients\n [~, objGradInit] = P.objective(zGuess);\n sparsityPattern.objective = (objGradInit~=0)';\nelse\n P.objective = @(z)( ...\n myObjective(z, pack, F.dynamics, F.pathObj, F.bndObj) ); %Numerical gradients\nend\n\nif flagGradCst\n P.nonlcon = @(z)( ...\n myCstGrad(z, pack, F.dynamics, F.pathObj, F.pathCst, F.bndCst, gradInfo) ); %Analytic gradients\n [~,~,cstIneqInit,cstEqInit] = P.nonlcon(zGuess);\n sparsityPattern.equalityConstraint = (cstEqInit~=0)';\n sparsityPattern.inequalityConstraint = (cstIneqInit~=0)';\nelse\n P.nonlcon = @(z)( ...\n myConstraint(z, pack, F.dynamics, F.pathObj, F.pathCst, F.bndCst) ); %Numerical gradients\nend\n\n\n% Check analytic gradients with DERIVEST package\nif strcmp(Opt.rungeKutta.adaptiveDerivativeCheck,'on')\n if exist('jacobianest','file')\n runGradientCheck(zGuess, pack,F.dynamics, F.pathObj, F.bndObj, F.pathCst, F.bndCst, gradInfo);\n Opt.nlpOpt.DerivativeCheck = []; %Disable built-in derivative check\n else\n Opt.rungeKutta.adaptiveDerivativeCheck = 'cannot find jacobianest.m';\n disp('Warning: the derivest package is not on search path.');\n disp(' --> Using fmincon''s built-in derivative checks.');\n end\nend\n\n% Build the standard fmincon problem struct\nP.x0 = zGuess;\nP.lb = zLow;\nP.ub = zUpp;\nP.Aineq = []; P.bineq = [];\nP.Aeq = []; P.beq = [];\nP.solver = 'fmincon';\nP.options = Opt.nlpOpt;\n\n%%%% Call fmincon to solve the non-linear program (NLP)\ntic;\n[zSoln, objVal,exitFlag,output] = fmincon(P);\n[tSpan,~,uSoln] = unPackDecVar(zSoln,pack);\nnlpTime = toc;\n\n%%%% Store the results:\n[tGrid,xGrid,uGrid] = simulateSystem(zSoln, pack, F.dynamics, F.pathObj);\nsoln.grid.time = tGrid;\nsoln.grid.state = xGrid;\nsoln.grid.control = uGrid;\n\n% Quadratic interpolation over each sub-step for the control:\ntSoln = linspace(tSpan(1),tSpan(2),nGridControl);\nsoln.interp.control = @(t)( interp1(tSoln', uSoln', t','pchip')' );\n\n% Cubic spline representation of the state over each substep:\ndxGrid = F.dynamics(tGrid,xGrid,uGrid);\nxSpline = pwch(tGrid, xGrid, dxGrid);\nsoln.interp.state = @(t)( ppval(xSpline,t) );\n\n% General information about the optimization run\nsoln.info = output;\nsoln.info.nlpTime = nlpTime;\nsoln.info.exitFlag = exitFlag;\nsoln.info.objVal = objVal;\nif flagGradCst || flagGradObj\n soln.info.sparsityPattern = sparsityPattern;\nend\n\nsoln.problem = problem; % Return the fully detailed problem struct\n\nend\n\n\n%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%\n%%%% SUB FUNCTIONS %%%%\n%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%\n\n\n\n\nfunction [decVars,pack] = packDecVar(tSpan,state,control)\n%\n% This function collapses the time (t), state (x)\n% and control (u) matricies into a single vector\n%\n% INPUTS:\n% tSpan = [1, 2] = time bounds\n% state = [nState, nGridState] = state vector at each grid point\n% control = [nControl, nGridControl] = control vector at each grid point\n%\n% OUTPUTS:\n% decVars = column vector of 2 + nState*nGridState + nControl*nGridControl) decision variables\n% pack = details about how to convert z back into t,x, and u\n% .nState\n% .nGridState\n% .nControl\n% .nGridControl\n%\n% NOTES:\n% nGridControl = 2*nSegment*nSubStep + 1;\n% nGridState = nSegment + 1;\n%\n\n[nState, nGridState] = size(state);\n[nControl, nGridControl] = size(control);\n\nnSegment = nGridState - 1;\nnSubStep = (nGridControl - 1)/(2*nSegment);\n\nxCol = reshape(state, nState*nGridState, 1);\nuCol = reshape(control, nControl*nGridControl, 1);\n\nindz = 1:numel(control)+numel(state)+numel(tSpan);\n\n% index of time in decVar\nindt = 1:2;\n\n% the z index of the first element of each state over time\nindtemp = 2 + (1 : (nState + (2*nSubStep)*nControl ) : numel(control)+numel(state));\n\n% remaining state elements at each time\nindx = repmat(indtemp,nState,1) + cumsum(ones(nState,nGridState),1) - 1;\n\n% index of control in decVar\nindu = indz;\nindu([indt(:);indx(:)])=[];\nindu = reshape(indu,nControl,nGridControl);\n\n% pack up decVars\ndecVars = zeros(numel(indz),1);\ndecVars(indt(:),1) = tSpan;\ndecVars(indx(:),1) = xCol;\ndecVars(indu(:),1) = uCol;\n\n% pack structure\npack.nState = nState;\npack.nGridState = nGridState;\npack.nControl = nControl;\npack.nGridControl = nGridControl;\npack.nSegment = nGridState - 1;\npack.nSubStep = (nGridControl-1)/(2*pack.nSegment);\npack.indt = indt;\npack.indx = indx;\npack.indu = indu;\n\nend\n\n%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%\n\nfunction [tSpan, state, control] = unPackDecVar(decVars,pack)\n%\n% This function unpacks the decision variables for\n% trajectory optimization into the time (t),\n% state (x), and control (u) matricies\n%\n% INPUTS:\n% decVars = column vector of 2 + nState*nGridState + nControl*nGridControl) decision variables\n% pack = details about how to convert z back into t,x, and u\n% .nState\n% .nGridState\n% .nControl\n% .nGridControl\n%\n% OUTPUTS:\n% tSpan = [1, 2] = time bounds\n% state = [nState, nGridState] = state vector at each grid point\n% control = [nControl, nGridControl] = control vector at each grid point\n%\n\ntSpan = [decVars(1),decVars(2)];\n\n% state = reshape(decVars((2+1):(2+nx)), pack.nState, pack.nGridState);\n% control = reshape(decVars((2+nx+1):(2+nx+nu)), pack.nControl, pack.nGridControl);\n\nstate = decVars(pack.indx);\ncontrol = decVars(pack.indu);\n\n% make sure x and u are returned as vectors, [nState,nTime] and\n% [nControl,nTime]\nstate = reshape(state,pack.nState,pack.nGridState);\ncontrol = reshape(control,pack.nControl,pack.nGridControl);\nend\n\n%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%\n\nfunction cost = myObjective(decVars, pack,dynamics, pathObj, bndObj)\n%\n% This function unpacks the decision variables, sends them to the\n% user-defined objective functions, and then returns the final cost\n%\n% INPUTS:\n% decVars = column vector of decision variables\n% pack = details about how to convert decision variables into t,x, and u\n% dynamics = user-defined dynamics function handle\n% pathObj = user-defined path-objective function\n% bndObj = user-defined boundary objective function\n%\n% OUTPUTS:\n% cost = scalar cost for this set of decision variables\n%\n%\n\n% All of the real work happens inside this function:\n[t,x,~,~,pathCost] = simulateSystem(decVars, pack, dynamics, pathObj);\n\n% Compute the cost at the boundaries of the trajectory\nif isempty(bndObj)\n bndCost = 0;\nelse\n t0 = t(1);\n tF = t(end);\n x0 = x(:,1);\n xF = x(:,end);\n bndCost = bndObj(t0,x0,tF,xF);\nend\n\ncost = bndCost + pathCost;\n\nend\n\n%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%\n\nfunction [c, ceq] = myConstraint(decVars, pack, dynamics, pathObj, pathCst, bndCst)\n%\n% This function unpacks the decision variables, computes the defects along\n% the trajectory, and then evaluates the user-defined constraint functions.\n%\n% INPUTS:\n% decVars = column vector of decision variables\n% pack = details about how to convert decision variables into t,x, and u\n% dynamics = user-defined dynamics function handle\n% pathObj = user-defined path-objective function\n% pathCst = user-defined path-constraint function\n% bndCst = user-defined boundary constraint function\n%\n% OUTPUTS:\n% c = non-linear inequality constraint\n% ceq = non-linear equatlity cosntraint\n%\n% NOTE:\n% - path constraints are satisfied at the start and end of each sub-step\n%\n\n\n[t,x,u,defects] = simulateSystem(decVars, pack, dynamics, pathObj);\n\n%%%% Call user-defined constraints and pack up:\n[c, ceq] = collectConstraints(t,x,u,...\n defects,...\n pathCst, bndCst);\n\nend\n\n\n%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%\n\n\nfunction [t,x,u,defects,pathCost] = simulateSystem(decVars, pack, dynFun, pathObj)\n%\n% This function does the real work of the transcription method. It\n% simulates the system forward in time across each segment of the\n% trajectory, computes the integral of the cost function, and then matches\n% up the defects between the end of each segment and the start of the next.\n%\n% INPUTS:\n% decVars = column vector of decision variables\n% pack = details about how to convert decision variables into t,x, and u\n% dynamics = user-defined dynamics function handle\n% pathObj = user-defined path-objective function\n%\n% OUTPUTS:\n% t = [1 x nGrid] = time vector for the edges of the sub-step grid\n% x = [nState x nGrid] = state vector\n% u = [nControl x nGrid] = control vector\n% defects = [nState x nSegment] = defect matrix\n% pathCost = scalar cost for the path integral\n%\n% NOTES:\n% - nGrid = nSegment*nSubStep+1\n% - This function is usually called twice for each combination of\n% decision variables: once by the objective function and once by the\n% constraint function. To keep the code fast I cache the old values and\n% only recompute when the inputs change.\n%\n\n\n%%%% CODE OPTIMIZATION %%%%\n%\n% Prevents the same exact code from being called twice by caching the\n% solution and reusing it when appropriate.\n%\nglobal RUNGE_KUTTA_t RUNGE_KUTTA_x RUNGE_KUTTA_u\nglobal RUNGE_KUTTA_defects RUNGE_KUTTA_pathCost\nglobal RUNGE_KUTTA_decVars\n%\nusePreviousValues = false;\nif ~isempty(RUNGE_KUTTA_decVars)\n if length(RUNGE_KUTTA_decVars) == length(decVars)\n if ~any(RUNGE_KUTTA_decVars ~= decVars)\n usePreviousValues = true;\n end\n end\nend\n%\nif usePreviousValues\n t = RUNGE_KUTTA_t;\n x = RUNGE_KUTTA_x;\n u = RUNGE_KUTTA_u;\n defects = RUNGE_KUTTA_defects;\n pathCost = RUNGE_KUTTA_pathCost;\nelse\n %\n %\n %%%% END CODE OPTIMIZATION %%%%\n \n \n [tSpan, state, control] = unPackDecVar(decVars,pack);\n \n nState = pack.nState;\n nSegment = pack.nSegment;\n nSubStep = pack.nSubStep;\n \n % NOTES:\n % The following bit of code is a bit confusing, mostly due to the\n % need for vectorization to make things run at a reasonable speed in\n % Matlab. Part of the confusion comes because the decision variables\n % include the state at the beginning of each segment, but the control\n % at the beginning and middle of each substep - thus there are more\n % control grid-points than state grid points. The calculations are\n % vectorized over segments, but not sub-steps, since the result of\n % one sub-step is required for the next.\n \n % time, state, and control at the ends of each substep\n nTime = 1+nSegment*nSubStep;\n t = linspace(tSpan(1), tSpan(2), nTime);\n x = zeros(nState, nTime);\n u = control(:,1:2:end); % Control a the endpoints of each segment\n uMid = control(:,2:2:end); %Control at the mid-points of each segment\n c = zeros(1, nTime-1); %Integral cost for each segment\n dt = (t(end)-t(1))/(nTime-1);\n \n idx = 1:nSubStep:(nTime-1); %Indicies for the start of each segment\n x(:,[idx,end]) = state; %Fill in the states that we already know\n \n for iSubStep = 1:nSubStep\n % March forward Runge-Kutta step\n \n t0 = t(idx);\n x0 = x(:,idx);\n \n k0 = combinedDynamics(t0, x0, u(:,idx), dynFun,pathObj);\n k1 = combinedDynamics(t0+0.5*dt, x0 + 0.5*dt*k0(1:nState,:), uMid(:,idx), dynFun,pathObj);\n k2 = combinedDynamics(t0+0.5*dt, x0 + 0.5*dt*k1(1:nState,:), uMid(:,idx), dynFun,pathObj);\n k3 = combinedDynamics(t0+dt, x0 + dt*k2(1:nState,:), u(:,idx+1), dynFun,pathObj);\n z = (dt/6)*(k0 + 2*k1 + 2*k2 + k3); %Change over the sub-step\n \n xNext = x0 + z(1:nState,:); %Next state\n c(idx) = z(end,:); %Integral of the cost function over this step\n \n if iSubStep == nSubStep %We've reached the end of the interval\n % Compute the defect vector:\n defects = xNext - x(:,idx+1);\n else\n % Store the state for next step in time\n idx = idx+1; % <-- This is important!!\n x(:,idx) = xNext;\n end\n \n end\n \n pathCost = sum(c); %Sum up the integral cost over each segment\n \n %%%% Cache results to use on the next call to this function.\n RUNGE_KUTTA_t = t;\n RUNGE_KUTTA_x = x;\n RUNGE_KUTTA_u = u;\n RUNGE_KUTTA_defects = defects;\n RUNGE_KUTTA_pathCost = pathCost;\n \nend\n\nend\n\n\n%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%\n\nfunction dz = combinedDynamics(t,x,u,dynFun,pathObj)\n% dz = combinedDynamics(t,x,u,dynFun,pathObj)\n%\n% This function packages the dynamics and the cost function together so\n% that they can be integrated at the same time.\n%\n% INPUTS:\n% t = [1, nTime] = time vector (grid points)\n% x = [nState, nTime] = state vector at each grid point\n% u = [nControl, nTime] = control vector at each grid point\n% dynamics(t,x,u) = dynamics function handle\n% dx = [nState, nTime] = dx/dt = derivative of state wrt time\n% pathObj(t,x,u) = integral cost function handle\n% dObj = [1, nTime] = integrand from the cost function\n%\n% OUTPUTS:\n% dz = [dx; dObj] = combined dynamics of state and cost\n\n\ndx = dynFun(t,x,u);\nif isempty(pathObj)\n dc = zeros(size(t));\nelse\n dc = pathObj(t,x,u);\nend\n\ndz = [dx;dc]; %Combine and return\n\n\nend\n\n\n\n\n\n\n\n\n\n\n\n\n\n%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%\n%%%% Analytic Gradient Stuff %%%%\n%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction gradInfo = grad_computeInfo(pack)\n%\n% This function computes the matrix dimensions and indicies that are used\n% to map the gradients from the user functions to the gradients needed by\n% fmincon. The key difference is that the gradients in the user functions\n% are with respect to their input (t,x,u) or (t0,x0,tF,xF), while the\n% gradients for fmincon are with respect to all decision variables.\n%\n% INPUTS:\n% nDeVar = number of decision variables\n% pack = details about packing and unpacking the decision variables\n% .nTime\n% .nState\n% .nControl\n%\n% OUTPUTS:\n% gradInfo = details about how to transform gradients\n%\n\n\n%nTime = pack.nTime;\nnState = pack.nState;\nnGridState = pack.nGridState;\nnControl = pack.nControl;\nnGridControl = pack.nGridControl;\n\nnDecVar = 2 + nState*nGridState + nControl*nGridControl;\n\nzIdx = 1:nDecVar;\ngradInfo.nDecVar = nDecVar;\n[tIdx, xIdx, uIdx] = unPackDecVar(zIdx,pack);\n\ngradInfo.tIdx = tIdx([1,end]);\ngradInfo.xIdx = xIdx;\ngradInfo.uIdx = uIdx;\n\nnSegment = pack.nSegment;\nnSubStep = pack.nSubStep;\n\n% indices of decVars associated with u\nindu = 1:2:(1+2*nSegment*nSubStep);\ngradInfo.indu = uIdx(:,indu);\n% indices of decVars associated with uMid\nindumid = 2:2:(1+2*nSegment*nSubStep);\ngradInfo.indumid = uIdx(:,indumid);\n\n%%%% For unpacking the boundary constraints and objective:\ngradInfo.bndIdxMap = [tIdx(1); xIdx(:,1); tIdx(end); xIdx(:,end)];\n\n\nend\n\n\n\n%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%\n\n\n\n\nfunction [fail] = runGradientCheck(z_test, pack,dynamics, pathObj, bndObj, pathCst, bndCst, gradInfo)\n%\n% This function tests the analytic gradients of the objective and\n% nonlinear constraints with the DERIVEST package. The finite difference\n% calculations in matlab's optimization package were not sufficiently\n% accurate.\n%\nGradientCheckTol = 1e-6; %Analytic gradients must match numerical within this bound\n\nfail = 0;\n\nfprintf('\\n%s\\n','____________________________________________________________')\nfprintf('%s\\n',' DerivativeCheck Information with DERIVEST Package ')\n\n% analytic gradient\n[~, dcost] = myObjGrad(z_test, pack, dynamics, pathObj, bndObj, gradInfo);\n\n% check gradient with derivest package\nderiv = gradest(@(z) myObjGrad(z, pack, dynamics, pathObj, bndObj, gradInfo),z_test);\n\n% print largest difference in numerical and analytic gradients\nfprintf('\\n%s\\n','Objective function derivatives:')\nfprintf('%s\\n','Maximum relative difference between user-supplied')\nfprintf('%s %1.5e \\n','and finite-difference derivatives = ',max(abs(dcost-deriv')))\nif any(abs(dcost-deriv') > GradientCheckTol)\n error('Objective gradient did not pass')\nend\n\n% analytic nonlinear constraints\n[c, ceq,dc, dceq] = myCstGrad(z_test, pack, dynamics, pathObj, pathCst, bndCst, gradInfo);\n\n% check nonlinear inequality constraints with 'jacobianest'\nif ~isempty(c)\n jac = jacobianest(@(z) myConstraint(z, pack, dynamics, pathObj, pathCst, bndCst),z_test);\n \n % print largest difference in numerical and analytic gradients\n fprintf('\\n%s\\n','Nonlinear inequality constraint function derivatives:')\n fprintf('%s\\n','Maximum relative difference between user-supplied')\n fprintf('%s %1.5e \\n','and finite-difference derivatives = ',max(max(abs(dc-jac'))))\n if any(any(abs(dc - jac') > GradientCheckTol))\n error('Nonlinear inequality constraint did not pass')\n end\nend\n\n% check nonlinear equality constraints with 'jacobianest'\nif ~isempty(ceq)\n jac = jacobianest(@(z) myCstGradCheckEq(z, pack, dynamics, pathObj, pathCst, bndCst),z_test);\n \n % print largest difference in numerical and analytic gradients\n fprintf('\\n%s\\n','Nonlinear equality constraint function derivatives:')\n fprintf('%s\\n','Maximum relative difference between user-supplied')\n fprintf('%s %1.5e \\n','and finite-difference derivatives = ',max(max(abs(dceq-jac'))))\n if any(any(abs(dceq - jac') > GradientCheckTol))\n error('Nonlinear equality constraint did not pass')\n end\nend\n\nfprintf('\\n%s\\n','DerivativeCheck successfully passed.')\nfprintf('%s\\n','____________________________________________________________')\nend\n\n\n%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%\n\n\n\nfunction ceq = myCstGradCheckEq(decVars, pack, dynamics, pathObj, pathCst, bndCst)\n% This function is necessary for runGradientCheck function\n% return only equality constraint (ceq) for use with jacobest.m\n\n[t,x,u,defects] = simulateSystem(decVars, pack, dynamics, pathObj);\n\n%%%% Call user-defined constraints and pack up:\n[~, ceq] = collectConstraints(t,x,u,...\n defects,...\n pathCst, bndCst);\n\nend\n\n\n%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%\n\n\n\n\nfunction [cost, dcost] = myObjGrad(decVars, pack,dynamics, pathObj, bndObj, gradInfo)\n%\n% This function unpacks the decision variables, sends them to the\n% user-defined objective functions, and then returns the final cost\n%\n% INPUTS:\n% decVars = column vector of decision variables\n% pack = details about how to convert decision variables into t,x, and u\n% dynamics = user-defined dynamics function handle\n% pathObj = user-defined path-objective function\n% bndObj = user-defined boundary objective function\n% gradInfo =\n%\n% OUTPUTS:\n% cost = scalar cost for this set of decision variables\n% dcost = gradient of cost\n% NOTE: gradients are only available for pathCost that depends only on\n% input parameters not states.\n%\n%\n\n% All of the real work happens inside this function:\n[t,x,~,~,pathCost,dxdalpha,dJdalpha] = simSysGrad(decVars, pack, dynamics, pathObj, gradInfo); %#ok\n% dxdalpha is included in outputs to make sure subsequent calls to\n% simulateSystem without change a to decVars have access to the correct value\n% of dxdalpha - see simulateSystem in which dxdalpha is not calculated unless\n% nargout > 5\n\n% Compute the cost at the boundaries of the trajectory\nif isempty(bndObj)\n bndCost = 0;\nelse\n t0 = t(1);\n tF = t(end);\n x0 = x(:,1);\n xF = x(:,end);\n bndCost = bndObj(t0,x0,tF,xF);\nend\n\ncost = pathCost + bndCost;\n\n% calculate gradient of cost function\nif nargout > 1\n \n nState = pack.nState;\n nControl = pack.nControl;\n nSegment = pack.nSegment;\n nSubStep = pack.nSubStep;\n nDecVar = 2+nState*(1+nSegment)+nControl*(1+nSegment*nSubStep*2);\n \n % allocate gradient of cost\n dcost_pth = zeros(nDecVar,1);\n dcost_bnd = zeros(nDecVar,1);\n \n % gradient assocated with bound objective\n if ~isempty(bndObj)\n \n % bound costs and gradients w.r.t. t0, x0, tF, xF\n [~, d_bnd] = bndObj(t0,x0,tF,xF);\n \n % gradients of t0, x0, tF, xF w.r.t. decision parameters (labeled alpha)\n dt0_dalpha = zeros(1,nDecVar);\n dt0_dalpha(1) = 1; % t0 is always the first decVar\n %\n dx0_dalpha = zeros(nState,nDecVar);\n dx0_dalpha(1:nState,gradInfo.xIdx(:,end)) = eye(nState);\n %\n dtF_dalpha = zeros(1,nDecVar);\n dtF_dalpha(2) = 1; % tF is always the second decVar\n %\n dxF_dalpha = zeros(nState,nDecVar);\n dxF_dalpha(1:nState,gradInfo.xIdx(:,end)) = eye(nState);\n \n % gradient of bound cost\n dcost_bnd(:) = [dt0_dalpha; dx0_dalpha; dtF_dalpha; dxF_dalpha]' * d_bnd';\n end\n \n % gradient assocated with path objective\n if ~isempty(pathObj)\n \n dcost_pth = dJdalpha';\n \n end\n \n dcost = dcost_pth + dcost_bnd;\n \nend\n\nend\n\nfunction [c, ceq, dc, dceq] = myCstGrad(decVars, pack, dynamics, pathObj, pathCst, bndCst, gradInfo)\n%\n% This function unpacks the decision variables, computes the defects along\n% the trajectory, and then evaluates the user-defined constraint functions.\n%\n% INPUTS:\n% decVars = column vector of decision variables\n% pack = details about how to convert decision variables into t,x, and u\n% dynamics = user-defined dynamics function handle\n% pathObj = user-defined path-objective function\n% pathCst = user-defined path-constraint function\n% bndCst = user-defined boundary constraint function\n% gradInfo =\n%\n% OUTPUTS:\n% c = non-linear inequality constraint\n% ceq = non-linear equatlity cosntraint\n% dc = gradient of c w.r.t. decVars\n% dceq = gradient of ceq w.r.t. decVars\n%\n% NOTE:\n% - path constraints are satisfied at the start and end of each sub-step\n%\n\n\n[t,x,u,defects,pathcost,dxdalpha] = simSysGrad(decVars, pack, dynamics, pathObj, gradInfo); %#ok\n\n%%%% Call user-defined constraints and pack up:\nif nargout <= 2\n [c, ceq] = collectConstraints(t,x,u,...\n defects,...\n pathCst, bndCst);\n \nelse\n \n [c, ceq, dc, dceq] = collectConstraintsGrad(t,x,u,...\n defects,...\n pathCst, bndCst, pack, gradInfo, dxdalpha);\n \nend\n\nend\n\n\nfunction [c, ceq, dc, dceq] = collectConstraintsGrad(t,x,u,defects, pathCst, bndCst, pack, gradInfo, dxdalpha)\n% [c, ceq, dc, dceq] = collectConstraints(t,x,u,defects, pathCst, bndCst, pack, gradInfo, dxdalpha)\n%\n% OptimTraj utility function.\n%\n% Collects the defects, calls user-defined constraints, and then packs\n% everything up into a form that is good for fmincon.\n%\n% INPUTS:\n% t = time vector (time at each substep) nTime = 1+nSegment*nSubStep\n% x = state matrix (states at each time in t)\n% u = control matrix (control at each time in t)\n% defects = defects matrix\n% pathCst = user-defined path constraint function\n% bndCst = user-defined boundary constraint function\n% pack =\n% gradInfo =\n% dxdalpha = partial derivative of state at each substep w.r.t. decVars\n%\n% OUTPUTS:\n% c = inequality constraint for fmincon\n% ceq = equality constraint for fmincon\n% dc = gradient of c w.r.t. decVars\n% dceq = gradient of ceq w.r.t. decVars\n%\n\n% problem dimensions\nnState = pack.nState;\nnControl = pack.nControl;\nnSegment = pack.nSegment;\nnSubStep = pack.nSubStep;\nnDecVar = 2+nState*(1+nSegment)+nControl*(1+nSegment*nSubStep*2);\n\n%%%% defect constraints\nceq_dyn = reshape(defects,numel(defects),1);\n\ndceq_dyn = zeros(nDecVar,length(ceq_dyn));\nInx = eye(nState);\nfor j = 1:nSegment\n rows = gradInfo.xIdx(:,j+1);\n cols = (j-1)*nState+(1:nState);\n dceq_dyn(:,cols) = dxdalpha{j}(:,:,end)'; % gradient w.r.t. to x_i(+)\n dceq_dyn(rows,cols) = -Inx; % gradient w.r.t. to x_i\nend\n\n\n%%%% Compute the user-defined constraints:\n\n%%%% path constraints\nif isempty(pathCst)\n c_path = [];\n ceq_path = [];\n dc_path = [];\n dceq_path = [];\nelse\n [c_pathRaw, ceq_pathRaw, c_pathGradRaw, ceq_pathGradRaw] = pathCst(t,x,u);\n c_path = reshape(c_pathRaw,numel(c_pathRaw),1);\n ceq_path = reshape(ceq_pathRaw,numel(ceq_pathRaw),1);\n \n dc_path = zeros(nDecVar,length(c_path));\n dceq_path = zeros(nDecVar,length(ceq_path));\n \n % dt/dalpha : gradient of time w.r.t. decVars\n dt_dalpha = zeros(1,nDecVar);\n nTime = 1+nSegment*nSubStep;\n n_time = 0:nTime-1;\n \n % gradients of path constraints\n nc = size(c_pathRaw,1); % number path constraints at each time\n nceq = size(ceq_pathRaw,1);\n for j = 1:(nSegment+1)\n for i = 1:nSubStep\n \n % d(t[n])/dalpha\n n_time0 = n_time((j-1)*nSubStep+i);\n dt_dalpha(1) = (1 - n_time0/(nTime-1));\n dt_dalpha(2) = (n_time0/(nTime-1));\n \n %\n if j < nSegment+1\n dxi_dalpha = dxdalpha{j}(:,:,i);\n else\n dxi_dalpha = zeros(nState,nDecVar);\n cols = gradInfo.xIdx(:,j);\n dxi_dalpha(:,cols) = eye(nState);\n end\n \n %\n dui_dalpha = zeros(nControl,nDecVar);\n cols = gradInfo.indu(:,(j-1)*nSubStep+i);\n dui_dalpha(:,cols) = eye(nControl);\n \n % inequality path constraints\n if nc > 0\n cols = (1:nc) + nc*((j-1)*nSubStep+i-1);\n dc_path(:,cols) = [dt_dalpha; dxi_dalpha; dui_dalpha]' * c_pathGradRaw(:,:,nSubStep*(j-1)+i)';\n end\n \n % equality path constraints\n if nceq > 0\n cols = (1:nceq) + nceq*((j-1)*nSubStep+i-1);\n dceq_path(:,cols) = [dt_dalpha; dxi_dalpha; dui_dalpha]' * ceq_pathGradRaw(:,:,nSubStep*(j-1)+i)';\n end\n \n % no need to continue with inner loop.\n if j == nSegment+1\n break;\n end\n end\n end\n \nend\n\n%%%% bound constraints\nif isempty(bndCst)\n c_bnd = [];\n ceq_bnd = [];\n dc_bnd = [];\n dceq_bnd = [];\n \nelse\n t0 = t(1);\n tF = t(end);\n x0 = x(:,1);\n xF = x(:,end);\n \n % bound constraints and gradients w.r.t. t0, x0, tF, xF\n [c_bnd, ceq_bnd, d_bnd, deq_bnd] = bndCst(t0,x0,tF,xF);\n \n % gradients of t0, x0, tF, xF w.r.t. decision parameters (labeled alpha)\n dt0_dalpha = zeros(1,nDecVar);\n dt0_dalpha(1) = 1; % t0 is always the first decVar\n %\n dx0_dalpha = zeros(nState,nDecVar);\n cols = gradInfo.xIdx(:,1);\n dx0_dalpha(1:nState,cols) = eye(nState);\n %\n dtF_dalpha = zeros(1,nDecVar);\n dtF_dalpha(2) = 1; % tF is always the second decVar\n %\n dxF_dalpha = zeros(nState,nDecVar);\n cols = gradInfo.xIdx(:,end);\n dxF_dalpha(1:nState,cols) = eye(nState);\n \n \n % inequality bound constraints\n dc_bnd = [dt0_dalpha; dx0_dalpha; dtF_dalpha; dxF_dalpha]' * d_bnd';\n \n % equality bound constraints\n dceq_bnd = [dt0_dalpha; dx0_dalpha; dtF_dalpha; dxF_dalpha]' * deq_bnd';\n \nend\n\n%%%% Pack everything up:\nc = [c_path;c_bnd];\nceq = [ceq_dyn; ceq_path; ceq_bnd];\n\ndc = [dc_path, dc_bnd];\ndceq = [dceq_dyn, dceq_path, dceq_bnd];\n\n\nend\n\n\n\n%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%\n\n\nfunction [t,x,u,defects,pathCost,dxdalpha,dJdalpha] = simSysGrad(decVars, pack, dynFun, pathObj, gradInfo)\n%\n% This function does the real work of the transcription method. It\n% simulates the system forward in time across each segment of the\n% trajectory, computes the integral of the cost function, and then matches\n% up the defects between the end of each segment and the start of the next.\n%\n% INPUTS:\n% decVars = column vector of decision variables\n% pack = details about how to convert decision variables into t,x, and u\n% dynamics = user-defined dynamics function handle\n% pathObj = user-defined path-objective function\n%\n% OUTPUTS:\n% t = [1 x nGrid] = time vector for the edges of the sub-step grid\n% x = [nState x nGrid] = state vector\n% u = [nControl x nGrid] = control vector\n% defects = [nState x nSegment] = defect matrix\n% pathCost = scalar cost for the path integral\n%\n% NOTES:\n% - nGrid = nSegment*nSubStep+1\n% - This function is usually called twice for each combination of\n% decision variables: once by the objective function and once by the\n% constraint function. To keep the code fast I cache the old values and\n% only recompute when the inputs change.\n%\n\n\n%%%% CODE OPTIMIZATION %%%%\n%\n% Prevents the same exact code from being called twice by caching the\n% solution and reusing it when appropriate.\n%\nglobal RUNGE_KUTTA_t RUNGE_KUTTA_x RUNGE_KUTTA_u\nglobal RUNGE_KUTTA_defects RUNGE_KUTTA_pathCost\nglobal RUNGE_KUTTA_decVars RUNGE_KUTTA_dxdalpha RUNGE_KUTTA_dJdalpha\n%\nusePreviousValues = false;\nif ~isempty(RUNGE_KUTTA_decVars)\n if length(RUNGE_KUTTA_decVars) == length(decVars)\n if ~any(RUNGE_KUTTA_decVars ~= decVars)\n usePreviousValues = true;\n end\n end\nend\n%\nif usePreviousValues\n t = RUNGE_KUTTA_t;\n x = RUNGE_KUTTA_x;\n u = RUNGE_KUTTA_u;\n defects = RUNGE_KUTTA_defects;\n pathCost = RUNGE_KUTTA_pathCost;\n dxdalpha = RUNGE_KUTTA_dxdalpha;\n dJdalpha = RUNGE_KUTTA_dJdalpha;\nelse\n %\n %\n %%%% END CODE OPTIMIZATION %%%%\n \n \n [tSpan, state, control] = unPackDecVar(decVars,pack);\n \n nState = pack.nState;\n nControl = pack.nControl;\n nSegment = pack.nSegment;\n nSubStep = pack.nSubStep;\n \n % NOTES:\n % The following bit of code is a bit confusing, mostly due to the\n % need for vectorization to make things run at a reasonable speed in\n % Matlab. Part of the confusion comes because the decision variables\n % include the state at the beginning of each segment, but the control\n % at the beginning and middle of each substep - thus there are more\n % control grid-points than state grid points. The calculations are\n % vectorized over segments, but not sub-steps, since the result of\n % one sub-step is required for the next.\n \n % time, state, and control at the ends of each substep\n nTime = 1+nSegment*nSubStep;\n t = linspace(tSpan(1), tSpan(2), nTime);\n x = zeros(nState, nTime);\n u = control(:,1:2:end); % Control a the endpoints of each segment\n uMid = control(:,2:2:end); %Control at the mid-points of each segment\n c = zeros(1, nTime-1); %Integral cost for each segment\n dt = (t(end)-t(1))/(nTime-1);\n \n idx = 1:nSubStep:(nTime-1); %Indicies for the start of each segment\n x(:,[idx,end]) = state; %Fill in the states that we already know\n \n % VARIABLES for analytic gradient evaluations.\n % size of decicion parameters (2 for time), nstate*(nSegment+1), ...\n % dxdalpha = partial derivative of state w.r.t. decVars (alpha)\n nalpha = 2 + nState*(1+nSegment) + nControl*(1+2*nSubStep*nSegment);\n dxdalpha = cell(1,nSegment);\n for i = 1:nSegment\n dxdalpha{i} = zeros(nState,nalpha,nSubStep+1);\n cols = gradInfo.xIdx(:,i);\n dxdalpha{i}(:,cols,1) = eye(nState);\n end\n dTdalpha = zeros(1,nalpha); dTdalpha(1:2) = [-1,1];\n dt_dalpha = zeros(1,nalpha);\n n_time = 0:nTime-1;\n \n % gradient of path cost\n dJdalpha = zeros(1,nalpha);\n \n for iSubStep = 1:nSubStep\n % March forward Runge-Kutta step\n \n t0 = t(idx);\n x0 = x(:,idx);\n \n \n \n %------------------------------------------\n % Code for calculating dxdalpha (partial derivative of state w.r.t.\n % the descision parameters): dxdalpha = nstate x nalpha\n % assume nargout <=5 when using finite difference calculation for\n % gradients in which case dxdalpha is unnecessary.\n \n % Gradient of time w.r.t. decVars\n % ------------------------------------------------------------\n % dt = (tF-t0)/(nTime-1)\n % t = t0 + n*dt\n % t = t0 + n*(tF-t0)/(nTime-1)\n % t = t0*(1-n/(nTime-1)) + tF*(n/(nTime-1))\n %\n % alpha = [t0, tF, x0, x1, ..., xN, u0, uM0, u1, ..., uN]\n % dt/dalpha = [1 - n/(nTime-1), n/(nTime-1), 0, 0, ... 0]\n % ------------------------------------------------------------\n \n n_time0 = n_time(idx);\n \n [k0, dk0] = combinedDynGrad(t0, x0, u(:,idx), dynFun,pathObj);\n [k1, dk1] = combinedDynGrad(t0+0.5*dt, x0 + 0.5*dt*k0(1:nState,:), uMid(:,idx), dynFun,pathObj);\n [k2, dk2] = combinedDynGrad(t0+0.5*dt, x0 + 0.5*dt*k1(1:nState,:), uMid(:,idx), dynFun,pathObj);\n [k3, dk3] = combinedDynGrad(t0+dt, x0 + dt*k2(1:nState,:), u(:,idx+1), dynFun,pathObj);\n z = (dt/6)*(k0 + 2*k1 + 2*k2 + k3); %Change over the sub-step\n \n for j = 1:nSegment\n \n % d(t[n])/dalpha\n dt_dalpha(1) = (1 - n_time0(j)/(nTime-1));\n dt_dalpha(2) = (n_time0(j)/(nTime-1));\n \n % du[n]/dalpha\n du_dalpha = zeros(nControl,nalpha);\n du_dalpha(:,gradInfo.indu(:,idx(j))) = eye(nControl);\n \n % duMid[n]/dalpha\n duMid_dalpha = zeros(nControl,nalpha);\n duMid_dalpha(:,gradInfo.indumid(:,idx(j))) = eye(nControl);\n \n % du[n+1]/dalpha\n du1_dalpha = zeros(nControl,nalpha);\n du1_dalpha(:,gradInfo.indu(:,idx(j)+1)) = eye(nControl);\n \n % dk0/dalpha\n dk0da = dk0(:,:,j) * [dt_dalpha; dxdalpha{j}(:,:,iSubStep); du_dalpha];\n \n % dk1/dalpha\n dk1da = dk1(:,:,j) * [dt_dalpha + 0.5/(nTime-1)*dTdalpha; dxdalpha{j}(:,:,iSubStep) + 0.5*dt*dk0da(1:nState,:) + 0.5/(nTime-1)*k0(1:nState,j)*dTdalpha; duMid_dalpha];\n \n % dk2/dalpha\n dk2da = dk2(:,:,j) * [dt_dalpha + 0.5/(nTime-1)*dTdalpha; dxdalpha{j}(:,:,iSubStep) + 0.5*dt*dk1da(1:nState,:) + 0.5/(nTime-1)*k1(1:nState,j)*dTdalpha; duMid_dalpha];\n \n % dk3/dalpha\n dk3da = dk3(:,:,j) * [dt_dalpha + 1/(nTime-1)*dTdalpha; dxdalpha{j}(:,:,iSubStep) + dt*dk2da(1:nState,:) + 1/(nTime-1)*k2(1:nState,j)*dTdalpha; du1_dalpha];\n \n dz = (dt/6)*(dk0da + 2*dk1da + 2*dk2da + dk3da)...\n + 1/(6*(nTime-1))*(k0(:,j)+2*k1(:,j)+2*k2(:,j)+k3(:,j))*dTdalpha;\n \n % update dxdalpha\n dxdalpha{j}(:,:,iSubStep+1) = dxdalpha{j}(:,:,iSubStep) + dz(1:nState,:);\n \n % update dJdalpha\n dJdalpha = dJdalpha + dz(nState+1,:);\n end\n \n \n xNext = x0 + z(1:nState,:); %Next state\n c(idx) = z(end,:); %Integral of the cost function over this step\n \n if iSubStep == nSubStep %We've reached the end of the interval\n % Compute the defect vector:\n defects = xNext - x(:,idx+1);\n else\n % Store the state for next step in time\n idx = idx+1; % <-- This is important!!\n x(:,idx) = xNext;\n end\n \n end\n \n pathCost = sum(c); %Sum up the integral cost over each segment\n \n %%%% Cache results to use on the next call to this function.\n RUNGE_KUTTA_t = t;\n RUNGE_KUTTA_x = x;\n RUNGE_KUTTA_u = u;\n RUNGE_KUTTA_defects = defects;\n RUNGE_KUTTA_pathCost = pathCost;\n RUNGE_KUTTA_dxdalpha = dxdalpha;\n RUNGE_KUTTA_dJdalpha = dJdalpha;\n \nend\n\nend\n\n\n%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%\n\nfunction [dz, J] = combinedDynGrad(t,x,u,dynFun,pathObj)\n% [dz, dJ] = combinedDynGrad(t,x,u,dynFun,pathObj)\n%\n% This function packages the dynamics and the cost function together so\n% that they can be integrated at the same time.\n%\n% INPUTS:\n% t = [1, nTime] = time vector (grid points)\n% x = [nState, nTime] = state vector at each grid point\n% u = [nControl, nTime] = control vector at each grid point\n% dynamics(t,x,u) = dynamics function handle\n% dx = [nState, nTime] = dx/dt = derivative of state wrt time\n% pathObj(t,x,u) = integral cost function handle\n% dObj = [1, nTime] = integrand from the cost function\n%\n% OUTPUTS:\n% dz = [dx; dObj] = combined dynamics of state and cost\n% dJ = [JAC(dynamics), JAC(objective)] = combined jacobian of dynamics\n% and objective w.r.t. (t,x,u)\n\n\n\nnState = size(x,1);\nnControl = size(u,1);\n\n[dx,Jx] = dynFun(t,x,u);\nif isempty(pathObj)\n dc = zeros(size(t));\n Jc = zeros(1,1+nState+nControl,length(t));\nelse\n [dc,Jc] = pathObj(t,x,u);\n Jc = reshape(Jc,1,1+nState+nControl,length(t));\nend\n\ndz = [dx;dc];\n\nJ = cat(1,Jx,Jc);\n\n\nend\n", "meta": {"author": "MatthewPeterKelly", "repo": "OptimTraj", "sha": "c97b57fda511dacc6a6187f683428f0f3a1965f2", "save_path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj", "path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj/OptimTraj-c97b57fda511dacc6a6187f683428f0f3a1965f2/rungeKutta.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49095499342114274}} {"text": "function [index_set, abundances, reconstruct, err] = AAM_no_subset( X, L, K )\n% AAM_NO_SUBSET Alternating angle minimization implementation of the MESMA\n% algorithm, called by AAM\n%\n% This function executes the AAM algorithm on a set of libraries. For every\n% pixel in x, an endmember set is constructed containing a single endmember\n% from each library. The indices and abundances are returned. The algorithm\n% employed is iterative alternating angle minimization.\n%\n% Input: X: the N data points to unmix in d dimensions, (d,N)\n% L: spectral library, cell array of p elements of size (d,~)\n% K: Optional number of iterations. Default 3\n% Output: index_set identifying the endmembers from each library, (p,N)\n% abundances with respect to these endmembers, (p,N)\n% reconstruct contains the reconstructed spectral (d,N)\n% err contains the reconstruction error (Euclidean distance) (1,N)\n%\n%\n% Rob Heylen, 2016, University of Antwerp.\n\n\n\n% Turn this on to activate sanity checks on the libraries and input values.\n% Turn this off if you are sure there are no doubles in the libraries, and\n% you do not want to check if pixels are contained in the libraries.\nlibrary_check=1;\n\n% Initializations\nif nargin==2\n K=3;\nend\n[d,numpx]=size(X);\np=numel(L);\nfor i=1:p\n N(i)=size(L{i},2);\nend\nflag=0;\nindex_set=zeros(p,numpx);\nabundances=zeros(p,numpx);\nF=zeros(d,p);\nI=ones(p,1);\nreconstruct=zeros(d,numpx);\nerr=zeros(1,numpx);\n\n\n% Main loop over all pixels\nfor px=1:numpx\n x=X(:,px);\n \n % Check if x is a library member. If so, we can finish immediately\n if library_check\n for i=1:p\n %if sum(sum(abs(L{i}-x*ones(1,N(i))))==0)>0\n if numel(find(~sum(abs(L{i}-x*ones(1,N(i))))))>0\n I=ones(p,1);\n I(i)=find(sum(abs(L{i}-x*ones(1,N(i))))==0);\n index_set(:,px)=I;\n flag=1;\n break;\n end\n end\n end\n if flag\n flag=0;\n continue;\n end\n\n % Create random initial endmember set \n for i=1:p\n I(i)=ceil(rand*N(i));\n F(:,i)=L{i}(:,I(i));\n end\n \n % Iterate K times\n for it=1:K\n % Alternating angle optimization\n for i=1:p\n % Calculate angles\n Fi=F(:,[1:i-1 i+1:p]); % Pivot\n Gi=[Fi x]; % Plane through pivot and pixel\n E1=plane_project2(L{i},Fi); % Project library onto pivot\n E2=plane_project2(L{i},Gi); % Project library onto plane\n p1=sqrt(sum((E1-L{i}).^2)); % Distances from library to pivot\n p2=sqrt(sum((E2-L{i}).^2)); % Distances from library to plane\n ang=asin(p2./p1); % Resulting angles\n \n % Find angles that should be inverted\n mask=(x-plane_project2(x,Fi))'*(E2-E1)<0;\n ang(mask)=pi-ang(mask);\n \n % Identify minimal angle, update index set\n [~,I(i)]=min(ang);\n \n % Update endmember set\n F(:,i)=L{i}(:,I(i));\n end\n end\n \n % Update index_set with obtained indices\n index_set(:,px)=I;\nend\n\n% Unmixing phase\nE=zeros(d,p);\ngo=0;\nfor px=1:numpx\n for i=1:p\n E(:,i)=L{i}(:,index_set(i,px));\n end\n % Plug in your favorite unmixing program here\n \n if go==0\n [at,opt]=FCLSU_fast2(X(:,px)',E);\n abundances(:,px)=at';\n go=1;\n else\n at=FCLSU_fast2(X(:,px)',E,opt);\n abundances(:,px)=at';\n end\n \n % Reconstruction\n reconstruct(:,px)=E*abundances(:,px);\n \n % Error\n err(px)=norm(reconstruct(:,px)-X(:,px));\nend\n\nend\n\n\n", "meta": {"author": "zhouyuanzxcv", "repo": "Hyperspectral", "sha": "f32dcca86677f8d37596376f57e9c733058f8cff", "save_path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral", "path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral/Hyperspectral-f32dcca86677f8d37596376f57e9c733058f8cff/GMM_SantaBarbara/competing_methods/AAM/AAM_no_subset.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4909549875154424}} {"text": "function [nav_e] = ins(imu, gnss, att_mode)\n% ins: inertial navigation system.\n%\n% INPUT\n% imu, IMU data structure.\n% t: Ix1 time vector (seconds).\n% fb: Ix3 accelerations vector in body frame XYZ (m/s^2).\n% wb: Ix3 turn rates vector in body frame XYZ (radians/s).\n% arw: 1x3 angle random walks (rad/s/root-Hz).\n% vrw: 1x3 velocity random walks (m/s^2/root-Hz).\n% g_std: 1x3 gyros standard deviations (radians/s).\n% a_std: 1x3 accrs standard deviations (m/s^2).\n% gb_sta: 1x3 gyros static biases or turn-on biases (radians/s).\n% ab_sta: 1x3 accrs static biases or turn-on biases (m/s^2).\n% gb_dyn: 1x3 gyros dynamic biases or bias instabilities (radians/s).\n% ab_dyn: 1x3 accrs dynamic biases or bias instabilities (m/s^2).\n% gb_corr: 1x3 gyros correlation times (seconds).\n% ab_corr: 1x3 accrs correlation times (seconds).\n% gb_psd: 1x3 gyros dynamic biases root-PSD (rad/s/root-Hz).\n% ab_psd: 1x3 accrs dynamic biases root-PSD (m/s^2/root-Hz);\n% freq: 1x1 sampling frequency (Hz).\n% ini_align: 1x3 initial attitude at t(1).\n% ini_align_err: 1x3 initial attitude errors at t(1).\n%\n%\tgnss, GNSS data structure.\n% t: Gx1 time vector (seconds).\n% lat: Gx1 latitude (radians).\n% lon: Gx1 longitude (radians).\n% h: Gx1 altitude (m).\n% vel: Gx3 NED velocities (m/s).\n% std: 1x3 position standard deviations (rad, rad, m).\n% stdm: 1x3 position standard deviations (m, m, m).\n% stdv: 1x3 velocity standard deviations (m/s).\n% larm: 3x1 lever arm from IMU to GNSS antenna (x-fwd, y-right, z-down) (m).\n% freq: 1x1 sampling frequency (Hz).\n% zupt_th: 1x1 ZUPT threshold (m/s).\n% zupt_win: 1x1 ZUPT time window (seconds).\n% eps: 1x1 time interval to compare current IMU time to current GNSS time vector (s).\n%\n% att_mode: attitude mode string.\n% 'quaternion': attitude updated in quaternion format. Default value.\n% 'dcm': attitude updated in Direct Cosine Matrix format.\n%\n% OUTPUT\n% nav_e, INS/GNSS navigation estimates data structure.\n% t: Ix1 INS time vector (seconds).\n% tg: Gx1 GNSS time vector, when Kalman filter was executed (seconds).\n% roll: Ix1 roll (radians).\n% pitch: Ix1 pitch (radians).\n% yaw: Ix1 yaw (radians).\n% vel: Ix3 NED velocities (m/s).\n% lat: Ix1 latitude (radians).\n% lon: Ix1 longitude (radians).\n% h: Ix1 altitude (m).\n% xi: Gxn Kalman filter a priori states.\n% xp: Gxn Kalman filter a posteriori states.\n% z: Gxr INS/GNSS measurements\n% v: Gxr Kalman filter innovations.\n% b: Gxr Kalman filter biases compensations, [gb_dyn ab_dyn].\n% A: Gxn^2 Kalman filter transition-state matrices, one matrix per\n% row ordered by columns.\n% Pp: Gxn^2 Kalman filter a posteriori covariance matrices, one\n% matrix per row ordered by columns.\n% Pi: Gxn^2 Kalman filter a priori covariance matrices, one matrix\n% per row ordered by columns.\n% K: Gx(n*r) Kalman gain matrices\n% S: Gxr^2 Innovation matrices\n% ob: Gx1 Number of observable states after each GNSS data arriving\n%\n% Copyright (C) 2014, Rodrigo Gonzalez, 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% R. 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. Alg. 2.\n%\n% Groves, P.D. (2013), Principles of GNSS, Inertial, and\n% Multisensor Integrated Navigation Systems (2nd Ed.). Artech House.\n%\n% Crassidis, J.L. and Junkins, J.L. (2011). Optimal Esti-\n% mation of Dynamic Systems, 2nd Ed. Chapman and Hall/CRC, USA.\n%\n% ZUPT algothim based on Groves, Chapter 15, \"INS Alignment, Zero Updates,\n% and Motion Constraints\".\n%\n% ins_gps.m, ins_gnss function is based on that previous NaveGo function.\n%\n% Version: 012\n% Date: 2022/07/19\n% Author: Rodrigo Gonzalez \n% URL: https://github.com/rodralez/navego\n\nif nargin < 3, att_mode = 'quaternion'; end\n\n%% ZUPT ALGORITHM\n\n% zupt_flag = false;\n\n%% PREALLOCATION\n\n% Kalman filter dimensions\nn = 15; % number of states\nr = 6; % number of sensors\n% q = 12; % number of inputs\n\n% Constant matrices\n% I = eye(3);\n% O = zeros(3);\n\n% Length of INS time vector\nLI = length(imu.t);\n\n% Length of GNSS time vector\nLG = length(gnss.t);\n\n% Preallocation of attitude vectors\nroll_e = zeros (LI, 1);\npitch_e = zeros (LI, 1);\nyaw_e = zeros (LI, 1);\n\n% Preallocation of velocity vector\nvel_e = zeros (LI, 3);\n\n% Preallocation of gravity vector\ngn_e = zeros (LI, 3);\n\n% Preallocation of position vectors\nlat_e = zeros (LI, 1);\nlon_e = zeros (LI, 1);\nh_e = zeros (LI, 1);\n\n% Preallocation of Kalman filter matrices for later performance analysis\nxi = zeros(LG, n); % Evolution of Kalman filter a priori states\nxp = zeros(LG, n); % Evolution of Kalman filter a posteriori states\nz = zeros(LG, r); % INS/GNSS measurements\nv = zeros(LG, r); % Kalman filter innovations\n\nA = zeros(LG, n^2); % Transition-state matrices\nPi = zeros(LG, n^2); % A priori covariance matrices\nPp = zeros(LG, n^2); % A posteriori covariance matrices\nK = zeros(LG, n*r); % Kalman gain matrices\nS = zeros(LG, r^2); % Innovation matrices\nob = zeros(LG, 1); % Number of observable states at each GNSS data arriving\n\nb = zeros(LG, r); % Biases compensantions after Kalman filter correction\n\n%% INITIAL VALUES AT INS TIME = 1\n\n% Initial attitude\nroll_e(1) = imu.ini_align(1);\npitch_e(1) = imu.ini_align(2);\nyaw_e(1) = imu.ini_align(3);\nDCMnb = euler2dcm([roll_e(1); pitch_e(1); yaw_e(1);]);\nDCMbn = DCMnb';\nqua = euler2qua([roll_e(1) pitch_e(1) yaw_e(1)]);\n\n% Initial velocity\nvel_e(1,:) = gnss.vel(1,:);\n\n% Initial position\nlat_e(1) = gnss.lat(1);\nlon_e(1) = gnss.lon(1);\nh_e(1) = gnss.h(1);\n\n% Initial dynamic biases\ngb_dyn = imu.gb_dyn';\nab_dyn = imu.ab_dyn';\n\n% Turn-rates update with both updated velocity and position\nomega_ie_n = earth_rate(lat_e(1));\nomega_en_n = transport_rate(lat_e(1), vel_e(1,1), vel_e(1,2), h_e(1));\n\n% Gravity update\ngn_e(1,:) = gravity(lat_e(1), h_e(1));\n\n%% INITIALIZATION OF KALMAN FILTER MATRICES\n\n% Prior estimates\n% kf.xi = [ zeros(1,9), imu.gb_dyn, imu.ab_dyn ]'; % Error vector state\n% kf.Pi = diag([imu.ini_align_err, gnss.stdv, gnss.std, imu.gb_dyn, imu.ab_dyn].^2);\n% \n% kf.Q = diag([imu.arw, imu.vrw, imu.gb_psd, imu.ab_psd].^2);\n% \n% fn = DCMbn * (imu.fb(1,:)' - ab_dyn - imu.ab_sta');\n% wn = DCMbn * (imu.wb(1,:)' - gb_dyn - imu.gb_sta');\n% \n% % Vector to update matrix F\n% upd = [gnss.vel(1,:) gnss.lat(1) gnss.h(1) fn' wn'];\n% \n% % Update matrices F and G\n% [kf.F, kf.G] = F_update(upd, DCMbn, imu);\n% \n% [RM,RN] = radius(gnss.lat(1));\n% Tpr = diag([(RM + gnss.h(1)), (RN + gnss.h(1)) * cos(gnss.lat(1)), -1]); % radians-to-meters\n% \n% % Update matrix H\n% kf.H = [ O I O O O ;\n% O O Tpr O O ; ];\n% kf.R = diag([gnss.stdv gnss.stdm]).^2;\n% kf.z = [ gnss.stdv, gnss.stdm ]';\n% \n% % Propagate prior estimates to get xp(1) and Pp(1)\n% kf = kf_update( kf );\n% \n% % Initial matrices for Kalman filter performance analysis\n% xi(1,:) = kf.xi';\n% xp(1,:) = kf.xp';\n% Pi(1,:) = reshape(kf.Pi, 1, n^2);\n% Pp(1,:) = reshape(kf.Pp, 1, n^2);\n% K(1,:) = reshape(kf.K, 1, n*r);\n% S(1,:) = reshape(kf.S, 1, r^2);\n% v(1,:) = kf.v';\n% z(1,:) = kf.z';\n% b(1,:) = [gb_dyn', ab_dyn'];\n\n%% INS (IMU) TIME IS THE MASTER CLOCK\nfor i = 2:LI\n\n %% INERTIAL NAVIGATION SYSTEM (INS)\n\n % Print a dot on console every 10,000 INS executions\n if (mod(i,10000) == 0), fprintf('. '); end\n % Print a return on console every 200,000 INS executions\n if (mod(i,200000) == 0), fprintf('\\n'); end\n\n % IMU sampling interval\n dti = imu.t(i) - imu.t(i-1);\n\n % Inertial sensors corrected with a posteriori KF biases estimation and\n % deterministic static biases\n wb_corrected = imu.wb(i,:)' - gb_dyn - imu.gb_sta';\n fb_corrected = imu.fb(i,:)' - ab_dyn - imu.ab_sta';\n fn = DCMbn * fb_corrected;\n% wn = DCMbn * wb_corrected;\n\n % Velocity update\n vel = vel_update(fn, vel_e(i-1,:), omega_ie_n, omega_en_n, gn_e(i-1,:)', dti);\n vel_e (i,:) = vel;\n\n % Position update\n pos = pos_update([lat_e(i-1) lon_e(i-1) h_e(i-1)], vel_e(i,:), dti);\n lat_e(i) = pos(1);\n lon_e(i) = pos(2);\n h_e(i) = pos(3);\n \n if ( h_e(i) < 0)\n h_e(i) = 10;\n end\n\n % Turn-rates update with both updated velocity and position\n omega_ie_n = earth_rate(lat_e(i));\n omega_en_n = transport_rate(lat_e(i), vel_e(i,1), vel_e(i,2), h_e(i));\n\n % Gravity update\n gn_e(i,:) = gravity(lat_e(i), h_e(i));\n\n % Attitude update\n [qua, DCMbn, euler] = att_update(wb_corrected, DCMbn, qua, ...\n omega_ie_n, omega_en_n, dti, att_mode);\n roll_e(i) = euler(1);\n pitch_e(i)= euler(2);\n yaw_e(i) = euler(3);\n\n %% ZUPT DETECTION ALGORITHM\n idz = floor( gnss.zupt_win / dti ); % Index to set ZUPT window time\n\n if ( i > idz )\n\n % Mean velocity value for the ZUPT window time\n vel_m = mean (vel_e(i-idz:i , :));\n\n % If mean velocity value is under the ZUPT threshold velocity...\n if (abs(vel_m) < gnss.zupt_th)\n\n % Current attitude is equal to the mean of previous attitudes\n % inside the ZUPT window time\n roll_e(i) = mean (roll_e(i-idz:i , :));\n pitch_e(i) = mean (pitch_e(i-idz:i , :));\n yaw_e(i) = mean (yaw_e(i-idz:i , :));\n\n % Current position is equal to the mean of previous positions\n % inside the ZUPT window time\n lat_e(i) = mean (lat_e(i-idz:i , :));\n lon_e(i) = mean (lon_e(i-idz:i , :));\n h_e(i) = mean (h_e(i-idz:i , :));\n\n % Alternative attitude ZUPT correction\n % roll_e(i) = (roll_e(i-idz , :));\n % pitch_e(i) = (pitch_e(i-idz , :));\n % yaw_e(i) = (yaw_e(i-idz, :));\n % lat_e(i) = (lat_e(i-idz:i , :));\n % lon_e(i) = (lon_e(i-idz:i , :));\n % h_e(i) = (h_e(i-idz:i , :));\n\n% zupt_flag = true;\n\n % fprintf(' z\\n') % DEBUG\n end\n end\n\n% %% KALMAN FILTER UPDATE\n% \n% % Check if there is a new GNSS measurement to process at current INS time\n% gdx = find (gnss.t >= (imu.t(i) - gnss.eps) & gnss.t < (imu.t(i) + gnss.eps));\n% \n% if ( ~isempty(gdx) && gdx > 1)\n% \n% % gdx % DEBUG\n% \n% %% MEASUREMENTS\n% \n% % Meridian and normal radii of curvature update\n% [RM,RN] = radius(lat_e(i));\n% \n% % Radians-to-meters matrix\n% Tpr = diag([(RM + h_e(i)), (RN + h_e(i)) * cos(lat_e(i)), -1]);\n% \n% % Position innovations in meters with lever arm correction\n% zp = Tpr * ([lat_e(i); lon_e(i); h_e(i);] - [gnss.lat(gdx); gnss.lon(gdx); gnss.h(gdx);]) ...\n% + (DCMbn * gnss.larm);\n% \n% % Velocity innovations with lever arm correction\n% zv = (vel_e(i,:) - gnss.vel(gdx,:) - ((omega_ie_n + omega_en_n) * (DCMbn * gnss.larm ))' ...\n% + (DCMbn * skewm(wb_corrected) * gnss.larm )' )';\n% \n% %% KALMAN FILTER\n% \n% % GNSS sampling interval\n% dtg = gnss.t(gdx) - gnss.t(gdx-1);\n% \n% % Vector to update matrix F\n% upd = [vel_e(i,:) lat_e(i) h_e(i) fn' wn'];\n% \n% % Matrices F and G update\n% [kf.F, kf.G] = F_update(upd, DCMbn, imu);\n% \n% % Matrix H update\n% if(zupt_flag == false)\n% kf.H = [ O I O O O ;\n% O O Tpr O O ; ];\n% kf.R = diag([gnss.stdv gnss.stdm]).^2;\n% kf.z = [ zv' zp' ]';\n% else\n% kf.H = [ O I O O O ; ];\n% kf.R = diag([gnss.stdv]).^2;\n% kf.z = zv;\n% end\n% \n% % a posteriori states are forced to be zero (error-state approach)\n% kf.xp = zeros(n , 1);\n% % Execution of the extended Kalman filter\n% kf = kalman(kf, dtg);\n% \n% %% OBSERVABILITY\n% \n% % Number the observable states at current GNSS time\n% ob(gdx) = rank(obsv(kf.F, kf.H));\n% \n% %% INS/GNSS CORRECTIONS\n% \n% % Quaternion correction\n% qua_skew = -skewm(qua(1:3)); % According to Crassidis, qua_skew should be\n% % positive, but if positive NaveGo diverges.\n% % Crassidis, Eq. A.174a\n% Xi = [qua(4)*eye(3) + qua_skew; -qua(1:3)'];\n% \n% % Crassidis, Eq. 7.34\n% qua = qua + 0.5 .* Xi * kf.xp(1:3);\n% qua = qua / norm(qua); % Brute-force normalization\n% \n% % DCM correction\n% DCMbn = qua2dcm(qua);\n% \n% % Attitude correction, method 1\n% % euler = qua2euler(qua);\n% % roll_e(i) = euler(1);\n% % pitch_e(i)= euler(2);\n% % yaw_e(i) = euler(3);\n% \n% % Attitude correction, method 2\n% roll_e(i) = roll_e(i) - kf.xp(1);\n% pitch_e(i) = pitch_e(i) - kf.xp(2);\n% yaw_e(i) = yaw_e(i) - kf.xp(3);\n% \n% % Velocity correction\n% vel_e(i,1) = vel_e(i,1) - kf.xp(4);\n% vel_e(i,2) = vel_e(i,2) - kf.xp(5);\n% vel_e(i,3) = vel_e(i,3) - kf.xp(6);\n% \n% % Position correction\n% lat_e(i) = lat_e(i) - kf.xp(7);\n% lon_e(i) = lon_e(i) - kf.xp(8);\n% h_e(i) = h_e(i) - kf.xp(9);\n% \n% % Biases estimation\n% gb_dyn = -kf.xp(10:12);\n% ab_dyn = -kf.xp(13:15);\n% \n% % Matrices for later Kalman filter performance analysis\n% xi(gdx,:) = kf.xi';\n% xp(gdx,:) = kf.xp';\n% b(gdx,:) = [gb_dyn', ab_dyn'];\n% A(gdx,:) = reshape(kf.A, 1, n^2);\n% Pi(gdx,:) = reshape(kf.Pi, 1, n^2);\n% Pp(gdx,:) = reshape(kf.Pp, 1, n^2);\n% \n% if(zupt_flag == false)\n% v(gdx,:) = kf.v';\n% z(gdx,:) = kf.z';\n% K(gdx,:) = reshape(kf.K, 1, n*r);\n% S(gdx,:) = reshape(kf.S, 1, r^2);\n% else\n% zupt_flag = false;\n% z(gdx,:) = [ kf.z' 0 0 0 ]';\n% v(gdx,:) = [ kf.v' 0 0 0 ]';\n% K(gdx,1:n*3) = reshape(kf.K, 1, n*3);\n% S(gdx,1:9) = reshape(kf.S, 1, 3^2);\n% end\n% end\nend\n\n%% Summary from INS/GNSS integration\n\nnav_e.t = imu.t(1:i, :); % INS time vector\nnav_e.tg = gnss.t; % GNSS time vector, which is the time vector when the Kalman filter was executed\nnav_e.roll = roll_e(1:i, :); % Roll\nnav_e.pitch = pitch_e(1:i, :); % Pitch\nnav_e.yaw = yaw_e(1:i, :); % Yaw\nnav_e.vel = vel_e(1:i, :); % NED velocities\nnav_e.lat = lat_e(1:i, :); % Latitude\nnav_e.lon = lon_e(1:i, :); % Longitude\nnav_e.h = h_e(1:i, :); % Altitude\nnav_e.gn = gn_e(1:i, :); % Gravity estimation in the nav-frame.\n\nnav_e.xi = xi; % A priori states\nnav_e.xp = xp; % A posteriori states\nnav_e.z = z; % INS/GNSS measurements\nnav_e.v = v; % Kalman filter innovations\nnav_e.b = b; % Biases compensations\n\nnav_e.A = A; % Transition matrices\nnav_e.Pi = Pi; % A priori covariance matrices\nnav_e.Pp = Pp; % A posteriori covariance matrices\nnav_e.K = K; % Kalman gain matrices\nnav_e.S = S; % Innovation matrices\nnav_e.ob = ob; % Number of observable states after each GNSS data arriving\n\nfprintf('\\n');\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/ins-gnss/ins.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.49094983293888095}} {"text": "% LOGSPEC - plot mean log power spectra of submitted data on loglog scale\n% using PLOTDATA or PLOTTOPO formats \n%\n% Usage:\n% >> [spectra,freqs] = logspec(data,frames,srate);\n% >> [spectra,freqs] = logspec(data,frames,srate,'title',...\n% [loHz-hiHz],'chan_locs',rm_mean);\n% Inputs:\n% data = input data (chans,frames*epochs)\n% frames = data samples per epoch {default length(data)}\n% srate = data sampling rate in Hz {default 256 Hz};\n% 'title' = plot title {default: none}\n% [loHz-hiHz] = [loHz hiHz] plotting limits \n% {default: [srate/fftlength srate/2]}\n% 'chan_locs' = channel location file (ala TOPOPLOT) \n% Else [rows cols] to plot data in a grid array\n% rm_mean = [0/1] 1 -> remove log mean spectrum from all\n%\n% Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 11-07-97 \n%\n% See also: PLOTDATA, PLOTTOPO\n\n% Copyright (C) 11-07-97 Scott Makeig, SCCN/INC/UCSD, scott@sccn.ucsd.edu\n%\n% This file is part of EEGLAB, see http://www.eeglab.org\n% for the documentation and details.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are met:\n%\n% 1. Redistributions of source code must retain the above copyright notice,\n% this list of conditions and the following disclaimer.\n%\n% 2. Redistributions in binary form must reproduce the above copyright notice,\n% this list of conditions and the following disclaimer in the documentation\n% and/or other materials provided with the distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n% THE POSSIBILITY OF SUCH DAMAGE.\n\n% Changed PLOTDATA below to PLOTTOPO 11/12/99 -sm\n% Mentioned new grid array option 12/22/99 -sm\n% 01-25-02 reformated help & license, added links -ad \n\nfunction [spectra,freqs] = logspec(data,frames,srate,titl,Hzlimits,chanlocs,rmmean)\n\nif nargin < 1\n help logspec\n return\nend\n[rows,cols] = size(data);\n\nicadefs % read plotdata chan limit\n\nif rows > MAXPLOTDATACHANS\n fprintf('logspec(): max plotdata() channels is %d.\\n',MAXPLOTDATACHANS);\n return\nend\nif rows < 2\n fprintf('logspec(): min plotdata() channels is %d.\\n',2);\n return\nend\nif nargin<7\n rmmean = 0; % default\nend\n\nif nargin < 5\n Hzlimits = 0;\nend\n\nif nargin < 4\n titl = ' ';\nend\n\nif nargin < 3\n srate = 256;\nend\n\nif nargin < 2,\n frames = cols;\nend\n\nepochs = fix(cols/frames);\nif epochs*frames ~= cols\n fprintf('logspec() - frames does not divide data length.\\n');\n return\nend\n\nfftlength = 2^floor(log(frames)/log(2));\n\nspectra = zeros(rows,epochs*fftlength/2);\nf2 = fftlength/2;\ndB = 10/log(10);\n\nif length(Hzlimits) < 2\n Hzlimits = [srate/fftlength srate/2];\nend\nif Hzlimits(2) <= Hzlimits(1)\n help logspec\n return\nend\n\nfor e=1:epochs\n for r=1:rows\n [Pxx,freqs] = pwelch(data(r,(e-1)*frames+1:e*frames),fftlength,...\n fftlength/4,fftlength,srate);\n spectra(r,(e-1)*f2+1:e*f2) = Pxx(2:f2+1)'; % omit DC bin\n end\nend\n\nclf\nfreqs = freqs(2:f2+1);\nfsi = find(freqs >= Hzlimits(1) & freqs <= Hzlimits(2));\nminf = freqs(fsi(1));\nmaxf = freqs(fsi(length(fsi)));\nnfs = length(fsi);\n\nshowspec = zeros(rows,length(fsi)*epochs);\nfor e = 1:epochs\n showspec(:,(e-1)*nfs+1:e*nfs) = dB*log(spectra(:,(e-1)*f2+fsi));\nend\n% minspec = min(min(showspec));\n% showspec = showspec-minspec; % make minimum 0 dB\n\nshowspec = blockave(showspec,nfs);\n\n% meanspec = mean(showspec);\n% showspec = showspec - ones(rows,1)*meanspec;\n\n% >> plotdata(data,frames,limits,title,channames,colors,rtitle)\n% diff = 0;\n% MINUEND = 6;\n% for r=1:rows\n% diff = diff - MINUEND;\n% showspec(r,:) = showspec(r<:)-diff;\n% end\n% semilogx(freqs(fsi),showspec');\n% ax = axis;\n% axis([minf maxf ax(3) ax(4)]);\n% title(titl);\n\nif nargin<6\n% >> plotdata(data,frames,limits,title,channames,colors,rtitle,ydir)\n if rmmean\n showspec = showspec - ones(rows,1)*mean(showspec);\n end\n plotdata(showspec,nfs,[minf maxf 0 0],titl);\nelse\n% >> plottopo(data,'chan_locs',frames,limits,title,channels,axsize,colors,ydir)\n if rmmean\n showspec = showspec - ones(rows,1)*mean(showspec);\n end\n plottopo(showspec,chanlocs,nfs,[minf maxf 0 0],titl);\nend\nax = get(gcf,'children');\nfor a = ax\n set(a,'XScale','log')\nend\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/miscfunc/logspec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4909151762583126}} {"text": "classdef KRVEA < ALGORITHM\n% \n% Surrogate-assisted RVEA\n% alpha --- 2 --- The parameter controlling the rate of change of penalty\n% wmax --- 20 --- Number of generations before updating Kriging models\n% mu --- 5 --- Number of re-evaluated solutions at each generation\n\n%------------------------------- Reference --------------------------------\n% T. Chugh, Y. Jin, K. Miettinen, J. Hakanen, and K. Sindhya, A surrogate-\n% assisted reference vector guided evolutionary algorithm for\n% computationally expensive many-objective optimization, IEEE Transactions\n% on Evolutionary Computation, 2018, 22(1): 129-142.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n% This function is written by Cheng He\n\n methods\n function main(Algorithm,Problem)\n %% Parameter setting\n [alpha,wmax,mu] = Algorithm.ParameterSet(2,20,5);\n\n %% Generate the reference points and population\n [V0,Problem.N] = UniformPoint(Problem.N,Problem.M);\n V = V0;\n NI = 11*Problem.D-1;\n P = UniformPoint(NI,Problem.D,'Latin');\n A2 = Problem.Evaluation(repmat(Problem.upper-Problem.lower,NI,1).*P+repmat(Problem.lower,NI,1));\n A1 = A2; \n THETA = 5.*ones(Problem.M,Problem.D);\n Model = cell(1,Problem.M);\n\n %% Optimization\n while Algorithm.NotTerminated(A2)\n % Refresh the model and generate promising solutions\n A1Dec = A1.decs;\n A1Obj = A1.objs;\n for i = 1 : Problem.M\n % The parameter 'regpoly1' refers to one-order polynomial\n % function, and 'regpoly0' refers to constant function. The\n % former function has better fitting performance but lower\n % efficiency than the latter one\n dmodel = dacefit(A1Dec,A1Obj(:,i),'regpoly1','corrgauss',THETA(i,:),1e-5.*ones(1,Problem.D),100.*ones(1,Problem.D));\n Model{i} = dmodel;\n THETA(i,:) = dmodel.theta;\n end\n PopDec = A1Dec;\n w = 1;\n while w <= wmax\n drawnow('limitrate');\n OffDec = OperatorGA(Problem,PopDec);\n PopDec = [PopDec;OffDec];\n [N,~] = size(PopDec);\n PopObj = zeros(N,Problem.M);\n MSE = zeros(N,Problem.M);\n for i = 1: N\n for j = 1 : Problem.M\n [PopObj(i,j),~,MSE(i,j)] = predictor(PopDec(i,:),Model{j});\n end\n end\n index = KEnvironmentalSelection(PopObj,V,(w/wmax)^alpha);\n PopDec = PopDec(index,:);\n PopObj = PopObj(index,:);\n % Adapt referece vectors\n if ~mod(w,ceil(wmax*0.1))\n V(1:Problem.N,:) = V0.*repmat(max(PopObj,[],1)-min(PopObj,[],1),size(V0,1),1);\n end\n w = w + 1; \n end\n\n % Select mu solutions for re-evaluation\n [NumVf,~] = NoActive(A1Obj,V0);\n PopNew = KrigingSelect(PopDec,PopObj,MSE(index,:),V,V0,NumVf,0.05*Problem.N,mu,(w/wmax)^alpha); \n New = Problem.Evaluation(PopNew);\n A2 = [A2,New];\n A1 = UpdataArchive(A1,New,V,mu,NI); \n end\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Algorithms/Multi-objective optimization/K-RVEA/KRVEA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711870587667, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.49085442106792043}} {"text": "function e_global = error_cam_proj(param);\n\nglobal n_ima x_1 X_1 xproj_1 x_proj_1 x_2 X_2 xproj_2 x_proj_2 x_3 X_3 xproj_3 x_proj_3 x_4 X_4 xproj_4 x_proj_4 x_5 X_5 xproj_5 x_proj_5 x_6 X_6 xproj_6 x_proj_6 x_7 X_7 xproj_7 x_proj_7 x_8 X_8 xproj_8 x_proj_8 x_9 X_9 xproj_9 x_proj_9 x_10 X_10 xproj_10 x_proj_10 x_11 X_11 xproj_11 x_proj_11 x_12 X_12 xproj_12 x_proj_12 x_13 X_13 xproj_13 x_proj_13 x_14 X_14 xproj_14 x_proj_14 x_15 X_15 xproj_15 x_proj_15 x_16 X_16 xproj_16 x_proj_16 x_17 X_17 xproj_17 x_proj_17 x_18 X_18 xproj_18 x_proj_18 x_19 X_19 xproj_19 x_proj_19 x_20 X_20 xproj_20 x_proj_20 x_21 X_21 xproj_21 x_proj_21 x_22 X_22 xproj_22 x_proj_22 x_23 X_23 xproj_23 x_proj_23 x_24 X_24 xproj_24 x_proj_24 x_25 X_25 xproj_25 x_proj_25 x_26 X_26 xproj_26 x_proj_26 x_27 X_27 xproj_27 x_proj_27 x_28 X_28 xproj_28 x_proj_28 x_29 X_29 xproj_29 x_proj_29 x_30 X_30 xproj_30 x_proj_30 \n\n% This is the same model, but with a simpler distortion model (no 6th order)\n\n% Computation of the errors:\n\nfc = param(1:2);\ncc = param(3:4);\nalpha_c = param(5);\nkc = [param(6:9);0];\n\ne_cam = [];\n\nfor kk = 1:n_ima,\n omckk = param(11+(kk-1)*6-1:11+(kk-1)*6+2-1);\n Tckk = param(11+(kk-1)*6+3-1:11+(kk-1)*6+3+2-1);\n \n eval(['Xkk = X_' num2str(kk) ';']);\n eval(['xkk = x_' num2str(kk) ';']);\n \n ekk = xkk - project_points2(Xkk,omckk,Tckk,fc,cc,kc,alpha_c);\n \n Rckk = rodrigues(omckk);\n eval(['omc_' num2str(kk) '= omckk;']);\n eval(['Tc_' num2str(kk) '= Tckk;']);\n eval(['Rc_' num2str(kk) '= Rckk;']);\n \n e_cam = [e_cam ekk];\n \nend;\n\nX_proj = [];\nx_proj = [];\n\nfor kk = 1:n_ima,\n eval(['xproj = xproj_' num2str(kk) ';']);\n xprojn = normalize_pixel(xproj,fc,cc,kc,alpha_c);\n eval(['Rc = Rc_' num2str(kk) ';']);\n eval(['Tc = Tc_' num2str(kk) ';']); \n Np_proj = size(xproj,2);\n\tZc = ((Rc(:,3)'*Tc) * (1./(Rc(:,3)' * [xprojn; ones(1,Np_proj)])));\n\tXcp = (ones(3,1)*Zc) .* [xprojn; ones(1,Np_proj)]; % % in the camera frame\n eval(['X_proj_' num2str(kk) ' = Xcp;']); % coordinates of the points in the \n eval(['X_proj = [X_proj X_proj_' num2str(kk) '];']);\n eval(['x_proj = [x_proj x_proj_' num2str(kk) '];']);\nend;\n\nfp = param((1:2)+n_ima * 6 + 10-1);\ncp = param((3:4)+n_ima * 6 + 10-1);\nalpha_p = param((5)+n_ima * 6 + 10-1);\nkp = [param((6-1:10-2)+n_ima * 6 + 10);0];\n\nom = param(10+n_ima*6+10+1-2:10+n_ima*6+10+1+2-2);\nT = param(10+n_ima*6+10+1+2+1-2:10+n_ima*6+10+1+2+1+2-2);\n\n\ne_proj = x_proj - project_points2(X_proj,om,T,fp,cp,kp,alpha_p);\n\n\ne_global = [e_cam e_proj];\n\n", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/EKF_monoSLAM_1pRANSAC/matlab_code/matlabcalibration2ourcalibration/TOOLBOX_calib/error_cam_proj2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4907357965807528}} {"text": "function DEM = ADEM_eyeblink(OPTION)\n% Simulation of eyeblink conditioning\n% FORMAT DEM = ADEM_eyeblink(OPTION)\n%\n% OPTION:\n% case{'EYEBLINK'} : spontaneous eye blinking\n% case{'AIRPUFF'} : unconditioned eyeblink response to air puff\n% case{'STARTLE'} : unconditioned startle response to a sound\n% case{'TRACE'} : trace conditioning to the sound\n% case{'DELAY'} : delay conditioning to the sound\n% case{'EXTINCTION'} : extinction of trace conditioning to sound\n%\n%__________________________________________________________________________\n%\n% This demonstration routine illustrates Pavlovian learning under active\n% inference. It uses the eyeblink conditioning paradigm to model startle\n% responses and the subsequent acquisition of an eyeblink - under delay and\n% trace learning. The various options above determine the nature of the\n% simulation (or edit the OPTION below). The generative model, in this\n% example, starts with a heteroclinic cycle with an inset. The cycle per se\n% generates autonomous eyeblinks periodically, while the inset is\n% activated by a conditioned stimulus (CS). The subsequent unstable fixed\n% points play the role of an echo-state and enables the learning or\n% association of a high-level hidden cause with subsequent unconditioned\n% responses (UR).\n%\n% In active inference, an unconditioned response corresponds to a prior\n% belief that a hidden state will generate action and the unconditioned\n% stimulus (US). Pavlovian conditioning is the learning of the Association\n% between a conditioned stimulus (CS) and the unconditioned response. The\n% dynamics entailed by the heteroclinic cycle enable trace conditioning,\n% which may be related to hippocampal function.\n%\n% In this example, there are two levels with the hidden states at the first\n% level modelling beliefs about eyeblinks, unconditioned responses and\n% unconditioned stimuli. Proprioceptive predictions are generated by\n% beliefs about ensuing eyeblinks and unconditioned responses (which\n% also predict the conditioned stimulus. Hidden states at the second level\n% embody a sense of time through Lotka-Volterra dynamics. Successive epochs\n% of time are passed to the first level via a softmax transform. Learning\n% corresponds to Hebbian plasticity (that minimises free energy) in the\n% connections between the state unit encoding expectations about a UR and\n% expectations about the CS (for delay conditioning) and heteroclinic\n% states (for trace conditioning): see the functions at the end of this\n% routine.\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: ADEM_eyeblink.m 7679 2019-10-24 15:54:07Z spm $\n\n\n% paradigm and stimuli\n%==========================================================================\n\n\n\n% options:\n%--------------------------------------------------------------------------\nif ~nargin, OPTION = 'STARTLE'; end\n\nP.x = 0; % connection strengths\nP.v = [0 0 0]; % connection strengths\nPC = 0; % prior covariance\nV = [8 4 0]; % sensory precision\n\nswitch OPTION\n \n case{'EYEBLINK'} % spontaneous eye blinking\n N = 256; % number of time bins\n NT = 1; % number of trials\n C(:,1) = sparse(1,N); % CS: loud sound\n C(:,2) = sparse(1,N); % US: air puff\n \n case{'AIRPUFF'} % unconditional response to US\n N = 256; % number of time bins\n NT = 1; % number of trials\n CS = 128; % onset of CS (bins)\n C(:,1) = sparse(1,N); % CS: loud sound\n C(:,2) = exp(-((1:N) - CS).^2/(2*4^2)); % US: air puff\n \n case{'STARTLE'} % startle response to CS\n N = 256; % number of time bins\n NT = 1; % number of trials\n CS = 128; % onset of CS (bins)\n C(:,1) = exp(-((1:N) - CS).^2/(2*4^2)); % CS: loud sound\n C(:,2) = sparse(1,N); % US: air puff\n \n case{'DELAY'} % delay learning of association\n N = 64; % number of time bins\n NT = 16; % number of trials\n CS = 48; % onset of CS (bins)\n C(:,1) = exp(-((1:N) - CS).^2/(2*8^2)); % CS: loud sound\n C(:,2) = exp(-((1:N) - CS - 4).^2/(2*4^2)); % US: air puff\n PC = 1; % enable learning\n\n case{'TRACE'} % trace learning of association (over time)\n N = 128; % number of time bins\n NT = 32; % number of trials\n CS = 48; % onset of CS (bins)\n C(:,1) = exp(-((1:N) - CS).^2/(2*4^2)); % CS: loud sound\n C(:,2) = exp(-((1:N) - CS - 32).^2/(2*4^2)); % US: air puff\n PC = 1; % enable learning\n \n case{'EXTINCTION'} % normalextinction\n N = 128; % number of time bins\n NT = 8; % number of trials\n CS = 48; % onset of CS (bins)\n C(:,1) = exp(-((1:N) - CS).^2/(2*4^2)); % CS: loud sound\n C(:,2) = sparse(1,N); % US: air puff\n P.x = 0; % connection strengths\n P.v = [0 0 0.6]; % connection strengths\n PC = 1; % enable learning \n V = [8 0 0]; % pirotoxin lesion\n V = [8 2 0]; % sensory precision\n \n otherwise\nend\n\n\n% generative process\n%==========================================================================\nM(1).E.n = 2;\nM(1).E.d = 2;\nM(1).E.s = 1;\nM(1).E.nN = 2;\nM(1).E.nE = 1;\n\n% level 1\n%--------------------------------------------------------------------------\nG(1).g = @(x,v,a,P) G1g(x,v,a,P);\nG(1).V = exp(16); % error precision\nG(1).U = exp(4); % motor gain\n\n\n% level 2\n%--------------------------------------------------------------------------\nG(2).v = [0;0]; % stimulus (CS and US)\nG(2).a = 0; % action\nG(2).V = exp(16);\n\n% generative model\n%==========================================================================\n\n% positions associated with each state (on unit circle)\n%--------------------------------------------------------------------------\nx.CS = 0;\nx.UR = 0;\nx.EB = 0;\n\n% level 1\n%--------------------------------------------------------------------------\nM(1).x = x;\nM(1).f = @(x,v,P) M1f(x,v,P);\nM(1).g = @(x,v,P) M1g(x,v,P);\nM(1).pE = P;\nM(1).pC = PC;\nM(1).W = diag(exp([4 0 4])); % cerebellar (IPN) lesion\nM(1).W = exp(4); % error precision\nM(1).V = exp(V); % sensory attenuation\n\n% for use with spm_ALAP (for state-dependent sensory attenuation)\n%--------------------------------------------------------------------------\nM(1).E.method.x = 0;\nM(1).ph = @(x,v,h,M) [8 4 4] - 2*(x.UR + x.EB); % sensory attenuation\n\n% level 2\n%--------------------------------------------------------------------------\nP = [\n +1 -0.5 0.2 0.2 0.2 0.2;\n +0.5 1 -0.5 0 0 0 ;\n -0.5 0.5 1 -0.5 0 0 ;\n -0.5 0 0.5 1 0 0.5;\n -0.5 0 0 0.5 1 -0.5;\n -0.5 0 0 -0.5 0.5 1 ] - 1;\n\n\nM(2).x = [0 0 0 4 0 0]' - 4;\nM(2).f = @(x,v,P) spm_lotka_volterra(x,v,P);\nM(2).g = @(x,v,P) spm_softmax(x);\nM(2).pE = P;\nM(2).V = exp(0); % hippocampal lesion\nM(2).V = exp(4); % error precision\nM(2).W = exp(4); % error precision\n\n% level 3\n%--------------------------------------------------------------------------\nM(3).v = 0; % inputs (null)\nM(3).V = exp(16);\n\n\n% ADEM\n%==========================================================================\nDEM.U = sparse(N,1);\nDEM.C = C;\nDEM.G = G;\nDEM.M = M;\nDEM.db = 0;\nfor i = 1:NT\n \n % integrate active inference scheme\n %----------------------------------------------------------------------\n DEM = spm_ADEM(DEM);\n \n if i == 1\n spm_figure('GetWin','Before learning');\n else\n spm_figure('GetWin','After learning');\n end\n spm_DEM_qU(DEM.qU,DEM.pU);\n \n if NT == 1, break, end\n \n % latency and vigour of CR\n %----------------------------------------------------------------------\n a = DEM.qU.a{2};\n a = abs(a(1:min(end,(CS + 32))));\n if max(a) > 1/4;\n q = sum((1:length(a)).*a/sum(a));\n else\n q = NaN;\n end\n \n CR(1,i) = q;\n CR(2,i) = max(a);\n \n % Baysian belief update\n %----------------------------------------------------------------------\n p = DEM.qP.P{1};\n DEM.M(1).pE = p;\n qP(:,i) = spm_vec(p);\n \n % plot\n %----------------------------------------------------------------------\n spm_figure('GetWin','Figure 1'); clf\n \n subplot(2,2,1),cla\n plot((1:i),CR(1,:) - CR(1,1)), hold on\n plot((1:i),qP',':b'), hold on\n plot((1:i),CR(2,:),'--'), hold off\n set(gca,'XLim',[0 (NT + 1)])\n title('latency and vigour','FontSize',16);\n xlabel('trials')\n ylabel('response')\n axis square\n \n subplot(2,2,2),cla\n imagesc(qP)\n title('plasticity','FontSize',16);\n set(gca,'XLim',[0.5 (NT + .5)])\n xlabel('trials')\n ylabel('connection')\n axis square\n \nend\n\n\n% functions of generative process and model (at the first level)\n%==========================================================================\nfunction s = G1g(x,v,a,P) % sensory process\ns.CS = v(1); % CS: amplitude sound \ns.US = v(2); % US: air puff\ns.R = a; % proprioception\n\nfunction s = M1g(x,v,P) % sensory prediction\ns.CS = x.CS; % prediction of CS\ns.US = x.UR; % prediction of US\ns.R = x.UR + x.EB; % prediction of UR\n\nfunction f = M1f(x,v,P) % dynamics of states\nf.CS = v(1) - x.CS; % dynamics of CS\nf.UR = P.v*v(1:3) + P.x*x.CS - x.UR; % dynamics of UR construct\nf.EB = v(6) - x.EB; % dynamics of eyeblinks\n\n\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/DEM/ADEM_eyeblink.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4906986834396845}} {"text": "% KNT_DERHAM: construct the knot vectors for discrete B-spline spaces in the De Rham diagram.\n%\n% USAGE:\n%\n% [knots, degree] = knt_derham (knots_h1, degree_h1, output_space)\n%\n% INPUTS:\n%\n% knots_h1: knot vectors for the H^1-conforming space, cell array of size (1 x ndim)\n% degree_h1: degree for the H^1 space, vector of size (1 x ndim)\n% output_space: string, with one of the following: 'H1', 'Hcurl', 'Hdiv', 'L2'\n%\n% OUTPUT\n%\n% The output are the knot vectors and the degrees for the chosen output space\n% Their size depend on the space:\n%\n% For H^1 and L^2 (scalar spaces)\n%\n% NAME TYPE SIZE DESCRIPTION\n% knots cell-array (1 x ndim)\n% degree vector (1 x ndim)\n%\n% For H(curl) and H(div) (vectorial spaces) each component of the\n% cell-array contains the same information for one component of the space.\n% That is, the knot vector is a cell-array of cell-arrays.\n%\n% NAME TYPE SIZE \n% knots cell-array (1 x ndim)\n% degree cell-array (1 x ndim)\n%\n% Copyright (C) 2010, 2015 Rafael Vazquez\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\n\nfunction [knots, degree] = knt_derham (knots_h1, degree_h1, output_space)\n\n if (nargin < 3)\n output_space = 'Hcurl';\n end\n \n if (nargout > 2)\n error (['Wrong number of output parameters. The use of knt_derham has changed since version 2.1.' ...\n 'Please read the help, or the examples in GeoPDEs, to understand its usage'])\n end\n \n if (~iscell (knots_h1))\n knots_h1 = {knots_h1};\n end\n\n ndim = numel (knots_h1);\n if (ndim ~= numel (degree_h1))\n error ('knt_derham: wrong input parameters. The dimension of the knot vector and the degree do not match')\n end\n \n for ii = 1:ndim\n knots_l2{ii} = knots_h1{ii}(2:end-1);\n end\n\n if (strcmpi (output_space, 'H1'))\n knots = knots_h1;\n degree = degree_h1;\n elseif (strcmpi (output_space, 'L2'))\n knots = knots_l2;\n degree = degree_h1 - 1;\n elseif (strcmpi (output_space, 'Hcurl'))\n if (ndim < 2 || ndim > 3)\n error ('knt_derham: Wrong dimension to compute the H(curl) space')\n end\n knots = cell (ndim, 1);\n degree = cell (ndim, 1);\n for idim = 1:ndim\n knots{idim} = knots_h1;\n degree{idim} = degree_h1;\n knots{idim}{idim} = knots_l2{idim};\n degree{idim}(idim) = degree_h1(idim) - 1;\n end\n elseif (strcmpi (output_space, 'Hdiv'))\n if (ndim < 2 || ndim > 3)\n error ('knt_derham: Wrong dimension to compute the H(div) space')\n end\n knots = cell (ndim, 1);\n degree = cell (ndim, 1);\n for idim = 1:ndim\n knots{idim} = knots_l2;\n degree{idim} = degree_h1 - 1;\n knots{idim}{idim} = knots_h1{idim};\n degree{idim}(idim) = degree_h1(idim);\n end\n end\n \n \n% if (numel (knots_h1) == 2)\n% knots_u1 = {knots_l2{1} knots_h1{2}};\n% knots_u2 = {knots_h1{1} knots_l2{2}};\n% \n% if (nargout == 2)\n% varargout = {knots_u1 knots_u2};\n% elseif (nargout == 4 && nargin == 2)\n% degree1 = [degree(1) - 1, degree(2)];\n% degree2 = [degree(1), degree(2) - 1];\n% varargout = {knots_u1 knots_u2 degree1 degree2};\n% elseif (nargout == 3 && nargin == 1)\n% varargout = {knots_u1 knots_u2 knots_l2};\n% elseif (nargout == 6 && nargin == 2)\n% degree1 = [degree(1) - 1, degree(2)];\n% degree2 = [degree(1), degree(2) - 1];\n% degree_l2 = [degree(1) - 1, degree(2) - 1];\n% varargout = {knots_u1 knots_u2 knots_l2 degree1 degree2 degree_l2};\n% else\n% error ('knt_derham: wrong number of input or output parameters');\n% end\n% \n% elseif (numel (knots_h1) == 3)\n% knots_u1 = {knots_l2{1} knots_h1{2} knots_h1{3}};\n% knots_u2 = {knots_h1{1} knots_l2{2} knots_h1{3}};\n% knots_u3 = {knots_h1{1} knots_h1{2} knots_l2{3}};\n% \n% if (nargout == 3)\n% varargout = {knots_u1 knots_u2 knots_u3};\n% elseif (nargout == 6 && nargin == 2)\n% degree1 = [degree(1) - 1, degree(2), degree(3)];\n% degree2 = [degree(1), degree(2) - 1, degree(3)];\n% degree3 = [degree(1), degree(2), degree(3) - 1];\n% varargout = {knots_u1 knots_u2 knots_u3 degree1 degree2 degree3};\n% else\n% error ('knt_derham: wrong number of input or output parameters');\n% end\n% end\n% \nend\n", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/utils/knt_derham.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6334102705979902, "lm_q1q2_score": 0.49062907096461106}} {"text": "function model = gpsimMapUpdateG(model)\n\n% GPSIMMAPUPDATEG Update the nonlinear transformation of f.\n% FORMAT\n% DESC updates the fields of model associated with the non-linear\n% transformation of f, namely g, g_grad and g_grad2.\n% ARG model : the model to be updated.\n% ARG model : the model with the updated g representation.\n%\n% COPYRIGHT : Neil D. Lawrence, 2006\n% \n% MODIFIED : Pei Gao, 2008\n%\n% SEEALSO : gpsimMapFunctionalExpandParam, gpsimMapCreate\n\n% SHEFFIELDML\n\n% Remove mean function value from m (if mean function present).\nif isfield(model, 'meanFunction') & ~isempty(model.meanFunction)\n f = model.f + modelOut(model.meanFunction, model.mapt);\nelse\n f = model.f;\nend\n\n% make sure f is a column vector\nf = reshape(f, length(f), 1);\n\nif model.ngParam == 0\n\nswitch model.nonLinearity\n case 'linear'\n model.g=f; %linear case \n model.g_grad=ones(size(model.g));\n model.g_grad2=zeros(size(model.g));\n model.g_grad3=zeros(size(model.g));\n model.isConcave = true; % Is the log likelihood concave?\n case 'exp'\n model.g=exp(f); %positive TF concentrations\n% model.gParam\n% if ~isempty(model.gParam)\n% model.ngParam = length(model.gParam(1,:));\n% model.dg = [];\n% model.dg2 = [];\n% end \n model.g_grad=model.g;\n model.g_grad2=model.g;\n model.g_grad3=model.g;\n model.isConcave = true;\n case 'quadratic'\n model.g=f.*f;\n model.g_grad=2*f;\n model.g_grad2=2*ones(size(f));\n model.isConcave = false;\n case 'negLogLogit'\n model.g=log(1+exp(f)); %positive TF concentrations\n model.g_grad=sigmoid(f);\n model.g_grad2=model.g_grad.*(1-model.g_grad);\n model.isConcave = true;\n case 'sigmoid'\n model.g = sigmoid(f);\n model.g_grad = model.g.*(1 - model.g);\n model.g_grad2 = model.g.*(1-model.g) - 2*model.g.*(model.g.*(1-model.g));\n model.isConcave = false;\n case 'repression'\n model.g = gpsimModelFunctions(model,'g');\n model.g_grad = gpsimModelFunctions(model,'grad');\n model.g_grad2 = gpsimModelFunctions(model,'grad2');\n model.g_grad3 = gpsimModelFunctions(model,'grad3');;\n model.isConcave = true; %% ??\n case 'activation'\n model.g = gpsimModelFunctions(model,'g');\n model.g_grad = gpsimModelFunctions(model,'grad');\n model.g_grad2 = gpsimModelFunctions(model,'grad2');\n model.g_grad3 = gpsimModelFunctions(model,'grad3');\n model.isConcave = true; %% ??\n if ~isempty(model.gParam)\n model.ngParam = length(model.gParam(1,:));\n model.dg = gpsimModelFunctions(model,'paramGrad');\n model.dg2 = gpsimModelFunctions(model,'paramGrad2');\n end \n otherwise\n error('Invalid non-linearity.')\nend\n\nelse\n model.g = gpsimModelFunctions(model,'g');\n model.g_grad = gpsimModelFunctions(model,'grad');\n model.g_grad2 = gpsimModelFunctions(model,'grad2');\n model.g_grad3 = gpsimModelFunctions(model,'grad3');\n model.isConcave = true;\n model.dg = gpsimModelFunctions(model,'paramGrad');\n model.dggrad = gpsimModelFunctions(model,'paramGgrad');\n model.dggrad2 = gpsimModelFunctions(model,'paramGgrad2');\nend\n\n\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/gpsim/gpsimMapUpdateG.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4905588358589976}} {"text": "%% Grain Tutorial\n%\n%%\n% The following script is a quick guide through the grain reconstruction\n% capabilities of MTEX. It uses the same data set as in the corresponding\n% publication\n% . Data courtesy of Daniel Rutte\n% and Bret Hacker, Stanford.\n\nmtexdata mylonite\n\n% plot a phase map\nplot(ebsd)\n\n%%\n% The phase map shows a multi-phase rock specimen with Andesina, Quartz,\n% Biotite and Orthoclase. Lets restrict it to a smaller region of interest.\n% The rectangle is defined by [xmin, ymin, xmax-xmin, ymax-ymin].\n\nregion = [19000 1500 4000 1500];\n% overlay the selected region on the phase map\nrectangle('position',region,'edgecolor','k','linewidth',2)\n\n%%\n% Now copy the EBSD data within the selected rectangle to a new variable\n\nebsd_region = ebsd(inpolygon(ebsd,region))\n\n%% Grain Reconstruction\n% Next we reconstruct the grains and grain boundaries in the region of\n% interest, using a 15 degree orientation change threshold.\n\ngrains = calcGrains(ebsd_region,'angle',15*degree)\n\n% plot a phase map of the region of interest\nplot(ebsd_region)\n\n% overlay the grain boundaries\nhold on\nplot(grains.boundary,'color','k','linewidth',1.5)\nhold off\n\n%%\n% We may also visualize the different quarz orientations together with the\n% grain boundaries.\n\n% plot a phase map of three of the phases based on the grains data \nplot(grains({'Andesina','Biotite','Orthoclase'}),'FaceAlpha',0.4)\n\nhold on\n% add the quarz orientations as ipf map based on EBSD data\nplot(ebsd_region('Quartz'),ebsd_region('Quartz').orientations)\n\n% plot grain boundaries so that those in the Quartz are shown\nplot(grains.boundary,'color','black');\nlegend off\nhold off\n\n%%\n% For the map created, most of the phases are coloured based on where they\n% exist, while only the Quartz phase is colored according to the\n% orientation. The quartz orientations are colured using the following ipf\n% color key\n\nclose all\nipfKey = ipfColorKey(ebsd_region('Quartz'));\nplot(ipfKey)\n\n\n%%\n% Alternatively, we may colorize each quarz grain according to its mean\n% orientation. Again, the other phases are colured based on where they\n% exist.\n\nplot(grains({'Andesina','Biotite','Orthoclase'}),'FaceAlpha',0.4)\nhold on\nplot(grains('Quartz'),grains('Quartz').meanOrientation)\nlegend off\n\n\n%% Highlight specific boundaries\n% We can create a phase map with certain grain boundaries highlighted. In\n% this case, we highlight where adjacent grains of Andesina and Orthoclase\n% have a misorientation with rotational axis close to the c-axis.\n\nclose all\n% copy all boundaries between Andesina Orthoclase to a new variable\nAOboundary = grains.boundary('Andesina','Orthoclase');\n% copy the misorientation angle of this boundary in radians to a new variable.\nangle = AOboundary.misorientation.angle;\n\nplot(grains,'FaceAlpha',0.4)\nhold on\n% highlight boundaries where the angle between the Andesina and Orthoclase phase is over 160 degrees\nplot(AOboundary(angle>160*degree),'linewidth',2,'linecolor','red')\nhold off\n\n%%\n% We can also represent the angular misorientation data between these two\n% phases as a histogram.\n\nfigure;histogram(angle./degree)\nxlabel('angle in degrees of boundary segment')\nylabel('count of boundary segments')\ntitle('angular relationships between Andesina and Orthoclase')\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/Tutorials/GrainTutorial.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.4905128150971881}} {"text": "function det = sgbdi ( abd, lda, n, ml, mu, ipvt )\n\n%*****************************************************************************80\n%\n%% SGBDI computes the determinant of a band matrix factored by SGBCO or SGBFA.\n%\n% Discussion:\n%\n% If the inverse is needed, use SGBSL N times.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 November 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Dongarra, Moler, Bunch and Stewart,\n% LINPACK User's Guide,\n% SIAM, (Society for Industrial and Applied Mathematics),\n% 3600 University City Science Center,\n% Philadelphia, PA, 19104-2688.\n% ISBN 0-89871-172-X\n%\n% Parameters:\n%\n% Input, real ABD(LDA,N), the output from SGBCO or SGBFA.\n%\n% Input, integer LDA, the leading dimension of the array ABD.\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, integer ML, MU, the number of diagonals below and above the\n% main diagonal. 0 <= ML < N, 0 <= MU < N.\n%\n% Input, integer IPVT(N), the pivot vector from SGBCO or SGBFA.\n%\n% Output, real DET(2), the determinant of the original matrix.\n% determinant = DET(1) * 10.0**DET(2)\n% with 1.0 <= abs ( DET(1) ) < 10.0 or DET(1) = 0.0.\n%\n ten = 10.0;\n\n m = ml + mu + 1;\n det(1) = 1.0;\n det(2) = 0.0;\n\n for i = 1 : n\n\n if ( ipvt(i) ~= i )\n det(1) = -det(1);\n end\n\n det(1) = abd(m,i) * det(1);\n\n if ( det(1) == 0.0 )\n return\n end\n\n while ( abs ( det(1) ) < 1.0 )\n det(1) = ten * det(1);\n det(2) = det(2) - 1.0;\n end\n\n while ( ten <= abs ( det(1) ) )\n det(1) = det(1) / ten;\n det(2) = det(2) + 1.0;\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linpack_s/sgbdi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.4904936632314789}} {"text": "function best_weights = GetBestMixingWeightForHarmonics(standard_deviation_list)\n% Best mixing of instantaneous frequencies with common mean\n% and built-in constraint (safeguard version designed for harmonics information mixing)\n%\n% best_weights = GetBestMixingWeightForHarmonics(sdListOrg)\n%\n% Input argument\n% standard_deviation_list : standard deviation of each variable\n%\n% Output argument\n% best_weights : best set of weights for mixing random variables\n%\n% Note\n% This mixing consists of heuristics. Re-design is needed.\n\n% Copyright 2016 Google Inc. All Rights Reserved.\n% Author: hidekik@google.com (Hideki Kawahara)\n\noriginal_list_length = length(standard_deviation_list);\nsafe_list = (1:original_list_length)';\nsafe_list = safe_list(standard_deviation_list > 0 & ...\n standard_deviation_list < 100 * min(abs(standard_deviation_list)));\nsdLsafe_SD_list = standard_deviation_list(safe_list);\nn_of_safe_SD = length(sdLsafe_SD_list);\nif n_of_safe_SD > 0\n H = ones(n_of_safe_SD-1, n_of_safe_SD-1) * sdLsafe_SD_list(n_of_safe_SD) ^ 2;\n H = H + diag(sdLsafe_SD_list(1:n_of_safe_SD - 1) .^ 2);\n v = ones(n_of_safe_SD - 1, 1) * sdLsafe_SD_list(n_of_safe_SD) ^ 2;\n a = H \\ v; % revised 23/May/2016 from inv(H) * v\n if sum(a) > 1\n a = a / sum(a);\n end;\n w = [a; 1 - sum(a)];\n best_weights = zeros(original_list_length, 1);\n best_weights(safe_list) = w;\nelse\n best_weights = zeros(original_list_length, 1);\n best_weights(1) = 1;\nend;\nend\n", "meta": {"author": "google", "repo": "yang_vocoder", "sha": "45787d4bbbb5b36617424b95c19430ced277db23", "save_path": "github-repos/MATLAB/google-yang_vocoder", "path": "github-repos/MATLAB/google-yang_vocoder/yang_vocoder-45787d4bbbb5b36617424b95c19430ced277db23/GetBestMixingWeightForHarmonics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4904131871907043}} {"text": "function [dist,proj] = ref_3d_projection(ref,EAST,NORTH,h)\n\n% SYNTAX:\n% [dist,proj] = ref_3d_projection(ref,EAST,NORTH,h)\n%\n% INPUT:\n% ref = reference path (X,Y,Z coordinates of the vertices)\n% EAST = estimated trajectory in UTM coordinates (EAST)\n% NORTH = estimated trajectory in UTM coordinates (NORTH)\n% h = ellipsoid height\n%\n% OUTPUT:\n% dist = 3D distance of each estimated point from the reference\n% proj = projected trajectory\n%\n% DESCRIPTION:\n% 3D projection on a reference path.\n% At the moment working only for adjacency matrix as in the following\n% example:\n%\n% adj_mat = [ 0 1 0 0 0 1\n% 1 0 1 0 0 0\n% 0 1 0 1 0 0\n% 0 0 1 0 1 0\n% 0 0 0 1 0 1\n% 1 0 0 0 1 0 ];\n\n%--- * --. --- --. .--. ... * ---------------------------------------------\n% ___ ___ ___\n% __ _ ___ / __| _ | __|\n% / _` / _ \\ (_ | _|__ \\\n% \\__, \\___/\\___|_| |___/\n% |___/ v 1.0RC1\n%\n%--------------------------------------------------------------------------\n% Copyright (C) 2021 Geomatics Research & Development srl (GReD)\n% Written by:\n% Contributors: ...\n% A list of all the historical goGPS contributors is in CREDITS.nfo\n%--------------------------------------------------------------------------\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n%--------------------------------------------------------------------------\n% 01100111 01101111 01000111 01010000 01010011\n%--------------------------------------------------------------------------\n\n%close the path by connecting the first and the last points\nref = [ref;ref(1,:)];\n\n%computation of the angular coefficients\nax = ref(2:end,1) - ref(1:end-1,1);\nay = ref(2:end,2) - ref(1:end-1,2);\naz = ref(2:end,3) - ref(1:end-1,3);\n\n%normalization on the segment distance\nad = sqrt(ax.^2 + ay.^2 + az.^2);\nax = ax ./ ad;\nay = ay ./ ad;\naz = az ./ ad;\n\n%offset of the curvilinear coordinate\ns0 = [0; cumsum(ad)];\n\nfor j = 1 : length(EAST)\n pos_R(1) = EAST(j);\n pos_R(2) = NORTH(j);\n pos_R(3) = h(j);\n\n d0 = sqrt((pos_R(1) - ref(:,1)).^2 + ...\n (pos_R(2) - ref(:,2)).^2 + ...\n (pos_R(3) - ref(:,3)).^2);\n\n [dmin0 i0] = min(d0);\n\n %projection on the reference path\n bx = pos_R(1) - ref(1:end-1,1) + ax.*s0(1:end-1);\n by = pos_R(2) - ref(1:end-1,2) + ay.*s0(1:end-1);\n bz = pos_R(3) - ref(1:end-1,3) + az.*s0(1:end-1);\n\n s_R = (ax.*bx + ay.*by + az.*bz) ./ (ax.^2 + ay.^2 + az.^2);\n\n pos_R_proj(:,1) = ref(1:end-1,1) + ax .* (s_R - s0(1:end-1));\n pos_R_proj(:,2) = ref(1:end-1,2) + ay .* (s_R - s0(1:end-1));\n pos_R_proj(:,3) = ref(1:end-1,3) + az .* (s_R - s0(1:end-1));\n\n %computation of the minimum distance\n d = sqrt((pos_R(1) - pos_R_proj(:,1)).^2 + ...\n (pos_R(2) - pos_R_proj(:,2)).^2 + ...\n (pos_R(3) - pos_R_proj(:,3)).^2);\n\n [dmin i] = min(d);\n\n %position in cartesian coordinates\n while (dmin < dmin0) & ((pos_R_proj(i,1) < min(ref(i,1),ref(i+1,1))) | (pos_R_proj(i,1) > max(ref(i,1),ref(i+1,1))) | ...\n (pos_R_proj(i,2) < min(ref(i,2),ref(i+1,2))) | (pos_R_proj(i,2) > max(ref(i,2),ref(i+1,2))) | ...\n (pos_R_proj(i,3) < min(ref(i,3),ref(i+1,3))) | (pos_R_proj(i,3) > max(ref(i,3),ref(i+1,3))))\n\n d(i) = 9e99;\n [dmin i] = min(d);\n\n end\n\n if dmin0 < dmin\n dist(j,1) = dmin0;\n\n proj(j,1) = ref(i0,1);\n proj(j,2) = ref(i0,2);\n proj(j,3) = ref(i0,3);\n\n else\n dist(j,1) = dmin;\n\n proj(j,1) = pos_R_proj(i,1);\n proj(j,2) = pos_R_proj(i,2);\n proj(j,3) = pos_R_proj(i,3);\n end\nend\n", "meta": {"author": "goGPS-Project", "repo": "goGPS_MATLAB", "sha": "30644df61d2459e3347ac5f3e31b71d9f69f4b01", "save_path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB", "path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB/goGPS_MATLAB-30644df61d2459e3347ac5f3e31b71d9f69f4b01/source/utility/ref_3d_projection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.49038084994178366}} {"text": "function outpoints = mni2tal(inpoints)\n% Converts coordinates from MNI brain to best guess\n% for equivalent Talairach coordinates\n% FORMAT outpoints = mni2tal(inpoints)\n% Where inpoints is N by 3 or 3 by N matrix of coordinates\n% (N being the number of points)\n% outpoints is the coordinate matrix with Talairach points\n% Matthew Brett 10/8/99\n\ndimdim = find(size(inpoints) == 3);\nif isempty(dimdim)\n ft_error('input must be a N by 3 or 3 by N matrix')\nend\nif dimdim == 2\n inpoints = inpoints';\nend\n\n% Transformation matrices, different zooms above/below AC\nupT = [\n 0.9900 0.0000 0.0000 0.0000\n 0.0000 0.9688 0.0460 0.0000\n 0.0000 -0.0485 0.9189 0.0000\n 0.0000 0.0000 0.0000 1.0000\n ];\n\ndownT = [\n 0.9900 0.0000 0.0000 0.0000\n 0.0000 0.9688 0.0420 0.0000\n 0.0000 -0.0485 0.8390 0.0000\n 0.0000 0.0000 0.0000 1.0000\n ];\n\ntmp = inpoints(3,:)<0; % 1 if below AC\ninpoints = [inpoints; ones(1, size(inpoints, 2))];\ninpoints(:, tmp) = downT * inpoints(:, tmp);\ninpoints(:, ~tmp) = upT * inpoints(:, ~tmp);\noutpoints = inpoints(1:3, :);\nif dimdim == 2\n outpoints = outpoints';\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/private/mni2tal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199592797929, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.49009240495827033}} {"text": "function dC=dervar3(C,n)\n\n%DERVAR3 for core rotations\n%\n%function dC=dervar3(C,n)\n%\n%This function determines the derivative of the nth mode of\n%the core rotation expression for the 3-way case w.r.t.\n%maximization of the variance of the core\n%\n%This version has been optimized for speed, see below for a\n%more easy to read scheme.\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\n% $ Version 2.00 $ May 2001 $ Changed to array notation $ RB $ Not compiled $\n\nW = size(C);\nC = reshape(C,W(1),prod(W(2:end)));\n\nmc = mean(mean(C.^2));\nE = (C.^2 - mc).*C;\ndC = zeros(W(n),W(n));\nW1 = W(1);\nW2 = W(2);\nW3 = W(3);\n\nif n==1,\n for a=1:W1,\n for b=1:W1,\n \n dc=0;\n for j=1:W3,\n tmp_0 = W2*(j-1);\n idxja = [1:W2] + tmp_0;\n dc = dc + sum(C(b,idxja).*E(a,idxja));\n end;\n \n dC(a,b) = dc;\n end;\n end;\nend;\n\nif n==2,\n for a=1:W2,\n for b=1:W2,\n \n dc=0;\n for j=1:W3,\n tmp_1 = W2*(j-1);\n idxja = a + tmp_1;\n idxjb = b + tmp_1;\n dc = dc + sum(C(:,idxjb).*E(:,idxja));\n end;\n \n dC(a,b) = dc;\n end;\n end;\nend; \t\n\nif n==3,\n for a=1:W3,\n tmp_2 = W2*(a-1);\n for b=1:W3,\n tmp_3 = W2*(b-1);\n \n dc=0;\n for j=1:W2,\n idxja = j + tmp_2;\n idxjb = j + tmp_3;\n dc = dc + sum(C(:,idxjb).*E(:,idxja));\n end;\n \n dC(a,b) = dc;\n end;\n end;\nend; \n\n\n%----------------------------------------------------------------------------------------\n%function dC=dervar3(C,W,n)\n%\n%%function dC=dervar3(C,W,n)\n%\n%%This function determines the derivative of the nth mode of\n%%the core rotation expression for the 3-way case w.r.t.\n%%maximization of the variance of the core\n%\n%mc=mean(mean(C.^2));\n%dC=zeros(W(n),W(n));\n%\n%if n==1,\n% for a=1:W(1),\n% for b=1:W(1),\n% \n% dc=0;\n% for i=1:W(2),\n% for j=1:W(3),\n% [idxia idxja]=getindxn(W,[a i j]);\n% [idxib idxjb]=getindxn(W,[b i j]);\n% dc = dc + (C(idxia,idxja)^2 - mc)*C(idxib,idxjb)*C(idxia,idxja);\n% end;\n% end;\n% \n% dC(a,b) = dc;\n% end;\n% end;\n%end;\n%\n%if n==2,\n% for a=1:W(2),\n% for b=1:W(2),\n% \n% dc=0;\n% for i=1:W(1),\n% for j=1:W(3),\n% [idxia idxja]=getindxn(W,[i a j]);\n% [idxib idxjb]=getindxn(W,[i b j]);\n% dc = dc + (C(idxia,idxja)^2 - mc)*C(idxib,idxjb)*C(idxia,idxja);\n% end;\n% end;\n% \n% dC(a,b) = dc;\n% end;\n% end;\n%end; \t\n%\n%if n==3,\n% for a=1:W(3),\n% for b=1:W(3),\n% \n% dc=0;\n% for i=1:W(1),\n% for j=1:W(2),\n% [idxia idxja]=getindxn(W,[i j a]);\n% [idxib idxjb]=getindxn(W,[i j b]);\n% dc = dc + (C(idxia,idxja)^2 - mc)*C(idxib,idxjb)*C(idxia,idxja);\n% end;\n% end;\n% \n% dC(a,b) = dc;\n% end;\n% end;\n%end;", "meta": {"author": "andrewssobral", "repo": "mtt", "sha": "0152a77df09f24af4c294f46845931e4e0e63b55", "save_path": "github-repos/MATLAB/andrewssobral-mtt", "path": "github-repos/MATLAB/andrewssobral-mtt/mtt-0152a77df09f24af4c294f46845931e4e0e63b55/libs/nway331/dervar3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.490092402586565}} {"text": "function Matdetec2 = findMatdetecFootprint(DetectFootPrint,XPsizeOut,YPsizeOut)\n% Fixed the calculation of footprint of Sentinel-2 detector based on old\n% version of Sentinel-2 data (17/12/2021 Shi)\n\nclear Matdetec k\n% sorted foot print from 1 to 4\n[DetectFootPrint.Ndect, idnews] = sort(DetectFootPrint.Ndect);\nDetectFootPrint.Nband = DetectFootPrint.Nband(idnews);\nDetectFootPrint.Data = DetectFootPrint.Data(idnews);\n\nfor i = 1:length(DetectFootPrint.Ndect)\n \n IDX = knnsearch(XPsizeOut',DetectFootPrint.Data{i,1}(:,1));\n IDY = knnsearch(YPsizeOut,DetectFootPrint.Data{i,1}(:,2));\n \n dum2 = single(poly2mask(double(IDX), double(IDY),length(XPsizeOut),length(XPsizeOut))) ;\n clear IDX IDY;\n dum2 = conv2(dum2,ones(3),'same')>0; % to fill boundary\n Matdetec(:,:,i) = dum2;\n clear dum*\n \n % find orientation of detect + slope for computing perpendicular kernel\n I=nan(size(Matdetec,2),1);\n for ii=1:size(Matdetec,1)\n dum=find(Matdetec(ii,:,i)==1,1,'first');\n if ~isempty(dum)\n I(ii,1)=dum;\n end\n end\n clear dum;\n J = [1:size(Matdetec,1)]' ;\n test = ~isnan(I) & I > 1 & I < size(Matdetec,2);\n warning off all % if warning => not enough point => slope=0 => good because tile boundary\n k{i,1} = polyfit(J(test),I(test),1);\n clear test;\n \n I=nan(size(Matdetec,2),1);\n for ii=1:size(Matdetec,1)\n dum=find(Matdetec(ii,:,i)==1,1,'last');\n if ~isempty(dum)\n I(ii,1)=dum;\n end\n end\n J = [1:size(Matdetec,1)]' ;\n test = ~isnan(I) & I > 1 & I < size(Matdetec,2);\n k{i,2} = polyfit(J(test),I(test),1);\n clear test;\n warning on all\n\nend\n\n% mediane\nfor i = 1:length(DetectFootPrint.Ndect)-1\n mediane = mean( [k{i,2} ; k{i+1,1}] ) ;\n \n k{i,2} = mediane ;\n k{i+1,1} = mediane ;\n clear mediane;\nend\nJ = [1:size(Matdetec,1)]' ;\nI = [1:size(Matdetec,2)] ;\n\n[Jmat Imat] = meshgrid(I,J);\nclear I J;\n\nMatdetec2 = nan(size(Matdetec,1),size(Matdetec,2));\nclear Matdetec;\nfor i = 1:length(DetectFootPrint.Ndect)\n \n liminf = polyval(k{i,1},Jmat);\n limsup = polyval(k{i,2},Jmat);\n \n if sum(k{i,2}) == 0 % footprint at low-right corner\n Matdetec2(Imat>=liminf) = DetectFootPrint.Ndect(i) ;\n elseif sum(k{i,1}) == 0 % footprint at up-left corner\n Matdetec2(Imat<=limsup) = DetectFootPrint.Ndect(i) ;\n else\n Matdetec2(Imat>=liminf & Imat<=limsup) = DetectFootPrint.Ndect(i) ;\n end\n clear liminf limsup;\nend\nclear Imat ImatJ k;\n\nMatdetec2 = Matdetec2';\n\n\n", "meta": {"author": "GERSL", "repo": "Fmask", "sha": "e9e0e23af163ec55c60b7f93e6ab8e72617ee851", "save_path": "github-repos/MATLAB/GERSL-Fmask", "path": "github-repos/MATLAB/GERSL-Fmask/Fmask-e9e0e23af163ec55c60b7f93e6ab8e72617ee851/findMatdetecFootprint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.490092402586565}} {"text": "%% DEMO_febio_0005_cube_tension_compression_shear\n% Below is a demonstration for:\n% \n% * Building geometry for a cube with hexahedral elements\n% * Defining the boundary conditions \n% * Coding the febio structure\n% * Running the model\n% * Importing and visualizing the displacement and stress results\n\n%% Keywords\n%\n% * febio_spec version 3.0\n% * febio, FEBio\n% * compression, tension, compressive, tensile, shear\n% * displacement control, displacement boundary condition\n% * hexahedral elements, hex8\n% * cube, box, rectangular\n% * static, solid\n% * hyperelastic, Ogden\n% * displacement logfile\n% * stress logfile\n\n%%\n\nclear; close all; clc;\n\n%% Plot settings\nfontSize=20;\nfaceAlpha1=0.8;\nmarkerSize=40;\nmarkerSize2=20;\nlineWidth=3;\n\n%% Control parameters\n\n% Path names\ndefaultFolder = fileparts(fileparts(mfilename('fullpath')));\nsavePath=fullfile(defaultFolder,'data','temp');\n\n% Defining file names\nfebioFebFileNamePart='tempModel';\nfebioFebFileName=fullfile(savePath,[febioFebFileNamePart,'.feb']); %FEB file name\nfebioLogFileName=[febioFebFileNamePart,'.txt']; %FEBio log file name\nfebioLogFileName_disp=[febioFebFileNamePart,'_disp_out.txt']; %Log file name for exporting displacement\nfebioLogFileName_stress=[febioFebFileNamePart,'_stress_out.txt']; %Log file name for exporting stress\n\n%Specifying dimensions and number of elements\ncubeSize=10; \nsampleWidth=cubeSize; %Width \nsampleThickness=cubeSize; %Thickness \nsampleHeight=cubeSize; %Height\npointSpacings=2*ones(1,3); %Desired point spacing between nodes\nnumElementsWidth=round(sampleWidth/pointSpacings(1)); %Number of elemens in dir 1\nnumElementsThickness=round(sampleThickness/pointSpacings(2)); %Number of elemens in dir 2\nnumElementsHeight=round(sampleHeight/pointSpacings(3)); %Number of elemens in dir 3\n\n%Define applied displacement \nstretchLoad=1.3;\ndisplacementMagnitude=(stretchLoad*sampleHeight)-sampleHeight; %The displacement magnitude\n\n%Material parameter set\nc1=1e-3; %Shear-modulus-like parameter\nm1=8; %Material parameter setting degree of non-linearity\nk_factor=1e2; %Bulk modulus factor \nk=c1*k_factor; %Bulk modulus\n\n% FEA control settings\nnumTimeSteps=10; %Number of time steps desired\nmax_refs=25; %Max reforms\nmax_ups=0; %Set to zero to use full-Newton iterations\nopt_iter=6; %Optimum number of iterations\nmax_retries=5; %Maximum number of retires\ndtmin=(1/numTimeSteps)/100; %Minimum time step size\ndtmax=1/numTimeSteps; %Maximum time step size\n\n%% Creating model geometry and mesh\n% A box is created with tri-linear hexahedral (hex8) elements using the\n% |hexMeshBox| function. The function offers the boundary faces with\n% seperate labels for the top, bottom, left, right, front, and back sides.\n% As such these can be used to define boundary conditions on the exterior. \n\n% Create a box with hexahedral elements\ncubeDimensions=[sampleWidth sampleThickness sampleHeight]; %Dimensions\ncubeElementNumbers=[numElementsWidth numElementsThickness numElementsHeight]; %Number of elements\noutputStructType=2; %A structure compatible with mesh view\n[meshStruct]=hexMeshBox(cubeDimensions,cubeElementNumbers,outputStructType);\n\n%Access elements, nodes, and faces from the structure\nE=meshStruct.elements; %The elements \nV=meshStruct.nodes; %The nodes (vertices)\nFb=meshStruct.facesBoundary; %The boundary faces\nCb=meshStruct.boundaryMarker; %The \"colors\" or labels for the boundary faces\nelementMaterialIndices=ones(size(E,1),1); %Element material indices\n\n%% \n% Plotting model boundary surfaces and a cut view\n\nhFig=cFigure; \n\nsubplot(1,2,1); hold on; \ntitle('Model boundary surfaces and labels','FontSize',fontSize);\ngpatch(Fb,V,Cb,'k',faceAlpha1); \ncolormap(gjet(6)); icolorbar;\naxisGeom(gca,fontSize);\n\nhs=subplot(1,2,2); hold on; \ntitle('Cut view of solid mesh','FontSize',fontSize);\noptionStruct.hFig=[hFig hs];\nmeshView(meshStruct,optionStruct);\naxisGeom(gca,fontSize);\n\ndrawnow;\n\n%% Defining the boundary conditions\n% The visualization of the model boundary shows colors for each side of the\n% cube. These labels can be used to define boundary conditions. \n\n%Define supported node sets\nlogicFace=Cb==5; %Logic for current face set\nFr=Fb(logicFace,:); %The current face set\nbcSupportList=unique(Fr(:)); %Node set part of selected face\n\n%Prescribed displacement nodes\nlogicPrescribe=Cb==6; %Logic for current face set\nFr=Fb(logicPrescribe,:); %The current face set\nbcPrescribeList=unique(Fr(:)); %Node set part of selected face\n\n%% \n% Visualizing boundary conditions. Markers plotted on the semi-transparent\n% model denote the nodes in the various boundary condition lists. \n\nhf=cFigure;\ntitle('Boundary conditions','FontSize',fontSize);\nxlabel('X','FontSize',fontSize); ylabel('Y','FontSize',fontSize); zlabel('Z','FontSize',fontSize);\nhold on;\n\ngpatch(Fb,V,'kw','k',0.5);\n\nhl(1)=plotV(V(bcSupportList,:),'k.','MarkerSize',markerSize);\nhl(2)=plotV(V(bcPrescribeList,:),'r.','MarkerSize',markerSize);\n\nlegend(hl,{'BC support','BC prescribe'});\n\naxisGeom(gca,fontSize);\ncamlight headlight; \ndrawnow; \n\n%% Defining the FEBio input structure\n% See also |febioStructTemplate| and |febioStruct2xml| and the FEBio user\n% manual.\n\n%Get a template with default settings \n[febio_spec]=febioStructTemplate;\n\n%febio_spec version \nfebio_spec.ATTR.version='3.0'; \n\n%Module section\nfebio_spec.Module.ATTR.type='solid'; \n\n%Create control structure for use by all steps\nstepStruct.Control.time_steps=numTimeSteps;\nstepStruct.Control.step_size=1/numTimeSteps;\nstepStruct.Control.solver.max_refs=max_refs;\nstepStruct.Control.solver.max_ups=max_ups;\nstepStruct.Control.time_stepper.dtmin=dtmin;\nstepStruct.Control.time_stepper.dtmax=dtmax; \nstepStruct.Control.time_stepper.max_retries=max_retries;\nstepStruct.Control.time_stepper.opt_iter=opt_iter;\n\n%Add template based default settings to proposed control section\n[stepStruct.Control]=structComplete(stepStruct.Control,febio_spec.Control,1); %Complement provided with default if missing\n\n%Remove control field (part of template) since step specific control sections are used\nfebio_spec=rmfield(febio_spec,'Control'); \n\nfebio_spec.Step.step{1}.Control=stepStruct.Control;\nfebio_spec.Step.step{1}.ATTR.id=1;\nfebio_spec.Step.step{2}.Control=stepStruct.Control;\nfebio_spec.Step.step{2}.ATTR.id=2;\nfebio_spec.Step.step{3}.Control=stepStruct.Control;\nfebio_spec.Step.step{3}.ATTR.id=3;\nfebio_spec.Step.step{4}.Control=stepStruct.Control;\nfebio_spec.Step.step{4}.ATTR.id=4;\nfebio_spec.Step.step{5}.Control=stepStruct.Control;\nfebio_spec.Step.step{5}.ATTR.id=5;\n\n%Material section\nmaterialName1='Material1';\nfebio_spec.Material.material{1}.ATTR.name=materialName1;\nfebio_spec.Material.material{1}.ATTR.type='Ogden';\nfebio_spec.Material.material{1}.ATTR.id=1;\nfebio_spec.Material.material{1}.c1=c1;\nfebio_spec.Material.material{1}.m1=m1;\nfebio_spec.Material.material{1}.c2=c1;\nfebio_spec.Material.material{1}.m2=-m1;\nfebio_spec.Material.material{1}.k=k;\n\n% Mesh section\n% -> Nodes\nfebio_spec.Mesh.Nodes{1}.ATTR.name='Object1'; %The node set name\nfebio_spec.Mesh.Nodes{1}.node.ATTR.id=(1:size(V,1))'; %The node id's\nfebio_spec.Mesh.Nodes{1}.node.VAL=V; %The nodel coordinates\n\n% -> Elements\npartName1='Part1';\nfebio_spec.Mesh.Elements{1}.ATTR.name=partName1; %Name of this part\nfebio_spec.Mesh.Elements{1}.ATTR.type='hex8'; %Element type\nfebio_spec.Mesh.Elements{1}.elem.ATTR.id=(1:1:size(E,1))'; %Element id's\nfebio_spec.Mesh.Elements{1}.elem.VAL=E; %The element matrix\n \n% -> NodeSets\nnodeSetName1='bcSupportList';\nnodeSetName2='bcPrescribeList';\n\nfebio_spec.Mesh.NodeSet{1}.ATTR.name=nodeSetName1;\nfebio_spec.Mesh.NodeSet{1}.node.ATTR.id=bcSupportList(:);\n\nfebio_spec.Mesh.NodeSet{2}.ATTR.name=nodeSetName2;\nfebio_spec.Mesh.NodeSet{2}.node.ATTR.id=bcPrescribeList(:);\n \n%MeshDomains section\nfebio_spec.MeshDomains.SolidDomain.ATTR.name=partName1;\nfebio_spec.MeshDomains.SolidDomain.ATTR.mat=materialName1;\n\n%Boundary condition section \n%-> Fix boundary conditions\nfebio_spec.Boundary.bc{1}.ATTR.type='fix';\nfebio_spec.Boundary.bc{1}.ATTR.node_set=nodeSetName1;\nfebio_spec.Boundary.bc{1}.dofs='x,y,z';\n\n%STEP 1 Tension\nfebio_spec.Step.step{1}.Boundary.bc{1}.ATTR.type='prescribe';\nfebio_spec.Step.step{1}.Boundary.bc{1}.ATTR.node_set=nodeSetName2;\nfebio_spec.Step.step{1}.Boundary.bc{1}.dof='z';\nfebio_spec.Step.step{1}.Boundary.bc{1}.scale.ATTR.lc=1;\nfebio_spec.Step.step{1}.Boundary.bc{1}.scale.VAL=displacementMagnitude;\nfebio_spec.Step.step{1}.Boundary.bc{1}.relative=1;\n\nfebio_spec.Step.step{1}.Boundary.bc{2}.ATTR.type='fix';\nfebio_spec.Step.step{1}.Boundary.bc{2}.ATTR.node_set=nodeSetName2;\nfebio_spec.Step.step{1}.Boundary.bc{2}.dofs='x,y';\n\n%STEP 2 Return form tension\nfebio_spec.Step.step{2}.Boundary.bc{1}.ATTR.type='prescribe';\nfebio_spec.Step.step{2}.Boundary.bc{1}.ATTR.node_set=nodeSetName2;\nfebio_spec.Step.step{2}.Boundary.bc{1}.dof='z';\nfebio_spec.Step.step{2}.Boundary.bc{1}.scale.ATTR.lc=2;\nfebio_spec.Step.step{2}.Boundary.bc{1}.scale.VAL=-displacementMagnitude;\nfebio_spec.Step.step{2}.Boundary.bc{1}.relative=1;\n\nfebio_spec.Step.step{2}.Boundary.bc{2}.ATTR.type='fix';\nfebio_spec.Step.step{2}.Boundary.bc{2}.ATTR.node_set=nodeSetName2;\nfebio_spec.Step.step{2}.Boundary.bc{2}.dofs='x,y';\n\n%STEP 3 Compression\nfebio_spec.Step.step{3}.Boundary.bc{1}.ATTR.type='prescribe';\nfebio_spec.Step.step{3}.Boundary.bc{1}.ATTR.node_set=nodeSetName2;\nfebio_spec.Step.step{3}.Boundary.bc{1}.dof='z';\nfebio_spec.Step.step{3}.Boundary.bc{1}.scale.ATTR.lc=3;\nfebio_spec.Step.step{3}.Boundary.bc{1}.scale.VAL=-displacementMagnitude;\nfebio_spec.Step.step{3}.Boundary.bc{1}.relative=1;\n\nfebio_spec.Step.step{3}.Boundary.bc{2}.ATTR.type='fix';\nfebio_spec.Step.step{3}.Boundary.bc{2}.ATTR.node_set=nodeSetName2;\nfebio_spec.Step.step{3}.Boundary.bc{2}.dofs='x,y';\n\n%STEP 4 Return from compression\nfebio_spec.Step.step{4}.Boundary.bc{1}.ATTR.type='prescribe';\nfebio_spec.Step.step{4}.Boundary.bc{1}.ATTR.node_set=nodeSetName2;\nfebio_spec.Step.step{4}.Boundary.bc{1}.dof='z';\nfebio_spec.Step.step{4}.Boundary.bc{1}.scale.ATTR.lc=4;\nfebio_spec.Step.step{4}.Boundary.bc{1}.scale.VAL=displacementMagnitude;\nfebio_spec.Step.step{4}.Boundary.bc{1}.relative=1;\n\nfebio_spec.Step.step{4}.Boundary.bc{2}.ATTR.type='fix';\nfebio_spec.Step.step{4}.Boundary.bc{2}.ATTR.node_set=nodeSetName2;\nfebio_spec.Step.step{4}.Boundary.bc{2}.dofs='x,y';\n\n%STEP 5 Shear\nfebio_spec.Step.step{5}.Boundary.bc{1}.ATTR.type='prescribe';\nfebio_spec.Step.step{5}.Boundary.bc{1}.ATTR.node_set=nodeSetName2;\nfebio_spec.Step.step{5}.Boundary.bc{1}.dof='x';\nfebio_spec.Step.step{5}.Boundary.bc{1}.scale.ATTR.lc=5;\nfebio_spec.Step.step{5}.Boundary.bc{1}.scale.VAL=displacementMagnitude;\nfebio_spec.Step.step{5}.Boundary.bc{1}.relative=1;\n\nfebio_spec.Step.step{5}.Boundary.bc{2}.ATTR.type='fix';\nfebio_spec.Step.step{5}.Boundary.bc{2}.ATTR.node_set=nodeSetName2;\nfebio_spec.Step.step{5}.Boundary.bc{2}.dofs='y,z';\n\n%LoadData section\n% -> load_controller\nfebio_spec.LoadData.load_controller{1}.ATTR.id=1;\nfebio_spec.LoadData.load_controller{1}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{1}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{1}.points.point.VAL=[0 0; 1 1];\n\nfebio_spec.LoadData.load_controller{2}.ATTR.id=2;\nfebio_spec.LoadData.load_controller{2}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{2}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{2}.points.point.VAL=[1 0; 2 1];\n\nfebio_spec.LoadData.load_controller{3}.ATTR.id=3;\nfebio_spec.LoadData.load_controller{3}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{3}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{3}.points.point.VAL=[2 0; 3 1];\n\nfebio_spec.LoadData.load_controller{4}.ATTR.id=4;\nfebio_spec.LoadData.load_controller{4}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{4}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{4}.points.point.VAL=[3 0; 4 1];\n\nfebio_spec.LoadData.load_controller{5}.ATTR.id=5;\nfebio_spec.LoadData.load_controller{5}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{5}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{5}.points.point.VAL=[4 0; 5 1];\n\n%Output section \n% -> log file\nfebio_spec.Output.logfile.ATTR.file=febioLogFileName;\nfebio_spec.Output.logfile.node_data{1}.ATTR.file=febioLogFileName_disp;\nfebio_spec.Output.logfile.node_data{1}.ATTR.data='ux;uy;uz';\nfebio_spec.Output.logfile.node_data{1}.ATTR.delim=',';\nfebio_spec.Output.logfile.node_data{1}.VAL=1:size(V,1);\n\nfebio_spec.Output.logfile.element_data{1}.ATTR.file=febioLogFileName_stress;\nfebio_spec.Output.logfile.element_data{1}.ATTR.data='s1';\nfebio_spec.Output.logfile.element_data{1}.ATTR.delim=',';\nfebio_spec.Output.logfile.element_data{1}.VAL=1:size(E,1);\n\n%% Quick viewing of the FEBio input file structure\n% The |febView| function can be used to view the xml structure in a MATLAB\n% figure window. \n\n%%\n% |febView(febio_spec); %Viewing the febio file|\n\n%% Exporting the FEBio input file\n% Exporting the febio_spec structure to an FEBio input file is done using\n% the |febioStruct2xml| function. \n\nfebioStruct2xml(febio_spec,febioFebFileName); %Exporting to file and domNode\n\n%% Running the FEBio analysis\n% To run the analysis defined by the created FEBio input file the\n% |runMonitorFEBio| function is used. The input for this function is a\n% structure defining job settings e.g. the FEBio input file name. The\n% optional output runFlag informs the user if the analysis was run\n% succesfully. \n\nfebioAnalysis.run_filename=febioFebFileName; %The input file name\nfebioAnalysis.run_logname=febioLogFileName; %The name for the log file\nfebioAnalysis.disp_on=1; %Display information on the command window\nfebioAnalysis.runMode='external';%'internal';\n\n[runFlag]=runMonitorFEBio(febioAnalysis);%START FEBio NOW!!!!!!!!\n\n%% Import FEBio results \n\nif runFlag==1 %i.e. a succesful run\n \n %% \n % Importing nodal displacements from a log file\n dataStruct=importFEBio_logfile(fullfile(savePath,febioLogFileName_disp),1,1);\n \n %Access data\n N_disp_mat=dataStruct.data; %Displacement\n timeVec=dataStruct.time; %Time\n \n %Create deformed coordinate set\n V_DEF=N_disp_mat+repmat(V,[1 1 size(N_disp_mat,3)]);\n \n %%\n % Importing element stress from a log file\n dataStruct=importFEBio_logfile(fullfile(savePath,febioLogFileName_stress),1,1);\n \n %Access data\n E_stress_mat=dataStruct.data;\n \n %% \n % Plotting the simulated results using |anim8| to visualize and animate\n % deformations \n \n DN_magnitude=sqrt(sum(N_disp_mat(:,:,end).^2,2)); %Current displacement magnitude\n \n % Create basic view and store graphics handle to initiate animation\n hf=cFigure; %Open figure \n gtitle([febioFebFileNamePart,': Press play to animate']);\n title('Displacement magnitude [mm]','Interpreter','Latex')\n hp=gpatch(Fb,V_DEF(:,:,end),DN_magnitude,'k',1); %Add graphics object to animate\n hp.Marker='.';\n hp.MarkerSize=markerSize2;\n hp.FaceColor='interp';\n gpatch(Fb,V,0.5*ones(1,3),'k',0.25); %A static graphics object\n \n axisGeom(gca,fontSize); \n colormap(gjet(250)); colorbar;\n caxis([0 max(DN_magnitude)]); \n axis(axisLim(V_DEF)); %Set axis limits statically\n camlight headlight; \n \n % Set up animation features\n animStruct.Time=timeVec; %The time vector \n for qt=1:1:size(N_disp_mat,3) %Loop over time increments \n DN_magnitude=sqrt(sum(N_disp_mat(:,:,qt).^2,2)); %Current displacement magnitude\n \n %Set entries in animation structure\n animStruct.Handles{qt}=[hp hp]; %Handles of objects to animate\n animStruct.Props{qt}={'Vertices','CData'}; %Properties of objects to animate\n animStruct.Set{qt}={V_DEF(:,:,qt),DN_magnitude}; %Property values for to set in order to animate\n end \n anim8(hf,animStruct); %Initiate animation feature \n drawnow;\n \n %% \n % Plotting the simulated results using |anim8| to visualize and animate\n % deformations \n \n [CV]=faceToVertexMeasure(E,V,E_stress_mat(:,:,end));\n \n % Create basic view and store graphics handle to initiate animation\n hf=cFigure; %Open figure \n gtitle([febioFebFileNamePart,': Press play to animate']);\n title('$\\sigma_{1}$ [MPa]','Interpreter','Latex')\n hp=gpatch(Fb,V_DEF(:,:,end),CV,'k',1); %Add graphics object to animate\n hp.Marker='.';\n hp.MarkerSize=markerSize2;\n hp.FaceColor='interp';\n gpatch(Fb,V,0.5*ones(1,3),'k',0.25); %A static graphics object\n \n axisGeom(gca,fontSize); \n colormap(gjet(250)); colorbar;\n% caxis([min(E_stress_mat(:)) max(E_stress_mat(:))]); \n axis(axisLim(V_DEF)); %Set axis limits statically \n camlight headlight; \n \n % Set up animation features\n animStruct.Time=timeVec; %The time vector \n for qt=1:1:size(N_disp_mat,3) %Loop over time increments \n \n [CV]=faceToVertexMeasure(E,V,E_stress_mat(:,:,qt));\n \n %Set entries in animation structure\n animStruct.Handles{qt}=[hp hp]; %Handles of objects to animate\n animStruct.Props{qt}={'Vertices','CData'}; %Properties of objects to animate\n animStruct.Set{qt}={V_DEF(:,:,qt),CV}; %Property values for to set in order to animate\n end \n anim8(hf,animStruct); %Initiate animation feature \n drawnow;\n \nend\n\n%% \n%\n% <>\n% \n% _*GIBBON*_ \n% \n% \n% _Kevin Mattheus Moerman_, \n \n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/docs/DEMO_febio_0005_cube_tension_compression_shear.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.760650658103136, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.49003024082391866}} {"text": "%% faceToVertexMeasure\n% Below is a demonstration of the features of the |patchPathAngles| function\n\n%%\nclear; close all; clc;\n\n%% Syntax\n% |[indAngles]=faceToVertexMeasure(F,V,ind,isClosedLoop);|\n\n%% Description \n% The |faceToVertexMeasure| function converts data for faces to data on\n% vertices through averaging. \n\n%% Examples \n\n%%\n% Plot settings\nmarkerSize=150;\n\n%% Example 1: Convert face data to vertex data\n[F,V]=geoSphere(2,1);\nVF=patchCentre(F,V);\nCF=VF(:,1);\n[CV]=faceToVertexMeasure(F,V,CF);\n\n%%\n\ncFigure; \nsubplot(1,2,1); hold on;\ntitle('Color data on faces')\ngpatch(F,V,CF);\nscatterV(VF,markerSize,CF,'filled');\ncolormap gjet; colorbar; \naxisGeom;\ncamlight headlight; \n\nsubplot(1,2,2); hold on;\ntitle('Converted data on vertices')\nhp=gpatch(F,V,CV);\nhp.FaceColor='Interp';\nscatterV(V,markerSize,CV,'filled');\ncolormap gjet; colorbar; \naxisGeom;\ncamlight headlight; \n\ndrawnow; \n\n%% Example 2: Convert face data on a mixed mesh to vertex data\n\n%%\n% Create an example of a mixed mesh consisting of triangles and\n% quadrilateral faces. \n\n% Create a triangular mesh\n[F,V]=geoSphere(2,1);\n\n% Converting to a quadrilateral mesh\noptionStruct.maxAngleDeviation=45*(pi/180);\noptionStruct.selectionMethod='best';\noptionStruct.triangleConvert=0;\noptionStruct.fourConnectConvert=0;\n[F,V]=tri2quadGroupSplit(F,V,optionStruct);\n\nVF=patchCentre(F,V);\nCF=VF;\nfor q=1:1:numel(VF) \n CF{q}=VF{q}(:,1);\nend\n[CV]=faceToVertexMeasure(F,V,CF);\n\n%%\n\ncFigure; \nsubplot(1,2,1); hold on;\ntitle('Color data on faces')\ngpatch(F,V,CF);\nfor q=1:1:numel(VF)\n scatterV(VF{q},markerSize,CF{q},'filled');\nend\ncolormap gjet; colorbar; \naxisGeom;\ncamlight headlight; \n\nsubplot(1,2,2); hold on;\ntitle('Converted data on vertices')\nhp=gpatch(F,V,CV);\n% hp.FaceColor='Interp';\nscatterV(V,markerSize,CV,'filled');\ncolormap gjet; colorbar; \naxisGeom;\ncamlight headlight; \ndrawnow; \n\n%% Example 3: Convert multi-dimensional face data (e.g. on a mixed mesh) to vertex data\n\nN=patchNormal(F,V); %get face normals\nNV=faceToVertexMeasure(F,V,N); %Convert to vertex normals\n\n%%\n\nVF=patchCentre(F,V); %Get face centres for plotting\n\ncFigure; \nsubplot(1,2,1); hold on;\ntitle('Vector data on faces')\ngpatch(F,V,CF);\nfor q=1:1:numel(F)\n quiverVec(VF{q},N{q},0.25,'k');\nend\ncolormap gjet; colorbar; \naxisGeom;\ncamlight headlight; \n\nsubplot(1,2,2); hold on;\ntitle('Converted data on vertices')\ngpatch(F,V,CV);\nquiverVec(V,NV,0.25,'k');\ncolormap gjet; colorbar; \naxisGeom;\ncamlight headlight; \ndrawnow; \n\n%% \n%\n% <>\n% \n% _*GIBBON*_ \n% \n% \n% _Kevin Mattheus Moerman_, \n \n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/docs/HELP_faceToVertexMeasure.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.4898416729711988}} {"text": "%LAMBDA2RGB RGB chromaticity coordinates\n%\n% RGB = LAMBDA2RG(LAMBDA) is the rg-chromaticity coordinate (1x2) for \n% illumination at the specific wavelength LAMBDA [m]. If LAMBDA is a\n% vector (Nx1), then P (Nx2) is a vector whose elements are the chromaticity\n% coordinates at the corresponding elements of LAMBDA.\n%\n% RGB = LAMBDA2RG(LAMBDA, E) is the rg-chromaticity coordinate (1x2) for an \n% illumination spectrum E (Nx1) defined at corresponding wavelengths\n% LAMBDA (Nx1).\n%\n% References::\n% - Robotics, Vision & Control, Section 10.2,\n% P. Corke, Springer 2011.\n%\n% See also CMFRGB, LAMBDA2XY.\n\n\n\n% Copyright (C) 1993-2011, by Peter I. Corke\n%\n% This file is part of The Machine Vision Toolbox for Matlab (MVTB).\n% \n% MVTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% MVTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with MVTB. If not, see .\nfunction [r,g] = lambda2rg(lambda, e)\n if nargin == 1,\n RGB = cmfrgb(lambda);\n elseif nargin == 2,\n RGB = cmfrgb(lambda, e);\n end\n cc = tristim2cc(RGB);\n\n if nargout == 1\n r = cc;\n elseif nargout == 2\n r = cc(:,1);\n g = cc(:,2);\n end\n", "meta": {"author": "petercorke", "repo": "machinevision-toolbox-matlab", "sha": "2d791168c19c5e56acef74d22eafd227b4b58e42", "save_path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab/machinevision-toolbox-matlab-2d791168c19c5e56acef74d22eafd227b4b58e42/lambda2rg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.48984166350454994}} {"text": "function [lf] = eeg_halfspace_medium_leadfield(rd, elc, vol)\n\n% HALFSPACE_MEDIUM_LEADFIELD calculate the halfspace medium leadfield\n% on positions pnt for a dipole at position rd and conductivity cond\n% The halfspace solution requires a plane dividing a conductive zone of\n% conductivity cond, from a non coductive zone (cond = 0)\n% \n% [lf] = halfspace_medium_leadfield(rd, elc, cond)\n\n% Copyright (C) 2011, Cristiano Micheli and Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id: eeg_halfspace_medium_leadfield.m 2781 2011-02-03 10:48:53Z roboos $\n\nsiz = size(rd);\nif any(siz==1)\n % positions are specified as a single vector\n Ndipoles = prod(siz)/3;\n rd = rd(:)'; % ensure that it is a row vector\nelseif siz(2)==3\n % positions are specified as a Nx3 matrix -> reformat to a single vector\n Ndipoles = siz(1);\n rd = rd';\n rd = rd(:)'; % ensure that it is a row vector\nelse\n error('incorrect specification of dipole locations');\nend\n\nNelc = size(elc,1);\nlf = zeros(Nelc,3*Ndipoles);\n\nfor i=1:Ndipoles\n % this is the position of dipole \"i\"\n dip1 = rd((1:3) + 3*(i-1));\n \n % distances electrodes - dipole\n r1 = elc - ones(Nelc,1) * dip1;\n \n % Method of mirror dipoles:\n % Defines the position of mirror dipoles being symmetric to the plane\n dip2 = get_mirror_pos(dip1,vol);\n \n % distances electrodes - mirror dipole\n r2 = elc - ones(Nelc,1) * dip2;\n \n % denominator\n R1 = (4*pi*vol.cond) * (sum(r1' .^2 ) .^ 1.5)';\n % denominator, mirror term\n R2 = -(4*pi*vol.cond) * (sum(r2' .^2 ) .^ 1.5)';\n \n % condition of dipoles falling in the non conductive halfspace \n invacuum = acos(dot(vol.ori,(dip1-vol.pnt)./norm(dip1-vol.pnt))) < pi/2;\n \n if invacuum\n warning('dipole lies on the vacuum side of the plane');\n lf(:,(1:3) + 3*(i-1)) = NaN(Nelc,3);\n elseif any(R1)==0\n warning('dipole coincides with one of the electrodes');\n lf(:,(1:3) + 3*(i-1)) = NaN(Nelc,3);\n else\n lf(:,(1:3) + 3*(i-1)) = (r1 ./ [R1 R1 R1]) + (r2 ./ [R2 R2 R2]);\n end\nend\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/fieldtrip_partial/forward/private/eeg_halfspace_medium_leadfield.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.48969744585264263}} {"text": "function g = orderedNoiseGradientParam(noise, mu, varsigma, y)\n\n\n% ORDEREDNOISEGRADIENTPARAM Gradient of ORDERED noise's parameters.\n% FORMAT\n% DESC computes the gradient of the log Z of the ordered categorical noise model with respect to the of functions with respect to the\n% ordered categorical\n% noise's parameters. \n% ARG noise : the noise structure for which the gradients are being\n% computed.\n% ARG mu : the input means for which the gradients are being computed.\n% ARG varSigma : the input variances for which the gradients are being computed.\n% ARG y : the target values for the noise model.\n% RETURN g : gradients of the log Z with respect to\n% the noise parameters. The ordering of the vector should match\n% that provided by the function noiseExtractParam.\n%\n%\n% SEEALSO orderedNoiseParamInit, orderednoiseGradVals, noiseGradientParam\n%\n% COPYRIGHT : Neil D. Lawrence, 2004, 2005\n\n% NOISE\n\n\nD = size(y, 2);\nc = 1./sqrt(noise.variance + varsigma);\ngnoise.bias = zeros(1, D);\ngnoise.widths = zeros(noise.C-2, 1);\nfor j = 1:D\n % Do lowest category first\n index = find(y(:, j)==0);\n if ~isempty(index)\n mu(index, j) = mu(index, j) + noise.bias(j) ;\n mu(index, j) = mu(index, j).*c(index, j);\n gnoise.bias(j) = gnoise.bias(j) - sum(c(index, j).*gradLogCumGaussian(-mu(index, j)));\n end\n\n % Intermediate categories\n index = find(y(:, j)>0 & y(:, j) 1)\n addpart = sum(c(index(subIndex), j)...\n .*B1(subIndex));\n gnoise.widths(1:cat-1) = gnoise.widths(1:cat-1) ...\n - repmat(addpart, cat-1, 1);\n end\n end\n end\n end\n \n % Highest category\n index = find(y(:, j) == noise.C-1);\n if ~isempty(index)\n for i = index'\n mu(i, j) = mu(i, j) + noise.bias(j) - sum(noise.widths(1:y(i, j)-1));\n end\n mu(index, j) = mu(index, j).*c(index, j);\n addpart = sum(c(index, j).*gradLogCumGaussian(mu(index, j)));\n gnoise.bias(j) = gnoise.bias(j) + addpart;\n if length(noise.widths > 0)\n gnoise.widths = gnoise.widths ...\n - repmat(addpart, noise.C-2, 1);\n end\n end\nend\nif length(noise.widths>0)\n g = [gnoise.bias gnoise.widths(:)'];\nelse\n g = gnoise.bias;\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/noise/orderedNoiseGradientParam.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4895530153473422}} {"text": "%% DEMO_febio_0037_lattice_test_octet_truss_01\n% Below is a demonstration for:\n%\n% * Building the geometry for the octet truss lattive with hexahedral elements\n% * Defining the boundary conditions\n% * Coding the febio structure\n% * Running the model\n% * Importing and visualizing the displacement and stress results\n\n%% Keywords\n%\n% * febio_spec version 3.0\n% * febio, FEBio\n% * compression, tension, compressive, tensile\n% * displacement control, displacement boundary condition\n% * hexahedral elements, hex8\n% * cube, box, rectangular\n% * Lattice\n% * static, solid\n% * hyperelastic, Ogden\n% * displacement logfile\n% * stress logfile\n\n%%\n\nclear; close all; clc;\n\n%% Plot settings\n% Plot settings\nfontSize=15;\nfaceAlpha1=0.8;\nfaceAlpha2=1;\nedgeColor=0.25*ones(1,3);\nedgeWidth=1.5;\nmarkerSize=25;\nmarkerSize2=25;\ncMap=gjet(4);\n\n%% Control parameters\n\n% Path names\ndefaultFolder = fileparts(fileparts(mfilename('fullpath')));\nsavePath=fullfile(defaultFolder,'data','temp');\n\n% Defining file names\nfebioFebFileNamePart='tempModel';\nfebioFebFileName=fullfile(savePath,[febioFebFileNamePart,'.feb']); %FEB file name\nfebioLogFileName=fullfile(savePath,[febioFebFileNamePart,'.txt']); %FEBio log file name\nfebioLogFileName_disp=[febioFebFileNamePart,'_disp_out.txt']; %Log file name for exporting displacement\nfebioLogFileName_force=[febioFebFileNamePart,'_force_out.txt']; %Log file name for exporting force\nfebioLogFileName_stress=[febioFebFileNamePart,'_stress_out.txt']; %Log file name for exporting stress\nfebioLogFileName_stiffness=[febioFebFileNamePart,'_stiffness_out.txt']; %Log file name for exporting stiffness\n\n%Specifying dimensions and number of elements\nsampleSize=10;\nlatticeType=1;\nelementType='hex8'; %'hex8'\nstrutThickness=0.5;\n\n%Define applied displacement\nappliedStrain=0.3; %Linear strain (Only used to compute applied stretch)\nloadingOption='compression'; % or 'tension'\nswitch loadingOption\n case 'compression'\n stretchLoad=1-appliedStrain; %The applied stretch for uniaxial loading\n case 'tension'\n stretchLoad=1+appliedStrain; %The applied stretch for uniaxial loading\nend\ndisplacementMagnitude=(stretchLoad*sampleSize)-sampleSize; %The displacement magnitude\n\n%Material parameter set\nE_youngs1=0.1; %Material Young's modulus\nnu1=0.4; %Material Poisson's ratio\n\n% FEA control settings\nnumTimeSteps=20; %Number of time steps desired\nmax_refs=50; %Max reforms\nmax_ups=0; %Set to zero to use full-Newton iterations\nopt_iter=15; %Optimum number of iterations\nmax_retries=5; %Maximum number of retires\ndtmin=(1/numTimeSteps)/100; %Minimum time step size\ndtmax=(1/numTimeSteps); %Maximum time step size\nmin_residual=1e-20;\nsymmetric_stiffness=0;\nrunMode='external'; %'internal' or 'external'\n\n%%\n\n%Specifying dimensions and number of elements\nr=0.5; %Radii, results in a width of 1\nn=3;\nnCopies=n*ones(1,3); %Number of offset copies\nd=2*r; %Diameter\nw=(n-1)*d; %sampleSize\n\nshrinkFactor=strutThickness./((sampleSize./n).*(sqrt(2)./2));\n\n%% Create lattice\n\nswitch latticeType\n case 1 %Octet truss\n [E,V,C,F,CF]=rhombicDodecahedronMesh(r,nCopies);\n V=V./(n-1);\n V=V*sampleSize;\n \n [indBoundary]=tesBoundary(F);\n cPar.shrinkFactor=shrinkFactor; %Strut sides are formed by shrinking the input mesh faces by this factor\n cPar.meshType='hex'; %desired output mesh type\n cPar.indBoundary=indBoundary; %indices of the boundary faces\n cPar.hexSplit=1;\n cPar.latticeSide=2; %1=side 1 the edge lattice, 2=side 2 the dual lattice to the edge lattice\n [Es,Vs,Cs]=element2lattice(E,V,cPar); %Get lattice structure\n \n logicKeep1=~(Vs(:,1)<=-1e-3);\n logicKeep2=~(Vs(:,2)<=-1e-3);\n logicKeep3=~(Vs(:,3)<=-1e-3);\n logicKeep4=~(Vs(:,1)>=sampleSize+1e-3);\n logicKeep5=~(Vs(:,2)>=sampleSize+1e-3);\n logicKeep6=~(Vs(:,3)>=sampleSize+1e-3);\n \n logicKeepEs=sum(logicKeep1(Es),2)>=4 &...\n sum(logicKeep2(Es),2)>=4 &...\n sum(logicKeep3(Es),2)>=4 &...\n sum(logicKeep4(Es),2)>=4 &...\n sum(logicKeep5(Es),2)>=4 &...\n sum(logicKeep6(Es),2)>=4;\n \n Es=Es(logicKeepEs,:);\n Cs=Cs(logicKeepEs,:);\n [Es,Vs,indFix]=patchCleanUnused(Es,Vs);\n \n % [Es,Vs,~,~]=subHex(Es,Vs,1,1);\n % Cs=repmat(Cs,8,1);\n \n % Create patch Data for visualization\n [Fs,CsF]=element2patch(Es,Cs); %Patch data for plotting\n \n %Get new boundary set\n indB=tesBoundary(Fs);\n Fb=Fs(indB,:);\n case 2 %Rhombic dodecahedron mesh (\"dual\" of octet truss lattice)\n [E,V,C,F,CF]=rhombicDodecahedronMesh(r,nCopies);\n V=V./(n-1);\n V=V*sampleSize;\n \n [indBoundary]=tesBoundary(F);\n cPar.shrinkFactor=0.15; %Strut sides are formed by shrinking the input mesh faces by this factor\n cPar.meshType='hex'; %desired output mesh type\n cPar.indBoundary=indBoundary; %indices of the boundary faces\n cPar.hexSplit=3;\n cPar.latticeSide=1; %1=side 1 the edge lattice, 2=side 2 the dual lattice to the edge lattice\n [Es,Vs,Cs]=element2lattice(E,V,cPar); %Get lattice structure\n \n logicKeep1=~(Vs(:,1)<=-1e-3);\n logicKeep2=~(Vs(:,2)<=-1e-3);\n logicKeep3=~(Vs(:,3)<=-1e-3);\n logicKeep4=~(Vs(:,1)>=sampleSize+1e-3);\n logicKeep5=~(Vs(:,2)>=sampleSize+1e-3);\n logicKeep6=~(Vs(:,3)>=sampleSize+1e-3);\n \n logicKeepEs=sum(logicKeep1(Es),2)>=4 &...\n sum(logicKeep2(Es),2)>=4 &...\n sum(logicKeep3(Es),2)>=4 &...\n sum(logicKeep4(Es),2)>=4 &...\n sum(logicKeep5(Es),2)>=4 &...\n sum(logicKeep6(Es),2)>=4;\n \n Es=Es(logicKeepEs,:);\n Cs=Cs(logicKeepEs,:);\n [Es,Vs,indFix]=patchCleanUnused(Es,Vs);\n \n % Create patch Data for visualization\n [Fs,CsF]=element2patch(Es,Cs); %Patch data for plotting\n \n %Get new boundary set\n indB=tesBoundary(Fs);\n Fb=Fs(indB,:);\nend\n\nif strcmp(elementType,'hex20')\n [Es,Vs,~,Fb]=hex8_hex20(Es,Vs,{},Fb);\nend\n%%\n% Visualizing input mesh and lattic structures\n\ncFigure;\nhs=subplot(1,2,1);\ntitle('The input mesh','fontSize',fontSize)\nhold on;\ngpatch(F,V,0.5*ones(1,3),'k',0.5);\naxisGeom(gca,fontSize);\ncamlight headlight; lighting flat;\n\n% Fst=[Fs(:,[1 2 3]); Fs(:,[3 4 1]);];\n% indB=tesBoundary(Fst,Vs);\n% Fbt=Fst(indB,:);\n\nsubplot(1,2,2);\ntitle('Lattice side 1','fontSize',fontSize)\nhold on;\ngpatch(Fb,Vs,'bw','k',1);\n% plotV(Vs(Fb(:),:),'r.');\n% patchNormPlot(Fs,Vs);\naxisGeom(gca,fontSize);\ncamlight headlight; lighting flat;\n\ndrawnow;\n\n%% DEFINE BC's\n\n% Define node set logics\nindAll=(1:1:size(Vs,1))';\nlogicBoundary=ismember(indAll,Fb);\n\nZ=Vs(:,3);\nlogicTop=Z>=(sampleSize-eps(sampleSize))& logicBoundary;\nlogicBottom=Z<=eps(sampleSize) & logicBoundary;\n\nX=Vs(:,1);\nlogicSide1=X>=(sampleSize-eps(sampleSize))& logicBoundary;\nlogicSide2=X<=eps(sampleSize)& logicBoundary;\n\nY=Vs(:,2);\nlogicSide3=Y>=(sampleSize-eps(sampleSize))& logicBoundary;\nlogicSide4=Y<=eps(sampleSize)& logicBoundary;\n\nbcPrescribeListCell{1}=find(logicSide1)';\nbcPrescribeListCell{2}=find(logicSide2)';\nbcPrescribeListCell{3}=find(logicSide3)';\nbcPrescribeListCell{4}=find(logicSide4)';\nbcPrescribeListCell{5}=find(logicTop)';\nbcPrescribeListCell{6}=find(logicBottom)';\n\n%% Smoothing lattice\n\n% indKeep=unique([bcPrescribeListCell{:}]);\n% [Fb_clean,Vb_clean,indFix]=patchCleanUnused(Fb,Vs);\n%\n% cPar.Method='HC';\n% cPar.n=6;\n%\n% cPar.RigidConstraints=indFix(indKeep);\n% % cPar.RigidConstraints=cPar.RigidConstraints(cPar.RigidConstraints>0);\n%\n% [Vb_clean]=tesSmooth(Fb_clean,Vb_clean,[],cPar);\n% ind=Fb(:);\n% ind=unique(ind(:));\n% Vs(ind,:)=Vb_clean;\n\n% cFigure; hold on;\n% gpatch(Fb,Vs,'bw','k',1);\n% % patchNormPlot(Fs,Vs);\n% % plotV(Vs(indKeep,:),'k.','MarkerSize',25)\n% axisGeom(gca,fontSize);\n% camlight headlight; lighting flat;\n% drawnow;\n\n%%\n\n%Prescribed displacement nodes\nbcPrescribeList=find(logicTop); \nbcSupportList=find(logicBottom); \n\n\n%%\n% Visualizing input mesh and lattice structures\n\ncFigure;\nhs=subplot(1,2,1);\ntitle('The input mesh','fontSize',fontSize)\nhold on;\ngpatch(F,V,0.5*ones(1,3),'k',0.5);\naxisGeom(gca,fontSize);\ncamlight headlight; lighting flat;\n\nsubplot(1,2,2);\ntitle('Lattice side 1','fontSize',fontSize)\nhold on;\ngpatch(Fb,Vs,'bw');\n% patchNormPlot(Fs,Vs);\naxisGeom(gca,fontSize);\ncamlight headlight; lighting flat;\n\ndrawnow;\n\n%%\n% Visualize BC's\n\nhf=cFigure; hold on;\ntitle('Boundary conditions model','FontSize',fontSize);\ngpatch(Fb,Vs,'w','none',0.5); \nhl2(1)=plotV(Vs(bcPrescribeList,:),'r.','MarkerSize',markerSize2);\nhl2(2)=plotV(Vs(bcSupportList,:),'b.','MarkerSize',markerSize2);\nlegend(hl2,{'BC prescribe','BC support'});\naxisGeom(gca,fontSize);\ncamlight headlight;\ndrawnow;\n\n%% Check porosity\n% Note it may be better to use the convex hull volume rather than the cube\n% for the octet truss\nvol_lattice=sum(hexVol(Es,Vs)); %Volume of hexahedra\nporosity_lattice=vol_lattice./sampleSize.^3; %Porosity\n\n%% Defining the FEBio input structure\n% See also |febioStructTemplate| and |febioStruct2xml| and the FEBio user\n% manual.\n\n%Get a template with default settings \n[febio_spec]=febioStructTemplate;\n\n%febio_spec version \nfebio_spec.ATTR.version='3.0'; \n\n%Module section\nfebio_spec.Module.ATTR.type='solid'; \n\n%Control section\nfebio_spec.Control.analysis='STATIC';\nfebio_spec.Control.time_steps=numTimeSteps;\nfebio_spec.Control.step_size=1/numTimeSteps;\nfebio_spec.Control.solver.max_refs=max_refs;\nfebio_spec.Control.solver.max_ups=max_ups;\nfebio_spec.Control.time_stepper.dtmin=dtmin;\nfebio_spec.Control.time_stepper.dtmax=dtmax; \nfebio_spec.Control.time_stepper.max_retries=max_retries;\nfebio_spec.Control.time_stepper.opt_iter=opt_iter;\n\n%Material section\nmaterialName1='Material1';\nfebio_spec.Material.material{1}.ATTR.name=materialName1;\nfebio_spec.Material.material{1}.ATTR.type='neo-Hookean';\nfebio_spec.Material.material{1}.ATTR.id=1;\nfebio_spec.Material.material{1}.E=E_youngs1;\nfebio_spec.Material.material{1}.v=nu1;\n\n%Mesh section\n% -> Nodes\nfebio_spec.Mesh.Nodes{1}.ATTR.name='nodeSet_all'; %The node set name\nfebio_spec.Mesh.Nodes{1}.node.ATTR.id=(1:size(Vs,1))'; %The node id's\nfebio_spec.Mesh.Nodes{1}.node.VAL=Vs; %The nodel coordinates\n\n% -> Elements\npartName1='Part1';\nfebio_spec.Mesh.Elements{1}.ATTR.name=partName1; %Name of this part\nfebio_spec.Mesh.Elements{1}.ATTR.type=elementType; %Element type \nfebio_spec.Mesh.Elements{1}.elem.ATTR.id=(1:1:size(Es,1))'; %Element id's\nfebio_spec.Mesh.Elements{1}.elem.VAL=Es; %The element matrix\n\n% -> NodeSets\nnodeSetName1='bcSupportList';\nfebio_spec.Mesh.NodeSet{1}.ATTR.name=nodeSetName1;\nfebio_spec.Mesh.NodeSet{1}.node.ATTR.id=bcSupportList(:);\n\nnodeSetName2='bcPrescribeList';\nfebio_spec.Mesh.NodeSet{2}.ATTR.name=nodeSetName2;\nfebio_spec.Mesh.NodeSet{2}.node.ATTR.id=bcPrescribeList(:);\n\n%MeshDomains section\nfebio_spec.MeshDomains.SolidDomain.ATTR.name=partName1;\nfebio_spec.MeshDomains.SolidDomain.ATTR.mat=materialName1;\n\n%Boundary condition section \n% -> Fix boundary conditions\nfebio_spec.Boundary.bc{1}.ATTR.type='fix';\nfebio_spec.Boundary.bc{1}.ATTR.node_set=nodeSetName1;\nfebio_spec.Boundary.bc{1}.dofs='x,y,z';\n\nfebio_spec.Boundary.bc{2}.ATTR.type='fix';\nfebio_spec.Boundary.bc{2}.ATTR.node_set=nodeSetName2;\nfebio_spec.Boundary.bc{2}.dofs='x,y';\n\nfebio_spec.Boundary.bc{3}.ATTR.type='prescribe';\nfebio_spec.Boundary.bc{3}.ATTR.node_set=nodeSetName2;\nfebio_spec.Boundary.bc{3}.dof='z';\nfebio_spec.Boundary.bc{3}.scale.ATTR.lc=1;\nfebio_spec.Boundary.bc{3}.scale.VAL=displacementMagnitude;\nfebio_spec.Boundary.bc{3}.relative=0;\n\n%LoadData section\n% -> load_controller\nfebio_spec.LoadData.load_controller{1}.ATTR.id=1;\nfebio_spec.LoadData.load_controller{1}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{1}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{1}.points.point.VAL=[0 0; 1 1];\n\n%Output section\n% -> log file\nfebio_spec.Output.logfile.ATTR.file=febioLogFileName;\nfebio_spec.Output.logfile.node_data{1}.ATTR.file=febioLogFileName_disp;\nfebio_spec.Output.logfile.node_data{1}.ATTR.data='ux;uy;uz';\nfebio_spec.Output.logfile.node_data{1}.ATTR.delim=',';\n\nfebio_spec.Output.logfile.node_data{2}.ATTR.file=febioLogFileName_force;\nfebio_spec.Output.logfile.node_data{2}.ATTR.data='Rx;Ry;Rz';\nfebio_spec.Output.logfile.node_data{2}.ATTR.delim=',';\n\n% febio_spec.Output.logfile.element_data{1}.ATTR.file=febioLogFileName_stress;\n% febio_spec.Output.logfile.element_data{1}.ATTR.data='sz';\n% febio_spec.Output.logfile.element_data{1}.ATTR.delim=',';\n% febio_spec.Output.logfile.element_data{1}.VAL=1:size(Es,1);\n\n%% Quick viewing of the FEBio input file structure\n% The |febView| function can be used to view the xml structure in a MATLAB\n% figure window.\n\n%%\n% |febView(febio_spec); %Viewing the febio file|\n\n%% Exporting the FEBio input file\n% Exporting the febio_spec structure to an FEBio input file is done using\n% the |febioStruct2xml| function.\n\nfebioStruct2xml(febio_spec,febioFebFileName); %Exporting to file and domNode\n\n%% Running the FEBio analysis\n% To run the analysis defined by the created FEBio input file the\n% |runMonitorFEBio| function is used. The input for this function is a\n% structure defining job settings e.g. the FEBio input file name. The\n% optional output runFlag informs the user if the analysis was run\n% succesfully.\n\nfebioAnalysis.run_filename=febioFebFileName; %The input file name\nfebioAnalysis.run_logname=febioLogFileName; %The name for the log file\nfebioAnalysis.disp_on=1; %Display information on the command window\nfebioAnalysis.runMode=runMode; %Run in external or in matlab terminal\n\n[runFlag]=runMonitorFEBio(febioAnalysis);%START FEBio NOW!!!!!!!!\n\n%% Import FEBio results\n\nif runFlag==1 %i.e. a succesful run\n \n % Importing nodal displacements from a log file\n [timeVec, N_disp_mat,~]=importFEBio_logfile(fullfile(savePath,febioLogFileName_disp)); %Nodal displacements\n timeVec=[0; timeVec(:)]; %Time\n \n N_disp_mat=N_disp_mat(:,2:end,:);\n sizImport=size(N_disp_mat);\n sizImport(3)=sizImport(3)+1;\n N_disp_mat_n=zeros(sizImport);\n N_disp_mat_n(:,:,2:end)=N_disp_mat;\n N_disp_mat=N_disp_mat_n;\n DN=N_disp_mat(:,:,end);\n DN_magnitude=sqrt(sum(DN(:,3).^2,2));\n Vs_def=Vs+DN;\n \n % % Importing element stress from a log file\n % [time_mat, E_stress_mat,~]=importFEBio_logfile(fullfile(savePath,febioLogFileName_stress)); %Nodal forces\n % time_mat=[0; time_mat(:)]; %Time\n % stress_cauchy_sim=[0; mean(squeeze(E_stress_mat(:,end,:)),1)'];\n %% \n % Importing nodal forces from a log file\n \n [dataStruct]=importFEBio_logfile(fullfile(savePath,febioLogFileName_force),1,1); %Nodal forces\n \n %Access data \n timeVec=dataStruct.time;\n f_sum_x=squeeze(sum(dataStruct.data(bcPrescribeList,1,:),1));\n f_sum_y=squeeze(sum(dataStruct.data(bcPrescribeList,2,:),1));\n f_sum_z=squeeze(sum(dataStruct.data(bcPrescribeList,3,:),1));\n\n %% \n % Visualize force data\n \n displacementApplied=timeVec.*displacementMagnitude; \n \n cFigure; hold on; \n xlabel('$u$ [mm]','Interpreter','Latex');\n ylabel('$F_z$ [N]','Interpreter','Latex');\n hp=plot(displacementApplied(:),f_sum_z(:),'b-','LineWidth',3);\n grid on; box on; axis square; axis tight; \n set(gca,'FontSize',fontSize);\n drawnow; \n \n %%\n % Plotting the simulated results using |anim8| to visualize and animate\n % deformations\n \n % Create basic view and store graphics handle to initiate animation\n hf=cFigure; %Open figure\n gtitle([febioFebFileNamePart,': Press play to animate']);\n hp=gpatch(Fb,Vs_def,DN_magnitude,'k',1); %Add graphics object to animate\n % gpatch(Fb,Vs,'kw','none',0.25); %A static graphics object\n hp.FaceColor='interp';\n \n axisGeom(gca,fontSize);\n colormap(gjet(250)); colorbar;\n clim([0 max(DN_magnitude)]);\n axis([min([Vs_def(:,1);Vs(:,1)]) max([Vs_def(:,1);Vs(:,1)])...\n min([Vs_def(:,2);Vs(:,2)]) max([Vs_def(:,2);Vs(:,2)])...\n min([Vs_def(:,3);Vs(:,3)]) max([Vs_def(:,3);Vs(:,3)]) ]); %Set axis limits statically\n % view(130,25); %Set view direction\n camlight headlight;\n \n % Set up animation features\n animStruct.Time=timeVec; %The time vector\n for qt=1:1:size(N_disp_mat,3) %Loop over time increments\n DN=N_disp_mat(:,:,qt); %Current displacement\n DN_magnitude=sqrt(sum(DN.^2,2)); %Current displacement magnitude\n Vs_def=Vs+DN; %Current nodal coordinates\n \n %Set entries in animation structure\n animStruct.Handles{qt}=[hp hp]; %Handles of objects to animate\n animStruct.Props{qt}={'Vertices','CData'}; %Properties of objects to animate\n animStruct.Set{qt}={Vs_def,DN_magnitude}; %Property values for to set in order to animate\n end\n anim8(hf,animStruct); %Initiate animation feature\n drawnow;\n\nend\n\n%%\n%\n% <>\n%\n% _*GIBBON*_\n% \n%\n% _Kevin Mattheus Moerman_, \n\n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/docs/DEMO_febio_0037_lattice_test_octet_truss_01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.48955301534734214}} {"text": "%COREG_INV invert coreg translations for coefficients\n%\n% Andy Hooper, Aug 2005\n%\n% ======================================================================\n% 04/2008 AH: Updated for compatibility with matlab 2008a\n% 11/2008 AH: Deltaline/pixel added for Doris 3.96 compatibility\n% ======================================================================\n\ncpmname=dir('CPM_Data.*');\n\nload coreg_parms\nLrange=coreg_parms(1)-1\nPrange=coreg_parms(2)-1\nN=coreg_parms(3)^2\n%osf=coreg_parms(4)\nosf=1\nn_ifg=coreg_parms(5)\n\nG=sparse(0,n_ifg*12);\nd=zeros(0,1);\n\nfor i=1:length(cpmname);\n \n thisname=cpmname(i).name;\n CPM_Data=load(thisname);\n \n posL1=((CPM_Data(:,2)-1)*4/Lrange)-2;\n posP1=((CPM_Data(:,3)-1)*4/Prange)-2;\n offL=CPM_Data(:,4);\n offP=CPM_Data(:,5);\n posL2=((CPM_Data(:,2)+offL-1)*4/Lrange)-2;\n posP2=((CPM_Data(:,3)+offP-1)*4/Prange)-2;\n n_pos=size(posL2,1);\n corrf=CPM_Data(:,6);\n stdev=sqrt(3/2/N).*sqrt(1-corrf.^2)/pi./corrf*osf^(3/2);\n weighting=1./stdev;\n ifgs=sscanf(thisname,'CPM_Data.%d.%d');\n ifg1=ifgs(1);\n ifg2=ifgs(2);\n \n Gblock1=[ones(size(posL1)),posL1,posP1,posL1.^2,posL1.*posP1,posP1.^2];\n Gblock1=Gblock1.*repmat(weighting,1,6);\n Gblock2=[ones(size(posL2)),posL2,posP2,posL2.^2,posL2.*posP2,posP2.^2];\n Gblock2=Gblock2.*repmat(weighting,1,6);\n Gnew=sparse(n_pos*2,n_ifg*12);\n if ifg1~=0\n Gnew(1:n_pos,(ifg1-1)*12+1:(ifg1-1)*12+6)=Gblock1;\n Gnew(n_pos+1:n_pos*2,(ifg1-1)*12+7:ifg1*12)=Gblock1;\n end\n Gnew(1:n_pos,(ifg2-1)*12+1:(ifg2-1)*12+6)=-Gblock2;\n Gnew(n_pos+1:n_pos*2,(ifg2-1)*12+7:ifg2*12)=-Gblock2;\n \n G=[G;Gnew];\n d=[d;weighting.*offL;weighting.*offP];\n %d=[d;offL;offP];\nend\n\n% coeff_s gives mapping of slave to master w.r.t. slave position\ncoeff_s=G\\d;\n\nload slave_corners.txt\ndeltaL=zeros(4,size(slave_corners,1));\ndeltaP=zeros(4,size(slave_corners,1));\nfor i = 1:size(slave_corners,1)\n posL1=((slave_corners(i,1:2))*4/Lrange)-2;\n posL1=[posL1(1);posL1(1);posL1(2);posL1(2)];\n posP1=((slave_corners(i,3:4))*4/Prange)-2;\n posP1=[posP1(1);posP1(2);posP1(1);posP1(2)];\n G=[ones(4,1),posL1,posP1,posL1.^2,posL1.*posP1,posP1.^2];\n deltaL(:,i)=G*coeff_s((i-1)*12+1:(i-1)*12+6);\n deltaP(:,i)=G*coeff_s((i-1)*12+7:(i)*12);\nend\ncorner_offsets=[deltaL(:)';deltaP(:)'];\ncorner_offsets=corner_offsets(:);\nsave('corner_offsets.txt','-ascii','corner_offsets')\n\n% we want mapping of slave to master w.r.t. master position\nl=[-2:0.05:2];\np=l;\n[Ls,Ps]=meshgrid(l,p);\nLs=Ls(:);\nPs=Ps(:);\nnsynth=length(Ls);\n\nGblock=[ones(nsynth,1),Ls,Ps,Ls.^2,Ls.*Ps,Ps.^2];\nGsynth=sparse(2*nsynth,12);\nGsynth(1:nsynth,1:6)=Gblock;\nGsynth(nsynth+1:end,7:12)=Gblock;\ncoeff_m=zeros(size(coeff_s));\n\nfor i=1:n_ifg\n ifg_coeff_s=coeff_s((i-1)*12+1:i*12);\n dsynth=Gsynth*ifg_coeff_s;\n Lm=Ls+dsynth(1:nsynth)*4/Lrange;\n Pm=Ps+dsynth(nsynth+1:end)*4/Prange;\n Gblock=[ones(nsynth,1),Lm,Pm,Lm.^2,Lm.*Pm,Pm.^2];\n Gsynth(1:nsynth,1:6)=Gblock;\n Gsynth(nsynth+1:end,7:12)=Gblock;\n coeff_m((i-1)*12+1:i*12)=Gsynth\\-dsynth;\nend\n\nsave('coreg_coeffs.txt','-ascii','coeff_m')\n \n \n", "meta": {"author": "dbekaert", "repo": "StaMPS", "sha": "c159eb81b16c446e0e8fdef7dd435eb22e0240ed", "save_path": "github-repos/MATLAB/dbekaert-StaMPS", "path": "github-repos/MATLAB/dbekaert-StaMPS/StaMPS-c159eb81b16c446e0e8fdef7dd435eb22e0240ed/matlab/coreg_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812552, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4895530096757607}} {"text": "function EUI_data=riceVST_EUI(Efz_data,sigma_data,VST_ABC)\n% Applies exact unbiased inverse of the variance-stabilizing transformation f\n% --------------------------------------------------------------------------------------------\n%\n% SYNTAX\n% ------\n% EUI_data = riceVST_EUI ( Efz_data , sigma_data , VST_ABC )\n%\n%\n% OUTPUT\n% ------\n% EUI_data : exact unbiased inverse of the input Efz_data\n%\n%\n% INPUTS\n% ------\n% Efz_data : Filtered variance-stabilized data (e.g, output of the denoising filter)\n% sigma_data : standard-deviation parameter of the Rice distribution; the method assumes\n% that the data z_data before stabilization is distributed according to\n% z_data ~ Rice(nu,sigma_data), nu being some unknown noise-free signal.\n% EUI_data should coincide with nu if the denoising of fz_data is perfect.\n% VST_ABC : file-selector for the variance-stabilizing transformation (default = 'A')\n%\n%\n% --------------------------------------------------------------------------------------------\n%\n% The software implements the method published in the paper:\n%\n% A. Foi, \"Noise Estimation and Removal in MR Imaging: the Variance-Stabilization Approach\",\n% in Proc. 2011 IEEE Int. Sym. Biomedical Imaging, ISBI 2011, Chicago (IL), USA, April 2011.\n% doi:10.1109/ISBI.2011.5872758\n%\n% --------------------------------------------------------------------------------------------\n%\n%\n% author: Alessandro Foi\n%\n% web page: http://www.cs.tut.fi/~foi/RiceOptVST\n%\n% contact: firstname.lastname@tut.fi\n%\n% --------------------------------------------------------------------------------------------\n% Copyright (c) 2010-2012 Tampere University of Technology.\n% All rights reserved.\n% This work should be used for nonprofit purposes only.\n% --------------------------------------------------------------------------------------------\n%\n% Disclaimer\n% ----------\n%\n% Any unauthorized use of these routines for industrial or profit-oriented activities is\n% expressively prohibited. By downloading and/or using any of these files, you implicitly\n% agree to all the terms of the TUT limited license (included in the file Legal_Notice.txt).\n% --------------------------------------------------------------------------------------------\n%\n\n\n\n%% Defaults\nif nargin<2\n sigma_data=1;\nend\nif isempty(sigma_data)\n sigma_data=1;\nend\n\nif nargin<3\n VST_ABC='A';\nend\nif isempty(VST_ABC)\n VST_ABC='A';\nend\n\nif ischar(VST_ABC)\n if numel(VST_ABC)==1\n Rice_VST_matFile=['Rice_VST_',VST_ABC];\n else\n Rice_VST_matFile=VST_ABC;\n end\nend\n\n\n%% load variance-stabilizing transformation and its exact unbiased inverse from file\nload(Rice_VST_matFile,'Efz','nu','z','f')\n\n%% scale data before applying exact unbiased inverse of the variance-stabilizing transformation (see riceVST.m)\nsigma_data_scaling=sigma_data;\na=f(end)-sqrt(sigma_data_scaling^2*max(z)^2/sigma_data^2-1/2);\nnu=nu*sigma_data_scaling;\n%% apply exact unbiased inverse of the variance-stabilizing transformation\nEUI_data=interp1(Efz,nu,Efz_data,'linear','extrap');\n%% small values (see Equation 11 in the ISBI2011 paper)\nEUI_data(Efz_data<=min(Efz))=min(nu);\n%% apply asymptotical exact unbiased inverse of the variance-stabilizing transformation (used only for large values)\nmaxEfz=max(Efz);\nif 0\n EUI_data(Efz_data>maxEfz)=sigma_data*sqrt((Efz_data(Efz_data>maxEfz)-a).^2+0.5); %% this is the asymptotic inversion to Ez (identical to the above theta_or_Ez==1 case)\n EUI_data(Efz_data>maxEfz)=EUI_data(Efz_data>maxEfz).*(1-0.5*(sigma_data./EUI_data(Efz_data>maxEfz)).^2); %% this is the asymptotic correction between nu and Ez\nelse\n EUI_data(Efz_data>maxEfz)=sigma_data*((Efz_data(Efz_data>maxEfz)-a).^2)./sqrt((Efz_data(Efz_data>maxEfz)-a).^2+0.5); %% this is the result of the two lines above\nend\n\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/åŽ»å™Ŗē®—ę³•/gl-hosvd-master/RiceOptVST/riceVST_EUI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321703143954, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.48955299833259747}} {"text": "function boolVal=isPermutation(possiblePerm,startIdx)\n%%ISPERMUTATION Given an array, determine whether it is a valid\n% permutation of the values startIdx:(startIdx+permLength-1).\n%\n%INPUTS: possiblePerm A length permLength vector to test for being a\n% permutation.\n% startIdx The starting index of the permutation values to\n% consider. If this input is omitted or an empty matrix\n% is passed, then the default of 1 is used.\n%\n%OUTPUTS: boolVal This is true if possiblePerm is a permutation vector and\n% false otherwise. Empty matrices are considered\n% permutation vectors.\n%\n%After initial checks, the function just allocates a vector having the\n%length of possiblePerm and adds 1 to each index given in possiblePerm. If\n%any index is repeated. Afterwards, it checks whether all of the indices\n%contain a \"1\".\n%\n%EXAMPLE:\n% boolVal1=isPermutation([1;4;3;5])\n% boolVal2=isPermutation([1;4;3;2;5])\n% boolVal3=isPermutation([13;16;15;17;14],13)\n%One will find boolVal1=false, boolVal2=true, boolVal3=true.\n%\n%September 2020 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<2||isempty(startIdx))\n startIdx=1;\nend\n\npossiblePerm=possiblePerm(:);\n\nif(~isnumeric(possiblePerm)||~isreal(possiblePerm)||any(~isfinite(possiblePerm))||any(possiblePerm~=fix(possiblePerm)))\n boolVal=false;\n return;\nend\n\nnumEls=length(possiblePerm);\n\npossiblePerm=possiblePerm-startIdx+1;\nif(any(possiblePerm>numEls)||any(possiblePerm<1))\n boolVal=false;\n return;\nend\n\nnumValsPresent=zeros(numEls,1);\nfor k=1:numEls\n idx=possiblePerm(k);\n numValsPresent(idx)=numValsPresent(idx)+1;\nend\n\nboolVal=all(numValsPresent==1);\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/Combinatorics/isPermutation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631556226292, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.48955299680962067}} {"text": "function SE = functionPowerOptimization_maxmin(signal,interference,Pmax,prelogFactor)\n%Compute DL power allocation that solves the max-min fairness problem,\n%using the algorithm in Theorem 7.1.\n%\n%This function require additional software packages to be used, which\n%need to be downloaded and installed separately. These packages are\n%developed independently and are delivered with separate licenses.\n%The implementation uses CVX (http://cvxr.com/cvx) and has been tested\n%using CVX version 2.1. We recommend the use of the Mosek solver (we\n%have tested using version 7.1.0.12).\n%\n%INPUT:\n%signal = K x L matrix where element (k,j) is a_jk in (7.2)\n%interference = K x L x K x L matrix where (l,i,j,k) is b_lijk in (7.3)\n%Pmax = Maximum transmit power per BS\n%prelogFactor = Prelog factor\n%\n%OUTPUT:\n%SE = K x L matrix where element (k,j) is the downlink SE of UE k in cell j\n% using the max-min power allocation solution\n%\n%\n%This Matlab function was developed to generate simulation results to:\n%\n%Emil Bjornson, Jakob Hoydis and Luca Sanguinetti (2017), \n%\"Massive MIMO Networks: Spectral, Energy, and Hardware Efficiency\", \n%Foundations and Trends in Signal Processing: Vol. 11, No. 3-4, \n%pp. 154-655. DOI: 10.1561/2000000093.\n%\n%For further information, visit: https://www.massivemimobook.com\n%\n%This is version 1.01 (Last edited: 2019-03-16)\n%\n%License: This code is licensed under the GPLv2 license. If you in any way\n%use this code for research that results in publications, please cite our\n%monograph as described above.\n\n\n%Extract number of UEs\nK = size(signal,1);\n\n%Extract number of cells\nL = size(signal,2);\n\n%Check which UEs that have non-zero channels, because these ones are\n%excluded (they are considered inactive)\nnonzero = reshape(signal,[K*L 1]);\nnonzero = nonzero(nonzero>0);\n\n%Initalize the gamma-variables in Algorithm 1\nrateLower = 0;\nrateUpper = log2(1+Pmax*min(nonzero));\n\n%Set the accuracy of the bisection\ndelta = 0.01;\n\n%Prepare to save the power solution\nrhoBest = zeros(K,L);\n\n%Solve the max-min problem by bisection - iterate until the difference\n%between the lower and upper points in the interval is smaller than delta\nwhile norm(rateUpper - rateLower) > delta\n \n %Compute the midpoint of the line. Note that we are performing the\n %bisection in the SE domain instead of the SINR domain as in Algorithm\n %1, since we can then specify delta as the SE difference\n rateCandidate = (rateLower+rateUpper)/2; \n \n %Transform the midpoints into SINR requirements\n gammaCandidate = 2.^(rateCandidate)-1;\n \n %Solve the feasibility problem using CVX\n [feasible,rhoSolution] = functionFeasibilityProblem_cvx(signal,interference,Pmax,K,L,gammaCandidate);\n \n \n %If the problem was feasible, then replace rateLower with\n %gammaCandidate and store rhoSolution as the new best solution.\n if feasible\n rateLower = rateCandidate;\n rhoBest = rhoSolution;\n else\n %If the problem was not feasible, then replace ratePoint with\n %gammaCandidate\n rateUpper = rateCandidate;\n end\n \nend\n\n%Compute the SEs using Theorem 4.6\nSE = functionComputeSE_DL_poweralloc(rhoBest,signal,interference,prelogFactor);\n\n\n\nfunction [feasible,rhoSolution] = functionFeasibilityProblem_cvx(signal,interference,Pmax,K,L,SINR)\n%Solve the linear feasibility problem in Algorithm 1 using CVX, by adding\n%an extra variable so that it becomes a minimization problem with better\n%properties.\n\ncvx_begin\ncvx_quiet(true); % This suppresses screen output from the solver\n\nvariable rho(K,L); %Variable for the K x L power allocation matrix\nvariable scaling %Scaling parameter for power constraints\n\nminimize scaling %Minimize the power indirectly by scaling the power constraints\n\nsubject to\n\nfor j = 1:L\n \n for k = 1:K\n \n if signal(k,j)>0\n \n %SINR constraints\n SINR*(sum(sum(rho.*interference(:,:,k,j))) + 1) - (rho(k,j)*signal(k,j)) <= 0\n \n end\n \n rho(k,j)>=0\n \n end\n \n sum(rho(:,j)) <= scaling*Pmax;\n \nend\n\nscaling >= 0; %Power constraints must be positive\n\ncvx_end\n\n\n%% Analyze the CVX output and prepare the output variables\nif isempty(strfind(cvx_status,'Solved')) %Both the power minimization problem and the feasibility problem are infeasible\n feasible = false;\n rhoSolution = [];\nelseif scaling>1 %Only the power minimization problem is feasible\n feasible = false;\n rhoSolution = rho;\nelse %Both the power minimization problem and feasibility problem are feasible\n feasible = true;\n rhoSolution = rho;\nend\n", "meta": {"author": "emilbjornson", "repo": "massivemimobook", "sha": "4e429497dea72d52172972f3f686b34d1d047013", "save_path": "github-repos/MATLAB/emilbjornson-massivemimobook", "path": "github-repos/MATLAB/emilbjornson-massivemimobook/massivemimobook-4e429497dea72d52172972f3f686b34d1d047013/Code/functionPowerOptimization_maxmin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4895286562422691}} {"text": "% l1dantzig_pd.m\n%\n% Solves\n% min_x ||x||_1 subject to ||A'(Ax-b)||_\\infty <= epsilon\n%\n% Recast as linear program\n% min_{x,u} sum(u) s.t. x - u <= 0\n% -x - u <= 0\n% A'(Ax-b) - epsilon <= 0\n% -A'(Ax-b) - epsilon <= 0\n% and use primal-dual interior point method.\n%\n% Usage: xp = l1dantzig_pd(x0, A, At, b, epsilon, pdtol, pdmaxiter, cgtol, cgmaxiter)\n%\n% x0 - Nx1 vector, initial point.\n%\n% A - Either a handle to a function that takes a N vector and returns a K \n% vector , or a KxN matrix. If A is a function handle, the algorithm\n% operates in \"largescale\" mode, solving the Newton systems via the\n% Conjugate Gradients algorithm.\n%\n% At - Handle to a function that takes a K vector and returns an N vector.\n% If A is a KxN matrix, At is ignored.\n%\n% b - Kx1 vector of observations.\n%\n% epsilon - scalar or Nx1 vector of correlation constraints\n%\n% pdtol - Tolerance for primal-dual algorithm (algorithm terminates if\n% the duality gap is less than pdtol). \n% Default = 1e-3.\n%\n% pdmaxiter - Maximum number of primal-dual iterations. \n% Default = 50.\n%\n% cgtol - Tolerance for Conjugate Gradients; ignored if A is a matrix.\n% Default = 1e-8.\n%\n% cgmaxiter - Maximum number of iterations for Conjugate Gradients; ignored\n% if A is a matrix.\n% Default = 200.\n%\n% Written by: Justin Romberg, Caltech\n% Email: jrom@acm.caltech.edu\n% Created: October 2005\n%\n\nfunction xp = l1dantzig_pd(x0, A, At, b, epsilon, pdtol, pdmaxiter, cgtol, cgmaxiter)\n\nlargescale = isa(A,'function_handle');\n\nif (nargin < 6), pdtol = 1e-3; end\nif (nargin < 7), pdmaxiter = 50; end\nif (nargin < 8), cgtol = 1e-8; end\nif (nargin < 9), cgmaxiter = 200; end\n\nN = length(x0);\n\nalpha = 0.01;\nbeta = 0.5;\nmu = 10;\n\ngradf0 = [zeros(N,1); ones(N,1)];\n\n\n% starting point --- make sure that it is feasible\nif (largescale)\n if (max( abs(At(A(x0) - b)) - epsilon ) > 0)\n disp('Starting point infeasible; using x0 = At*inv(AAt)*y.');\n AAt = @(z) A(At(z));\n [w, cgres] = cgsolve(AAt, b, cgtol, cgmaxiter, 0);\n if (cgres > 1/2)\n disp('A*At is ill-conditioned: cannot find starting point');\n xp = x0;\n return;\n end\n x0 = At(w);\n end\nelse\n if (max(abs(A'*(A*x0 - b)) - epsilon ) > 0)\n disp('Starting point infeasible; using x0 = At*inv(AAt)*y.');\n opts.POSDEF = true; opts.SYM = true;\n [w, hcond] = linsolve(A*A', b, opts);\n if (hcond < 1e-14)\n disp('A*At is ill-conditioned: cannot find starting point');\n xp = x0;\n return;\n end\n x0 = A'*w;\n end \nend\nx = x0;\nu = (0.95)*abs(x0) + (0.10)*max(abs(x0));\n\n% set up for the first iteration\nif (largescale)\n Atr = At(A(x) - b);\nelse\n Atr = A'*(A*x - b);\nend\nfu1 = x - u;\nfu2 = -x - u;\nfe1 = Atr - epsilon;\nfe2 = -Atr - epsilon;\nlamu1 = -(1./fu1);\nlamu2 = -(1./fu2);\nlame1 = -(1./fe1);\nlame2 = -(1./fe2);\nif (largescale)\n AtAv = At(A(lame1-lame2));\nelse\n AtAv = A'*(A*(lame1-lame2));\nend\n\n% sdg = surrogate duality gap\nsdg = -[fu1; fu2; fe1; fe2]'*[lamu1; lamu2; lame1; lame2];\ntau = mu*(4*N)/sdg;\n\n% residuals\nrdual = gradf0 + [lamu1-lamu2 + AtAv; -lamu1-lamu2];\nrcent = -[lamu1.*fu1; lamu2.*fu2; lame1.*fe1; lame2.*fe2] - (1/tau);\nresnorm = norm([rdual; rcent]);\n\n% iterations\npditer = 0;\ndone = (sdg < pdtol) | (pditer >= pdmaxiter);\ndispProgress('Newton', 0, pdmaxiter);\nwhile (~done)\n\n % solve for step direction\n w2 = - 1 - (1/tau)*(1./fu1 + 1./fu2);\n \n sig11 = -lamu1./fu1 - lamu2./fu2;\n sig12 = lamu1./fu1 - lamu2./fu2;\n siga = -(lame1./fe1 + lame2./fe2);\n sigx = sig11 - sig12.^2./sig11;\n \n if (largescale)\n w1 = -(1/tau)*( At(A(1./fe2-1./fe1)) + 1./fu2 - 1./fu1 );\n w1p = w1 - (sig12./sig11).*w2;\n hpfun = @(z) At(A(siga.*At(A(z)))) + sigx.*z;\n [dx, cgres, cgiter] = cgsolve(hpfun, w1p, cgtol, cgmaxiter, 0);\n if (cgres > 1/2)\n disp('Cannot solve system. Returning previous iterate. (See Section 4 of notes for more information.)');\n xp = x;\n return\n end\n AtAdx = At(A(dx));\n else\n w1 = -(1/tau)*( A'*(A*(1./fe2-1./fe1)) + 1./fu2 - 1./fu1 );\n w1p = w1 - (sig12./sig11).*w2;\n Hp = A'*(A*sparse(diag(siga))*A')*A + diag(sigx);\n opts.POSDEF = true; opts.SYM = true;\n [dx, hcond] = linsolve(Hp, w1p,opts);\n if (hcond < 1e-14)\n disp('Matrix ill-conditioned. Returning previous iterate. (See Section 4 of notes for more information.)');\n xp = x;\n return\n end\n AtAdx = A'*(A*dx);\n end\n du = w2./sig11 - (sig12./sig11).*dx;\n \n dlamu1 = -(lamu1./fu1).*(dx-du) - lamu1 - (1/tau)*1./fu1;\n dlamu2 = -(lamu2./fu2).*(-dx-du) - lamu2 - (1/tau)*1./fu2;\n dlame1 = -(lame1./fe1).*(AtAdx) - lame1 - (1/tau)*1./fe1;\n dlame2 = -(lame2./fe2).*(-AtAdx) - lame2 - (1/tau)*1./fe2;\n if (largescale) \n AtAdv = At(A(dlame1-dlame2)); \n else\n AtAdv = A'*(A*(dlame1-dlame2)); \n end\n\t\n \n % find minimal step size that keeps ineq functions < 0, dual vars > 0\n iu1 = find(dlamu1 < 0); iu2 = find(dlamu2 < 0); \n ie1 = find(dlame1 < 0); ie2 = find(dlame2 < 0);\n ifu1 = find((dx-du) > 0); ifu2 = find((-dx-du) > 0); \n ife1 = find(AtAdx > 0); ife2 = find(-AtAdx > 0); \n smax = min(1,min([...\n -lamu1(iu1)./dlamu1(iu1); -lamu2(iu2)./dlamu2(iu2); ...\n -lame1(ie1)./dlame1(ie1); -lame2(ie2)./dlame2(ie2); ...\n -fu1(ifu1)./(dx(ifu1)-du(ifu1)); -fu2(ifu2)./(-dx(ifu2)-du(ifu2)); ...\n -fe1(ife1)./AtAdx(ife1); -fe2(ife2)./(-AtAdx(ife2)) ]));\n s = 0.99*smax;\n \n % backtracking line search\n suffdec = 0;\n backiter = 0;\n while (~suffdec)\n xp = x + s*dx; up = u + s*du;\n Atrp = Atr + s*AtAdx; AtAvp = AtAv + s*AtAdv;\n fu1p = fu1 + s*(dx-du); fu2p = fu2 + s*(-dx-du);\n fe1p = fe1 + s*AtAdx; fe2p = fe2 + s*(-AtAdx);\n lamu1p = lamu1 + s*dlamu1; lamu2p = lamu2 + s*dlamu2;\n lame1p = lame1 + s*dlame1; lame2p = lame2 + s*dlame2;\n rdp = gradf0 + [lamu1p-lamu2p + AtAvp; -lamu1p-lamu2p];\n rcp = -[lamu1p.*fu1p; lamu2p.*fu2p; lame1p.*fe1p; lame2p.*fe2p] - (1/tau);\n suffdec = (norm([rdp; rcp]) <= (1-alpha*s)*resnorm);\n s = beta*s;\n backiter = backiter+1;\n if (backiter > 32)\n disp('Stuck backtracking, returning last iterate. (See Section 4 of notes for more information.)')\n xp = x;\n return\n end\n end\n \n % setup for next iteration\n x = xp; u = up;\n Atr = Atrp; AtAv = AtAvp;\n fu1 = fu1p; fu2 = fu2p; \n fe1 = fe1p; fe2 = fe2p;\n lamu1 = lamu1p; lamu2 = lamu2p; \n lame1 = lame1p; lame2 = lame2p;\n \n sdg = -[fu1; fu2; fe1; fe2]'*[lamu1; lamu2; lame1; lame2];\n tau = mu*(4*N)/sdg;\n\n rdual = rdp;\n rcent = -[lamu1.*fu1; lamu2.*fu2; lame1.*fe1; lame2.*fe2] - (1/tau);\n resnorm = norm([rdual; rcent]);\n \n pditer = pditer+1;\n done = (sdg < pdtol) | (pditer >= pdmaxiter);\n dispProgress('Newton', pditer/pdmaxiter);\n \n% disp(sprintf('Iteration = %d, tau = %8.3e, Primal = %8.3e, PDGap = %8.3e, Dual res = %8.3e',...\n% pditer, tau, sum(u), sdg, norm(rdual)));\n% if (largescale)\n% disp(sprintf(' CG Res = %8.3e, CG Iter = %d', cgres, cgiter));\n% else\n% disp(sprintf(' H11p condition number = %8.3e', hcond));\n% end\n \nend\ndispProgress('Newton', 'Close');\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/@L1_Magic/private/l1dantzig_pd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4895286504268241}} {"text": "function C = long(d)\n%LONG Long class constructor\n%\n% C = long(d)\n%\n% C is long scalar or column vector, array input d forced to be column vector\n%\n%Long representation\n%\n% C = C.sign * sum( C.mantissa(i)*beta^(-i) ) * beta^C.exponent +/- C.error\n%\n%where C.error = C.error.mant * beta^C.error.exp and with\n% summation from 1 to precision (=size(C.mantissa,2)) with\n%\n% 1 <= precision <= INTLAB_LONG_PRECISION\n%\n%and integers\n%\n% C.sign in {-1,1}\n% C.mantissa in 0 .. beta-1\n% C.exponent representable integer ( -2^52+1 .. 2^52-1 )\n% C.error nonnegative double, stored by C.error.mant and C.error.exp\n%\n%Computations can be executed with or w/o error term, see longinit. For\n% computational speed, comparison, min/max and absolute value refer to\n% midpoint.\n% To compare, for example, intervals (for computation with error term)\n% use inf(A)>sup(B) instead of A>B, and so forth.\n%\n%For control of working precision, see help longprecision. Base beta is a\n% power of 2 so that double precision floating point numbers are stored\n% without error.\n%An example of long arithmetic with big cancellation is\n%\n% x = long(-20);\n% y = long(1); t = long(1); i = 0;\n% while abs(t)>1e-20\n% i = i+1;\n% t = t*x/i;\n% y = y+t;\n% end\n% format long\n% Y = long2intval(y)\n%\n%producing\n%\n% intval Y =\n% 1.0e-008 *\n% 0.20612_________\n%\n%The poor accuracy improves with more precision. After\n% longprecision(40);\n%and the same statements as above we obtain\n%\n% intval Y =\n% 1.0e-008 *\n% 0.20611536224378\n%\n%For more information try demolong .\n%\n\n% written 12/30/98 S.M. Rump\n% modified 02/09/01 S.M. Rump performance improvement\n% modified 09/29/02 S.M. Rump care for NaN components\n% modified 04/04/04 S.M. Rump set round to nearest for safety\n% modified 04/06/05 S.M. Rump rounding unchanged\n% modified 08/26/12 S.M. Rump global variables removed\n%\n\n INTLAB_LONG_LOGBETA = getappdata(0,'INTLAB_LONG_LOGBETA');\n INTLAB_LONG_BETA = getappdata(0,'INTLAB_LONG_BETA');\n INTLAB_LONG_ERROR = getappdata(0,'INTLAB_LONG_ERROR');\n \n if nargin==0\n C.sign = [];\n C.exponent = [];\n C.mantissa = [];\n C.error.mant = [];\n C.error.exp = [];\n C = class(C,'long');\n return\n end\n\n if isa(d,'long')\n C = d;\n else\n if isempty(d)\n C.sign = [];\n C.exponent = [];\n C.mantissa = [];\n C.error.mant = [];\n C.error.exp = [];\n C = class(C,'long');\n return\n end\n sized = size(d);\n n = prod(sized);\n if n~=sized(1)\n warning('input array for long forced to be column vector')\n d = d(:);\n end\n indexNaN = isnan(d);\n d(indexNaN) = [];\n [s e m] = splitdble(d);\n\n % get sign\n C.sign = s;\n\n % get exponent\n q = ceil(e/INTLAB_LONG_LOGBETA);\n C.exponent = q;\n\n % get mantissa digits\n C.mantissa = zeros(size(d,1),ceil(53/INTLAB_LONG_LOGBETA)+1);\n p = 0;\n while any(m)\n p = p+1;\n m = m*INTLAB_LONG_BETA;\n C.mantissa(:,p) = floor(m);\n m = m - C.mantissa(:,p);\n end\n\n % treat zero components\n index = ( d==0 );\n if any(index)\n C.sign(index) = 1;\n C.exponent(index) = -inf;\n end\n\n % adjust mantissa digits to exponent\n r = INTLAB_LONG_LOGBETA*q - e;\n index = ( r~=0 );\n if any(index)\n C.mantissa(index,:) = shiftright(C.mantissa(index,:),r(index));\n end\n\n % omit trailing zeros (improves performance)\n [m index] = max(C.mantissa(:,end:-1:1)~=0,[],2);\n index(all(C.mantissa'==0)) = size(C.mantissa,2);\n if min(index)~=1\n C.mantissa = C.mantissa(:,1:end-min(index)+1);\n end\n\n if any(indexNaN)\n Csign = C.sign;\n Cexponent = C.exponent;\n Cmantissa = C.mantissa;\n C.sign = zeros(n,1);\n C.exponent = zeros(n,1);\n C.mantissa = zeros(n,size(Cmantissa,2));\n C.sign(indexNaN) = NaN;\n C.exponent(indexNaN) = NaN;\n C.mantissa(indexNaN) = NaN;\n C.sign(~indexNaN) = Csign;\n C.exponent(~indexNaN) = Cexponent;\n C.mantissa(~indexNaN) = Cmantissa;\n end\n \n % set error\n C.error.mant = zeros(n,1);\n C.error.exp = zeros(n,1);\n\n C = class(C,'long');\n\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/long/@long/long.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.4895237203079935}} {"text": "function [Bx, By, Bz] = igrf(time, latitude, longitude, altitude, coord)\n\n% IGRF Earth's magnetic field from IGRF model.\n% \n% Usage: [BX, BY, BZ] = IGRF(TIME, LATITUDE, LONGITUDE, ALTITUDE, COORD)\n% or [BX, BY, BZ] = IGRF(COEFS, LATITUDE, LONGITUDE, ALTITUDE, COORD)\n% or B = IGRF(TIME, LATITUDE, LONGITUDE, ALTITUDE, COORD)\n% or B = IGRF(COEFS, LATITUDE, LONGITUDE, ALTITUDE, COORD)\n% \n% Calculates the components of the Earth's magnetic field using the\n% International Geomagnetic Reference Field (IGRF) model. The inputs for\n% the position can be scalars or vectors (in the latter case each should\n% have the same number of elements or be a scalar), but TIME must be a\n% scalar.\n% \n% When all the coordinate inputs are scalars, the function can be run more\n% efficiently by providing the proper IGRF coefficient vector for a given\n% time rather than the time itself. This mode is useful when making\n% multiple calls to the function while keeping the time the same (meaning\n% the coefficients will be the same for each run) as loading the\n% coefficients can be the most time-consuming part of the function. The\n% coefficient vector can be easily loaded using the function LOADIGRFCOEFS.\n% This mode is assumed when all the coordinate inputs are scalars and the\n% first input is a vector. In this case, the coefficient vector should be\n% formatted as (LOADIGRFCOEFS provides this):\n% \n% [g(n=1,m=0) g(n=1,m=1) h(n=1,m=1) g(n=2,m=0) g(n=2,m=1) h(n=2,m=1) ...]\n% \n% Regardless of the size of the inputs, the outputs will be column vectors.\n% If only one output is requested, B = [BX(:), BY(:), BZ(:)] is output.\n% Note that the other parameters the IGRF gives can be computed from BX,\n% BY, and BZ as:\n% \n% Horizonal intensity: hypot(BX, BY) (i.e., sqrt(BX.^2 + BY.^2) )\n% Total intensity: hypot(BX, hypot(BY, BZ))\n% Declination: atan2(BY, BX)\n% Inclination: atan(BZ./hypot(BX, BY))\n% \n% This function relies on having the file igrfcoefs.mat in the MATLAB\n% path to function properly when a time is input. If this file cannot be\n% found, this function will try to create it by calling GETIGRFCOEFS.\n% \n% The IGRF is a spherical harmonic expansion of the Earth's internal\n% magnetic field. Currently, the IGRF model is valid between the years 1900\n% and 2015. See the health warning for the IGRF model here:\n% http://www.ngdc.noaa.gov/IAGA/vmod/igrfhw.html\n% \n% Reference:\n% International Association of Geomagnetism and Aeronomy, Working Group \n% V-MOD (2010), International Geomagnetic Reference Field: the eleventh\n% generation, _Geophys. J. Int._, _183_(3), 1216-1230, \n% doi:10.1111/j.1365-246X.2010.04804.x.\n% \n% Inputs:\n% -TIME: Time to get the magnetic field values either in MATLAB serial\n% date number format or a string that can be converted into MATLAB serial\n% date number format using DATENUM with no format specified (see\n% documentation of DATENUM for more information).\n% -COEFS: Instead of inputting a time, you can simply specify the proper\n% coefficients for the time you want by inputting in the first argument\n% the proper coefficient vector from igrfcoefs.mat.\n% -LATITUDE: Geocentric or geodetic latitude in degrees.\n% -LONGITUDE: Geocentric or geodetic longitude in degrees.\n% -ALTITUDE: For geodetic coordiates, the height in km above the Earth's\n% surface. For geocentric coordiates, the radius in km from the center of\n% the Earth.\n% -COORD: String specifying the coordinate system to use. Either\n% 'geocentric' or 'geodetic' (optional, default is geodetic). Note that\n% only geodetic coordinates have been verified.\n% \n% Outputs:\n% -BX: Northward component of the magnetic field in nanoteslas (nT).\n% -BY: Eastward component of the magnetic field in nT.\n% -BZ: Downward component of the magnetic field in nT.\n% -B: [BX(:), BY(:), BZ(:)].\n% \n% See also: LOADIGRFCOEFS, GETIGRFCOEFS, IGRFLINE, DATENUM, IGRF11MAGM.\n\n% Run IGRFS if all position inputs are scalars.\nif isscalar(latitude) && isscalar(longitude) && isscalar(altitude)\n if nargin < 5\n [Bx, By, Bz] = igrfs(time, latitude, longitude, altitude);\n else\n [Bx, By, Bz] = igrfs(time, latitude, longitude, altitude, coord);\n end\n% Otherwise run IGRFV.\nelse\n if nargin < 5\n [Bx, By, Bz] = igrfv(time, latitude, longitude, altitude);\n else\n [Bx, By, Bz] = igrfv(time, latitude, longitude, altitude, coord);\n end\nend\n\nif nargout <= 1\n Bx = [Bx(:), By(:), Bz(:)];\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%% IGRF vector function. %%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [Bx, By, Bz] = igrfv(time, latitude, longitude, altitude, coord)\n\n% Fundamental constant.\nRearth_km = 6371.2;\n\n%%% CHECK INPUT VALIDITY %%%\n% Convert time to a datenumber if it is a string.\nif ischar(time)\n time = datenum(time);\nend\n\n% Make sure time has only one element.\nif numel(time) > 1\n error('igrf:timeInputInvalid', ['The input TIME can only have one ' ...\n 'element.']);\nend\n\n% Check that the inputs all have either one or the same number of elements.\nnumlat = numel(latitude);\nnumlon = numel(longitude);\nnumalt = numel(altitude);\nif numlat > 1\n if numlon == 1\n longitude = repmat(longitude, size(latitude));\n end\n if numalt == 1\n altitude = repmat(altitude, size(latitude));\n end\nelseif numlon > 1\n latitude = repmat(latitude, size(longitude));\n if numalt == 1\n altitude = repmat(altitude, size(latitude));\n end\nelseif numalt > 1\n latitude = repmat(latitude, size(altitude));\n longitude = repmat(longitude, size(altitude));\nend\nnumlat = numel(latitude);\nnumlon = numel(longitude);\nnumalt = numel(altitude);\nif numlat ~= numlon || numlat ~= numalt || numlon ~= numalt\n error('igrf:inputNotSameSize', ['The input coordinates must have ' ...\n 'the same number of elements.']);\nend\n\n%%% SPHERICAL COORDINATE CONVERSION %%%\n% Convert the latitude, longitude, and altitude coordinates input into\n% spherical coordinates r (radius), theta (inclination angle from +z axis),\n% and phi (azimuth angle from +x axis). Also, make the coordinates go down\n% the rows.\n% We want cos(theta) and sin(theta) rather than theta itself.\ncostheta = cos((90 - latitude(:))*pi/180);\nsintheta = sin((90 - latitude(:))*pi/180);\n\n% Convert from geodetic coordinates to geocentric coordinates if necessary.\n% This method was adapted from igrf11syn, which was a conversion of the\n% IGRF subroutine written in FORTRAN.\nif nargin < 5 || isempty(coord) || strcmpi(coord, 'geodetic') || ...\n strcmpi(coord, 'geod') || strcmpi(coord, 'gd')\n a = 6378.137; f = 1/298.257223563; b = a*(1 - f);\n rho = hypot(a*sintheta, b*costheta);\n r = sqrt( altitude(:).^2 + 2*altitude(:).*rho + ...\n (a^4*sintheta.^2 + b^4*costheta.^2) ./ rho.^2 );\n cd = (altitude(:) + rho) ./ r;\n sd = (a^2 - b^2) ./ rho .* costheta.*sintheta./r;\n oldcos = costheta;\n costheta = costheta.*cd - sintheta.*sd;\n sintheta = sintheta.*cd + oldcos.*sd;\nelseif strcmpi(coord, 'geocentric') || strcmpi(coord, 'geoc') || ...\n strcmpi(coord, 'gc')\n r = altitude(:);\n cd = 1;\n sd = 0;\nelse\n error('igrf:coordInputInvalid', ['Unrecognized command ' coord ...\n ' for COORD input.']);\nend\n\n% Special case when sin(theta) = 0.\nsintheta0 = sintheta == 0;\nanysintheta0 = any(sintheta0);\nanysinthetanot0 = any(~sintheta0);\n\n% Convert longitude to radians.\nphi = longitude(:)*pi/180;\n\n%%% GET PROPER IGRF COEFFICIENTS %%%\n[g, h] = loadigrfcoefs(time);\nnmax = size(g, 1);\n\n% We need cos(m*phi) and sin(m*phi) multiple times, so precalculate into a\n% matrix here:\ncosphi = cos(bsxfun(@times, 0:nmax, phi));\nsinphi = sin(bsxfun(@times, 0:nmax, phi));\n\n%%% BEGIN MAGNETIC FIELD CALCULATION %%%\n% Initialize variables used in for loop below.\nBr = zeros(size(r));\nBt = zeros(size(r));\nBp = zeros(size(r));\nlastP = 1;\nlastdP_1 = 0;\nlastdP_2 = 0;\n\n% Sum for each n value.\nfor n = 1 : nmax\n \n m = 0 : n;\n \n % Calculate legendre values. The output of the function has each m\n % value going down the rows, but since m goes along the columns\n % (coordinates go down the rows, remember?), permute it.\n P = legendre(n, costheta, 'sch').';\n \n % We also need the derivative of the legendre with respect to theta. It\n % is given by a recursive function of both the previous legendre values\n % as well as the previous derivatives. Functionally, it is:\n % dP(0, 0) = 0, dP(1, 1) = cos(theta)\n % dP(n, n) = sqrt(1 - 1/(2n))*(sin(theta)*dP(n-1, n-1) +\n % cos(theta)*P(n-1, n-1))\n % dP(n, m) = (2n - 1)/sqrt(n^2 - m^2)*(cos(theta)*dP(n-1, m) -\n % sin(theta)*P(n-1, m)) - sqrt(((n-1)^2 - m^2)/(n^2 - m^2))*\n % dP(n-2, m)\n dP = [bsxfun(@minus, bsxfun(@times, ...\n (2*n - 1)./sqrt(n^2 - m(1:end-1).^2), ...\n bsxfun(@times, costheta, lastdP_1) - bsxfun(@times, sintheta, ...\n lastP)), bsxfun(@times, sqrt(((n - 1)^2 - m(1:end-1).^2)./...\n (n^2 - m(1:end-1).^2)), lastdP_2)), zeros(size(costheta))];\n if n > 1\n dP(:, end) = sqrt(1 - 1/(2*n))*...\n (sintheta*lastdP_1(end) + costheta*lastP(end));\n lastdP_2 = [lastdP_1 zeros(size(costheta))];\n else\n dP(:, end) = costheta;\n lastdP_2 = lastdP_1;\n end\n lastP = P;\n lastdP_1 = dP;\n \n % Multiply coefficients by proper longitude trigonemetric term.\n gcos = bsxfun(@times, g(n, m + 1), cosphi(:, m + 1));\n gsin = bsxfun(@times, g(n, m + 1), sinphi(:, m + 1));\n hcos = bsxfun(@times, h(n, m + 1), cosphi(:, m + 1));\n hsin = bsxfun(@times, h(n, m + 1), sinphi(:, m + 1));\n \n % Calculate the magnetic field components as a running sum. Find\n % explicit expressions for these in Global Earth Physics: a Handbook of\n % Physical Constants by Thomas J. Aherns (1995), pg. 49. Link:\n % http://books.google.com/books?id=aqjU_NHyre4C&lpg=PP1&dq=Global%20\n % earth%20physics%3A%20a%20handbook%20of%20physical%20constants&pg=PA49\n % #v=onepage&q&f=false\n % (except equation 6 is missing a required 1/sin(theta) and m; correct\n % equations on page 5 (equations 3a-3c) of:\n % http://hanspeterschaub.info/Papers/UnderGradStudents/\n % MagneticField.pdf)\n a_r = (Rearth_km./r).^(n + 2);\n Br = Br + a_r.*(n+1).*sum((gcos + hsin).*P, 2);\n Bt = Bt - a_r.*sum((gcos + hsin).*dP, 2);\n % Different case when sin(theta) == 0 for phi component.\n if anysinthetanot0\n Bp(~sintheta0) = Bp(~sintheta0) - 1./sintheta(~sintheta0).*...\n a_r(~sintheta0).*sum(bsxfun(@times, m, ...\n (-gsin(~sintheta0, :) + hcos(~sintheta0, :)).*...\n P(~sintheta0, :)), 2);\n end\n if anysintheta0\n Bp(sintheta0) = Bp(sintheta0) - costheta(sintheta0).*...\n a_r(sintheta0).*sum((-gsin(sintheta0, :) ...\n + hcos(sintheta0, :)).*dP(sintheta0, :), 2);\n end\n \nend\n\n% Convert from spherical to (x,y,z) = (North,East,Down).\nBx = -Bt;\nBy = Bp;\nBz = -Br;\n\n% Convert back to geodetic coordinates if necessary.\nBx_old = Bx;\nBx = Bx.*cd + Bz.*sd;\nBz = Bz.*cd - Bx_old.*sd;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%% IGRF scalar function. %%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [Bx, By, Bz] = igrfs(time, latitude, longitude, altitude, coord)\n\n% Fundamental constant.\nRearth_km = 6371.2;\n\n%%% CHECK INPUT VALIDITY %%%\n% Convert time to a datenumber if it is a string.\nif ischar(time)\n time = datenum(time);\nend\n\n% Check that the input coordinates are scalars.\nif ~isscalar(latitude) || ~isscalar(longitude) || ~isscalar(altitude)\n error('igrf1:inputNotScalar', ...\n 'The input coordinates must be scalars.');\nend\n\n%%% SPHERICAL COORDINATE CONVERSION %%%\n% Convert the latitude, longitude, and altitude coordinates input into\n% spherical coordinates r (radius), theta (inclination angle from +z axis),\n% and phi (azimuth angle from +x axis).\n% We want cos(theta) and sin(theta) rather than theta itself.\ncostheta = cos((90 - latitude)*pi/180);\nsintheta = sin((90 - latitude)*pi/180);\n\n% Convert from geodetic coordinates to geocentric coordinates if necessary.\n% This method was adapted from igrf11syn, which was a conversion of the\n% IGRF subroutine written in FORTRAN.\nif nargin < 5 || isempty(coord) || strcmpi(coord, 'geodetic') || ...\n strcmpi(coord, 'geod') || strcmpi(coord, 'gd')\n a = 6378.137; f = 1/298.257223563; b = a*(1 - f);\n rho = hypot(a*sintheta, b*costheta);\n r = sqrt( altitude.^2 + 2*altitude.*rho + ...\n (a^4*sintheta.^2 + b^4*costheta.^2) ./ rho.^2 );\n cd = (altitude + rho) ./ r;\n sd = (a^2 - b^2) ./ rho .* costheta.*sintheta./r;\n oldcos = costheta;\n costheta = costheta.*cd - sintheta.*sd;\n sintheta = sintheta.*cd + oldcos.*sd;\nelseif strcmpi(coord, 'geocentric') || strcmpi(coord, 'geoc') || ...\n strcmpi(coord, 'gc')\n r = altitude;\n cd = 1;\n sd = 0;\nelse\n error('igrf:coordInputInvalid', ['Unrecognized command ' coord ...\n ' for COORD input.']);\nend\n\n% Convert longitude to radians.\nphi = longitude*pi/180;\n\n%%% GET PROPER IGRF COEFFICIENTS %%%\nif isscalar(time)\n gh = loadigrfcoefs(time);\n nmax = sqrt(numel(gh) + 1) - 1;\n% Assume a vector input means the coefficients are the input.\nelse\n gh = time;\n nmax = sqrt(numel(gh) + 1) - 1;\n % nmax should be an integer.\n if nmax - round(nmax) ~= 0\n error('igrf:timeInputInvalid', ['TIME input should either be ' ...\n 'a single date or a valid coefficient vector.']);\n end\nend\n\n% We need cos(m*phi) and sin(m*phi) multiple times, so precalculate into a\n% vector here:\ncosphi = cos((1:nmax)*phi);\nsinphi = sin((1:nmax)*phi);\n\nPmax = (nmax+1)*(nmax+2)/2;\n\n%%% BEGIN MAGNETIC FIELD CALCULATION %%%\n% Initialize variables used in for loop below.\nBr = 0; Bt = 0; Bp = 0;\n P = zeros(1, Pmax); P(1) = 1; P(3) = sintheta;\ndP = zeros(1, Pmax); dP(1) = 0; dP(3) = costheta;\n\n% For this initial condition, the first if will result in n = 1, m = 0.\nm = 1; n = 0; coefindex = 1;\n\na_r = (Rearth_km/r)^2;\n\n% Increment through all the n's and m's. gh will be a vector with g\n% followed by h for incrementing through n and m except when h would be\n% redundant (i.e., when m = 0).\nfor Pindex = 2:Pmax\n \n % Increment to the next n when m becomes larger than n.\n if n < m\n m = 0;\n n = n + 1;\n a_r = a_r*(Rearth_km/r); % We need (Rearth_km./r)^(n+2)\n end\n \n % Calculate P and dP. They are given recursively according to:\n % \n % P(0, 0) = 1, P(1, 1) = sin(theta) <- Specified above\n % P(n, n) = sqrt(1 - 1/(2n))*sin(theta)*P(n-1, n-1)\n % P(n, m) = (2n - 1)/sqrt(n^2 - m^2)*cos(theta)*P(n-1, m) -\n % sqrt(((n-1)^2 - m^2) / (n^2 - m^2)) * P(n-2, m)\n % \n % dP(0, 0) = 0, dP(1, 1) = cos(theta) <- Specified above\n % dP(n, n) = sqrt(1 - 1/(2n))*(sin(theta)*dP(n-1, n-1) +\n % cos(theta)*P(n-1, n-1))\n % dP(n, m) = (2n - 1)/sqrt(n^2 - m^2)*(cos(theta)*dP(n-1, m) -\n % sin(theta)*P(n-1, m)) - sqrt(((n-1)^2 - m^2)/(n^2 - m^2))*\n % dP(n-2, m)\n if m < n && Pindex ~= 3 % (Pindex=3 is n=1, m=1, initial cond. above)\n last1n = Pindex - n;\n last2n = Pindex - 2*n + 1;\n P(Pindex) = (2*n - 1)/sqrt(n^2 - m^2)*costheta*P(last1n) - ...\n sqrt(((n-1)^2 - m^2) / (n^2 - m^2)) * P(last2n);\n dP(Pindex) = (2*n - 1)/sqrt(n^2 - m^2)*(costheta*dP(last1n) - ...\n sintheta*P(last1n)) - sqrt(((n-1)^2 - m^2) / (n^2 - m^2)) * ...\n dP(last2n);\n elseif Pindex ~= 3\n lastn = Pindex - n - 1;\n P(Pindex) = sqrt(1 - 1/(2*m))*sintheta*P(lastn);\n dP(Pindex) = sqrt(1 - 1/(2*m))*(sintheta*dP(lastn) + ...\n costheta*P(lastn));\n end\n \n % Calculate the magnetic field components as a running sum. Find\n % explicit expressions for these in Global Earth Physics: a Handbook of\n % Physical Constants by Thomas J. Aherns (1995), pg. 49. Link:\n % http://books.google.com/books?id=aqjU_NHyre4C&lpg=PP1&dq=Global%20\n % earth%20physics%3A%20a%20handbook%20of%20physical%20constants&pg=PA49\n % #v=onepage&q&f=false\n % (except equation 6 is missing a required 1/sin(theta) and m; correct\n % equations on page 5 (equations 3a-3c) of:\n % http://hanspeterschaub.info/Papers/UnderGradStudents/\n % MagneticField.pdf)\n if m == 0 % Implies h = 0, so only coefficient in gh is g\n coef = a_r*gh(coefindex); %*cos(0*phi) = 1\n Br = Br + (n+1)*coef*P(Pindex);\n Bt = Bt - coef*dP(Pindex);\n % Bp is 0 for m = 0.\n coefindex = coefindex + 1; % Only need to skip over g this time.\n else\n coef = a_r*(gh(coefindex)*cosphi(m) + gh(coefindex+1)*sinphi(m));\n Br = Br + (n+1)*coef*P(Pindex);\n Bt = Bt - coef*dP(Pindex);\n if sintheta == 0 % Use different formula when dividing by 0.\n Bp = Bp - costheta*a_r*(-gh(coefindex)*sinphi(m) + ...\n gh(coefindex+1)*cosphi(m))*dP(Pindex);\n else\n Bp = Bp - 1/sintheta*a_r*m*(-gh(coefindex)*sinphi(m) + ...\n gh(coefindex+1)*cosphi(m))*P(Pindex);\n end\n coefindex = coefindex + 2; % Skip over g and h this time.\n end\n \n % Increment m.\n m = m + 1;\n \nend\n\n% Convert from spherical to (x,y,z) = (North,East,Down).\nBx = -Bt;\nBy = Bp;\nBz = -Br;\n\n% Convert back to geodetic coordinates if necessary.\nBx_old = Bx;\nBx = Bx.*cd + Bz.*sd;\nBz = Bz.*cd - Bx_old.*sd;", "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/34388-international-geomagnetic-reference-field-igrf-model/igrf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.4895237149067962}} {"text": "%FEATSELM Feature selection map\n% \n% [W,R] = FEATSELM(A,CRIT,METHOD,K,T,PAR1,...)\n% \n% INPUT\n% A \tTraining dataset \n% CRIT \tName of criterion: 'in-in', 'maha-s', 'NN' or others \n% (see FEATEVAL) or an untrained classifier V (default: 'NN')\n% METHOD - 'forward' : selection by featself (default)\n% \t - 'float' : selection by featselp\n% \t - 'backward': selection by featselb\n% \t - 'b&b' : branch and bound selection by featselo\n% \t - 'ind' : individual\n% \t - 'lr' : plus-l-takeaway-r selection by featsellr\n% - 'sparse' : use sparse untrained classifier CRIT\n% K \tDesired number of features (default: K = 0, return optimal set)\n% T \tTuning set to be used in FEATEVAL (optional)\n% PAR1,.. Optional parameters:\n% \t - L,R : for 'lr' (default: L = 1, R = 0)\n%\n% OUTPUT\n% W Feature selection mapping\n% R Matrix with step by step results \n%\n% DESCRIPTION\n% Computation of a mapping W selecting K features. This routines offers a\n% central interface to all other feature selection methods. W can be used\n% for selecting features in a dataset B using B*W.\n% \n% SEE ALSO (PRTools Guide)\n% MAPPINGS, DATASETS, FEATEVAL, FEATSELO, FEATSELB, FEATSELI,\n% FEATSELP, FEATSELF, FEATSELLR\n\n% Copyright: R.P.W. Duin, r.p.w.duin@37steps.com\n% Faculty EWI, Delft University of Technology\n% P.O. Box 5031, 2600 GA Delft, The Netherlands\n\nfunction [w,res] = featselm(a,crit,arg3,ksel,t,par1,par2)\n\n\t\t\n\tif (nargin < 2 | isempty(crit))\n\t\tprwarning(2,'criterion not specified, assuming NN');\n\t\tcrit = 'NN'; \n\tend\n\tif (nargin < 3 | isempty(arg3))\n\t\tprwarning(2,'method not specified, assuming forward');\n\t\targ3 = 'forward'; \n\tend\n\tif (nargin < 4)\n\t\tksel = [];\n\tend\n\tif (nargin < 5)\n\t\tprwarning(3,'no tuning set supplied (risk of overfit)');\n\t\tt = []; \n\tend\n\tif (nargin < 6), par1 = []; end;\n\tif (nargin < 7), par2 = []; end;\n\n\t% If no arguments are supplied, return an untrained mapping.\n\n\tif (nargin == 0) | (isempty(a))\n\t\tw = prmapping('featselm',{crit,arg3,ksel,t,par1,par2});\n\t\tw = setname(w,'Feature Selection');\n\t\treturn\n\tend\n\n\ta = testdatasize(a);\n\t[m,k] = size(a);\n\n\tif (isstr(arg3))\n\t\tmethod = arg3;\t\t\t\t\t\t\t\t\t\t\t\t% If the third argument is a string,\n\t\tswitch (method)\t\t\t\t\t\t\t\t\t\t\t\t% it specifies the method to use.\n\t\t case {'forward','featself'}\t\t\t\t\t\t\t\t\t\t\t\n\t\t [w,res] = featself(a,crit,ksel,t);\n\t\t case {'float','featselp'}\n\t\t [w,res] = featselp(a,crit,ksel,t);\n\t\t case {'backward','featselb'}\n\t\t [w,res] = featselb(a,crit,ksel,t);\n\t\t case {'b&b','featselo'}\n\t\t [w,res] = featselo(a,crit,ksel,t);\n\t\t case {'ind','featseli'}\n\t\t [w,res] = featseli(a,crit,ksel,t);\n\t\t case {'lr','featsellr'}\n\t\t [w,res] = featsellr(a,crit,ksel,par1,par2,t);\n\t\t case {'sparse'}\n\t\t v = a*crit;\n\t\t if isaffine(v)\n\t\t \tv = getdata(v,'rot');\n\t\t \tw = featsel(size(a,2),find(v(:,1) == 0));\t\n\t\t\telse\n\t\t\t\tv = getdata(v,'beta');\n\t\t end\n\t\t w = featsel(size(a,2),find(v(:,1) ~= 0));\n\t\t otherwise\n\t\t error('Unknown method specified.')\n\t\tend\n\telseif (ismapping(arg3))\t\t\t\t\t\t\t\t\n\t\tw = arg3;\t\t\t\t\t\t\t\t\t\t\t\t% If the third argument is a mapping,\n\t\tisuntrained(w);\t\t\t\t\t\t\t\t\t% assert it is untrained and train\n\t\t[w,res] = feval(mfilename,a,crit,w.mapping_file,ksel,t,par1,par2);\n\telse\n\t\terror('Illegal method specified.')\n\tend\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/featselm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.48952371381007376}} {"text": "% Filtering A Delta Function Input Signal Example Part 2\n%\n% This example illustrates how numerical aliasing can be avoided by\n% spatially smoothing the source mask.\n%\n% author: Bradley Treeby\n% date: 19th January 2010\n% last update: 24th August 2014\n% \n% This function is part of the k-Wave Toolbox (http://www.k-wave.org)\n% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox\n\n% This file is part of k-Wave. k-Wave is free software: you can\n% redistribute it and/or modify it under the terms of the GNU Lesser\n% General Public License as published by the Free Software Foundation,\n% either version 3 of the License, or (at your option) any later version.\n% \n% k-Wave is distributed in the hope that it will be useful, but WITHOUT ANY\n% WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n% FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for\n% more details. \n% \n% You should have received a copy of the GNU Lesser General Public License\n% along with k-Wave. If not, see . \n\nclear all\n\n% =========================================================================\n% SIMULATION\n% =========================================================================\n\n% create the computational grid\nNx = 256; % number of grid points in the x (row) direction\ndx = 10e-3/Nx; % grid point spacing in the x direction [m]\nkgrid = makeGrid(Nx, dx);\n\n% define the properties of the propagation medium\nmedium.sound_speed = 1500; % [m/s]\n\n% create a time array\nnum_time_steps = 1024;\n[kgrid.t_array, dt] = makeTime(kgrid, medium.sound_speed);\nkgrid.t_array = 0:dt:dt*(num_time_steps - 1);\n\n% define a single element source\nsource_offset = 50;\nsource.p_mask = zeros(Nx, 1);\nsource.p_mask(1 + source_offset, 1) = 1;\n\n% spatially smooth the source mask maintaining the maximum magnitude\nsource.p_mask = smooth(kgrid, source.p_mask, true);\n\n% threshold out small values\nsource.p_mask(source.p_mask < 0.05) = 0;\n\n% define a delta function input pulse\ntemporal_offset = 100; % [time steps]\nsource_magnitude = 2; % [au]\nsource_func = zeros(size(kgrid.t_array));\nsource_func(temporal_offset) = source_magnitude;\n\n% assign and scale the input pulse based on the source mask\nsource.p(1:sum(source.p_mask ~= 0),:) = source.p_mask(source.p_mask ~= 0)*source_func;\n\n% force the source mask to be binary\nsource.p_mask(source.p_mask ~= 0) = 1;\n\n% define a single element sensor\nsensor.mask = zeros(Nx, 1);\nsensor.mask(end - source_offset, 1) = 1;\n\n% run the simulation\nsensor_data = kspaceFirstOrder1D(kgrid, medium, source, sensor, 'PMLSize', 30);\n\n% compute the amplitude spectra of the recorded time series\n[f, output_as] = spect(sensor_data, 1/dt);\n\n% extract the maximum frequency supported by the grid (two points per\n% wavelength)\nf_max = kgrid.k_max * min(medium.sound_speed(:)) / (2*pi);\n\n% =========================================================================\n% VISUALISATION\n% =========================================================================\n\n% plot the input and recorded time series\nfigure;\n[t_sc, scale, prefix] = scaleSI(max(kgrid.t_array(:)));\nplot(kgrid.t_array*scale, source.p(floor(sum(source.p_mask(:))/2) + 1, :), 'k-', kgrid.t_array*scale, sensor_data, 'b-');\nxlabel(['Time [' prefix 's]']);\nylabel('Pressure [au]');\nlegend('input pulse', 'recorded pulse');\n\n% plot the amplitude spectrum\n[f_sc, scale, prefix] = scaleSI(max(f));\nfigure;\nplot(f*scale, output_as, 'b-');\nxlabel(['Frequency [' prefix 'Hz]']);\nylabel('Amplitude [au]');\n\n% plot the maximum frequency supported by the grid\nylim = get(gca, 'YLim');\nhold on;\nline([f_max*scale, f_max*scale], [0, ylim(2)], 'LineStyle','--', 'Color', 'k');\nlegend('amplitude spectrum of recorded pulse', 'maximum frequency supported by grid');", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/K-wave/k-Wave/examples/example_na_filtering_part_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6297745935070808, "lm_q1q2_score": 0.48952370410440144}} {"text": "function M = ptv_params_to_matrix(params, transform_type)\n if isnumeric(transform_type)\n if transform_type == -1\n transform_type = 'translate';\n elseif transform_type == -2\n transform_type = 'rigid';\n elseif transform_type == -3\n transform_type = 'rigid_scale';\n elseif transform_type == -4\n transform_type = 'affine';\n end\n end\n \n \n if strcmp(transform_type, 'affine')\n M = [1 + params(3), params(4), params(1); ...\n params(5), 1 + params(6), params(2)];\n elseif strcmp(transform_type, 'rigid')\n theta = params(3);\n M = [cos(theta), -sin(theta), params(1); ...\n sin(theta), cos(theta), params(2)];\n elseif strcmp(transform_type, 'rigid_scale')\n theta = params(3);\n scale = 1 + params(4);\n M = [cos(theta) * scale, -sin(theta) * scale, params(1); ...\n sin(theta) * scale, cos(theta) * scale, params(2)];\n elseif strcmp(transform_type, 'translate')\n M = [1, 0, params(1); ...\n 0, 1, params(2)];\n end\nend", "meta": {"author": "visva89", "repo": "pTVreg", "sha": "c359620e3c8435392db02354274d6c74d682d437", "save_path": "github-repos/MATLAB/visva89-pTVreg", "path": "github-repos/MATLAB/visva89-pTVreg/pTVreg-c359620e3c8435392db02354274d6c74d682d437/ptv/ptv_params_to_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.4894293260345464}} {"text": "function [sos,g] = driving_function_imp_nfchoa_pw(N,R,conf)\n%DRIVING_FUNCTION_IMP_NFCHOA_PW second-order section representation for a\n%plane wave in NFC-HOA\n%\n% Usage: sos = driving_function_imp_nfchoa_pw(N,R,conf)\n%\n% Input parameters:\n% N - order of spherical Hankel function\n% R - radius of secondary source array / m\n% conf - configuration struct (see SFS_config)\n%\n% Output parameters:\n% sos - second-order section representation\n% g - scalar gain factor\n%\n% See also: sound_field_imp, sound_field_imp_nfchoa,\n% driving_function_imp_nfchoa\n%\n% References:\n% Spors, Kuscher, Ahrens (2011) - \"Efficient realization of model-based\n% rendering for 2.5-dimensional near-field compensated higher order\n% Ambisonics\", IEEE Workshop on Applications of Signal Processing to Audio\n% and Acoustics (WASPAA), pp. 61-64,\n% https://doi.org/10.1109/ASPAA.2011.6082325\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 = 3;\nnargmax = 3;\nnarginchk(nargmin,nargmax);\nisargpositivescalar(N,R);\nisargstruct(conf);\n\n\n%% ===== Configuration ==================================================\nc = conf.c;\ndimension = conf.dimension;\ndriving_functions = conf.driving_functions;\n\n\n%% ===== Computation =====================================================\n% Find spherical Hankel function zeros\n[z,p] = sphbesselh_zeros(N);\n\n% Get the delay and weighting factors\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 plane wave.'],upper(mfilename),driving_functions);\n end\n\n\nelseif strcmp('2.5D',dimension) || strcmp('3D',dimension)\n\n % === 2.5- & 3-Dimensional ==========================================\n\n switch driving_functions\n case 'default'\n % --- SFS Toolbox ------------------------------------------------\n % 2.5D for a plane wave as source model\n %\n [sos, g] = zp2sos(p,z*c/R,1,'down','none');\n g = g * (-1)^abs(N) * 4*pi * R;\n %\n % Compare Spors et al. (2011), eq. (10)\n %\n otherwise\n error(['%s: %s, this type of driving function is not implemented', ...\n 'for a 2.5D plane wave.'],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_time_domain/driving_functions_imp/driving_function_imp_nfchoa_pw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6150878696277513, "lm_q1q2_score": 0.4893996457199097}} {"text": "function [xUpdate,PUpdate,innov,Pzz,W]=cubKalUpdate(xPred,PPred,z,R,h,xi,w,innovTrans,measAvgFun,stateDiffTrans,stateTrans)\n%CUBKALUPDATE Perform the measurement update step in the cubature Kalman\n% filter with additive measurement noise. Unlike the square\n% root version, one can use cubature points with negative\n% weights.\n%\n%INPUTS: xPred The xDim X 1 predicted target state.\n% PPred The xDim X xDim predicted state covariance matrix. \n% z The zDim X 1 vector measurement.\n% R The zDim X zDim measurement covariance matrix in the native\n% coordinate system of the measurement.\n% h A function handle for the measurement function that takes\n% the state as its argument.\n% xi An xDim X numCubPoints matrix of cubature points. If this\n% and the next parameter are omitted or empty matrices are\n% passed, then fifthOrderCubPoints(xDim) is used. It is \n% suggested that xi and w be provided to avoid needless\n% recomputation of the cubature points.\n% w A numCubPoints X 1 vector of the weights associated with the\n% cubature points.\n% innovTrans An optional function handle that computes and optionally\n% transforms the value of the difference between the\n% observation and any predicted points. This is called as\n% innovTrans(a,b) and the default if omitted or an empty\n% matrix is passed is @(a,b)bsxfun(@minus,a,b). This must be\n% able to handle sets of values. For a zDimX1 measurement,\n% either of the inputs could be zDimXN in size while one of\n% the inputs could be zDimX1 in size. This only needs to be\n% supplied when a measurement difference must be restricted\n% to a certain range. For example, the innovation between two\n% angles will be 2*pi if one angle is zero and the other\n% 2*pi, even though they are the same direction. In such an\n% instance, a function handle to the\n% wrapRange(bsxfun(@minus,a,b),-pi,pi) function with the\n% appropriate parameters should be passed for innovTrans.\n% measAvgFun An optional function handle that, when given N measurement\n% values with weights, produces the weighted average. This\n% function only has to be provided if the domain of the\n% measurement is not linear. For example, when averaging\n% angular values, then the function meanAng should be used.\n% stateDiffTrans An optional function handle that takes an xDimXN matrix of\n% N differences between states and transforms them however\n% might be necessary. If not transformation is necessary, this\n% parameter can be omitted or an empty matrix passed.\n% stateTrans An optional function that takes a state estimate and\n% transforms it. This is useful if one wishes the elements of\n% the state to be bound to a certain domain. For example, if\n% an element of the state is an angle, one might generally\n% want to bind it to the region +/-pi.\n%\n%OUTPUTS: xUpdate The xDim X 1 updated state vector.\n% PUpdate The updated xDim X xDim state covariance matrix.\n% innov, Pzz The zDimX1 innovation and the zDimXzDim innovation\n% covariance matrix are returned in case one wishes to\n% analyze the consistency of the estimator or use those\n% values in gating or likelihood evaluation.\n% W The xDimXzDim gain used in the update. This can be\n% useful when gating and using the function\n% calcMissedGateCov.\n%\n%If the function h needs additional parameters beyond the state, then the\n%parameters can be passed by using an anonymous function as the function\n%handle. For example, suppose that the measurement function is measFunc and\n%it needs the additional parameters param1 and param2. In this instance,\n%rather than using\n%h=@measFunc\n%one should use\n%h=@(x)measFunc(x,param1,param2)\n%This way, every time cubKalUpdate calls measFunc (via h) with a\n%different x, those two parameters are always passed.\n%\n%The mathematics behind the function cubKalUpdate are described in\n%detail in Section IX of [1] and in [2]. Note that this is essentially the\n%\"unscented Kalman filter\" with additive noise. One simply has to provide\n%the filter with the appropriate cubature points and weights.\n%\n%The optional parameters innovTrans and measAvgFun are not described in\n%references [1] and [2], but allow for possible modifications to the filter\n%as described in [3]. The parameters have been added to allow the filter to\n%be used with angular quantities. For example, if the measurement consisted\n%of range and angle, z=[r;theta], then\n%innovTrans=@(a,b)[bsxfun(@minus,a(1,:),b(1,:));\n% wrapRange(bsxfun(@minus,a(2,:),b(2,:)),-pi,pi)];\n%measAvgFun=@(z,w)[calcMixtureMoments(z(1,:),w);\n% meanAng(z(2,:),w')];\n%should be used to approximately deal with the circular nature of the\n%measurements.\n%\n%REFERENCES:\n%[1] D. F. Crouse , \"Basic tracking using nonlinear 3D monostatic and\n% bistatic measurements,\" IEEE Aerospace and Electronic Systems Magazine,\n% vol. 29, no. 8, Part II, pp. 4-53, Aug. 2014.\n%[2] I. Arasaratnam and S. Haykin, \"Cubature Kalman filters,\" IEEE\n% Transactions on Automatic Control, vol. 54, no. 6, pp. 1254-1269,\n% Jun. 2009.\n%[3] D. F. Crouse, \"Cubature/ unscented/ sigma point Kalman filtering with\n% angular measurement models,\" in Proceedings of the 18th International\n% Conference on Information Fusion, Washington, D.C., 6-9 Jul. 2015.\n%\n%September 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n xDim=size(xPred,1);\n \n if(nargin<6||isempty(xi))\n [xi,w]=fifthOrderCubPoints(xDim);\n end\n\n if(nargin<8||isempty(innovTrans))\n %The function just returns the input difference.\n innovTrans=@(a,b)bsxfun(@minus,a,b);\n end\n \n if(nargin<9||isempty(measAvgFun))\n measAvgFun=@(zPoints,w)calcMixtureMoments(zPoints,w);\n end\n \n if(nargin<10||isempty(stateDiffTrans))\n stateDiffTrans=@(x)x; \n end\n \n if(nargin<11||isempty(stateTrans))\n stateTrans=@(x)x; \n end\n \n zDim=size(z,1);\n\n numCubPoints=size(xi,2);\n \n %cholSemiDef is used instead of chol in case a positive semi-definite\n %covariance matrix is passed.\n SPred=cholSemiDef(PPred,'lower');\n %Predicted cubature state points\n xPredPoints=stateTrans(transformCubPoints(xi,xPred,SPred));\n\n %Predicted cubature measurement points\n zPredPoints=zeros(zDim,numCubPoints);\n for curP=1:numCubPoints\n zPredPoints(:,curP)=h(xPredPoints(:,curP));\n end\n \n %Measurement prediction.\n zPred=measAvgFun(zPredPoints,w);\n \n %The innovation, transformed as necessary to keep values in a desired\n %range.\n innov=innovTrans(z,zPred);\n \n xPredCenPoints=stateDiffTrans(bsxfun(@minus,xPredPoints,xPred));\n %Centered, predicted cubature measurement points, transformed as\n %necessary to keep the values within a desired range.\n zPredCenPoints=innovTrans(zPredPoints,zPred);\n Pzz=R;\n Pxz=zeros(xDim,zDim);\n for curP=1:numCubPoints\n diff=zPredCenPoints(:,curP);\n Pzz=Pzz+w(curP)*(diff*diff');\n Pxz=Pxz+w(curP)*xPredCenPoints(:,curP)*diff';\n end\n \n %The filter gain\n W=Pxz/Pzz;\n \n %Updated state estimate\n xUpdate=stateTrans(xPred+W*innov);\n \n %Updated state covariance matrix\n %We could just do a simple one-line solution as in [1] and [2].\n %However, that does not guarantee that PUpdate will always be position\n %(semi)definite. Thus, we use an equivalent but more complicated update\n %formula based on Equation in Appendix C of [1].\n PUpdate=W*R*W';\n for curP=1:numCubPoints\n diff=stateDiffTrans(xPredCenPoints(:,curP)-W*zPredCenPoints(:,curP));\n PUpdate=PUpdate+w(curP)*(diff*diff');\n end\n %Ensure symmetry\n PUpdate=(PUpdate+PUpdate')/2;\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/Measurement_Update/Complete_Measurement_Updates/cubKalUpdate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4893996344918333}} {"text": "function [w,run] = train_dual(x,w,lambda,priority,mod)\n\n% Written by Thomas P Minka\n\nflops(0);\n% kernel matrix\nc = x'*x;\ndc = diag(c);\nv = 1/lambda;\n% for flop counting, multiplication by lambda is free\n\n[d,n] = size(x);\n% this assumes w = 0\nalpha = repmat(1e-4,n,1);\n% Keerthi-type initialization\nalpha = repmat(1/n,n,1);\nif nargin < 4\n priority = 1;\nend\nif nargin < 5\n mod = 0;\nend\n\ncount = 1;\nfor iter = 1:2000\n old_alpha = alpha;\n % annealing for expt2\n %v = v + 1e2\n if ~priority \n if mod\n for i = 1:n\n\ttheta = log(alpha(i)./(1-alpha(i)));\n\tg = v*(c(i,:)*alpha) + theta;\n\ta = alpha(i)*(1-alpha(i));\n\th = v*dc(i) + 1/a;\n\t%h = h*a*a;\n\t%h = h*a + g*(1-2*alpha(i));\n\tif 1\n\t a = alpha(i);\n\t c2 = ((1+log(a))*a*h-g)/((1+log(a))*a/(1-a) + 1+log(1-a));\n\t c1 = a*(h - c2/(1-a));\n\t as = linspace(eps,1-eps,100);\n\t f = [];\n\t f2 = [];\n\t f0 = 0.5*v*(alpha'*c*alpha) + ...\n\t sum(alpha.*log(alpha)) + sum((1-alpha).*log(1-alpha));\n\t for k = 1:length(as)\n\t alpha(i) = as(k);\n\t f(k) = 0.5*v*(alpha'*c*alpha) + ...\n\t\tsum(alpha.*log(alpha)) + sum((1-alpha).*log(1-alpha));\n\t f2(k) = c1*as(k)*log(as(k))+c2*(1-as(k))*log(1-as(k));\n\t f2(k) = f2(k) - (c1*a*log(a)+c2*(1-a)*log(1-a)) + f0;\n\t end\n\t if 0\n\t plot(as,f,as,f2)\n\t drawnow\n\t ax = axis;\n\t line([a a],[ax(3) ax(4)],'Color','r')\n\t axis_pct\n\t pause\n\t end\n\tend\n\ttheta = theta - g/h;\n\talpha(i) = 1/(1+exp(-theta));\n end\n flops(flops + n*(6+2+flops_exp));\n else\n for i = 1:n\n\tg = v*(c(i,:)*alpha) + log(alpha(i)./(1-alpha(i)));\n\th = v*dc(i) + 1/alpha(i)/(1-alpha(i));\n\talpha(i) = alpha(i) - g./h;\n\tif alpha(i) < eps\n\t alpha(i) = eps;\n\telseif alpha(i) > 1-eps\n\t alpha(i) = 1-eps;\n\tend\n end\n end\n flops(flops + n*(flops_mul(1,n,1)+3+flops_exp + 4 + 2));\n else\n % incremental algorithm\n if iter == 1\n g = v*(c*alpha) + log(alpha./(1-alpha));\n flops(flops + flops_mul(c,alpha)+n*(flops_exp+3));\n end\n for j = 1:n\n [dummy,i] = max(abs(g));\n %disp(['i=' num2str(i) ' g=' num2str(g(i))])\n %i = j;\n o_alpha = alpha(i);\n h = v*dc(i) + 1/alpha(i)/(1-alpha(i));\n if mod\n\ttheta = log(alpha(i)./(1-alpha(i)));\n\ta = alpha(i)*(1-alpha(i));\n\tgt = g(i)*a;\n\th = h*a*a + gt*(1-2*alpha(i));\n\ttheta = theta - g/h;\n\talpha(i) = 1/(1+exp(-theta));\n else\n\talpha(i) = alpha(i) - g(i)./h;\n end\n if alpha(i) < eps\n\talpha(i) = eps;\n elseif alpha(i) > 1-eps\n\talpha(i) = 1-eps;\n end\n % update all g(i)\n da = alpha(i) - o_alpha; % no cost\n dg = da*c(:,i)*v;\n dg(i) = dg(i) + log(alpha(i)/(1-alpha(i))) - ...\n\t log(o_alpha/(1-o_alpha));\n % no cost for second log\n g = g + dg;\n end\n flops(flops + n*(2*n-1 + 4 + 2 + 2) + n*(n + flops_exp+4 + n));\n end\n\n % computations here don't count\n w = v*x*alpha;\n run.w(:,count) = w;\n run.flops(count) = flops;\n run.e(count) = logProb(x,w) -0.5/v*w'*w;\n e2(count) = 0.5/v*w'*w + sum(alpha.*log(alpha)) + sum((1-alpha).*log(1-alpha));\n count = count + 1;\n if rem(count,200) == 0\n fprintf('Kernel count %d\\n', count)\n end\n \n if max(abs(alpha - old_alpha)) < 1e-8\n break\n end\nend\nif iter == 2000\n warning('not enough iters')\nend\nif nargout > 1\n figure(2)\n % e should go up, e2 go down\n plot(1:length(run.e), run.e, 1:length(e2), e2)\nend\n", "meta": {"author": "FuzhenZhuang", "repo": "Transfer-Learning-Toolkit", "sha": "24b5323b354aee844b8b7df9fcad17fdfb191dc4", "save_path": "github-repos/MATLAB/FuzhenZhuang-Transfer-Learning-Toolkit", "path": "github-repos/MATLAB/FuzhenZhuang-Transfer-Learning-Toolkit/Transfer-Learning-Toolkit-24b5323b354aee844b8b7df9fcad17fdfb191dc4/utilities/TLLibrary64/LR/logreg/train_dual.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.4891150630442531}} {"text": "% OP_UXN_VXN_2D: assemble the matrix M = [m(i,j)], m(i,j) = (mu u_j x n, v_i x n), with n the exterior normal vector.\n%\n% mat = op_uxn_vxn_2d (spu, spv, msh, coeff);\n% [rows, cols, values] = op_uxn_vxn_2d (spu, spv, msh, coeff);\n%\n% INPUT:\n% \n% spu: structure representing the space of trial functions (see sp_vector/sp_eval_boundary_side)\n% spv: structure representing the space of test functions (see sp_vector/sp_eval_boundary_side)\n% msh: structure containing the domain partition and the quadrature rule (see msh_cartesian/msh_eval_boundary_side)\n% coeff: physical parameter\n%\n% OUTPUT:\n%\n% mat: assembled matrix\n% rows: row indices of the nonzero entries\n% cols: column indices of the nonzero entries\n% values: values of the nonzero entries\n% \n% Copyright (C) 2009, 2010 Carlo de Falco, Rafael Vazquez\n% Copyright (C) 2011, 2017 Rafael Vazquez\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\nfunction varargout = op_uxn_vxn_2d (spu, spv, msh, coeff)\n \n rows = zeros (msh.nel * spu.nsh_max * spv.nsh_max, 1);\n cols = zeros (msh.nel * spu.nsh_max * spv.nsh_max, 1);\n values = zeros (msh.nel * spu.nsh_max * spv.nsh_max, 1);\n\n jacdet_weights = msh.jacdet .* msh.quad_weights .* coeff;\n\n ncounter = 0;\n for iel = 1:msh.nel\n if (all (msh.jacdet(:, iel)))\n shpu_iel = reshape (spu.shape_functions(:, :, :, iel), spu.ncomp, msh.nqn, spu.nsh_max);\n shpv_iel = reshape (spv.shape_functions(:, :, :, iel), spv.ncomp, msh.nqn, spv.nsh_max);\n\n normal_iel = reshape (msh.normal(:,:,iel), 2, msh.nqn);\n shpu_x_n = bsxfun (@times, shpu_iel(1,:,:), normal_iel(2,:)) - ...\n bsxfun (@times, shpu_iel(2,:,:), normal_iel(1,:));\n shpv_x_n = bsxfun (@times, shpv_iel(1,:,:), normal_iel(2,:)) - ...\n bsxfun (@times, shpv_iel(2,:,:), normal_iel(1,:));\n shpu_x_n = reshape (shpu_x_n, msh.nqn, 1, spu.nsh_max);\n shpv_x_n = reshape (shpv_x_n, msh.nqn, spv.nsh_max, 1);\n \n jacdet_iel = jacdet_weights(:,iel);\n jacdet_shpu = bsxfun (@times, jacdet_iel, shpu_x_n);\n tmp1 = bsxfun (@times, jacdet_shpu, shpv_x_n);\n elementary_values = reshape (sum (tmp1, 1), spv.nsh_max, spu.nsh_max);\n\n [rows_loc, cols_loc] = ndgrid (spv.connectivity(:,iel), spu.connectivity(:,iel));\n indices = rows_loc & cols_loc;\n rows(ncounter+(1:spu.nsh(iel)*spv.nsh(iel))) = rows_loc(indices);\n cols(ncounter+(1:spu.nsh(iel)*spv.nsh(iel))) = cols_loc(indices);\n values(ncounter+(1:spu.nsh(iel)*spv.nsh(iel))) = elementary_values(indices);\n ncounter = ncounter + spu.nsh(iel)*spv.nsh(iel);\n\n else\n warning ('geopdes:jacdet_zero_at_quad_node', 'op_uxn_vxn_2d: singular map in element number %d', iel)\n end\n end\n\n if (nargout == 1 || nargout == 0)\n varargout{1} = sparse (rows(1:ncounter), cols(1:ncounter), ...\n values(1:ncounter), spv.ndof, spu.ndof);\n elseif (nargout == 3)\n varargout{1} = rows(1:ncounter);\n varargout{2} = cols(1:ncounter);\n varargout{3} = values(1:ncounter);\n else\n error ('op_uxn_vxn_2d: wrong number of output arguments')\n end\n\nend\n", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/operators/op_uxn_vxn_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.754914975839675, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.4890325811873987}} {"text": "function optimizeFFT( dimension, dim, kernelSize, fft_planner_method, fftdimPerformed, lambdaCalib, flagZeropadding, sPrecision )\n%OPTIMIZEFFT optimize the fft command\n%\n% (c) Thomas Kuestner\n% ---------------------------------------------------------------------\n\nfprintf('Optimizing fft command\\n');\nif(strcmp(dimension,'2D'))\n if(dim(4) == 1)\n dimImg = [dim(1), dim(2), dim(5)]; % y-x-cha \n dimKernel = [dimImg(1)+kernelSize(1)-1, dimImg(2)+kernelSize(2)-1, dimImg(3)];\n else\n dimImg = [dim(4), dim(1), dim(2), dim(5)]; % t-y-x-cha\n dimKernel = [dimImg(1), dimImg(2)+kernelSize(1)-1, dimImg(3)+kernelSize(2)-1, dimImg(4)];\n end \nelseif(strcmp(dimension,'3D'))\n dimImg = [dim(1), dim(3), dim(2), dim(5)]; % y-z-x-cha\n dimKernel = [dimImg(1)+kernelSize(1)-1, dimImg(2)+kernelSize(2)-1, dimImg(3)+kernelSize(3)-1, dimImg(4)];\nelseif(strcmp(dimension,'4D'))\n dimImg = [dim(4), dim(1), dim(3), dim(2), dim(5)]; % t - y - z - x - cha\n dimKernel = [dimImg(1), dimImg(2)+kernelSize(1)-1, dimImg(3)+kernelSize(2)-1, dimImg(4)+kernelSize(3)-1, dimImg(5)];\nelseif(strcmp(dimension,'5D'))\n dimImg = [dim(4), dim(1), dim(3), dim(2), dim(6), dim(5)]; % t - y - z - x - g - cha\n dimKernel = [dimImg(1), dimImg(2)+kernelSize(1)-1, dimImg(3)+kernelSize(2)-1, dimImg(4)+kernelSize(3)-1, dimImg(5), dimImg(6)];\nend\n\n% check fft along dimensions\n% maximal fftdims = {1, 2, 3, [1 2], [1 3], [2 3], 1:3};\nfftdims = {fftdimPerformed};\nif(lambdaCalib > 0)\n fftdims{end+1} = 1:3; % due to corrKernelKspace -> convKernelImgspace\nend\n\n% check if wisdom file already exists\nif(evalin('base','exist(''fftw_wisdom'',''var'')'))\n sizesCalculated = evalin('base', 'fftw_wisdom.sizesCalculated');\n doOptimization = false;\n if(size(sizesCalculated,3) ~= length(fftdims) || isemtpy(ismember(reshape(ipermute(sizesCalculated,[1 3 2]),2*size(sizesCalculated,3),size(sizesCalculated,2)),dimImg,'rows')) || isemtpy(ismember(reshape(ipermute(sizesCalculated,[1 3 2]),2*size(sizesCalculated,3),size(sizesCalculated,2)),dimKernel,'rows')))\n evalin('base', 'clear ''fftw_wisdom''');\n doOptimization = true;\n end\nelse\n doOptimization = true;\nend\n% if(exist([currpath,filesep,'utils',filesep,'general',filesep,'fftw_wisdom.mat'],'file'))\n% load([currpath,filesep,'utils',filesep,'general',filesep,'fftw_wisdom.mat']);\n% doOptimization = false;\n% if(size(sizesCalculated,3) ~= length(fftdims) || isemtpy(ismember(reshape(ipermute(sizesCalculated,[1 3 2]),2*size(sizesCalculated,3),size(sizesCalculated,2)),dimImg,'rows')) || isemtpy(ismember(reshape(ipermute(sizesCalculated,[1 3 2]),2*size(sizesCalculated,3),size(sizesCalculated,2)),dimKernel,'rows')))\n% delete([currpath,filesep,'utils',filesep,'general',filesep,'fftw_wisdom.mat']);\n% doOptimization = true;\n% end\n% else\n% doOptimization = true;\n% end\n\nif(doOptimization)\n testImg = complex(randn(dimImg,sPrecision),randn(dimImg,sPrecision));\n if(flagZeropadding && lambdaCalib > 0)\n testKernel = complex(randn(dimKernel,sPrecision),randn(dimKernel,sPrecision));\n end\n \n sizesCalculated = zeros(2,length(dimImg),7);\n wisdom_str = cell(2,7);\n for i=1:length(fftdims)\n depth = sum(fftdims{i});\n if(length(fftdims{i}) > 1), depth = depth + 1; end;\n % optimize fft for image dimension\n fftw('planner',fft_planner_method);\n tmp = fftnshift(testImg,fftdims{i});\n wisdom_str{1,depth} = fftw('wisdom');\n sizesCalculated(1,:,depth) = dimImg;\n \n if(flagZeropadding && lambdaCalib > 0)\n % optimize fft for image kernel dimension\n fftw('planner',fft_planner_method);\n tmp = fftnshift(testKernel,fftdims{i});\n wisdom_str{2,depth} = fftw('wisdom');\n sizesCalculated(2,:,depth) = dimKernel; \n end\n end \n \n fftw_wisdom.sizesCalculated = sizesCalculated;\n fftw_wisdom.wisdom_str = wisdom_str;\n assignin('base', 'fftw_wisdom', fftw_wisdom);\n% save([currpath,filesep,'utils',filesep,'general',filesep,'fftw_wisdom.mat'], 'wisdom_str', 'sizesCalculated');\n clear 'testimg' 'testKernel';\nend\n\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/preproc/optimizeFFT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.48901156718994343}} {"text": "function y_buffer = BF_MakeBuffer(y,bufferSize)\n% BF_MakeBuffer Make a buffered version of a time series\n%\n% y_buffer contains segments (rows) of length bufferSize (columns) corresponding\n% to consecutive, non-overlapping segments of the series of length bufferSize\n\n% ------------------------------------------------------------------------------\n% Copyright (C) 2020, Ben D. Fulcher ,\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\nN = length(y);\n\nnumBuffers = floor(N/bufferSize);\n\n% May need trimming:\ny_buffer = y(1:numBuffers*bufferSize);\n\n% Then reshape:\ny_buffer = reshape(y_buffer,bufferSize,numBuffers)';\n\n% (Each buffer is a contiguous subsequence of the time series; a row of y_buffer)\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/PeripheryFunctions/BF_MakeBuffer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.48899063975647283}} {"text": "function [sol, infos] = gsp_wiener_optimization(G, x0, f, psd, psd_noise, param)\n%GSP_WIENER_OPTIMIZATION Solve wiener optimization problem\n% Usage: sol = gsp_wiener_optimization(G, x0, ffid, psd, psd_noise)\n% sol = gsp_wiener_optimization(G, x0, ffid, psd, psd_noise, param)\n% [sol, infos] = gsp_wiener_optimization(...)\n%\n% Input parameters:\n% G : Graph (GSP structure)\n% x0 : Starting point (column vector)\n% f : Fidelity term - UNLocBox structure\n% psd : PSD filter (anonymous function)\n% psd_noise : PSD filter of the noise or single number\n% param : Optional optimization parameters\n% Output parameters:\n% sol : Solution\n% infos : Convergence informations\n%\n% This function solves the following wiener optimization problem:\n%\n% .. argmin_x f(x) + || w(L) x ||_2^2 \n%\n% .. math:: arg\\min_x f(x) + \\| w(L) x \\|_2^2 \n%\n% Please refer to the reference for more information about this problem.\n% This function requires the UNLocBox to work.\n%\n% Please refer to the function gsp_filter_analysis and solvep to know how\n% *param* can be set.\n% \n% References: perraudin2016stationary\n\n% Author : Nathanael Perraudin\n% Date: 6 January 2016\n\n\nif nargin<6\n param = struct;\nend\n\nif isnumeric(psd_noise)\n if sum(abs(psd_noise(:)))==0\n error('This function cannot solve this problem')\n end\n if sum(abs(psd_noise(:)))<1e-10\n warning('This function can prabaly not solve this case');\n end\n wl = @(x) psd_noise./(psd(x)+eps);\n fprox = @(T) @(x) psd(x)./(psd(x)+2*T*psd_noise + eps); \nelse\n wl = @(x) psd_noise(x)./(psd(x)+eps);\n fprox = @(T) @(x) psd(x)./(psd(x)+2*T*psd_noise(x) + eps);\n\nend\n\n%fprox = @(x) 1./(wl(x)+1);\n\n% In order to be faster\nparam.stopping_criterion = 'rel_norm_obj';\n\n\n% Wiener term \nfwiener.prox = @(x,T) gsp_filter_analysis(G,fprox(T),x, param);\nfwiener.eval = @(x) 0.5*norm(gsp_filter_analysis(G,wl,x,param),'fro')^2;\n\n% Call the solver\n[sol , infos ] = solvep(x0,{f,fwiener},param);\n\nend", "meta": {"author": "epfl-lts2", "repo": "gspbox", "sha": "a7d9aac5e239f1bcb37a9bb09998cc161be2732f", "save_path": "github-repos/MATLAB/epfl-lts2-gspbox", "path": "github-repos/MATLAB/epfl-lts2-gspbox/gspbox-a7d9aac5e239f1bcb37a9bb09998cc161be2732f/stationarity/gsp_wiener_optimization.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.4888936041668201}} {"text": "function femIF = genP1IFEM3DFace(mesh,fem,femI)\n%% Usage: Generate Quadrature Information on Interface Faces Used in PPIFEM\n% Each interface face (triangle) is cut into 3 small triangles\n% A1 A1\n% D E or E D equivalent\n% A2 A3 A3 A2\n%\n% p = [A1;D;E;A2;A3];\n% t = [1 2 3; 2 3 4; 3 4 5]\n%\n% femIF.tL --- global index of left element\n% femIF.tR --- global index of right element\n% femIF.basL --- 3*nfi-4-4 matrix basis functions of left elem on small tri\n% femIF.basR --- 3*nfi-4-4 matrix basis functions of right elem on small tri\n% femIF.gx --- Gaussian x nodes on small tri\n% femIF.gy --- Gaussian y nodes on small tri\n% femIF.gz --- Gaussian z nodes on small tri\n% femIF.gw --- Gaussian weights on small tri (3 Gaussian pt for linear IFEM)\n% femIF.area --- Areas of all small tri\n% femIF.normal --- unit normal vector of each small tri\n\n% Last Modified by Xu Zhang 08/07/2020\n%%\nnfI = -min(mesh.fLoc); % number of interface faces\nintFID = find(mesh.fLoc<0);\nnfIB = size(find(mesh.f_t(intFID,2)==0),1); % # of interface faces on Boundary\nnfII = nfI - nfIB; % # of internal interface faces: two tetra share it L&R\ntL = zeros(3*nfII,4); tR = zeros(3*nfII,4);\nbasL = zeros(3*nfII,4,4); basR = zeros(3*nfII,4,4);\ngx = zeros(3*nfII,3); gy = zeros(3*nfII,3); gz = zeros(3*nfII,3);\nA = zeros(3*nfII,1); normal = zeros(3*nfII,3);\n\ntB = zeros(3*nfIB,4); basB = zeros(3*nfIB,4,4); \ngxB = zeros(3*nfIB,3); gyB = zeros(3*nfIB,3); gzB = zeros(3*nfIB,3);\nAB = zeros(3*nfIB,1); normalB = zeros(3*nfIB,3);\n\nid = 0; idB = 0;\nfor i = 1:nfI\n %% Form small triangular partition on the interface face\n fID = intFID(i); % face index\n f_e = mesh.f_e(fID,:); % three surrounding edge index\n idE = find(mesh.eLoc(f_e)<0); % find index of two interface edges\n tmp = [mesh.e(f_e(idE(1)),:), mesh.e(f_e(idE(2)),:)];\n nd1 = sum(tmp) - sum(unique(tmp)); % the node of two interface edges\n nd2 = sum(mesh.e(f_e(idE(1)),:)) - nd1;\n nd3 = sum(mesh.e(f_e(idE(2)),:)) - nd1;\n p = [mesh.p(nd1,:); mesh.eIntP(-mesh.eLoc(f_e(idE(1))),:); ...\n mesh.eIntP(-mesh.eLoc(f_e(idE(2))),:); mesh.p(nd2,:); mesh.p(nd3,:)];\n t = [1 2 3; 2 3 4; 3 4 5];\n \n %% gx gy gz on a triangle with 3 internal point, accurate upto pd = 2\n X1 = p(t(:,1),:); X2 = p(t(:,2),:); X3 = p(t(:,3),:);\n G = zeros(3,9); w1 = 2/3; w2 = 1/6; % see gaussPtri.m\n G(:,[1,4,7]) = w1*X1 + w2*(X2+X3);\n G(:,[2,5,8]) = w1*X2 + w2*(X1+X3);\n G(:,[3,6,9]) = w1*X3 + w2*(X1+X2);\n \n %% triangle area on three-dimension.\n% x1 = X1(:,1); y1 = X1(:,2); z1 = X1(:,3);\n% x2 = X2(:,1); y2 = X2(:,2); z2 = X2(:,3);\n% x3 = X3(:,1); y3 = X3(:,2); z3 = X3(:,3);\n% AT = 1/2*(((x1-x3).*(y2-y1) - (x1-x2).*(y3-y1)).^2 + ...\n% ((y1-y3).*(z2-z1) - (y1-y2).*(z3-z1)).^2 + ...\n% ((z1-z3).*(x2-x1) - (z1-z2).*(x3-x1)).^2).^(1/2);\n AT = TriArea3D(X1,X2,X3);\n \n %% Left and Right Element\n tIDL = mesh.f_t(fID,1); % element index of left element\n tIDR = mesh.f_t(fID,2); % element index of right element\n if tIDR > 0 % Internal Face \n tIDLi = -mesh.tLoc(tIDL); % intf elem index of left element\n tIDRi = -mesh.tLoc(tIDR); % intf elem index of right element\n \n %% Determine piece\n nd1ID = mesh.pLoc(nd1); tLp = femI.plusPC(tIDLi); tRp = femI.plusPC(tIDRi);\n if (nd1ID < 0 && tLp == 1) || (nd1ID > 0 && tLp == 2)\n basL(id+1,:,:) = femI.bas2(tIDLi,:,:);\n basL(id+2,:,:) = femI.bas1(tIDLi,:,:);\n basL(id+3,:,:) = femI.bas1(tIDLi,:,:);\n elseif (nd1ID < 0 && tLp == 2) || (nd1ID > 0 && tLp == 1)\n basL(id+1,:,:) = femI.bas1(tIDLi,:,:);\n basL(id+2,:,:) = femI.bas2(tIDLi,:,:);\n basL(id+3,:,:) = femI.bas2(tIDLi,:,:);\n end\n if (nd1ID < 0 && tRp == 1) || (nd1ID > 0 && tRp == 2)\n basR(id+1,:,:) = femI.bas2(tIDRi,:,:);\n basR(id+2,:,:) = femI.bas1(tIDRi,:,:);\n basR(id+3,:,:) = femI.bas1(tIDRi,:,:);\n elseif (nd1ID < 0 && tRp == 2) || (nd1ID > 0 && tRp == 1)\n basR(id+1,:,:) = femI.bas1(tIDRi,:,:);\n basR(id+2,:,:) = femI.bas2(tIDRi,:,:);\n basR(id+3,:,:) = femI.bas2(tIDRi,:,:);\n end\n \n gx(id+1:id+3,:) = G(:,1:3);\n gy(id+1:id+3,:) = G(:,4:6);\n gz(id+1:id+3,:) = G(:,7:9);\n \n A(id+1:id+3,:) = AT;\n normal(id+1:id+3,:) = repmat(mesh.f_norm(fID,:),3,1);\n \n %% tL and tR, use locID, b/c index on interface cell is different\n temp = fem.t(tIDL,:);\n temp1 = temp(femI.locID(tIDLi,:));\n tL(id+1:id+3,:) = repmat(temp1,3,1);\n \n temp = fem.t(tIDR,:);\n temp2 = temp(femI.locID(tIDRi,:));\n tR(id+1:id+3,:) = repmat(temp2,3,1);\n id = id+3;\n \n elseif tIDR == 0 % Boundary Face\n tIDLi = -mesh.tLoc(tIDL); % intf elem index of left element\n \n %% Determine piece: only one element.\n nd1ID = mesh.pLoc(nd1); tLp = femI.plusPC(tIDLi); \n if (nd1ID < 0 && tLp == 1) || (nd1ID > 0 && tLp == 2)\n basB(idB+1,:,:) = femI.bas2(tIDLi,:,:);\n basB(idB+2,:,:) = femI.bas1(tIDLi,:,:);\n basB(idB+3,:,:) = femI.bas1(tIDLi,:,:);\n elseif (nd1ID < 0 && tLp == 2) || (nd1ID > 0 && tLp == 1)\n basB(idB+1,:,:) = femI.bas1(tIDLi,:,:);\n basB(idB+2,:,:) = femI.bas2(tIDLi,:,:);\n basB(idB+3,:,:) = femI.bas2(tIDLi,:,:);\n end\n \n gxB(idB+1:idB+3,:) = G(:,1:3);\n gyB(idB+1:idB+3,:) = G(:,4:6);\n gzB(idB+1:idB+3,:) = G(:,7:9);\n \n AB(idB+1:idB+3,:) = AT;\n normalB(idB+1:idB+3,:) = repmat(mesh.f_norm(fID,:),3,1);\n \n %% tB use locID, b/c index on interface cell is different\n temp = fem.t(tIDL,:);\n temp1 = temp(femI.locID(tIDLi,:));\n tB(idB+1:idB+3,:) = repmat(temp1,3,1);\n idB = idB+3;\n end\nend\n\nfemIF = struct('tL',tL,'tR',tR,'tB',tB,'basL',basL,'basR',basR,'basB',basB, ...\n 'gx',gx,'gy',gy,'gz',gz,'gxB',gxB,'gyB',gyB,'gzB',gzB,'area',A,'areaB',AB,...\n 'gw',[1/3;1/3;1/3],'normal',normal,'normalB',normalB);\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/IVEM/genP1IFEM3DFace.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835330070838, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4888423794802381}} {"text": "% Implement the back propagation of an LSTM layer.\n% Author: Xiong Xiao, Temasek Labs, NTU, Singapore.\n% Last modified: 13 Oct 2015\n%\nfunction [grad, grad_W, grad_b] = B_LSTM(input, LSTM_layer, future_layers)\nW = LSTM_layer.W;\nif strcmpi(class(input), 'gpuArray'); useGPU=1; else useGPU = 0; end\nprecision = class(gather(input(1)));\n\n[dim, nFr, nSeg] = size(input);\ninput = permute(input, [1 3 2]);\n\nnCell = LSTM_layer.dim(1); % number of LSTM cells in the layer\n\nuseHidden = 1;\nusePastState = 1;\nusePastStateAsFeature = LSTM_layer.usePastState;\n\nfuture_layer_grad = 0;\nfor fli = 1:length(future_layers)\n future_layer_grad = future_layer_grad + future_layers{fli}.grad; % this is the gradient of LSTM output from the cost function\nend\ngrad_ht_cost = future_layer_grad;\ngrad_ht_cost = permute(grad_ht_cost,[1 3 2]);\n\nft = LSTM_layer.ft;\nit = LSTM_layer.it;\not = LSTM_layer.ot;\nCt_raw = LSTM_layer.Ct_raw;\nCt = LSTM_layer.Ct;\nht = LSTM_layer.a;\nht = permute(ht, [1 3 2]);\nCt0 = LSTM_layer.Ct0;\nht0 = LSTM_layer.ht0;\n\n% allocate memory for the gradients of gates and states\nif useGPU == 0\n grad_xt = zeros(dim, nSeg, nFr, precision);\n grad_ft = zeros(nCell, nSeg, nFr, precision); % forget gates\n grad_it = zeros(nCell, nSeg, nFr, precision); % input gates\n grad_ot = zeros(nCell, nSeg, nFr, precision); % output gates\n grad_Ct_raw = zeros(nCell, nSeg, nFr, precision); % candidate cell states\n grad_Ct = zeros(nCell, nSeg, nFr, precision); % cell states\n grad_Ct_future = zeros(nCell, nSeg, nFr, precision); % cell states\n grad_ht = zeros(nCell, nSeg, nFr, precision); % hidde layer output, i.e. the output of the LSTM layer\n grad_ht_future = zeros(nCell, nSeg, nFr, precision); % hidde layer output, i.e. the output of the LSTM layer\n grad_zt = zeros(nCell*4,nSeg, nFr, precision);\nelse\n grad_xt = gpuArray.zeros(dim, nSeg, nFr, precision);\n grad_ft = gpuArray.zeros(nCell, nSeg, nFr, precision); % forget gates\n grad_it = gpuArray.zeros(nCell, nSeg, nFr, precision); % input gates\n grad_ot = gpuArray.zeros(nCell, nSeg, nFr, precision); % output gates\n grad_Ct_raw = gpuArray.zeros(nCell, nSeg, nFr, precision); % candidate cell states\n grad_Ct = gpuArray.zeros(nCell, nSeg, nFr, precision); % cell states\n grad_Ct_future = gpuArray.zeros(nCell, nSeg, nFr, precision); % cell states\n grad_ht = gpuArray.zeros(nCell, nSeg, nFr, precision); % hidde layer output, i.e. the output of the LSTM layer\n grad_ht_future = gpuArray.zeros(nCell, nSeg, nFr, precision); % hidde layer output, i.e. the output of the LSTM layer\n grad_zt = gpuArray.zeros(nCell*4,nSeg, nFr, precision);\nend\n \nfor t = nFr:-1:1\n % compute the gradient of ht and Ct that requires gradients from\n % future. At frame nFr, the future gradients are initialized to 0.\n Ct_raw_curr = Ct_raw(:,:,t);\n if useHidden\n grad_ht_curr = grad_ht_future(:,:,t) + grad_ht_cost(:,:,t);\n else\n grad_ht_curr = grad_ht_cost(:,:,t);\n end\n tanh_Ct = tanh(Ct(:,:,t));\n grad_Ct(:,:,t) = grad_Ct_future(:,:,t) + grad_ht_curr .* (1-tanh_Ct.*tanh_Ct) .* ot(:,:,t);\n \n % compute the gradient of gates and candidate states\n if usePastState\n if t==1\n grad_ft(:,:,t) = grad_Ct(:,:,t) .* Ct0;\n grad_Ct_future0 = grad_Ct(:,:,t) .* ft(:,:,t);\n else\n grad_ft(:,:,t) = grad_Ct(:,:,t) .* Ct(:,:,t-1);\n grad_Ct_future(:,:,t-1) = grad_Ct(:,:,t) .* ft(:,:,t);\n end\n end\n grad_Ct_raw(:,:,t) = grad_Ct(:,:,t) .* it(:,:,t);\n grad_it(:,:,t) = grad_Ct(:,:,t) .* Ct_raw_curr;\n grad_ot(:,:,t) = grad_ht_curr .* tanh(Ct(:,:,t));\n \n % compute the gradient of the gates before the activation function.\n\n grad_zCt_raw = grad_Ct_raw(:,:,t) .* (1-Ct_raw_curr.*Ct_raw_curr);\n if 1\n gates = [ft(:,:,t); it(:,:,t); ot(:,:,t)];\n grad_gates = [grad_ft(:,:,t); grad_it(:,:,t); grad_ot(:,:,t)];\n grad_zgates = grad_gates .* gates .* (1-gates);\n grad_zt_curr = [grad_zgates(1:nCell,:); grad_zCt_raw; grad_zgates(nCell+1:end,:)];\n else\n grad_zft = grad_ft(:,:,t) .* ft(:,:,t) .* (1-ft(:,:,t));\n grad_zit = grad_it(:,:,t) .* it(:,:,t) .* (1-it(:,:,t));\n grad_zot = grad_ot(:,:,t) .* ot(:,:,t) .* (1-ot(:,:,t));\n grad_zt_curr = [grad_zft; grad_zCt_raw; grad_zit; grad_zot];\n end\n grad_zt(:,:,t) = grad_zt_curr;\n \n % compute the gradient of the W, b, and past hidden, past state, and x\n grad_yt = W' * grad_zt_curr;\n if usePastStateAsFeature\n grad_xt(:,:,t) = grad_yt(nCell*2+1:end,:);\n else\n grad_xt(:,:,t) = grad_yt(nCell+1:end,:);\n end\n if t==1\n% grad_ht_future0 = grad_yt(nCell+1:nCell*2);\n% grad_Ct_future0 = grad_Ct_future0 + grad_yt(1:nCell);\n% grad_W = grad_W + grad_zt * [Ct0*usePastStateAsFeature; ht0*useHidden; input(:,t)]';\n else\n grad_ht_future(:,:,t-1) = grad_yt(nCell+1:nCell*2,:);\n if usePastStateAsFeature\n grad_Ct_future(:,:,t-1) = grad_Ct_future(:,:,t-1) + grad_yt(1:nCell,:);\n end\n% grad_W = grad_W + grad_zt * [Ct(:,t-1)*usePastStateAsFeature; ht(:,t-1)*useHidden; input(:,t)]';\n end\n% grad_b = grad_b + grad_zt;\n grad_ht(:,:,t) = grad_ht_curr;\nend\nif usePastStateAsFeature\n tmpMat = [Ct(:,:,1:nFr-1); ht(:,:,1:nFr-1)*useHidden; input(:,:,2:nFr)];\nelse\n tmpMat = [ht(:,:,1:nFr-1)*useHidden; input(:,:,2:nFr)];\nend\ntmpMat = reshape(tmpMat, size(tmpMat,1), nSeg*(nFr-1));\ntmpMat2 = reshape(grad_zt(:,:,2:nFr), nCell*4, nSeg*(nFr-1));\ngrad_W = tmpMat2 * tmpMat';\nif usePastStateAsFeature\n grad_W = grad_W + grad_zt(:,:,1) * [Ct0; ht0*useHidden; input(:,:,1)]';\nelse\n grad_W = grad_W + grad_zt(:,:,1) * [ht0*useHidden; input(:,:,1)]';\nend\n\ngrad_b = sum(sum(grad_zt,3),2);\ngrad = permute(grad_xt,[1 3 2]);\nend\n", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/graph/B_LSTM_back.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.488746935283583}} {"text": "function l = tpl(tab, varargin)\n%TPL compute total projection length\n% TPL(IMG) compute the total projection length of structure in image IMG.\n% Projection is computed along the last dimension of image. It\n% correspond to total diameter defined by Serra.\n%\n% TPL(IMG, PDIM) specifies dimensions to manage. PDIM= [0 .. 0 1]\n% correspond to the default case. If PDIM contains only one 1, it is a\n% total diameter computation. If PDIM contains 2 ones, it is a total\n% projected surface computation. If PDIM contains only zeros, TPL\n% performs an Euler-Poincare Characteristic computation. If PDIM contains\n% only ones, it performs an area (2D case), volume (3D case), or\n% Lebesgue measure.\n%\n% TPL(IMG, PDIM, CONN) also specifies the neighbourhood configuration to\n% use, which can be 'minimal', or 'maximal'. Default is 'minimal'.\n%\n% See also :\n% TPL, MINKOWSKI\n%\n%\n% ---------\n%\n% author : David Legland\n% INRA - TPV URPOI - BIA IMASTE\n% created the 10/09/2003.\n%\n\n% HISTORY\n% 20/04/2004 : 2D : do not call epc, accelerating processing\n\n\n% remove useless dimensions and convert to binary image\ntab = squeeze(tab)~=0;\n\n% input image size\ndim = size(tab);\n\n% set default direction for projection : along the last dimension\nif length(dim)==2 && (dim(1)==1 || dim(2)==1)\n pdim = 1; % dimension 1\nelse\n pdim = zeros(1, length(dim)); % dimension > 1\n pdim(length(pdim))=1;\nend\n\n\nif ~isempty(varargin)\n pdim = varargin{1};\nend\n\n% init\n%nc=0;\nl = 0;\n\n% dimension 1 -------------------------------------------\n\nif length(dim)==2 && (dim(1)==1 || dim(2)==1)\n if pdim(1)==1\n l = sum(tab); % total length computation\n else\n l = epc(tab); % EPC in dimension 1\n end\nend\n\n\n\n% dimension 2 -------------------------------------------\n\nif length(dim)==2 && dim(1)~=1 && dim(2)~=1\n N1 = dim(1); N2 = dim(2);\n if sum(pdim==[1 0])==2\n % projection along y (first dimension of img)\n l = sum(sum(~tab(:,1:N2-1) & tab(:,2:N2))) + sum(tab(:,1));\n elseif sum(pdim == [0 1])==2\n % projection along x (second dimension of img)\n l = sum(sum(~tab(1:N1-1,:) & tab(2:N1,:))) + sum(tab(1,:));\n elseif sum(pdim == [0 0])==2\n % EPC in dimension 2\n l = epc(tab);\n elseif sum(pdim == [1 1])==2\n % area computation\n l = sum(tab(:));\n end\nend\n\n\n% dimension 3 -------------------------------------------\n\nif length(dim)==3\n N1 = dim(1); N2 = dim(2); N3 = dim(3);\n \n \n % three total diameters computations\n if sum(pdim == [1 0 0])==3\n % total diameter in x axis\n n = sum(tab(:));\n n1 = sum(sum(sum(tab(:,1:N2-1,:)&tab(:,2:N2,:))));\n n2 = sum(sum(sum(tab(:,:,1:N3-1)&tab(:,:,2:N3))));\n n12 = sum(sum(sum(tab(:,1:N2-1,1:N3-1) & tab(:,1:N2-1,2:N3) & ...\n tab(:,2:N2,1:N3-1) & tab(:,2:N2,2:N3) )));\n l = n - n1 - n2 + n12;\n \n elseif sum(pdim == [0 1 0])==3\n % total diameter in y axis\n n = sum(tab(:));\n n1 = sum(sum(sum(tab(1:N1-1,:,:)&tab(2:N1,:,:))));\n n2 = sum(sum(sum(tab(:,:,1:N3-1)&tab(:,:,2:N3))));\n n12 = sum(sum(sum(tab(1:N1-1,:,1:N3-1) & tab(1:N1-1,:,2:N3) & ...\n tab(2:N1,:,1:N3-1) & tab(2:N1,:,2:N3) )));\n l = n - n1 - n2 + n12;\n \n elseif sum(pdim == [0 0 1])==3\n % total diameter in z axis\n n = sum(tab(:));\n n1 = sum(sum(sum(tab(1:N1-1,:, :)&tab(2:N1,:, :))));\n n2 = sum(sum(sum(tab(:,1:N2-1, :)&tab(:,2:N2, :))));\n n12 = sum(sum(sum(tab(1:N1-1,1:N2-1, :) & tab(1:N1-1,2:N2,:) & ...\n tab(2:N1,1:N2-1,:) & tab(2:N1,2:N2,:) )));\n l = n - n1 - n2 + n12;\n \n % three total projected area computations\n elseif sum(pdim == [1 1 0])==3\n % projected area on xy plane\n l = sum(sum(sum(~tab(:,:,1:N3-1) & tab(:,:,2:N3)))) + ...\n sum(sum(tab(:, :, 1)));\n elseif sum(pdim == [1 0 1])==3\n % projected area on xz plane\n l = sum(sum(sum(~tab(:,1:N2-1,:) & tab(:,2:N2,:)))) + ...\n sum(sum(tab(:, 1, :)));\n elseif sum(pdim == [0 1 1])==3\n % projected area on yz plane\n l = sum(sum(sum(~tab(1:N1-1,:,:) & tab(2:N1,:,:)))) + ...\n sum(sum(tab(1, :, :)));\n \n elseif sum(pdim == [0 0 0])==3\n % EPC in dimension 3\n l = epc(tab);\n \n elseif sum(pdim == [1 1 1])==3\n % volume computation\n l = sum(tab(:));\n \n end\n \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/imMinkowski/tpl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.4886424836173236}} {"text": "%% retraction of d in T_X(M_r) onto M_r\n% X=U*diag(S)*V'\n% d=U*M*V'+U_p*V'+U*V_p'\n% cf. [Van12]\n\nfunction [S1,U1,V1]=rtr_fr(d,S,U,V)\n\nn1=size(U,1);\nn2=size(V,1);\nn3=size(S,1);\n\nsig=0;\nif size(S,2)>1, S=diag(S); sig=1; end\n\neps=1e-3;\n\n% Pu=U*U'; Pv=V*V';\n\nM=U'*d*V;\n% U_p=d*V-Pu*d*V; V_p=d'*U-Pv*d'*U;\nU_p=d*V-U*M; V_p=d'*U-V*M';\n\n[Q_u,R_u]=qr(U_p,0);\n[Q_v,R_v]=qr(V_p,0);\nM1=[diag(S)+M, R_v'; R_u, zeros(n3)];\n[U1,S1,V1]=svd(M1);\nS1=diag(S1); S1=S1(1:n3);\nU1=[U,Q_u]*U1(:,1:n3);\nV1=[V,Q_v]*V1(:,1:n3);\n\nS1=max(S1,eps);\n\nif sig==1, S1=diag(S1); end\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/R2PCP/rtr_fr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028205, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4886310518096749}} {"text": "function [ fea, out ] = ex_planestrain1( varargin )\n%EX_PLANESTRAIN1 Plane strain analysis of a pressure vessel.\n%\n% [ FEA, OUT ] = EX_PLANESTRAIN1( VARARGIN ) Benchmark example for plane strain\n% approximation of a pressure vessel (annular cross section with symmetry).\n%\n% Reference. B. J. Mac Donald, Practical Stress Analysis with Finite Elements (2nd Ed),\n% case study E on page 327, 2007.\n%\n% Accepts the following property/value pairs.\n%\n% Input Value/{Default} Description\n% -----------------------------------------------------------------------------------\n% E scalar {207e9} Modulus of elasticity\n% nu scalar {0.27} Poissons ratio\n% sfun string {sflag1} Shape function for displacements\n% iplot scalar 0/{1} Plot solution (=1)\n% .\n% Output Value/(Size) Description\n% -----------------------------------------------------------------------------------\n% fea struct Problem definition struct\n% out struct Output struct\n\n% Copyright 2013-2022 Precise Simulation, Ltd.\n\n\ncOptDef = { ...\n 'E', 207e9; ...\n 'nu', 0.27; ...\n 'sfun', 'sflag1'; ...\n 'iplot', 1; ...\n 'igrid', 1; ...\n 'tol', 0.1; ...\n 'fid', 1 };\n[got,opt] = parseopt( cOptDef, varargin{:} );\nfid = opt.fid;\n\n\n% Geometry and grid.\nfea.sdim = { 'x' 'y' }; % Coordinate names.\nfea.grid = ringgrid( 12, 216, 100e-3, 120e-3 );\nfea.grid = delcells( fea.grid, selcells( fea.grid, '(x<=eps) | (y<=eps)') );\nif( opt.igrid~=1 )\n fea.grid = quad2tri( fea.grid );\nend\nn_bdr = max(fea.grid.b(3,:)); % Number of boundaries.\n\n\n% Problem definition.\nfea = addphys( fea, @planestrain );\nfea.phys.psn.eqn.coef{1,end} = { opt.nu };\nfea.phys.psn.eqn.coef{2,end} = { opt.E };\nfea.phys.psn.sfun = { opt.sfun opt.sfun };\n\n\n% Boundary conditions.\nbctype = mat2cell( zeros(2,n_bdr), [1 1], ones(1,n_bdr) );\nbctype{1,4} = 1;\nbctype{2,3} = 1;\nfea.phys.psn.bdr.coef{1,5} = bctype;\n\nbccoef = mat2cell( zeros(2,n_bdr), [1 1], ones(1,n_bdr) );\nbccoef{1,1} = '-nx*1e4';\nbccoef{2,1} = '-ny*1e4';\nfea.phys.psn.bdr.coef{1,end} = bccoef;\n\n\n% Parse and solve problem.\nfea = parsephys( fea );\nfea = parseprob( fea ); % Check and parse problem struct.\nfea.sol.u = solvestat( fea, 'fid', fid, 'icub', 1+str2num(strrep(opt.sfun,'sflag','')) ); % Call to stationary solver.\n\n\n% Postprocessing.\ns_disp = fea.phys.psn.eqn.vars{2,end};\nif( opt.iplot>0 )\n figure\n postplot( fea, 'surfexpr', s_disp )\n title( 'Total displacement' )\nend\n\n\n% Error checking.\ns_sx = fea.phys.psn.eqn.vars{5,end};\ns_sy = fea.phys.psn.eqn.vars{6,end};\ns_sxy = fea.phys.psn.eqn.vars{8,end};\ns_sp1 = fea.phys.psn.eqn.vars{9,end};\ns_sp2 = fea.phys.psn.eqn.vars{10,end};\ns_sp3 = fea.phys.psn.eqn.vars{11,end};\nv_disp = evalexpr( s_disp, [100e-3 120e-3-2*sqrt(eps);0 0]+sqrt(eps), fea )';\nv_dref = [2.64e-8 2.41e-8];\n[v_sx(1),v_sx(2)] = minmaxsubd( s_sx, fea );\nv_sxref = [-10000 55454];\n[v_sy(1),v_sy(2)] = minmaxsubd( s_sy, fea );\nv_syref = [-10000 55454];\n[v_sxy(1),v_sxy(2)] = minmaxsubd( s_sxy, fea );\nv_sxyref = [-32730 0];\n[v_sp1(1),v_sp1(2)] = minmaxsubd( s_sp1, fea );\nv_sp1ref = [4.5e4 55454];\n[v_sp2(1),v_sp2(2)] = minmaxsubd( s_sp2, fea );\nv_sp2ref = [1.227e4 1.227e4];\n[v_sp3(1),v_sp3(2)] = minmaxsubd( s_sp3, fea );\nv_sp3ref = [-1e4 0];\nout.err = [ abs([v_dref-v_disp])./v_dref ;\n abs([v_sxref-v_sx])./v_sxref ;\n abs([v_syref-v_sy])./v_syref ;\n abs([v_sxyref(1)-v_sxy(1)])./v_sxyref(1) 0 ;\n abs([v_sp1ref(2)-v_sp1(2)])./v_sp1ref(2) 0 ;\n abs([v_sp2ref-v_sp2])./v_sp2ref ;\n abs([v_sp3ref(1)-v_sp3(1)])./v_sp3ref(1) 0 ];\nout.pass = all( out.err(:) <= opt.tol );\n\n\nif( nargout==0 )\n clear fea out\nend\n", "meta": {"author": "precise-simulation", "repo": "featool-multiphysics", "sha": "861c771adda317a9f091263d16dca060116bd516", "save_path": "github-repos/MATLAB/precise-simulation-featool-multiphysics", "path": "github-repos/MATLAB/precise-simulation-featool-multiphysics/featool-multiphysics-861c771adda317a9f091263d16dca060116bd516/examples/ex_planestrain1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.48837241291552075}} {"text": "function sgmga_weight_test ( dim_num, importance, level_weight, ...\n level_max_min, level_max_max, rule, growth, np, p, tol )\n\n%****************************************************************************80\n%\n%% SGMGA_WEIGHT_TEST checks the sum of the quadrature weights.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 June 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, real IMPORTANCE(DIM_NUM), the anisotropic importance\n% for each dimension.\n%\n% Input, real LEVEL_WEIGHT(DIM_NUM), the anisotropic weight\n% for each dimension.\n%\n% Input, integer LEVEL_MAX_MIN, LEVEL_MAX_MAX, the minimum and\n% maximum values of LEVEL_MAX.\n%\n% Input, integer RULE(DIM_NUM), the rule in each dimension.\n% 1, \"CC\", Clenshaw Curtis, Closed Fully Nested.\n% 2, \"F2\", Fejer Type 2, Open Fully Nested.\n% 3, \"GP\", Gauss Patterson, Open Fully Nested.\n% 4, \"GL\", Gauss Legendre, Open Weakly Nested.\n% 5, \"GH\", Gauss Hermite, Open Weakly Nested.\n% 6, \"GGH\", Generalized Gauss Hermite, Open Weakly Nested.\n% 7, \"LG\", Gauss Laguerre, Open Non Nested.\n% 8, \"GLG\", Generalized Gauss Laguerre, Open Non Nested.\n% 9, \"GJ\", Gauss Jacobi, Open Non Nested.\n% 10, \"HGK\", Hermite Genz-Keister, Open Fully Nested.\n% 11, \"UO\", User supplied Open, presumably Non Nested.\n% 12, \"UC\", User supplied Closed, presumably Non Nested.\n%\n% Input, integer GROWTH(DIM_NUM), the growth in each dimension.\n% 0, \"DF\", default growth associated with this quadrature rule;\n% 1, \"SL\", slow linear, L+1;\n% 2 \"SO\", slow linear odd, O=1+2((L+1)/2)\n% 3, \"ML\", moderate linear, 2L+1;\n% 4, \"SE\", slow exponential;\n% 5, \"ME\", moderate exponential;\n% 6, \"FE\", full exponential.\n%\n% Input, integer NP(DIM_NUM), the number of parameters used by each rule.\n%\n% Input, real P(*), the parameters needed by each rule.\n%\n% Input, real TOL, a tolerance for point equality.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SGMGA_WEIGHT_TEST:\\n' );\n fprintf ( 1, ' Compute the weights of a sparse grid.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Each sparse grid is of spatial dimension DIM_NUM,\\n' );\n fprintf ( 1, ' and is made up of product grids of levels up to LEVEL_MAX.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' IMPORTANCE: ');\n for dim = 1 : dim_num\n fprintf ( 1, ' %14f', importance(dim) );\n end\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' LEVEL_WEIGHT: ');\n for dim = 1 : dim_num\n fprintf ( 1, ' %14f', level_weight(dim) );\n end\n fprintf ( 1, '\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Dimension Rule Growth Parameters\\n' );\n fprintf ( 1, '\\n' );\n\n p_index = 1;\n\n for dim = 1 : dim_num\n\n if ( rule(dim) == 1 )\n fprintf ( 1, ' %8d %8d %11d\\n', dim, rule(dim), growth(dim) );\n elseif ( rule(dim) == 2 )\n fprintf ( 1, ' %8d %8d %11d\\n', dim, rule(dim), growth(dim) );\n elseif ( rule(dim) == 3 )\n fprintf ( 1, ' %8d %8d %11d\\n', dim, rule(dim), growth(dim) );\n elseif ( rule(dim) == 4 )\n fprintf ( 1, ' %8d %8d %11d\\n', dim, rule(dim), growth(dim) );\n elseif ( rule(dim) == 5 )\n fprintf ( 1, ' %8d %8d %11d\\n', dim, rule(dim), growth(dim) );\n elseif ( rule(dim) == 6 )\n fprintf ( 1, ' %8d %8d %11d %14f\\n', dim, rule(dim), growth(dim), p(p_index) );\n elseif ( rule(dim) == 7 )\n fprintf ( 1, ' %8d %8d %11d\\n', dim, rule(dim), growth(dim) );\n elseif ( rule(dim) == 8 )\n fprintf ( 1, ' %8d %8d %11d %14f\\n', dim, rule(dim), growth(dim), p(p_index) );\n elseif ( rule(dim) == 9 )\n fprintf ( 1, ' %8d %8d %11d %14f %14f\\n', ...\n dim, rule(dim), growth(dim), p(p_index), p(p_index+1) );\n elseif ( rule(dim) == 10 )\n fprintf ( 1, ' %8d %8d %11d\\n', dim, rule(dim), growth(dim) );\n elseif ( rule(dim) == 11 )\n fprintf ( 1, ' %8d %8d %11d\\n', dim, rule(dim), growth(dim) );\n elseif ( rule(dim) == 12 )\n fprintf ( 1, ' %8d %8d %11d\\n', dim, rule(dim), growth(dim) );\n end\n\n p_index = p_index + np(dim);\n\n end\n\n weight_sum_exact = 1.0;\n\n p_index = 1;\n\n for dim = 1 : dim_num\n\n if ( rule(dim) == 1 )\n weight_sum_exact = weight_sum_exact * 2.0;\n elseif ( rule(dim) == 2 )\n weight_sum_exact = weight_sum_exact * 2.0;\n elseif ( rule(dim) == 3 )\n weight_sum_exact = weight_sum_exact * 2.0;\n elseif ( rule(dim) == 4 )\n weight_sum_exact = weight_sum_exact * 2.0;\n elseif ( rule(dim) == 5 )\n weight_sum_exact = weight_sum_exact * sqrt ( pi );\n elseif ( rule(dim) == 6 )\n alpha = p(p_index);\n weight_sum_exact = weight_sum_exact * gamma ( 0.5 * ( alpha + 1.0 ) );\n elseif ( rule(dim) == 7 ) \n weight_sum_exact = weight_sum_exact * 1.0;\n elseif ( rule(dim) == 8 )\n alpha = p(p_index);\n weight_sum_exact = weight_sum_exact * gamma ( alpha + 1.0 );\n elseif ( rule(dim) == 9 )\n alpha = p(p_index);\n beta = p(p_index+1);\n arg1 = - alpha;\n arg2 = 1.0;\n arg3 = beta + 2.0;\n arg4 = - 1.0;\n value1 = r8_hyper_2f1 ( arg1, arg2, arg3, arg4 );\n arg1 = - beta;\n arg2 = 1.0;\n arg3 = alpha + 2.0;\n arg4 = - 1.0;\n value2 = r8_hyper_2f1 ( arg1, arg2, arg3, arg4 );\n weight_sum_exact = weight_sum_exact * ( ...\n value1 / ( beta + 1.0 ) + value2 / ( alpha + 1.0 ) );\n elseif ( rule(dim) == 10 )\n weight_sum_exact = weight_sum_exact * sqrt ( pi );\n elseif ( rule(dim) == 11 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SGMGA_WEIGHT_TEST - Fatal error!\\n' );\n fprintf ( 1, ' Do not know how to deal with RULE = 11.\\n' );\n error ( 'SGMGA_WEIGHT_TEST - Fatal error!' );\n elseif ( rule(dim) == 12 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SGMGA_WEIGHT_TEST - Fatal error!\\n' );\n fprintf ( 1, ' Do not know how to deal with RULE = 12.\\n' );\n error ( 'SGMGA_WEIGHT_TEST - Fatal error!' );\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SGMGA_WEIGHT_TEST - Fatal error!\\n' );\n fprintf ( 1, ' Unexpected value of RULE = %d\\n', rule(dim) );\n error ( 'SGMGA_WEIGHT_TEST - Fatal error!' );\n end\n\n p_index = p_index + np(dim);\n\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1,' As a simple test, sum these weights.\\n' );\n fprintf ( 1, ' They should sum to exactly %f\\n', weight_sum_exact );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Level Weight sum Expected sum Difference\\n' );\n fprintf ( 1, '\\n' );\n\n for level_max = level_max_min : level_max_max\n\n point_total_num = sgmga_size_total ( dim_num, level_weight, level_max, ...\n rule, growth );\n\n point_num = sgmga_size ( dim_num, level_weight, level_max, rule, growth, ...\n np, p, tol );\n\n sparse_unique_index = sgmga_unique_index ( dim_num, level_weight, ...\n level_max, rule, growth, np, p, tol, point_num, point_total_num );\n\n [ sparse_order, sparse_index ] = sgmga_index ( dim_num, level_weight, ...\n level_max, rule, growth, point_num, point_total_num, sparse_unique_index );\n\n sparse_weight = sgmga_weight ( dim_num, level_weight, level_max, rule, ...\n growth, np, p, point_num, point_total_num, sparse_unique_index );\n\n weight_sum = sum ( sparse_weight(1:point_num) );\n\n weight_sum_error = abs ( weight_sum - weight_sum_exact );\n\n fprintf ( 1, ' %8d %14f %14f %14e\\n', ...\n level_max, weight_sum, weight_sum_exact, weight_sum_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/sgmga/sgmga_weight_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185318, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.48832963215356656}} {"text": "function K = sdlfmXsdlfmKernCompute(sdlfmKern1, sdlfmKern2, t1, t2, covIC, type)\n\n% SDLFMXSDLFMKERNCOMPUTE Compute a cross kernel between two SDLFM kernels.\n% FORMAT\n% DESC computes cross kernel terms between two switching dynamical\n% LFM kernels for the multiple output kernel.\n% ARG sdlfmKern1 : the kernel structure associated with the first SDLFM\n% kernel.\n% ARG sdlfmKern2 : the kernel structure associated with the second SDLFM\n% kernel.\n% ARG t : inputs for which kernel is to be computed.\n% ARG covIC : covariance for the initial conditions\n% RETURN K : block of values from kernel matrix.\n%\n% FORMAT\n% DESC computes cross kernel terms between two SDLFM kernels for\n% the multiple output kernel.\n% ARG sdlfmKern1 : the kernel structure associated with the first SDLFM\n% kernel.\n% ARG sdlfmKern2 : the kernel structure associated with the second SDLFM\n% kernel.\n% ARG t1 : row inputs for which kernel is to be computed.\n% ARG t2 : column inputs for which kernel is to be computed.\n% ARG covIC : covariance for the initial conditions\n% RETURN K : block of values from kernel matrix.\n%\n% FORMAT\n% DESC computes cross kernel terms between two SDLFM kernels for\n% the multiple output kernel. The SDLFM kernels can correspond to Position\n% X Position (default), Velocity X Position, Velocity X Velocity,\n% Acceleration X Position, Acceleration X Velocity, Acceleration X\n% Acceleration. The type of kernel to be computed is specified in 'type'. \n% ARG sdlfmKern1 : the kernel structure associated with the first SDLFM\n% kernel.\n% ARG sdlfmKern2 : the kernel structure associated with the second SDLFM\n% kernel.\n% ARG t1 : row inputs for which kernel is to be computed.\n% ARG t2 : column inputs for which kernel is to be computed.\n% ARG covIC : covariance for the initial conditions\n% ARG type : specifies the type of kerne to be computed\n% RETURN K : block of values from kernel matrix.\n%\n% SEEALSO : sdlfmKernParamInit, sdlfmKernCompute, sdlfmKernParamInit\n%\n% COPYRIGHT : Mauricio A. Alvarez, 2010\n\n% KERN\n\nif nargin < 6\n type = 'PosPos';\n if nargin < 5\n covIC = t2;\n t2 = t1;\n end\nend\n\nif size(t1, 2) > 1 || size(t2, 2) > 1\n error('Input can only have one column');\nend\n\ncompareInverseWidth = sdlfmKern1.inverseWidth == sdlfmKern2.inverseWidth;\nif sum(sum(compareInverseWidth))~=(sdlfmKern1.nIntervals*sdlfmKern1.nlfPerInt)\n error('Kernels cannot be cross combined if they have different inverse widths.')\nend\ncompareSwitchingTimes = sdlfmKern1.switchingTimes == sdlfmKern2.switchingTimes;\nif sum(sum(compareSwitchingTimes))~=sdlfmKern1.nIntervals\n error('Kernels cannot be cross combined if they have different switching points.')\nend\n\nswitch type\n case 'PosPos'\n fhandle = 'sdlfmXsdlfmKernComputeBlock';\n case 'VelPos'\n fhandle = 'sdlfmvXsdlfmKernComputeBlock';\n case 'VelVel'\n fhandle = 'sdlfmvXsdlfmvKernComputeBlock';\n case 'AccelPos'\n fhandle = 'sdlfmaXsdlfmKernComputeBlock';\n case 'AccelVel'\n fhandle = 'sdlfmaXsdlfmvKernComputeBlock';\n case 'AccelAccel'\n fhandle = 'sdlfmaXsdlfmaKernComputeBlock'; \nend\n\nfhandle = str2func(fhandle);\n \n%Form the basic kernels\nlfmKern1 = struct();\nlfmKern2 = struct();\n\n% Create structures that will make easy the computation of the kernels\n\nspVector = [cumsum(sdlfmKern1.switchingTimes) t1(end)+50];\n\ndim1 = zeros(1, sdlfmKern1.nIntervals); dim2 = zeros(1, sdlfmKern1.nIntervals);\n\nfor i=1:sdlfmKern1.nIntervals\n for j =1:sdlfmKern1.nlfPerInt\n % Create the appropriate set of kernel structures\n lfmKern1(i,j).mass = sdlfmKern1.mass;\n lfmKern1(i,j).spring = sdlfmKern1.spring;\n lfmKern1(i,j).damper = sdlfmKern1.damper;\n lfmKern1(i,j).inverseWidth = sdlfmKern1.inverseWidth(j,i);\n lfmKern1(i,j).sensitivity = sdlfmKern1.sensitivity(j,i);\n lfmKern2(i,j).mass = sdlfmKern2.mass;\n lfmKern2(i,j).spring = sdlfmKern2.spring;\n lfmKern2(i,j).damper = sdlfmKern2.damper;\n lfmKern2(i,j).inverseWidth = sdlfmKern2.inverseWidth(j,i);\n lfmKern2(i,j).sensitivity = sdlfmKern2.sensitivity(j,i);\n lfmKern1(i,j).limit = spVector(i+1) - spVector(i);\n lfmKern2(i,j).limit = spVector(i+1) - spVector(i);\n lfmKern1(i,j).isNormalised = sdlfmKern1.isNormalised;\n lfmKern2(i,j).isNormalised = sdlfmKern2.isNormalised;\n end\n newt1 = t1(t1> spVector(i) & t1 spVector(i) & t2j\n lfmKern1Local = lfmKern1(j,:);\n lfmKern2Local = lfmKern2(j,:);\n else\n lfmKern1Local = lfmKern1(i,:);\n lfmKern2Local = lfmKern2(i,:);\n end \n endValThree = endValThree + dim2(j);\n % POS -- POS (Kernel and initial positions)\n K(startValOne:endValOne, startValThree:endValThree) = fhandle(lfmKern1Local, ...\n lfmKern2Local, t1(startValOne:endValOne) - spVector(i), t2(startValThree:endValThree) - spVector(j), ...\n kyy(i,j), kyv(i,j), kvy(i,j), kvv(i,j), i, j, generalConst); \n % Time vector initial conditions\n tInit1 = [spVector(i) - spVector(i);spVector(i+1) - spVector(i)];\n tInit2 = [spVector(j) - spVector(j);spVector(j+1) - spVector(j)]; \n tempPosPos{i,j} = sdlfmXsdlfmKernComputeBlock(lfmKern1Local, ...\n lfmKern2Local, tInit1, tInit2, ...\n kyy(i,j), kyv(i,j), kvy(i,j), kvv(i,j), i, j, generalConst);\n kyy = organizeIC(kyy, tempPosPos, i, j);\n % VEL -- POS\n tempVelPos{i,j} = sdlfmvXsdlfmKernComputeBlock(lfmKern1Local, ...\n lfmKern2Local, tInit1, tInit2 , ...\n kyy(i,j), kyv(i,j), kvy(i,j), kvv(i,j), i, j, generalConst);\n kvy = organizeIC(kvy, tempVelPos, i, j);\n % POS -- VEL\n tempPosVel{i,j} = sdlfmXsdlfmvKernComputeBlock(lfmKern1Local, ...\n lfmKern2Local, tInit1, tInit2, ...\n kyy(i,j), kyv(i,j), kvy(i,j), kvv(i,j), i, j, generalConst);\n kyv = organizeIC(kyv, tempPosVel, i, j);\n % POS -- VEL\n tempVelVel{i,j} = sdlfmvXsdlfmvKernComputeBlock(lfmKern1Local, ...\n lfmKern2Local, tInit1, tInit2, ...\n kyy(i,j), kyv(i,j), kvy(i,j), kvv(i,j), i, j, generalConst);\n kvv = organizeIC(kvv, tempVelVel, i, j);\n startValThree = endValThree + 1;\n end\n startValOne = endValOne + 1;\nend\n\nK = real(K);\n\n\n\n\n\n\n\n\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/sdlfmXsdlfmKernCompute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.48813995538989013}} {"text": "function s = SaturationPouli(C, I)\n%\n% s = SaturationPouli(C, I)\n%\n% This computes the saturation using channel C and I from LCh color\n% space\n%\n% input:\n% - C: chroma channel from LCh\n% - I: intensity channel from LCh\n%\n% output:\n% - S: saturation channel\n%\n% Copyright (C) 2013 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% The paper describing this technique is:\n% \"Color Correction for Tone Reproduction\"\n% \t by Tania Pouli1, Alessandro Artusi, Francesco Banterle, \n% Ahmet Oguz Akyuz, Hans-Peter Seidel and Erik Reinhard\n% in the Twenty-first Color and Imaging Conference (CIC21), Albuquerque, Nov. 2013 \n%\n%\n\nD = sqrt(C.^2 + I.^2);\ns = C ./ D;\n\nend", "meta": {"author": "banterle", "repo": "HDR_Toolbox", "sha": "a2b45dc48b7169192fb633097a83879e71a0c0f2", "save_path": "github-repos/MATLAB/banterle-HDR_Toolbox", "path": "github-repos/MATLAB/banterle-HDR_Toolbox/HDR_Toolbox-a2b45dc48b7169192fb633097a83879e71a0c0f2/source_code/ColorSpace/SaturationPouli.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4880175196377078}} {"text": "% this is a very naiive and non-optimized cardiac cine GRE sequence \n\nseq=mr.Sequence(); % Create a new sequence object\nfov=256e-3; Nx=128; Ny=Nx; % Define FOV and resolution\nalpha=5; % flip angle\nsliceThickness=5e-3; % slice\n%TE=[7.38 9.84]*1e-3; % give a vector here to have multiple TEs (e.g. for field mapping)\nTE=4.92e-3;\nTR=9e-3; % only a single value for now\n\n% cardiac features\nphases = 8;\nhearbeats = 15; % odd numbers of heartbeats / segments work better\n\n% more in-depth parameters\nrfSpoilingInc=117; % RF spoiling increment\nrf_duration = 2e-3;\nadc_duration = 3.2e-3;\npre_duration = 1e-3;\n\n% set system limits\nsys = mr.opts('MaxGrad', 28, 'GradUnit', 'mT/m', ...\n 'MaxSlew', 150, 'SlewUnit', 'T/m/s', 'rfRingdownTime', 20e-6, ...\n 'rfDeadTime', 100e-6, 'adcDeadTime', 10e-6);\n\n% Create fat-sat pulse \n% (in Siemens interpreter from January 2019 duration is limited to 8.192 ms, and although product EPI uses 10.24 ms, 8 ms seems to be sufficient)\n% B0=2.89; % 1.5 2.89 3.0\n% sat_ppm=-3.45;\n% sat_freq=sat_ppm*1e-6*B0*lims.gamma;\n% rf_fs = mr.makeGaussPulse(110*pi/180,'system',lims,'Duration',8e-3,...\n% 'bandwidth',abs(sat_freq),'freqOffset',sat_freq);\n% gz_fs = mr.makeTrapezoid('z',sys,'delay',mr.calcDuration(rf_fs),'Area',1/1e-4); % spoil up to 0.1mm\n\n% define the trigger to play out\ntrig=mr.makeTrigger('physio1','duration', 2000e-6); % duration after\n%trig=mr.makeTriggerPulse('osc0','duration', 4100e-6); % possible channels: 'osc0','osc1','ext1'\ntrig_out=mr.makeDigitalOutputPulse('ext1','duration', 100e-6,'delay',500e-6); % possible channels: 'osc0','osc1','ext1'\n\n\n% Create alpha-degree slice selection pulse and gradient\n[rf, gz] = mr.makeSincPulse(alpha*pi/180,'Duration',rf_duration,...\n 'SliceThickness',sliceThickness,'apodization',0.5,'timeBwProduct',4,'system',sys);\n\n% Define other gradients and ADC events\ndeltak=1/fov;\ngx = mr.makeTrapezoid('x','FlatArea',Nx*deltak,'FlatTime',adc_duration,'system',sys);\nadc = mr.makeAdc(Nx,'Duration',gx.flatTime,'Delay',gx.riseTime,'system',sys);\ngxPre = mr.makeTrapezoid('x','Area',-gx.area/2,'Duration',pre_duration,'system',sys);\ngzReph = mr.makeTrapezoid('z','Area',-gz.area/2,'Duration',pre_duration,'system',sys);\n\nlines_per_segment = round(Ny/hearbeats);\nNs=ceil(Ny/lines_per_segment);\nNy=Ns*lines_per_segment; % it can be that because of the rounding above we measure few more k-space lines...\nphaseAreas = ((0:Ny-1)-Ny/2)*deltak;\n% now reverse the order in every second segment\nphaseAreasSeg=reshape(phaseAreas,lines_per_segment,Ns);\nphaseAreasSeg(:,2:2:end)=phaseAreasSeg(end:-1:1,2:2:end);\nphaseAreas=phaseAreasSeg(:);\n\n% gradient spoiling\ngxSpoil=mr.makeTrapezoid('x','Area',2*Nx*deltak,'system',sys);\ngzSpoil=mr.makeTrapezoid('z','Area',4/sliceThickness,'system',sys);\n\n% Calculate timing\ndelayTE=ceil((TE - mr.calcDuration(gxPre) - gz.fallTime - gz.flatTime/2 ...\n - mr.calcDuration(gx)/2)/seq.gradRasterTime)*seq.gradRasterTime;\ndelayTR=ceil((TR - mr.calcDuration(gxPre) - mr.calcDuration(gz) ...\n - mr.calcDuration(gx) - delayTE)/seq.gradRasterTime)*seq.gradRasterTime;\nassert(all(delayTR>=mr.calcDuration(gxSpoil,gzSpoil)));\n\nfprintf('the sequence will acquire %d lines per segment resulting in a temporal resolution of %g ms per phase\\n', lines_per_segment, TR*lines_per_segment*1e3);\nfprintf('cardiac acquisition window is: %g ms\\n', TR*phases*lines_per_segment*1e3);\n\nrf_phase=0;\nrf_inc=0;\n\n% Loop over phase encodes and define sequence blocks\nfor s=1:Ns\n seq.addBlock(trig); % wait for the cardiac trigger\n for p=1:phases\n for l=1:lines_per_segment\n % restore the line counter\n i=(s-1)*lines_per_segment+l;\n %seq.addBlock(rf_fs,gz_fs); % fat-sat\n rf.phaseOffset=rf_phase/180*pi;\n adc.phaseOffset=rf_phase/180*pi;\n rf_inc=mod(rf_inc+rfSpoilingInc, 360.0);\n rf_phase=mod(rf_phase+rf_inc, 360.0);\n %\n seq.addBlock(rf,gz,trig_out);\n gyPre = mr.makeTrapezoid('y','Area',phaseAreas(i),'Duration',pre_duration,'system',sys);\n seq.addBlock(gxPre,gyPre,gzReph);\n if delayTE>0 \n seq.addBlock(mr.makeDelay(delayTE));\n end\n seq.addBlock(gx,adc);\n gyPre.amplitude=-gyPre.amplitude;\n seq.addBlock(mr.makeDelay(delayTR),gxSpoil,gyPre,gzSpoil)\n end\n end\nend\n\n%% check whether the timing of the sequence is correct\n[ok, error_report]=seq.checkTiming;\n\nif (ok)\n fprintf('Timing check passed successfully\\n');\nelse\n fprintf('Timing check failed! Error listing follows:\\n');\n fprintf([error_report{:}]);\n fprintf('\\n');\nend\n\n%% prepare sequence export\nseq.setDefinition('FOV', [fov fov sliceThickness]);\nseq.setDefinition('Name', 'cine-gre');\n\nseq.write('cine_gre.seq') % Write to pulseq file\n\n%seq.install('siemens');\nreturn\n\n%% plot sequence and k-space diagrams\n\nseq.plot('timeRange', [0 5*TR]);\n\n% new single-function call for trajectory calculation\n[ktraj_adc, ktraj, t_excitation, t_refocusing, t_adc] = seq.calculateKspace();\n\n% plot k-spaces\ntime_axis=(1:(size(ktraj,2)))*sys.gradRasterTime;\nfigure; plot(time_axis, ktraj'); % plot the entire k-space trajectory\nhold; plot(t_adc,ktraj_adc(1,:),'.'); % and sampling points on the kx-axis\nfigure; plot(ktraj(1,:),ktraj(2,:),'b'); % a 2D plot\naxis('equal'); % enforce aspect ratio for the correct trajectory display\nhold;plot(ktraj_adc(1,:),ktraj_adc(2,:),'r.'); % plot the sampling points\n\n%% very optional slow step, but useful for testing during development e.g. for the real TE, TR or for staying within slewrate limits \n\nrep = seq.testReport;\nfprintf([rep{:}]);\n\n", "meta": {"author": "pulseq", "repo": "pulseq", "sha": "b4c8fee2a1ffa491d53bd6f507cba2029bf32835", "save_path": "github-repos/MATLAB/pulseq-pulseq", "path": "github-repos/MATLAB/pulseq-pulseq/pulseq-b4c8fee2a1ffa491d53bd6f507cba2029bf32835/matlab/demoSeq/writeCineGradientEcho.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4880175140547458}} {"text": "function p=baselineParameters()\n\np=struct();\n\np.h = 0.8;\np.gz = 0.001;\np.pi_ss = 1.005;\np.beta = 0.9975;\np.kappa1 = 5;\np.kappa2 = 0.5;\np.epsilon = 6;\np.phi = 10;\np.eta = 2;\np.xi = 0.5;\np.rho_r = 0.8;\np.rho_a = 0.9;\np.sig_r = 0.01;\np.sig_a = 0.01;\np.sig_pi = 0.01;\np.sig_z = 0.01;\np.sigma = 2;\np.d = 1;\n\nend", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/examples/occbin/oneConstraint/baselineParameters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.48801750847178355}} {"text": "function [ydum,xdum,breaks]=varprior(nv,nx,lags,mnprior,vprior)\n%function [ydum,xdum,breaks]=varprior(nv,nx,lags,mnprior,vprior)\n% ydum, xdum: dummy observation data that implement the prior\n% breaks: vector of points in the dummy data after which new dummy obs's start\n% Set breaks=T+[0;breaks], ydata=[ydata;ydum], xdum=[xdata;xdum], where \n% actual data matrix has T rows, in preparing input for rfvar3\n% nv,nx,lags: VAR dimensions\n% mnprior.tight:Overall tightness of Minnesota prior\n% mnprior.decay:Standard deviations of lags shrink as lag^(-decay)\n% vprior.sig: Vector of prior modes for diagonal elements of r.f. covariance matrix\n% vprior.w: Weight on prior on vcv. 1 corresponds to \"one dummy observation\" weight\n% Should be an integer, and will be rounded if not. vprior.sig is needed\n% to scale the Minnesota prior, even if the prior on sigma is not used itself.\n% Set vprior.w=0 to achieve this.\n% Note: The original Minnesota prior treats own lags asymmetrically, and therefore\n% cannot be implemented entirely with dummy observations. It is also usually\n% taken to include the sum-of-coefficients and co-persistence components\n% that are implemented directly in rfvar3.m. The diagonal prior on v, combined\n% with sum-of-coefficients and co-persistence components and with the unit own-first-lag\n% prior mean generates larger prior variances for own than for cross-effects even in \n% this formulation, but here there is no way to shrink toward a set of unconstrained \n% univariate AR's.\n\n% Original file downloaded from:\n% http://sims.princeton.edu/yftp/VARtools/matlab/varprior.m\n\nif ~isempty(mnprior)\n xdum = zeros(lags+1,nx,lags,nv);\n ydum = zeros(lags+1,nv,lags,nv);\n for il = 1:lags\n ydum(il+1,:,il,:) = il^mnprior.decay*diag(vprior.sig);\n end\n ydum(1,:,1,:) = diag(vprior.sig);\n ydum = mnprior.tight*reshape(ydum,[lags+1,nv,lags*nv]);\n ydum = flipdim(ydum,1);\n xdum = mnprior.tight*reshape(xdum,[lags+1,nx,lags*nv]);\n xdum = flipdim(xdum,1);\n breaks = (lags+1)*[1:(nv*lags)]';\n lbreak = breaks(end);\nelse\n ydum = [];\n xdum = [];\n breaks = [];\n lbreak = 0;\nend\n% elle = 0;\n% for j1 = 1 : nv\n% for j2 = 1 : lags\n% elle = 1 + elle;\n% ydum(:,:,elle) = ydum(:,:,elle) * mnprior.unit_root_(j1);\n% end\n% end\nif ~isempty(vprior) && vprior.w>0\n ydum2 = zeros(lags+1,nv,nv);\n xdum2 = zeros(lags+1,nx,nv);\n ydum2(end,:,:) = diag(vprior.sig);\n for i = 1:vprior.w\n ydum = cat(3,ydum,ydum2);\n xdum = cat(3,xdum,xdum2);\n breaks = [breaks;(lags+1)*[1:nv]'+lbreak];\n lbreak = breaks(end);\n end\nend\ndimy = size(ydum);\nydum = reshape(permute(ydum,[1 3 2]),dimy(1)*dimy(3),nv);\nxdum = reshape(permute(xdum,[1 3 2]),dimy(1)*dimy(3),nx);\nbreaks = breaks(1:(end-1));\n\n\n", "meta": {"author": "naffe15", "repo": "BVAR_", "sha": "4c935f440a2e98475ead4f873ebdfd03378a0eee", "save_path": "github-repos/MATLAB/naffe15-BVAR_", "path": "github-repos/MATLAB/naffe15-BVAR_/BVAR_-4c935f440a2e98475ead4f873ebdfd03378a0eee/bvartools/varprior.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.48799701310186816}} {"text": "function y=v_rhartley(x,n)\n%V_RHARTLEY Calculate the Hartley transform of real data Y=(X,N)\n% Data is truncated/padded to length N if specified.\n% The inverse transformation is x=hartley(y,n)/n\n\n% Copyright (C) Mike Brookes 1998\n% Version: $Id: v_rhartley.m 10865 2018-09-21 17:22:45Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif nargin < 2\n y=fft(real(x));\nelse\n y=fft(real(x),n);\nend\ny=real(y)-imag(y);\n", "meta": {"author": "ImperialCollegeLondon", "repo": "sap-voicebox", "sha": "28f2654b7584f724277ec81de533debe28ff51ac", "save_path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox", "path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox/sap-voicebox-28f2654b7584f724277ec81de533debe28ff51ac/voicebox/v_rhartley.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4879970131018681}} {"text": "classdef CNSDEDVC < ALGORITHM\n% \n% Constrained nondominated sorting differential evolution based on decision variable classification\n% SN --- 4 --- Number of perturbed solutions\n% PN --- 6 --- Number of perturbations\n% TN --- 15 --- Number of repeated times of perturbation\n% theta --- 0.001 --- Threshold for DVC operation\n% eta --- 0.001 --- Desired level of robustness\n\n%------------------------------- Reference --------------------------------\n% W. Du, W. Zhong, Y. Tang, W. Du, and Y. Jin, High-dimensional robust\n% multi-objective optimization for order scheduling: A decision variable\n% classification approach, IEEE Transactions on Industrial Informatics,\n% 15(1): 293-304.\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 methods\n function main(Algorithm,Problem)\n %% Parameter setting\n [SN,PN,TN,theta,eta] = Algorithm.ParameterSet(4,6,15,0.001,0.001);\n\n %% Generate random population\n Population = Problem.Initialization();\n [HR,LR] = DVC(Problem,Population,SN,PN,TN,theta);\n [~,FrontNo,CrowdDis] = EnvironmentalSelection(Problem,Population,Problem.N,false,eta);\n \n %% Optimization\n while Algorithm.NotTerminated(Population)\n if ~isempty(HR)\n for subgen = 1 : 10\n OffDec = Population(TournamentSelection(2,end,FrontNo,-CrowdDis)).decs;\n NewDec = OperatorDE(Problem,Population.decs,Population(randi(end,1,end)).decs,Population(randi(end,1,end)).decs,{0.9,0.5,1,20});\n OffDec(:,HR) = NewDec(:,HR);\n Offspring = Problem.Evaluation(OffDec);\n [Population,FrontNo,CrowdDis] = EnvironmentalSelection(Problem,[Population,Offspring],Problem.N,true,eta);\n end\n end\n if ~isempty(LR)\n for subgen = 1 : 2\n OffDec = Population(TournamentSelection(2,end,FrontNo,-CrowdDis)).decs;\n NewDec = OperatorDE(Problem,Population.decs,Population(randi(end,1,end)).decs,Population(randi(end,1,end)).decs,{0.9,0.5,1,20});\n OffDec(:,LR) = NewDec(:,LR);\n Offspring = Problem.Evaluation(OffDec);\n [Population,FrontNo,CrowdDis] = EnvironmentalSelection(Problem,[Population,Offspring],Problem.N,false,eta);\n end\n end\n end\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Algorithms/Multi-objective optimization/CNSDE-DVC/CNSDEDVC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867825403177, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4879970101668089}} {"text": "%function gppca_demo_poster\n\n\n% Good seeds: 16, 20\nseed = 16\nrandn('state', seed)\nrand('state', seed)\n\ninX = 100*(1:200);\ninW = 10*rand(2,30);\n\nN = size(inX,2);\nM = size(inW,2);\n\nD = 0;\n\n% Trend\nD = D + 1;\ncovfuncX{D} = @gpcov;\nlogthetaX{D} = log(365*(10+10*rand)); % 10-20 years\ninitthetaX{D} = logthetaX{D} + 1;%log(365*(10+10*rand));\ndensityX(D) = 1;\n\n% Periodical (it is difficult to learn from a badly initialized\n% periodicity :( )\nD = D + 1;\ncovfuncX{D} = {@gpcovProduct, @gpcov, @gpcovPeriodic};\n%logthetaX{D} = log([5*365, 2, 4*365]); % 1 year\nlogthetaX{D} = log([250*365, 1.6, 3*365]); % decay 100 years, period 3 year\ninitthetaX{D} = logthetaX{D};%log([300*365, 2, 365*(3.5+1*rand)]);\ndensityX(D) = 1;\n\n% Short-scale\nD = D + 1;\ncovfuncX{D} = @gpcov;\nlogthetaX{D} = log(365*1); % 1 year\ninitthetaX{D} = logthetaX{D} - 0.1;%log(30*(20+20*rand));\ndensityX(D) = 1;\n\n% Short-scale, almosta noise\nD = D + 1;\ncovfuncX{D} = @gpcovPP;\nlogthetaX{D} = log(30*4); % 4 months\ninitthetaX{D} = logthetaX{D} - 0.1;%log(30*(3+6*rand));\ndensityX(D) = 1;\n\n% Generate latent signals\nX = zeros(D,N);\nfor d=1:D\n X(d,:) = gprnd(inX, logthetaX{d}, covfuncX{d});\nend\n\nscales = [2^2 3^2 3^2 1.0^2];\nlengthscales = [5 1.5 1.5 0.9];\nbias = [3 0 0 0];\n% Working set\n% $$$ scales = [2^2 3^2 5^2 1.0^2];\n% $$$ lengthscales = [5 2.5 1.5 0.9];\n% $$$ bias = [3 0 0 0];\nW = zeros(M,D);\n[coord1,coord2] = meshgrid(linspace(0,10,50), linspace(0,10,50));\ninWh = [coord1(:)'; coord2(:)'];\nW_function = zeros(numel(coord1), D);\nfor d=1:D\n% $$$ covfuncW{d} = {@(logtheta,x1,x2) gpcov(logtheta,x1,x2,@sqdistEuclidean)};\n% $$$ logthetaW{d} = [log(2)];\n% $$$ initthetaW{d} = [log(6)];\n covfuncW{d} = {@gpcovScale, @(logtheta,x1,x2) gpcov(logtheta,x1,x2,@ ...\n sqdistEuclidean)};\n logthetaW{d} = [log(scales(d)); log(lengthscales(d))];\n initthetaW{d} = logthetaW{d} - 0.1;%[log(5); log(6)];\n densityW(d) = 1;\n W(:,d) = bias(d) + gprnd(inW, logthetaW{d}, covfuncW{d});\n% $$$ tmp = bias(d) + gprnd([inW, inWh], logthetaW{d}, covfuncW{d});\n% $$$ W(:,d) = tmp(1:M);\n% $$$ W_function(:,d) = tmp((M+1):end);\nend\nfor d=1:D\n %tmp = bias(d) + gprnd([inW, inWh], logthetaW{d}, covfuncW{d});\n W_function(:,d) = bias(d) + gppred(inW, W(:,d), 0, inWh, logthetaW{d}, ...\n covfuncW{d});\nend\n \n% $$$ size_inW = size(inW)\n% $$$ size_W = size(W)\n\n% Scale X to unit second moment, so comparison is more valid\nscale = sqrt(mean(X.^2,2));\nscale = [-1; -1; -1; 1] .* scale; % comparable sign rotation\nX = diag(1./scale) * X;\nW = W * diag(scale);\nW_function = W_function * diag(scale);\n\n%hax = tsplot(inX, X, 'k');\n%return\n\n% Data\nY = W*X;\n[M,N] = size(Y);\n\n% $$$ variance_noiseless = [(1:M)', std(Y,1,2)]\n% $$$ mean_std_noiseless = sqrt(mean(var(Y,1,2)))\n% $$$ return\n\n% Noise\nYn = Y + 1*randn(size(Y));\n\nM = size(W,1);\nrandom = randperm(M);\n%examples = random([4 9 14 15]);\nexamples = [19 1 20 5];\n\n% $$$ tsplot(X)\n% $$$ tsplot(W')\n% $$$ tsplot(Y(examples,:));\n% $$$ return\n\n% Missing values\nYnm = Yn;\nItrain = rand(size(Yn))<0.9;\nYnm(Itrain) = nan;\nYtest = Yn;\nYtest(~Itrain) = nan;\nYtest(rand(size(Ytest))<0.87) = nan;\n\n% Create a gap\nYgap = nan*Ynm;\nYnm(:,100:150) = nan;\n\n% $$$ size_Y = size(Ynm)\n% $$$ num_of_observations = sum(~isnan(Ynm(:)))\n% $$$ \n% $$$ first_Y = Y(:,1:5)\n\nnum_of_observations = sum(sum( ~isnan(Ynm) ))\n%return\n\n% $$$ vbpca = false;\n% $$$ if vbpca\n% $$$ Qvb = pca_full(Ynm,D,'maxiters',50,'rotate2pca',true, 'algorithm','vb');\n% $$$ \n% $$$ % Plot VBPCA latent components\n% $$$ varS = zeros(size(Qvb.S));\n% $$$ for n=1:N\n% $$$ varS(:,n) = diag(Qvb.Sv{n});\n% $$$ end\n% $$$ hax = tsgpplot(inX', Qvb.S', 2*sqrt(varS)');\n% $$$ for i=1:length(hax)\n% $$$ set(hax(i), 'xtick', [], 'ytick', []);\n% $$$ axes(hax(i));\n% $$$ line(100*[100, 100], [-1000 1000], 'Color', [0 0 0])\n% $$$ line(100*[150, 150], [-1000 1000], 'Color', [0 0 0])\n% $$$ lab = sprintf('x_{%d}(t)', i);\n% $$$ ylabel(lab);\n% $$$ end\n% $$$ xlabel('time, t');\n% $$$ set_figure_size(gcf, 12, 7);\n% $$$ set_label_fontsize(hax, 6);\n% $$$ print('-depsc', '/home/jluttine/thesis_slides/fig_artificial_vbpca_latent');\n% $$$ \n% $$$ % Plot VBPCA predictive distribution\n% $$$ Yvb = bsxfun(@plus, Qvb.A*Qvb.S, Qvb.Mu);\n% $$$ varYpvb = zeros(size(Yvb));\n% $$$ for m=1:M\n% $$$ CovA = Qvb.Av{m};\n% $$$ for n=1:N\n% $$$ CovS = Qvb.Sv{n};\n% $$$ varYvb(m,n) = Qvb.A(m,:)*CovS*Qvb.A(m,:)' + Qvb.S(:,n)'*CovA*Qvb.S(:,n) ...\n% $$$ + traceprod(CovS,CovA,true); \n% $$$ end\n% $$$ end\n% $$$ varYvb = bsxfun(@plus, varYvb, Qvb.Muv + Qvb.V);\n% $$$ hax = tsgpplot(inX', Yvb(examples,:)', 2*sqrt(varYvb(examples,:))');\n% $$$ addtsplot(inX, Yn(examples,:), 'r-');\n% $$$ addtsplot(inX, Yvb(examples,:), 'k-'); % draw vbpca mean again..\n% $$$ addtsplot(inX, Ynm(examples,:), '+', 'MarkerSize', 7, 'Color', [0 0 1]);\n% $$$ for i=1:length(hax)\n% $$$ set(hax(i), 'xtick', [], 'ytick', []);\n% $$$ axes(hax(i));\n% $$$ line(100*[100, 100], [-1000 1000], 'Color', [0 0 0])\n% $$$ line(100*[150, 150], [-1000 1000], 'Color', [0 0 0])\n% $$$ lab = sprintf('y_{%d}(t)', examples(i));\n% $$$ ylabel(lab);\n% $$$ end\n% $$$ %xlabel('time, t');\n% $$$ set_figure_size(gcf, 12, 10.5);\n% $$$ set_label_fontsize(hax, 6);\n% $$$ print('-depsc', ['/home/jluttine/papers/2009NIPS/poster/' ...\n% $$$ 'fig_artificial_vbpca_predictive']);\n% $$$ end\n\n%return\n\nQgp = vbgppcamv_full(Ynm, D,...\n inW, inX,...\n covfuncW, initthetaW,...\n covfuncX,initthetaX, ...\n 'maxiter',50, ...\n 'pseudodensityx', densityX, ...\n 'pseudodensityw', densityW, ...\n 'loglikelihood', true, ...\n 'updatehyper', [5 10 20 50 80 100], ...\n 'updatepseudox', false, ...\n 'updatepseudow', false, ...\n 'maxsearchx', 3, ...\n 'maxsearchw', 3, ...\n 'checkgradw', false, ...\n 'checkgradx', false);\n\n\nYgp = Qgp.W * Qgp.X;\nif false\n disp('Using inaccurate prediction variance.');\n varYgp = Qgp.W.^2*Qgp.varX + Qgp.varW*Qgp.X.^2 + Qgp.varW*Qgp.varX + ...\n 1/Qgp.tau;\nelse\n disp('Using accurate prediction variance.')\n varYgp = zeros(size(Ygp));\n for m=1:M\n CovWm = Qgp.CovW(Qgp.indsW(m,:),Qgp.indsW(m,:));\n for n=1:N\n CovXn = Qgp.CovX(Qgp.indsX(:,n),Qgp.indsX(:,n));\n varYgp(m,n) = Qgp.W(m,:)*CovXn*Qgp.W(m,:)' + Qgp.X(:,n)'*CovWm*Qgp.X(:,n) ...\n + traceprod(CovXn,CovWm,true); \n end\n end\n varYgp = varYgp + 1/Qgp.tau;\nend\n\n% Plot latent signals\nhax = tsgpplot(inX', Qgp.X', 2*sqrt(Qgp.varX)');\nfor i=1:length(hax)\n set(hax(i), 'xtick', [], 'ytick', []);\n axes(hax(i));\n line(100*[100, 100], [-1000 1000], 'Color', [0 0 0])\n line(100*[150, 150], [-1000 1000], 'Color', [0 0 0])\n lab = sprintf('x_{%d}(t)', i);\n% ylabel(lab);\nend\n%xlabel('time, t');\nset_subplot_positions(hax, 4, 1, [0.01 0.01 0.01 0.01], [0.02 0.02]);\nset_figure_size(gcf, 7, 6);\nset_label_fontsize(hax, 6);\nset(gcf, 'Color','none');\nset(hax, 'Color', 'none');\nexport_fig('/home/jluttine/thesis/slides/novac2010_artificial_latent', ...\n '-eps');\n% $$$ print('-depsc', '/home/jluttine/papers/2009NIPS/poster/fig_artificial_latent');\n\n% $$$ % Plot true latent signals\n% $$$ hax = tsplot(inX, X, 'k');\n% $$$ hold on\n% $$$ yl = max(-min(X,[],2), max(X,[],2))\n% $$$ for i=1:length(hax)\n% $$$ set(hax(i), 'YLim', [-yl(i) yl(i)]);\n% $$$ set(hax(i), 'xtick', [], 'ytick', []);\n% $$$ axes(hax(i));\n% $$$ line(100*[100, 100], [-1000 1000], 'Color', [0 0 0])\n% $$$ line(100*[150, 150], [-1000 1000], 'Color', [0 0 0])\n% $$$ lab = sprintf('x_{%d}(t)', i);\n% $$$ ylabel(lab);\n% $$$ end\n% $$$ xlabel('time, t');\n% $$$ set_figure_size(gcf, 7, 6);\n% $$$ set_label_fontsize(hax, 6);\n% $$$ print('-depsc', '/home/jluttine/papers/2009NIPS/poster/fig_artificial_true_latent');\n\n% Compare latent signals\n% $$$ Qgp.X = bsxfun(@minus, Qgp.X, mean(Qgp.X,2));\n% $$$ Qgp.varX = bsxfun(@rdivide, Qgp.varX, std(Qgp.X,1,2).^2);\n% $$$ Qgp.X = bsxfun(@rdivide, Qgp.X, std(Qgp.X,1,2));\n% $$$ X = bsxfun(@minus, X, mean(X,2));\n% $$$ X = bsxfun(@rdivide, X, std(X,1,2));\n% $$$ tsgpplot(inX', Qgp.X', 2*sqrt(Qgp.varX)');\n% $$$ addtsplot(inX, X, 'r')\n\n% Show predictive distribution\nhax = tsgpplot(inX', Ygp(examples,:)', 2*sqrt(varYgp(examples,:))');\naddtsplot(inX, Yn(examples,:), 'r-');%, 'MarkerSize', 1)\naddtsplot(inX, Ygp(examples,:), 'k-') % draw gp mean again..\naddtsplot(inX, Ynm(examples,:), '+', 'MarkerSize', 4, 'Color', [0 0 1]);\n% $$$ addtsplot(inX, Ytest(examples,:), 'o', 'MarkerSize', 4, 'Color', [0 ...\n% $$$ 0 0.8]);\nfor i=1:length(hax)\n set(hax(i), 'xtick', [], 'ytick', []);\n axes(hax(i));\n line(100*[100, 100], [-1000 1000], 'Color', [0 0 0])\n line(100*[150, 150], [-1000 1000], 'Color', [0 0 0])\n% $$$ lab = sprintf('y_{%d}(t)', examples(i));\n% $$$ ylabel(lab);\nend\n%xlabel('time, t');\nset_subplot_positions(hax, 4, 1, [0.01 0.01 0.01 0.01], [0.02 0.02]);\nset_figure_size(gcf, 7, 6);\nset_label_fontsize(hax, 6);\nset(gcf, 'Color','none');\nset(hax, 'Color', 'none');\nexport_fig('/home/jluttine/thesis/slides/novac2010_artificial_predictive', ...\n '-eps');\n% $$$ print('-depsc', '/home/jluttine/papers/2009NIPS/poster/fig_artificial_predictive');\n\nexp(Qgp.logthetaX{1})\nexp(Qgp.logthetaX{2})\nexp(Qgp.logthetaX{3})\n\n%return\n\n% Plot spatial components\nMh = size(inWh,2);\nWh = zeros(Mh,D);\nvarWh = zeros(Mh,D);\nfig1 = figure;\n% $$$ fig2 = figure;\n% $$$ fig3 = figure;\nhax = [];\nfor d=1:D\n %first = (d-1)*M + 1;\n %last = first + M - 1;\n %inds = first:last;\n inds = Qgp.indsW(:,d);\n [Wh(:,d), varWh(:,d)] = gppred(Qgp.inW, Qgp.W(:,d), Qgp.CovW(inds,inds), ...\n inWh, Qgp.logthetaW{d}, Qgp.covfuncW{d});\n \n % Plot mean map\n figure(fig1)\n subplot(2,ceil(D/2),d)\n contourf(coord1,coord2,reshape(Wh(:,d), size(coord1)),20);\n hax(d,1) = gca;\n hold on\n plot(inW(1,:),inW(2,:), 'kx', 'MarkerSize', 8);\n plot(inW(1,examples),inW(2,examples), 'ko', 'MarkerSize', 8);\n % plot(inW(1,examples),inW(2,examples), 'kx', 'MarkerSize', 10);\n shading('flat');\n cl = get(gca, 'clim');\n cl = max(abs(cl));\n set(gca, 'clim', [-cl cl]);\n mapcolormap;\n set(gca, 'xtick', [], 'ytick', []);\n %pbaspect([1 1 1]);\n% h_cb(d,1) = colorbar('SouthOutside');\n \n% $$$ % Plot uncertainty map\n% $$$ figure(fig2)\n% $$$ % subplot(1,D,d);\n% $$$ subplot(2,D,D+d);\n% $$$ contourf(coord1,coord2,reshape(sqrt(varWh(:,d)), size(coord1)),20);\n% $$$ hax(d,2) = gca;\n% $$$ hold on\n% $$$ plot(inW(1,:),inW(2,:), 'kx', 'MarkerSize', 8);\n% $$$ plot(inW(1,examples),inW(2,examples), 'ko', 'MarkerSize', 8);\n% $$$ % plot(inW(1,examples),inW(2,examples), 'kx', 'MarkerSize', 10);\n% $$$ shading('flat');\n% $$$ cl = get(gca, 'clim');\n% $$$ cl = max(abs(cl));\n% $$$ set(gca, 'clim', [0 cl]);\n% $$$ %mapcolormap;\n% $$$ m = colormap('hot');\n% $$$ colormap(m(end:-1:1,:));\n% $$$ set(gca, 'xtick', [], 'ytick', []);\n% $$$ %pbaspect([1 1 1]);\n% $$$ h_cb(d,2) = colorbar('SouthOutside');\n \n% $$$ % Plot real map\n% $$$ figure(fig3)\n% $$$ subplot(1,D,d)\n% $$$ contourf(coord1,coord2,reshape(W_function(:,d), size(coord1)),20);\n% $$$ hax(d,3) = gca;\n% $$$ hold on\n% $$$ plot(inW(1,:),inW(2,:), 'kx', 'MarkerSize', 8);\n% $$$ plot(inW(1,examples),inW(2,examples), 'ko', 'MarkerSize', 8);\n% $$$ % plot(inW(1,examples),inW(2,examples), 'kx', 'MarkerSize', 10);\n% $$$ shading('flat');\n% $$$ cl = get(gca, 'clim');\n% $$$ cl = max(abs(cl));\n% $$$ set(gca, 'clim', [-cl cl]);\n% $$$ mapcolormap;\n% $$$ set(gca, 'xtick', [], 'ytick', []);\n% $$$ %pbaspect([1 1 1]);\n% $$$ h_cb(d,3) = colorbar('SouthOutside');\n \nend\ncb_height = 0.0;\ncb_textheight = 0.0;\ncb_sep = 0.0;\n\nfor i=1:1\n set_subplot_positions(hax(:,i), 2, 2, [0.01 0.01 0.01 0.01], [0.02 0.02]);\nend\nfor d=1:numel(hax)\n pos_ax = get( hax(d), 'Position');\n cb_pos = pos_ax;\n cb_pos(2) = pos_ax(2) - cb_height - cb_sep;\n cb_pos(4) = cb_height;\n axis(hax(d), 'square')\n% set(h_cb(d), 'Position', cb_pos, 'FontSize', 7);\nend\n\nset_figure_size(fig1, 6, 6);\n% $$$ set_figure_size(fig2, 12, 4);\n% $$$ set_figure_size(fig3, 12, 4);\nprint(fig1, '-depsc', ['/home/jluttine/thesis/slides/' ...\n 'novac2010_artificial_loadings']);\n% $$$ print(fig2, '-depsc', ['/home/jluttine/papers/2009NIPS/poster/' ...\n% $$$ 'novac2010_artificial_loadings_uncertainty']);\n% $$$ print(fig3, '-depsc', ['/home/jluttine/papers/2009NIPS/poster/' ...\n% $$$ 'novac2010_artificial_true_loadings']);\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/publications/novac2010/gppca_demo_novac2010.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.4879216076185594}} {"text": "%%*****************************************************************************\n%% sqlp: solve an semidefinite-quadratic-linear program \n%% by infeasible path-following method. \n%%\n%% [obj,X,y,Z,info,runhist] = sqlp(blk,At,C,b,OPTIONS,X0,y0,Z0);\n%%\n%% Input: blk: a cell array describing the block diagonal structure of SQL data.\n%% At: a cell array with At{p} = [svec(Ap1) ... svec(Apm)] \n%% b,C: data for the SQL instance.\n%% (X0,y0,Z0): an initial iterate (if it is not given, the default is used).\n%% OPTIONS: a structure that specifies parameters required in sqlp.m,\n%% (if it is not given, the default in sqlparameters.m is used). \n%%\n%% Output: obj = [ ].\n%% (X,y,Z): an approximately optimal solution or a primal or dual\n%% infeasibility certificate. \n%% info.termcode = termination-code \n%% info.iter = number of iterations\n%% info.obj = [primal-obj, dual-obj]\n%% info.cputime = total-time\n%% info.gap = gap\n%% info.pinfeas = primal_infeas\n%% info.dinfeas = dual_infeas \n%% runhist.pobj = history of primal objective value. \n%% runhist.dobj = history of dual objective value.\n%% runhist.gap = history of . \n%% runhist.pinfeas = history of primal infeasibility. \n%% runhist.dinfeas = history of dual infeasibility. \n%% runhist.cputime = history of cputime spent.\n%%----------------------------------------------------------------------------\n%% The OPTIONS structure specifies the required parameters: \n%% vers gam predcorr expon gaptol inftol steptol \n%% maxit printlevel scale_data ...\n%% (all have default values set in sqlparameters.m).\n%%\n%%*************************************************************************\n%% SDPT3: version 3.1\n%% Copyright (c) 1997 by\n%% K.C. Toh, M.J. Todd, R.H. Tutuncu\n%% Last Modified: 16 Sep 2004\n%%*************************************************************************\n\n function [obj,X,y,Z,info,runhist] = sqlp(blk,At,C,b,OPTIONS,X0,y0,Z0);\n%% \n%%-----------------------------------------\n%% get parameters from the OPTIONS structure. \n%%-----------------------------------------\n%%\n global matlabversion ispc_hp_ibm\n global spdensity iter solve_ok switch2LU depconstr\n global cachesize smallblkdim printlevel\n global schurfun schurfun_par \n\n warning off; \n matlabversion = sscanf(version,'%f');\n matlabversion = matlabversion(1);\n ispc_hp_ibm = strncmp(computer,'PC',2) | strncmp(computer,'HP',2) | ...\n strncmp(computer,'IBM',3); \n\n vers = 1; \n predcorr = 1; \n gam = 0; \n expon = 1; \n gaptol = 1e-8;\n inftol = 1e-8;\n steptol = 1e-6;\n maxit = 100;\n printlevel = 3;\n stoplevel = 1; \n scale_data = 0;\n spdensity = 0.5; \n rmdepconstr = 0; \n cachesize = 256; \n smallblkdim = 15; \n schurfun = cell(size(blk,1),1);\n schurfun_par = cell(size(blk,1),1); \n if exist('OPTIONS')\n if isfield(OPTIONS,'vers'); vers = OPTIONS.vers; end\n if isfield(OPTIONS,'predcorr'); predcorr = OPTIONS.predcorr; end \n if isfield(OPTIONS,'gam'); gam = OPTIONS.gam; end\n if isfield(OPTIONS,'expon'); expon = OPTIONS.expon; end\n if isfield(OPTIONS,'gaptol'); gaptol = OPTIONS.gaptol; end\n if isfield(OPTIONS,'inftol'); inftol = OPTIONS.inftol; end\n if isfield(OPTIONS,'steptol'); steptol = OPTIONS.steptol; end\n if isfield(OPTIONS,'maxit'); maxit = OPTIONS.maxit; end\n if isfield(OPTIONS,'printlevel'); printlevel = OPTIONS.printlevel; end \n if isfield(OPTIONS,'stoplevel'); stoplevel = OPTIONS.stoplevel; end \n if isfield(OPTIONS,'scale_data'); scale_data = OPTIONS.scale_data; end\n if isfield(OPTIONS,'spdensity'); spdensity = OPTIONS.spdensity; end\n if isfield(OPTIONS,'rmdepconstr'); rmdepconstr = OPTIONS.rmdepconstr; end\n if isfield(OPTIONS,'cachesize'); cachesize = OPTIONS.cachesize; end\n if isfield(OPTIONS,'smallblkdim'); smallblkdim = OPTIONS.smallblkdim; end\n if isfield(OPTIONS,'schurfun'); \n schurfun = OPTIONS.schurfun; \n if ~isempty(schurfun); scale_data = 0; end\n end\n if isfield(OPTIONS,'schurfun_par'); schurfun_par = OPTIONS.schurfun_par; end\n if isempty(schurfun); schurfun = cell(size(blk,1),1); end\n if isempty(schurfun_par); schurfun_par = cell(size(blk,1),1); end\n end\n%%\n if all(vers-[1 2]); error('*** vers must be 1 or 2 ***'); end; \n%%\n%%-----------------------------------------\n%% convert matrices to cell arrays. \n%%-----------------------------------------\n%%\n if ~iscell(At); At = {At}; end;\n if ~iscell(C); C = {C}; end;\n m = length(b); \n if all(size(At) == [size(blk,1), m]); \n convertyes = zeros(size(blk,1),1); \n for p = 1:size(blk,1)\n if strcmp(blk{p,1},'s') & all(size(At{p,1}) == sum(blk{p,2}))\n convertyes(p) = 1; \n end\n end\n if any(convertyes)\n if (printlevel); fprintf('\\n sqlp: converting At into required format'); end\n At = svec(blk,At,ones(size(blk,1),1));\n end\n end \n if (nargin <= 5) | (isempty(X0) | isempty(y0) | isempty(Z0)); \n [X0,y0,Z0] = infeaspt(blk,At,C,b); \n end\n X = X0; y = y0; Z = Z0; \n if ~iscell(X); X = {X}; end;\n if ~iscell(Z); Z = {Z}; end;\n%%\n%%-----------------------------------------\n%% validate SQLP data. \n%%-----------------------------------------\n%%\n tstart = cputime; \n [blk,At,C,b,dim,numblk,X,Z] = validate(blk,At,C,b,X,y,Z);\n if (printlevel>=2)\n fprintf('\\n num. of constraints = %2.0d',length(b)); \n if dim(1); \n fprintf('\\n dim. of sdp var = %2.0d,',dim(1)); \n fprintf(' num. of sdp blk = %2.0d',numblk(1)); \n end\n if dim(2); \n fprintf('\\n dim. of socp var = %2.0d,',dim(2)); \n fprintf(' num. of socp blk = %2.0d',numblk(2)); \n end\n if dim(3); fprintf('\\n dim. of linear var = %2.0d',dim(3)); end\n if dim(4); fprintf('\\n dim. of free var = %2.0d',dim(4)); end\n end\n%%\n%%-----------------------------------------\n%% convert unrestricted blk to linear blk. \n%%-----------------------------------------\n%%\n ublkidx = zeros(size(blk,1),1); \n for p = 1:size(blk,1) \n if strcmp(blk{p,1},'u') \n ublkidx(p) = 1; \n n = 2*blk{p,2}; \n blk{p,1} = 'l'; \n blk{p,2} = n;\n At{p} = [At{p}; -At{p}]; \n C{p} = [C{p}; -C{p}];\n b2 = 1 + abs(b'); \n normC = 1+norm(C{p});\n normA = 1+sqrt(sum(At{p}.*At{p}));\n X{p} = max(1,max(b2./normA)) *ones(n,1);\n Z{p} = max(1,max([normA,normC])/sqrt(n)) *ones(n,1);\n end\n end\n%%\n%%-----------------------------------------\n%% check whether {A1,...,Am} is \n%% linearly independent. \n%%-----------------------------------------\n%%\n m0 = length(b); \n [At,b,y,indeprows,depconstr,feasible] = checkdepconstr(blk,At,b,y,rmdepconstr);\n if (~feasible)\n fprintf('\\n sqlp: SQLP is not feasible'); return; \n end\n%%\n%%-----------------------------------------\n%% scale SQLP data. Note: must be done only \n%% after checkdepconstr\n%%-----------------------------------------\n%%\n normC2 = zeros(length(C),1); \n for p = 1:length(C); normC2(p) = max(max(abs(C{p}))); end\n normC2 = 1+max(normC2); \n normb2 = 1+max(abs(b)); \n normX0 = 1+ops(X0,'norm'); normZ0 = 1+ops(Z0,'norm'); \n if (scale_data)\n [At,C,b,X,y,Z,normA,normC,normb] = scaling(blk,At,C,b,X,y,Z);\n else\n normA = 1; normC = 1; normb = 1;\n end \n%%\n%%-----------------------------------------\n%% find the combined list of non-zero \n%% elements of Aj, j = 1:k, for each k. \n%%-----------------------------------------\n%% \n m = length(b); \n [At,C,X,Z,par.permA,par.permZ] = sortA(blk,At,C,b,X,Z);\n [par.isspA,par.nzlistA,par.nzlistAsum,par.isspAy,par.nzlistAy] = nzlist(blk,At,m); \n%%\n%%-----------------------------------------\n%% initialization\n%%-----------------------------------------\n%%\n [Xchol,indef(1)] = blkcholfun(blk,X); \n [Zchol,indef(2)] = blkcholfun(blk,Z); \n if any(indef)\n if (printlevel); fprintf('\\n Stop: X, Z are not both positive definite'); end\n termcode = -3;\n return;\n end \n nn = 0; \n for p = 1:size(blk,1);\n pblk = blk(p,:); \n if strcmp(pblk{1},'s') | strcmp(pblk{1},'q') | strcmp(pblk{1},'l') \n nn = nn + sum(pblk{2}); \n end\n end\n AX = AXfun(blk,At,par.permA,X); \n rp = b-AX;\n ZpATy = ops(Z,'+',Atyfun(blk,At,par.permA,par.isspAy,y));\n ZpATynorm = ops(ZpATy,'norm');\n Rd = ops(C,'-',ZpATy);\n obj = (normb*normC)*[blktrace(blk,C,X), b'*y];\n trXZ = blktrace(blk,X,Z); \n gap = (normb*normC)*trXZ; \n mu = trXZ/nn; \n rel_gap = gap/(1+sum(abs(obj)));\n prim_infeas = norm(rp)/normb2;\n dual_infeas = ops(Rd,'norm')/normC2;\n infeas_meas = max(prim_infeas,dual_infeas); \n if (scale_data)\n infeas_org(1) = norm(normA.*rp)*normb/normb2;\n infeas_org(2) = ops(Rd,'norm')*normC/normC2;\n else\n infeas_org = [0,0]; \n end\n termcode = -6; \n pstep = 0; dstep = 0; pred_convg_rate = 1; corr_convg_rate = 1;\n prim_infeas_bad = 0; homRd = inf; homrp = inf; \n runhist.pobj = obj(1);\n runhist.dobj = obj(2); \n runhist.gap = gap;\n runhist.relgap = rel_gap;\n runhist.pinfeas = prim_infeas;\n runhist.dinfeas = dual_infeas;\n runhist.infeas = infeas_meas; \n runhist.step = 0; \n runhist.cputime = cputime-tstart; \n ttime.preproc = runhist.cputime; \n ttime.pred = 0; ttime.pred_pstep = 0; ttime.pred_dstep = 0; \n ttime.corr = 0; ttime.corr_pstep = 0; ttime.corr_dstep = 0; \n ttime.pchol = 0; ttime.dchol = 0; ttime.misc = 0; \n%%\n%%-----------------------------------------\n%% display parameters and initial info\n%%-----------------------------------------\n%%\n if (printlevel >= 2)\n fprintf('\\n********************************************');\n fprintf('***********************\\n');\n fprintf(' SDPT3: Infeasible path-following algorithms'); \n fprintf('\\n********************************************');\n fprintf('***********************\\n');\n [hh,mm,ss] = mytimed(ttime.preproc); \n if (printlevel>=3) \n fprintf(' version predcorr gam expon scale_data\\n');\n if (vers == 1); fprintf(' HKM '); elseif (vers == 2); fprintf(' NT '); end\n fprintf(' %1.0f %4.3f',predcorr,gam);\n fprintf(' %1.0f %1.0f %1.0f\\n',expon,scale_data); \n fprintf('\\nit pstep dstep p_infeas d_infeas gap')\n fprintf(' mean(obj) cputime\\n');\n fprintf('------------------------------------------------');\n fprintf('-------------------\\n');\n fprintf('%2.0f %4.3f %4.3f %2.1e %2.1e',0,0,0,prim_infeas,dual_infeas);\n fprintf(' %2.1e %- 7.6e %d:%d:%d',gap,mean(obj),hh,mm,ss);\n end\n end\n%%\n%%---------------------------------------------------------------\n%% start main loop\n%%---------------------------------------------------------------\n%%\n param.inftol = inftol;\n param.normA = normA; \n param.normC = normC;\n param.normb = normb;\n param.normX0 = normX0; \n param.normZ0 = normZ0; \n param.m0 = m0;\n param.indeprows = indeprows;\n param.gaptol = gaptol;\n param.inftol = inftol; \n param.scale_data = scale_data;\n param.printlevel = printlevel; \n%%\n for iter = 1:maxit; \n\n update_iter = 0; breakyes = 0; pred_slow = 0; corr_slow = 0; step_short = 0; \n tstart = cputime; \n timeold = cputime;\n%%\n%%---------------------------------------------------------------\n%% predictor step.\n%%---------------------------------------------------------------\n%%\n if (predcorr)\n sigma = 0; \n else \n sigma = 1-0.9*min(pstep,dstep); \n if (iter == 1); sigma = 0.5; end; \n end\n sigmu = sigma*mu; \n\n invXchol = cell(size(blk,1),1); \n invZchol = ops(Zchol,'inv'); \n if (vers == 1);\n [par,dX,dy,dZ,coeff,L,hRd] = ...\n HKMpred(blk,At,par,rp,Rd,sigmu,X,Z,invZchol);\n elseif (vers == 2);\n [par,dX,dy,dZ,coeff,L,hRd] = ...\n NTpred(blk,At,par,rp,Rd,sigmu,X,Z,Zchol,invZchol);\n end\n if (solve_ok <= 0)\n fprintf('\\n Stop: difficulty in computing predictor directions'); \n runhist.cputime(iter+1) = cputime-tstart; \n termcode = -4;\n break;\n end\n timenew = cputime;\n ttime.pred = ttime.pred + timenew-timeold; timeold = timenew; \n%%\n%%-----------------------------------------\n%% step-lengths for predictor step\n%%-----------------------------------------\n%%\n if (gam == 0) \n gamused = 0.9 + 0.09*min(pstep,dstep); \n else\n gamused = gam;\n end \n [Xstep,invXchol] = steplength(blk,X,dX,Xchol,invXchol); \n pstep = min(1,gamused*Xstep);\n if (Xstep > .99e12) & (blktrace(blk,C,dX) < -1e-3) & (prim_infeas < 1e-3)\n pstep = Xstep; \n if (printlevel); fprintf('\\n Predictor: dual seems infeasible.'); end\n end\n timenew = cputime; \n ttime.pred_pstep = ttime.pred_pstep + timenew-timeold; timeold = timenew; \n Zstep = steplength(blk,Z,dZ,Zchol,invZchol); \n dstep = min(1,gamused*Zstep);\n if (Zstep > .99e12) & (b'*dy > 1e-3) & (dual_infeas < 1e-3)\n dstep = Zstep; \n if (printlevel); fprintf('\\n Predictor: primal seems infeasible.'); end\n end\n trXZpred = trXZ + pstep*blktrace(blk,dX,Z) + dstep*blktrace(blk,X,dZ) ...\n + pstep*dstep*blktrace(blk,dX,dZ); \n gappred = (normb*normC)*trXZpred; \n mupred = trXZpred/nn; \n mupredhist(iter) = mupred; \n timenew = cputime; \n ttime.pred_dstep = ttime.pred_dstep + timenew-timeold; timeold = timenew; \n%%\n%%-----------------------------------------\n%% stopping criteria for predictor step.\n%%-----------------------------------------\n%%\n if (min(pstep,dstep) < steptol) & (stoplevel)\n if (printlevel) \n fprintf('\\n Stop: steps in predictor too short:');\n fprintf(' pstep = %3.2e, dstep = %3.2e\\n',pstep,dstep);\n end\n runhist.cputime(iter+1) = cputime-tstart; \n termcode = -2; \n breakyes = 1; \n end\n if (iter >= 2) \n idx = [max(2,iter-2) : iter];\n pred_slow = all(mupredhist(idx)./mupredhist(idx-1) > 0.4);\n idx = [max(2,iter-5) : iter];\n pred_convg_rate = mean(mupredhist(idx)./mupredhist(idx-1));\n pred_slow = pred_slow + (mupred/mu > 5*pred_convg_rate);\n end \n if (~predcorr)\n if (max(mu,infeas_meas) < 1e-6) & (pred_slow) & (stoplevel)\n if (printlevel) \n fprintf('\\n Stop: lack of progress in predictor:');\n fprintf(' mupred/mu = %3.2f, pred_convg_rate = %3.2f.',...\n mupred/mu,pred_convg_rate);\n end\n runhist.cputime(iter+1) = cputime-tstart; \n termcode = -1; \n breakyes = 1;\n else \n update_iter = 1; \n end\n end\n%%\n%%---------------------------------------------------------------\n%% corrector step.\n%%---------------------------------------------------------------\n%%\n if (predcorr) & (~breakyes)\n step_pred = min(pstep,dstep);\n if (mu > 1e-6)\n if (step_pred < 1/sqrt(3)); \n expon_used = 1; \n else\n expon_used = max(expon,3*step_pred^2); \n end\n else \n expon_used = max(1,min(expon,3*step_pred^2)); \n end \n sigma = min( 1, (mupred/mu)^expon_used );\n sigmu = sigma*mu; \n%%\n if (vers == 1)\n [dX,dy,dZ] = HKMcorr(blk,At,par,rp,Rd,sigmu,hRd,...\n dX,dZ,coeff,L,X,Z);\n elseif (vers == 2)\n [dX,dy,dZ] = NTcorr(blk,At,par,rp,Rd,sigmu,hRd,...\n dX,dZ,coeff,L,X,Z); \n end\n if (solve_ok <= 0)\n fprintf('\\n Stop: difficulty in computing corrector directions');\n runhist.cputime(iter+1) = cputime-tstart; \n termcode = -4;\n break;\n end\n timenew = cputime;\n ttime.corr = ttime.corr + timenew-timeold; timeold = timenew; \n%%\n%%-----------------------------------\n%% step-lengths for corrector step\n%%-----------------------------------\n%%\n if (gam == 0) \n gamused = 0.9 + 0.09*min(pstep,dstep); \n else\n gamused = gam;\n end \n Xstep = steplength(blk,X,dX,Xchol,invXchol);\n pstep = min(1,gamused*Xstep);\n if (Xstep > .99e12) & (blktrace(blk,C,dX) < -1e-3) & (prim_infeas < 1e-3)\n pstep = Xstep;\n if (printlevel); fprintf('\\n Corrector: dual seems infeasible.'); end\n end\n timenew = cputime;\n ttime.corr_pstep = ttime.corr_pstep + timenew-timeold; timeold = timenew;\n Zstep = steplength(blk,Z,dZ,Zchol,invZchol);\n dstep = min(1,gamused*Zstep);\n if (Zstep > .99e12) & (b'*dy > 1e-3) & (dual_infeas < 1e-3)\n dstep = Zstep;\n if (printlevel); fprintf('\\n Corrector: primal seems infeasible.'); end\n end \n trXZcorr = trXZ + pstep*blktrace(blk,dX,Z) + dstep*blktrace(blk,X,dZ)...\n + pstep*dstep*blktrace(blk,dX,dZ); \n gapcorr = (normb*normC)*trXZcorr;\n mucorr = trXZcorr/nn;\n timenew = cputime;\n ttime.corr_dstep = ttime.corr_dstep + timenew-timeold; timeold = timenew; \n%%\n%%-----------------------------------------\n%% stopping criteria for corrector step\n%%-----------------------------------------\n%%\n if (iter >= 2) \n idx = [max(2,iter-2) : iter];\n corr_slow = all(runhist.gap(idx)./runhist.gap(idx-1) > 0.8); \n idx = [max(2,iter-5) : iter];\n corr_convg_rate = mean(runhist.gap(idx)./runhist.gap(idx-1));\n corr_slow = corr_slow + (mucorr/mu > max(min(1,5*corr_convg_rate),0.8)); \n end \n\t if (max(mu,infeas_meas) < 1e-6) & (iter > 10) & (corr_slow) & (stoplevel)\n \t if (printlevel) \n fprintf('\\n Stop: lack of progress in corrector:');\n fprintf(' mucorr/mu = %3.2f, corr_convg_rate = %3.2f',...\n mucorr/mu,corr_convg_rate); \n end\n runhist.cputime(iter+1) = cputime-tstart; \n termcode = -1; \n breakyes = 1;\n else\n update_iter = 1;\n end\n end \n%%\n%%---------------------------------------------------------------\n%% udpate iterate\n%%---------------------------------------------------------------\n%%\n indef = [1,1]; \n if (update_iter)\n for t = 1:5\n [Xchol,indef(1)] = blkcholfun(blk,ops(X,'+',dX,pstep)); \n timenew = cputime;\n ttime.pchol = ttime.pchol + timenew-timeold; timeold = timenew;\n if (indef(1)); pstep = 0.8*pstep; else; break; end \n end\n\t if (t > 1); pstep = gamused*pstep; end\n\t for t = 1:5\n [Zchol,indef(2)] = blkcholfun(blk,ops(Z,'+',dZ,dstep)); \n timenew = cputime;\n ttime.dchol = ttime.dchol + timenew-timeold; timeold = timenew; \n if (indef(2)); dstep = 0.8*dstep; else; break; end \n end\n\t if (t > 1); dstep = gamused*dstep; end\n AXtmp = AX + pstep*AXfun(blk,At,par.permA,dX);\n prim_infeasnew = norm(b-AXtmp)/normb2;\n if any(indef)\n if (printlevel); fprintf('\\n Stop: X, Z not both positive definite'); end\n termcode = -3;\n breakyes = 1; \n elseif (prim_infeasnew > max([rel_gap,20*prim_infeas,1e-8])) ... \t \n\t | (prim_infeasnew > max([1e-4,20*prim_infeas]) & (switch2LU))\n if (stoplevel) & (max(pstep,dstep)<=1)\n if (printlevel)\n fprintf('\\n Stop: primal infeas has deteriorated too much, %2.1e',prim_infeasnew);\n end\n termcode = -7; \n breakyes = 1; \n end\n else\n X = ops(X,'+',dX,pstep); \n y = y+dstep*dy; \n Z = ops(Z,'+',dZ,dstep);\n end\n end\n%%---------------------------------------------------------------\n%% adjust linear blk arising from unrestricted blk\n%%---------------------------------------------------------------\n%%\n for p = 1:size(blk,1)\n if (ublkidx(p) == 1)\n len = blk{p,2}/2;\n alpha = 0.8;\n xtmp = min(X{p}([1:len]),X{p}(len+[1:len])); \n X{p}([1:len]) = X{p}([1:len]) - alpha*xtmp;\n X{p}(len+[1:len]) = X{p}(len+[1:len]) - alpha*xtmp;\n if (mu < 1e-8)\n Z{p} = 0.5*mu./max(1,X{p});\n\t else\n ztmp = min(1,max(Z{p}([1:len]),Z{p}(len+[1:len]))); \n beta1 = xtmp'*(Z{p}([1:len])+Z{p}(len+[1:len]));\n beta2 = (X{p}([1:len])+X{p}(len+[1:len])-2*xtmp)'*ztmp;\n beta = max(0.1,min(beta1/beta2,0.5));\n Z{p}([1:len]) = Z{p}([1:len]) + beta*ztmp;\n Z{p}(len+[1:len]) = Z{p}(len+[1:len]) + beta*ztmp;\n end\n end\n end\n%%\n%%---------------------------------------------------------------\n%% compute rp, Rd, infeasibities, etc.\n%%---------------------------------------------------------------\n%%\n trXZ = blktrace(blk,X,Z); \n gap = (normb*normC)*trXZ;\n mu = trXZ/nn;\n AX = AXfun(blk,At,par.permA,X); \n rp = b-AX;\n ZpATy = ops(Z,'+',Atyfun(blk,At,par.permA,par.isspAy,y));\n ZpATynorm = ops(ZpATy,'norm');\n Rd = ops(C,'-',ZpATy); \n obj = (normb*normC)*[blktrace(blk,C,X), b'*y]; \n rel_gap = gap/(1+sum(abs(obj))); \n prim_infeas = norm(rp)/normb2;\n dual_infeas = ops(Rd,'norm')/normC2;\n if (scale_data)\n infeas_org(1) = norm(normA.*rp)*normb/normb2;\n infeas_org(2) = ops(Rd,'norm')*normC/normC2;\n end\n infeas_meas = max(prim_infeas,dual_infeas); \n if (obj(2) > 0); homRd = ZpATynorm/(obj(2)/(normb*normC)); else; homRd = inf; end\n if (obj(1) < 0); homrp = norm(AX)/(-obj(1)/(normb*normC)); else; homrp = inf; end\n runhist.pobj(iter+1) = obj(1); \n runhist.dobj(iter+1) = obj(2); \n runhist.gap(iter+1) = gap;\n runhist.relgap(iter+1) = rel_gap;\n runhist.pinfeas(iter+1) = prim_infeas;\n runhist.dinfeas(iter+1) = dual_infeas;\n runhist.infeas(iter+1) = infeas_meas;\n runhist.step(iter+1) = min(pstep,dstep); \n runhist.cputime(iter+1) = cputime-tstart; \n timenew = cputime;\n ttime.misc = ttime.misc + timenew-timeold; timeold = timenew; \n [hh,mm,ss] = mytimed(sum(runhist.cputime)); \n if (printlevel>=3)\n fprintf('\\n%2.0f %4.3f %4.3f',iter,pstep,dstep);\n fprintf(' %2.1e %2.1e %2.1e',prim_infeas,dual_infeas,gap);\n fprintf(' %- 7.6e %d:%d:%d',mean(obj),hh,mm,ss);\n end\n%%\n%%--------------------------------------------------\n%% check convergence.\n%%--------------------------------------------------\n%%\n param.iter = iter; \n param.obj = obj;\n param.rel_gap = rel_gap; \n param.gap = gap; \n param.mu = mu; \n param.prim_infeas = prim_infeas;\n param.dual_infeas = dual_infeas;\n param.homRd = homRd; \n param.homrp = homrp; \n param.AX = AX; \n param.ZpATynorm = ZpATynorm;\n param.normX = ops(X,'norm'); \n param.normZ = ops(Z,'norm'); \n param.termcode = termcode;\n param.stoplevel = stoplevel; \n param.prim_infeas_bad = prim_infeas_bad; \n%%\n if (~breakyes)\n [termcode,breakyes,prim_infeas_bad,restart] = sqlpcheckconvg(param,runhist); \n end\n if (breakyes); break; end\n if (restart)\n [X,y,Z] = infeaspt(blk,At,C,b,2,1e5); \n trXZ = blktrace(blk,X,Z); \n gap = (normb*normC)*trXZ;\n mu = trXZ/nn;\n rp = b-AXfun(blk,At,par.permA,X); \n ZpATy = ops(Z,'+',Atyfun(blk,At,par.permA,par.isspAy,y));\n Rd = ops(C,'-',ZpATy); \n prim_infeas = norm(rp)/normb2;\n dual_infeas = ops(Rd,'norm')/normC2;\n infeas_meas = max(prim_infeas,dual_infeas); \n [Xchol,indef(1)] = blkcholfun(blk,X); \n [Zchol,indef(2)] = blkcholfun(blk,Z); \n stoplevel = 3;\n end\n end\n%%\n%%---------------------------------------------------------------\n%% end of main loop\n%%---------------------------------------------------------------\n%%\n%%---------------------------------------------------------------\n%% unscale and produce infeasibility certificates if appropriate\n%%---------------------------------------------------------------\n%%\n if (iter >= 1)\n param.termcode = termcode; \n [X,y,Z,termcode,resid,reldist] = sqlpmisc(blk,At,C,b,X,y,Z,par.permZ,param); \n end \n%%\n%%---------------------------------------------------------------\n%% recover unrestricted blk from linear blk\n%%---------------------------------------------------------------\n%% \n for p = 1:size(blk,1)\n if (ublkidx(p) == 1)\n n = blk{p,2}/2; \n X{p} = X{p}(1:n)-X{p}(n+[1:n]); \n Z{p} = Z{p}(1:n); \n end\n end\n%%\n%%---------------------------------------------------------------\n%% print summary\n%%---------------------------------------------------------------\n%%\n if (scale_data)\n dimacs = [infeas_org(1); 0; infeas_org(2); 0]; \n else\n dimacs = [prim_infeas; 0; dual_infeas; 0];\n end\n dimacs = [dimacs; [-diff(obj); gap]/(1+sum(abs(obj)))];\n info.dimacs = dimacs; \n info.termcode = termcode;\n info.iter = iter; \n info.obj = obj; \n info.gap = gap; \n info.relgap = rel_gap;\n info.pinfeas = prim_infeas;\n info.dinfeas = dual_infeas;\n info.cputime = sum(runhist.cputime); \n info.resid = resid;\n info.reldist = reldist; \n%%\n nnorm.b = norm(b); nnorm.C = ops(C,'norm'); nnorm.A = ops(At,'norm'); \n nnorm.X = ops(X,'norm'); nnorm.y = norm(y); nnorm.Z = ops(Z,'norm'); \n sqlpsummary(info,ttime,infeas_org,nnorm,printlevel);\n%%*****************************************************************************\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/SDPT3-4.0/SDPT3-4.0/Solver/Oldmfiles/sqlpold.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.4879215901819799}} {"text": "function ALAP_demo_attenuation\n% This demonstration illustrates context or state-dependent precision (i.e.\n% attention), which is necessary to disambiguate between sensations\n% caused exogenously and self-generated sensations. In brief, it is\n% necessary to attend away from the sensory consequences of action to\n% preclude sensory evidence overriding the prior beliefs that cause\n% movement. This necessarily reduced the confidence in self-generated\n% sensations and provides a simple (Bayes-optimal) explanation for sensory\n% attenuation - in terms of the attention of sensory precision. We\n% illustrate this in the setting of the force matching illusion and go on\n% to show that increasing the conviction in (precision of) prior beliefs\n% abolishes sensory attenuation at the expense of false (delusional) \n% posterior beliefs about antagonistic external forces.\n%__________________________________________________________________________\n% Copyright (C) 2012 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: ALAP_demo_attenuation.m 4826 2012-08-03 16:45:09Z karl $\n \n% process (G) and model (M)\n%==========================================================================\n \n% set dimensions for generalised coordinates\n%--------------------------------------------------------------------------\nG(1).E.d = 2; % approximation order\nG(1).E.n = 4; % embedding order\n \nM(1).E.d = 2; % approximation order\nM(1).E.n = 4; % embedding order\nM(1).E.s = 1/2; % embedding order\n \nM(1).E.method.x = 1; % state-dependent noise\nM(1).E.method.v = 1; % state-dependent noise\nM(1).E.method.h = 0; % suppress optimisation\nM(1).E.method.g = 0; % suppress optimisation\n \nG(1).f = inline('tanh(a) - x/4','x','v','a','P');\nG(1).g = inline('[x; v + x]','x','v','a','P');\nG(1).x = 0; % hidden state\nG(1).v = [0; 0]; % hidden cause (sensory data)\nG(1).V = exp(8); % precision (noise)\nG(1).W = exp(8); % precision (states)\nG(1).U = [exp(0) 0]; % precision (action)\n \n \n% level 2; causes\n%--------------------------------------------------------------------------\nG(2).v = 0; % exogenous cause\nG(2).a = 0; % endogenous cause (action)\nG(2).V = exp(16);\n \n \n% state-dependent precision (attentional bias) in generative model (M):\n%--------------------------------------------------------------------------\nM(1).f = inline('v - x/4','x','v','P');\nM(1).g = inline('[x(1); sum(x)]','x','v','P');\nM(1).x = [0; 0]; % hidden states\nM(1).v = [0; 0]; % hidden causes\nM(1).W = exp(4); % precision (states)\nM(1).ph = inline('[1; 1]*(8 - h*tanh(v(1) + x(1)))','x','v','h','M');\nM(1).hE = 6;\n \n \n% level 2; causes\n%--------------------------------------------------------------------------\nM(2).v = [0; 0]; % hidden cause\nM(2).V = [exp(6); exp(0)];\n \n \n \n \n% Demonstration of the need for sensory attenuation\n%==========================================================================\n \n% hidden cause and prior expectations\n%--------------------------------------------------------------------------\nN = 32;\nC = zeros(1,N);\nU(1,:) = exp(-((1:N) - N/2).^2/(4.^2))*1;\nU(2,:) = zeros(1,N);\n \n% assemble model structure\n%--------------------------------------------------------------------------\nDEM.M = M;\nDEM.G = G;\nDEM.C = C;\nDEM.U = U;\n \nhE = (-4:1:6);\nfor i = 1:length(hE)\n \n rng('default')\n \n LAP = DEM;\n LAP.M(1).hE = hE(i);\n LAP = spm_ALAP(LAP);\n \n % true and perceived force exerted (endogenously)\n %----------------------------------------------------------------------\n Px(i) = max(LAP.pU.x{1}(1,:));\n Qx(i) = max(LAP.qU.x{1}(1,:));\n \n \n % plot self-generated movement\n %----------------------------------------------------------------------\n if hE(i) == 0\n \n spm_figure('GetWin','Figure 1: Low attenuation');\n spm_DEM_qU(LAP.qU,LAP.pU)\n \n elseif hE(i) == 6\n \n spm_figure('GetWin','Figure 2: High attenuation');\n spm_DEM_qU(LAP.qU,LAP.pU)\n \n end\nend\n \n% adjust axes\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 2: High attenuation');\nsubplot(2,2,2); spm_axis tight, a = axis;\nsubplot(2,2,1); axis(a);\nspm_figure('GetWin','Figure 1: Low attenuation');\nsubplot(2,2,2); axis(a);\nsubplot(2,2,1); axis(a);\n \nspm_figure('GetWin','Figure 2: High attenuation');\nsubplot(2,2,3); spm_axis tight, a = axis;\nsubplot(2,2,4); axis(a);\nspm_figure('GetWin','Figure 1: Low attenuation');\nsubplot(2,2,3); axis(a);\nsubplot(2,2,4); axis(a);\n \n \n \n% plot\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 3');\n \nsubplot(2,1,1)\nplot(hE,[Px; Qx])\naxis square\nxlabel('attenuation of sensory precicion','FontSize',12)\nylabel('true and perceived force exerted','FontSize',12)\nlegend({'true','perceived'})\ntitle('Sensory attenuation and action','FontSize',16)\n \n \n \n% Demonstration of sensory attenuation\n%==========================================================================\n \n% replay internal force as external force\n%--------------------------------------------------------------------------\nrng('default')\nDEM.C = [C LAP.pU.x{1}];\nDEM.U = [U sparse(2,N)];\nDEM = spm_ALAP(DEM);\n \n% plot\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 4');\nspm_DEM_qU(DEM.qU,DEM.pU)\n \n \n \n% Force matching\n%==========================================================================\n \n% replay perceived (at 90% confidence) internal force\n%--------------------------------------------------------------------------\nfor i = 1:N\n CI(i) = 1.694*sqrt(LAP.qU.S{i}(1,1));\nend\n \nDEM.C = [C (LAP.qU.x{1}(1,:) - CI)];\nDEM.U = [U sparse(2,N)];\nDEM = spm_ALAP(DEM);\n \n% plot\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 5');\nspm_DEM_qU(DEM.qU,DEM.pU)\nsubplot(2,2,2); spm_axis tight, a = axis;\nsubplot(2,2,1); axis(a);\nsubplot(2,2,3); spm_axis tight, a = axis;\nsubplot(2,2,4); axis(a);\n \n \n \n% Use a range of self-generated forces - with D = 0\n%==========================================================================\nF = (1:4)/2;\nfor i = 1:length(F)\n \n DEM.C = C;\n DEM.U = U*F(i);\n DEM = spm_ALAP(DEM);\n \n % self-generated and matched (inferred) force\n %----------------------------------------------------------------------\n [x j] = max(DEM.pU.x{1}(1,:));\n Sx(i) = x;\n Tx(i) = DEM.qU.x{1}(1,j) - 1.694*sqrt(DEM.qU.S{j}(1,1));\n \nend\n \n% repeat with (delusional) precision D = 2\n%--------------------------------------------------------------------------\nD = 2;\nDEM.M(1).hE = 6 - D;\nDEM.M(1).W = exp(4 + D);\nDEM.M(2).V = [exp(6 + D); exp(0)];\n \n \nfor i = 1:length(F)\n \n DEM.C = C;\n DEM.U = U*F(i);\n DEM = spm_ALAP(DEM);\n \n % self-generated and matched (inferred) force\n %----------------------------------------------------------------------\n [x j] = max(DEM.pU.x{1}(1,:));\n sx(i) = x;\n tx(i) = DEM.qU.x{1}(1,j) - 1.694*sqrt(DEM.qU.S{j}(1,1));\n \nend\n \n% plot results of force matching\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 6');\n \nsubplot(2,1,1)\nplot(Tx,Sx,'-'); hold on,\nplot(Tx,Sx,'.','MarkerSize',32), hold on\nplot(tx,sx,'-.'); hold on,\nplot(tx,sx,'.','MarkerSize',16), hold on\nplot([0 3],[0 3],':'); hold off\n \naxis square\nxlabel('external (perceptually matched) force','FontSize',12)\nylabel('self-generated force','FontSize',12)\ntitle('Force matching illusion','FontSize',16)\n \n% Illustrate false inference with delusional precision\n%==========================================================================\nD = 4;\nDEM.M(1).hE = 6 - D;\nDEM.M(1).W = exp(4 + D);\nDEM.M(2).V = [exp(6 + D); exp(0)];\n \n \n% replay perceived (at 90% confidence) internal force\n%--------------------------------------------------------------------------\nDEM.C = C;\nDEM.U = U*2;\nDEM = spm_ALAP(DEM);\n \nfor i = 1:N\n CI(i) = 1.694*sqrt(DEM.qU.S{i}(1,1));\nend\n \nDEM.C = [C (DEM.qU.x{1}(1,:) - CI)];\nDEM.U = [U*2 sparse(2,N)];\nDEM = spm_ALAP(DEM);\n \n \n% plot false inference under high D\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 7: False (delusional) inference');\nspm_DEM_qU(DEM.qU,DEM.pU)\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/DEM/ALAP_demo_attenuation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4878298387108655}} {"text": "function [Out1,Out2]=qsynth(Action,In1,In2)\n% Dick Benson \n% Design single terminated elliptic passive LC low pass filters.\n% Copyright 2001-2013 The MathWorks, Inc.\n% [L,C] = qsynth('getLC');\n\n if nargin ==0\n Action = 'init';\n end; \n\n if ~strcmp(Action,'init')\n Hqsynth_ = get(gcf,'userdata');\n end\n\n % handle index definitions\n i_f1 = 1;\n i_topology = 2;\n i_order = 3;\n i_synthpb = 4;\n i_ripl = 5;\n i_ripv = 6;\n i_stopl = 7;\n i_stopv = 8;\n i_ax1 = 9;\n i_pl1 = 10;\n i_pl2 = 11;\n i_fcl = 12;\n i_fcv = 13;\n i_lv = 14;\n i_cv = 15;\n i_lcl = 16;\n i_testpb = 17;\n \n if strcmp(Action,'init')\n \n Hqsynth_(i_f1)= figure('Color',[0 0 0] ,'Name','Qsynth: Single Terminated Ladder Elliptic Filter',... \n 'Position',[20 20 640 440],...\n 'Resize','off',...\n 'Color',[0 0 1],...\n 'NumberTitle','off','visible','on');\n % ###### userdata contains vector of handles if desired\n \n Hqsynth_(i_topology)=uicontrol('Style','popup','visible','on',...\n 'String','RIN=1,RL=inf|RIN=0,RL=1',...\n 'Position',[10 400 105 20],...\n 'BackgroundColor',[0 0 0],...\n 'ForeGroundColor',[0 1 1],...\n 'Value',1,...\n 'callback','qsynth(''clear'')',...\n 'HorizontalAlignment','Left'); \n \n Hqsynth_(i_order)=uicontrol('Style','popup','visible','on',...\n 'String','Order:3|Order:5|Order:7|Order:9|Order:11',...\n 'Position',[10 380 105 20],...\n 'BackgroundColor',[0 0 0],...\n 'ForeGroundColor',[0 1 1],...\n 'Value',4,...\n 'HorizontalAlignment','Left'); \n \n Hqsynth_(i_ripl) = uicontrol('Style','text','visible','on',...\n 'String','Ripple (dB):',...\n 'Position',[10,355,60,18],...\n 'BackGroundColor',[1 1 1]*0.8,...\n 'ForeGroundColor',[0 0 0],...\n 'HorizontalAlignment','left'); \n \n \n Hqsynth_(i_ripv) = uicontrol('Style','edit','visible','on',...\n 'Position',[70,355,45,18],...\n 'String','1',...\n 'BackgroundColor',[1 1 0],...\n 'ForeGroundColor',[0 0 0],...\n 'HorizontalAlignment','center',...\n 'Max',1);\n\n \n Hqsynth_(i_stopl) = uicontrol('Style','text','visible','on',...\n 'String','Stop (dB):',...\n 'Position',[10,330,60,18],...\n 'BackGroundColor',[1 1 1]*0.8,...\n 'ForeGroundColor',[0 0 0],...\n 'HorizontalAlignment','left'); \n \n \n Hqsynth_(i_stopv) = uicontrol('Style','edit','visible','on',...\n 'Position',[70,330,45,18],...\n 'String','60',...\n 'BackgroundColor',[1 1 0],...\n 'ForeGroundColor',[0 0 0],...\n 'HorizontalAlignment','center',...\n 'Max',1);\n \n Hqsynth_(i_fcl) = uicontrol('Style','text','visible','on',...\n 'String','Cutoff (Hz):',...\n 'Position',[10,305,60,18],...\n 'BackGroundColor',[1 1 1]*0.8,...\n 'ForeGroundColor',[0 0 0],...\n 'HorizontalAlignment','left'); \n \n \n Hqsynth_(i_fcv) = uicontrol('Style','edit','visible','on',...\n 'Position',[70,305,45,18],...\n 'String','1.0e6',...\n 'BackgroundColor',[1 1 0],...\n 'ForeGroundColor',[0 0 0],...\n 'HorizontalAlignment','center',...\n 'Max',1);\n \n Hqsynth_(i_lcl) = uicontrol('Style','text','visible','on',...\n 'String',' L C',...\n 'Position',[10,280,165,18],...\n 'BackGroundColor',[1 1 1]*0.8,...\n 'ForeGroundColor',[0 0 0],...\n 'HorizontalAlignment','left'); \n \n Hqsynth_(i_lv) = uicontrol('Style','edit','visible','on',...\n 'Position',[10,35,85,240],... % was 80\n 'String','',...\n 'BackgroundColor',[1 1 0],...\n 'ForeGroundColor',[0 0 0],...\n 'HorizontalAlignment','left',...\n 'Max',14); \n \n Hqsynth_(i_cv) = uicontrol('Style','edit','visible','on',...\n 'Position',[100,35,85,240],... % was 95,35,80\n 'String','',...\n 'BackgroundColor',[1 1 0],...\n 'ForeGroundColor',[0 0 0],...\n 'HorizontalAlignment','left',...\n 'Max',14); \n \n \n Hqsynth_(i_ax1)=axes('Units','pixels','Position',[240,80,370,300],... \n 'Box','on',...\n 'visible','on',...\n 'NextPlot','add',...\n 'DrawMode','fast',... \n 'Color',[0 0 0],...\n 'TickDir','out',...\n 'YlimMode','auto',...\n 'XlimMode','auto',...\n 'Xcolor',[1 1 1],... \n 'Ycolor',[1 1 1],...\n 'FontSize',12);\n \n title('Singly Terminated Elliptic Filter ','color',[1 1 1],'fontsize',9);\n xlabel('Frequency in Hz','fontsize',9);\n ylabel('Magnitude in dB','fontsize',9)\n \n Hqsynth_(i_pl1) = plot(Hqsynth_(i_ax1),0,0,'clipping','on',...\n 'Color',[0 1 0],...\n 'erasemode','xor','visible','on');\n \n Hqsynth_(i_pl2) = plot(Hqsynth_(i_ax1),0,0,'clipping','on',...\n 'Color',[1 0 0],...\n 'erasemode','xor','visible','on');\n \n Hqsynth_(i_synthpb) = uicontrol('Style','Pushbutton',...\n 'Position',[10,10,105,20],...\n 'String','Synthesize',...\n 'Callback','qsynth(''synth'');');\n\n Hqsynth_(i_testpb) = uicontrol('Style','Pushbutton',...\n 'Position',[120,10,105,20],...\n 'String','Test',...\n 'Callback','qsynth(''test'');');\n\n \n set(Hqsynth_(i_f1),'userdata',Hqsynth_);\n zoom on\n \n elseif strcmp(Action,'synth')\n fmtstr = '%8.5g';\n \n n = get(Hqsynth_(i_order),'value')*2+1; % only odd orders supported \n rp = str2num(get(Hqsynth_(i_ripv),'string'));\n rs = str2num(get(Hqsynth_(i_stopv),'string'));\n wn = 2*pi*str2num(get(Hqsynth_(i_fcv),'string'));\n \n [b,a]=ellip(n,rp,rs,wn,'s');\n save lpf_coefs b a\n w = 0:(wn/25):10*wn;\n h = freqs(b,a,w);\n \n \n set(Hqsynth_(i_ax1),'Ylim',[-rs-20,5],'Xlim',[0,10*wn/(2*pi)]);\n set(Hqsynth_(i_pl1),'xdata',w/(2*pi),'ydata',20*log10(h));\n \n topology = get(Hqsynth_(i_topology),'value');\n if topology ==1\n % Rin = 1, Rl = inf , Vsource with 1 ohm Z0, no load \n % must be odd order\n m = b(2:length(b));\n zeros = roots(m);\n m2 = [];\n n2 = [];\n for i=1:length(a) \n if rem(i,2)\n n2=[n2,a(i),0];\n else\n m2=[m2,a(i),0];\n end;\n end;\n m2=m2(1:(length(m2)-1));\n \n % remove admittance pole @ s=inf\n % z=m2/n2 y = n2/m2 yp = n2/m2-c1s\n \n C(1) = n2(1)/m2(1); % shunt capacitor\n n2 = n2 - conv(m2,[C(1),0]);\n % now it gets tricky ....\n for i = 1:(n-1)/2\n % need an xmission zero @ w=wx\n wx = j*abs(zeros(2*i)); % pick an xmission zero....\n % do a partial removal of the impedance pole @ inf\n % first evaluate impedance @ w=wx\n zmag = polyval(m2,wx)/polyval(n2,wx);\n L(2*i) = zmag/wx;\n \n if i==1\n n2=n2(3:length(n2));\n end;\n % this partially removes the pole\n m2 = m2-conv(n2,[L(2*i),0]);\n \n % now remaining admittance has a pole at w=wx\n % remove it by shunting a series LC\n \n % first must determine L & C values\n [q,r1]= deconv(m2,[1 0 abs(wx)^2]); % r should be zero\n k = n2(1);\n n2p = n2/k;\n n2p = n2p(1:length(n2p)-1);\n L(2*i+1)=1/(k*(polyval(n2p,wx)/polyval(q,wx)));\n C(2*i+1)= 1/(L(2*i+1)*(abs(wx)^2));\n\n % then remove the addmittance.... not obvious! \n [n2pp,r2] = deconv(( n2p-q/(k*L(2*i+1)) )*k,[1 0 1/(C(2*i+1)*L(2*i+1))]);\n n2 = conv(n2pp,[1 0]);\n m2 = q;\n end;\n L=L';\n C=C';\n\n \n elseif topology==2\n % Rin=0, Rl=1 (Vsource input, 1 ohm load)\n % \n m = b(2:length(b)); % drop leading 0.0 term\n zeros = roots(m); % \n m2 = [];\n n2 = [];\n for i=1:length(a) \n if rem(i,2)\n n2=[n2,a(i),0];\n else\n m2=[m2,a(i),0];\n end;\n end;\n \n m2=m2(1:(length(m2)-1));\n for i = 1:(n-1)/2\n % need an xmission zero @ w=wx\n wx = j*abs(zeros(2*i)); % pick an xmission zero....\n\n % do a partial removal of the impedance pole @ inf\n % first evaluate impedance @ w=wx\n zmag = polyval(n2,wx)/polyval(m2,wx);\n L(2*i-1) = zmag/wx;\n % this partially removes the pole\n\n n2 = n2-conv(m2,[L(2*i-1),0]);\n % now remaining admittance has a pole at w=wx\n\n % remove it by shunting a series LC\n % first must determine L & C values\n [q,r1] = deconv(n2,[1 0 abs(wx)^2]); % r should be zero\n k = polyval(m2,wx)/polyval(conv(q,[1 0]),wx);\n L(2*i) = 1/k;\n C(2*i) = 1/(L(2*i)*(abs(wx)^2));\n [p,r2] = deconv( m2-k*conv(q,[1 0]) , [1 0 abs(wx)^2]);\n m2=p;\n n2=q;\n end;\n L(n)= n2(1)/m2; % final series L .... amazing .... absolutly amazing! \n L = fliplr(L)'; % need to reverse this network \n C = [0,fliplr(C)]'; % \n \n end;\n set(Hqsynth_(i_ripl),'userdata',L);\n set(Hqsynth_(i_ripv),'userdata',C);\n \n s='';\n for i=1:(length(L)-1)\n s=[s,sprintf([fmtstr,'\\n'],L(i))];\n end;\n s=[s,sprintf(fmtstr,L(length(L)))];\n set(Hqsynth_(i_lv),'string',s);\n s='';\n for i=1:(length(C)-1)\n s=[s,sprintf([fmtstr,'\\n'],C(i))];\n end;\n s=[s,sprintf(fmtstr,C(length(C)))];\n set(Hqsynth_(i_cv),'string',s);\n \n elseif strcmp(Action,'getLC');\n % Out1 = get(Hqsynth_(i_ripl),'userdata'); % inductors\n % Out2 = get(Hqsynth_(i_ripv),'userdata'); % capacitors\n % huh? , should get it from strings in edit fields\n caps = get(Hqsynth_(i_cv),'string'); \n inds = get(Hqsynth_(i_lv),'string'); \n \n for i=1:length(caps(:,1))\n Out2(i) = str2num(caps(i,:));\n end;\n \n for i=1:length(inds(:,1))\n Out1(i) = str2num(inds(i,:));\n end;\n \n \n elseif strcmp(Action,'test')\n topology = get(Hqsynth_(i_topology),'value'); % network topology\n wn = 2*pi*str2num(get(Hqsynth_(i_fcv),'string'));\n w = 0:(wn/25):10*wn;\n [L,C]=qsynth('getLC');\n if topology ==1\n % test the synthesis \n % begin with source resistor \n [a,b,c,d,q]=pabcd([],[],[],[],[],'rs',1);\n % then the shunt capacitor\n [a,b,c,d,q]=pabcd(a,b,c,d,q,'cp',C(1)); \n for i = 1:(length(L)-1)/2\n % series L\n [a,b,c,d,q]=pabcd(a,b,c,d,q,'ls',L((i*2)));\n % shunt series LC\n [a,b,c,d,q]=pabcd(a,b,c,d,q,'lcs',L((i*2)+1),C((i*2)+1));\n end;\n \n elseif topology ==2\n a = []; b = []; c = []; d = []; q = [];\n for i = 1:(length(L)-1)/2\n % series L\n [a,b,c,d,q]=pabcd(a,b,c,d,q,'ls',L((i*2-1)));\n % shunt series LC\n [a,b,c,d,q]=pabcd(a,b,c,d,q,'lcs',L((i*2)),C((i*2)));\n end;\n % finish with a series L\n [a,b,c,d,q]=pabcd(a,b,c,d,q,'ls',L(length(L)));\n % and a 1 ohm shunt R load resistor\n [a,b,c,d,q]=pabcd(a,b,c,d,q,'rp',1);\n end;\n \n % [mag,phase] = bode(q,a,w);\n h = freqs(q,a,w);\n set(Hqsynth_(i_pl2),'xdata',w/(2*pi),'ydata',20*log10(h));\n \n \n elseif strcmp(Action,'clear')\n set(Hqsynth_(i_ripl),'userdata',[]);\n set(Hqsynth_(i_ripv),'userdata',[]);\n set(Hqsynth_(i_cv),'string','');\n set(Hqsynth_(i_lv),'string','');\n set(Hqsynth_(i_pl2),'xdata',[],'ydata',[]);\n set(Hqsynth_(i_pl1),'xdata',[],'ydata',[]);\n \n else\n disp([Action,' not reconized in qsynth'])\n end;\n \n\n% end qsynth\n\nfunction [aout,bout,cout,dout,qout]=pabcd(ain,bin,cin,din,qin,element,val1,val2,val3)\n% [aout,bout,cout,dout,qout]=pabcd(ain,bin,cin,din,qin,element,val1,val2)\n% Uses chain matrix parameters to cascades abcd with denominator q (in) \n% with an element that has val1 (val2 for LC). \n% Useful for computing functions & parameters of ladder networks. \n% element code description \n% rs = series resistor\n% lcs = shunt series lc val1=l val2=c\n% ls = series l\n% cp = shunt c\n% rp = shunt r\n% lcp = series chunt lc val1=l val2=c val3 = r (in series with l for loss)\n% \n% a*e2-b*i2 = e1\n% c*e2-d*i2 = i1\n% \n% Dick Benson \n%\n\n if strcmp(element,'rs')\n % rs = series resistor\n a = 1;\n b = val1;\n c = 0;\n d = 1;\n q = 1;\n elseif strcmp(element,'lcs')\n % lcs = shunt series lc\n % l=val1 c=val2\n q = [val1*val2, 0 , 1];\n a = q;\n b = 0;\n c = [val2 0];\n d = q;\n \n elseif strcmp(element,'lcp')\n % l=val1 c=val2\n q = [val1*val2 val2*val3 1];\n a = q;\n b = [val1 val3];\n c = 0;\n d = q;\n elseif strcmp(element,'ls') \n % ls = series l\n a = 1;\n b = [val1 0];\n c = 0;\n d = 1;\n q = 1;\n elseif strcmp(element,'cp')\n % cp = shunt c\n q = 1;\n a = 1;\n b = 0;\n c = [val1 0];\n d = 1;\n elseif strcmp(element,'rp')\n % rp = shunt r\n q = 1;\n a = 1;\n b = 0;\n c = 1/val1;\n d = 1; \n else\n disp([element,' not supported in pabcd '])\n end;\n\n if isempty(ain)\n aout=a;\n bout=b;\n cout=c;\n dout=d;\n qout=q;\n else\n aout = padd(conv(ain,a),conv(bin,c));\n bout = padd(conv(ain,b),conv(bin,d));\n cout = padd(conv(cin,a),conv(din,c)); \n dout = padd(conv(cin,b),conv(din,d)); \n qout = conv(qin,q);\n end;\n\n% end function\n\nfunction pout = padd(p1,p2)\n lp1 = length(p1);\n lp2 = length(p2);\n if lp1==lp2\n pout = p1+p2;\n elseif lp2>lp1 \n pout = p2;\n pout((lp2-lp1+1):lp2)=pout((lp2-lp1+1):lp2)+p1;\n else\n pout = p1;\n pout((lp1-lp2+1):lp1)=pout((lp1-lp2+1):lp1)+p2;\n end;\n% end padd\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/1320-analog-mixed-signal-examples/lc_passive/qsynth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.629774621301746, "lm_q1q2_score": 0.4878129574290894}} {"text": "function [x, infos] = mu_conv_nmf(V, rank, t, in_options)\n% Multiplicative update (MU) based convolutive non-negative matrix factorization (MU-Conv-NMF).\n%\n% The problem of interest is defined as\n%\n%\n% Given a non-negative matrix V, factorized non-negative matrices {W, H} are calculated.\n%\n%\n% Inputs:\n% matrix V\n% rank rank\n% \n% Output:\n% w solution of w\n% infos information\n%\n% References:\n%\n% \n% This file is part of NMFLibrary\n%\n% This file has been ported by H.Kasai from \n% convNMF_MM1.m and convNMF_MM2.m at https://github.com/lyn202206/ADMM-Convolutive-NMF.\n%\n% Ported by H.Kasai on June 29, 2022\n%\n% Change log: \n%\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 = 'beta-div';\n local_options.d_beta = 2; \n local_options.alg = 'type1';\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 if ~isfield(options, 'x_init')\n W = zeros(m, rank, t);\n for i = 1 : t\n [init_factors, ~] = generate_init_factors(V, rank, init_options); \n W(:, :, i) = init_factors.W;\n end\n H = init_factors.H; \n else\n W = init_options.x_init.W;\n H = init_options.x_init.H; \n end\n\n % initialize\n epoch = 0; \n grad_calc_count = 0;\n\n options = check_divergence(options);\n sub_mode = sprintf('beta=%.1f', options.d_beta);\n if ~strcmp(options.metric_type, 'beta-div')\n sub_mode = options.metric_type;\n end\n method_name = sprintf('MU-Conv (%s)', sub_mode); \n\n if options.verbose > 0\n fprintf('# %s: started ...\\n', method_name); \n end \n\n % initialize for this algorithm\n V_hat = zeros(m, n);\n for i = 0 : t-1\n V_hat = V_hat + W(:, :, i+1) * shift_t(H, i);\n end \n\n % store initial info\n clear infos; \n\n [Wcon, Hcon] = reconstruct_wh(W, H, t);\n [infos, f_val, optgap] = store_nmf_info(V, Wcon, Hcon, [], options, [], epoch, grad_calc_count, 0);\n \n \n if options.verbose > 1\n fprintf('MU-Conv (%s): Epoch = 0000, cost = %.16e, optgap = %.4e\\n', sub_mode, 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 sequentially\n for i = 1 : n\n \n num = zeros(rank, 1); \n denom = num;\n if i <= n-t+1\n for n_prime = i : i+t-1 \n num = num + W(:, :, n_prime-i+1)' * ((V(:, n_prime) + eps) .* (V_hat(:, n_prime) + eps) .^ (options.d_beta - 2));\n denom = denom + W(:, :, n_prime-i+1)'*(V_hat(:, n_prime)+eps).^(options.d_beta-1);\n end\n else\n for n_prime = i : n\n num = num + W(:, :, n_prime-i+1)' * ((V(:, n_prime) + eps) .* (V_hat(:, n_prime) + eps) .^ (options.d_beta - 2));\n denom = denom + W(:, :, n_prime-i+1)'*(V_hat(:, n_prime) + eps) .^ (options.d_beta-1);\n end\n end\n \n if strcmp(options.alg, 'type1')\n h_n_old = H(:, i);\n H(:, i) = H(:, i) .* (num./denom) .^ gamma_beta(options.d_beta);\n \n if i <= n-t+1\n for n_prime = i:i+t-1\n V_hat(:, n_prime) = max(V_hat(:, n_prime) + W(:, :, n_prime - i + 1) * (H(:, i) - h_n_old), 0);\n % max(.,0) ensures the nonnegativity\n end\n else\n for n_prime = i:n\n V_hat(:, n_prime) = max(V_hat(:, n_prime) + W(:, :, n_prime - i + 1) * (H(:, i) - h_n_old), 0);\n end\n end\n else\n H(:, i) = H(:, i) .* (num./denom) .^ gamma_beta(options.d_beta);\n end\n \n end\n\n if strcmp(options.alg, 'type2')\n \n V_hat = zeros(m, n);\n for i = 0 : t-1\n V_hat = V_hat + W(:, :, i+1) * shift_t(H, i);\n end \n end\n \n \n % update W\n for i = 0 : t - 1\n W_t_old = W(:, :, i+1);\n H_shift_t = shift_t(H, i);\n W(:, :, i+1) = W(:, :, i+1) .* (((((V + eps) .* (V_hat + eps) .^ (options.d_beta - 2)) * H_shift_t') ...\n ./ ((V_hat + eps).^(options.d_beta - 1) * H_shift_t'))) .^ gamma_beta(options.d_beta);\n V_hat = max(V_hat + (W(:, :, i+1) - W_t_old) * H_shift_t, 0); \n % max(.,0) ensures nonnegativity\n end\n\n [W, H] = renormalize_convNMF(W,H);\n \n if strcmp(options.alg, 'type1') \n % recalate the V_hat\n X_hat = zeros(size(V));\n for i=0:t-1\n tW = W(:, :, i+1);\n tH = shift_t(H, i);\n X_hat = X_hat + tW * tH;\n end\n V_hat = max(X_hat,0);\n end\n \n\n % measure gradient calc count\n grad_calc_count = grad_calc_count + m*n;\n\n % measure elapsed time\n elapsed_time = toc(start_time); \n\n % update epoch\n epoch = epoch + 1; \n \n % store info\n [Wcon, Hcon] = reconstruct_wh(W, H, t); \n infos = store_nmf_info(V, Wcon, Hcon, [], options, infos, epoch, grad_calc_count, elapsed_time); \n \n % display info\n display_info(method_name, epoch, infos, options);\n\n end\n \n x.W = W;\n x.H = H; \n \nend\n\n\nfunction [W_concat, H_concat] = reconstruct_wh(W, H, t)\n \n W_concat = [];\n H_concat = []; \n for j = 1 : t\n W_concat = [W_concat W(:, :,j)];\n H_concat = [H_concat; shift_t(H, j-1)]; \n end \nend", "meta": {"author": "hiroyuki-kasai", "repo": "NMFLibrary", "sha": "ed44132dfe1b5495df685006b42259f0bd16bea3", "save_path": "github-repos/MATLAB/hiroyuki-kasai-NMFLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-NMFLibrary/NMFLibrary-ed44132dfe1b5495df685006b42259f0bd16bea3/solver/convolutive/mu_conv_nmf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4876285118396438}} {"text": "%% FUNCTION Logistic_Trace\n% Trace-Norm Regularized Learning with Logistic Loss.\n%\n%% OBJECTIVE\n% argmin_{W,C} { sum_i^t (- sum(log (1./ (1+ exp(-X{i}*W(:, i) - Y{i} .* C(i)))))/length(Y{i}))\n% + rho1 * \\|W\\|_*}\n% where \\|W\\|_* = sum(svd(W, 0)) is the trace norm\n%\n%% INPUT\n% X: {n * d} * t - input matrix\n% Y: {n * 1} * t - output matrix\n% rho1: trace norm regularization parameter\n%\n%% OUTPUT\n% W: model: d * t\n% C: model: 1 * t\n% funcVal: function value vector.\n%\n%% LICENSE\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% Copyright (C) 2011 - 2012 Jiayu Zhou and Jieping Ye\n%\n% You are suggested to first read the Manual.\n% For any problem, please contact with Jiayu Zhou via jiayu.zhou@asu.edu\n%\n% Last modified on June 3, 2012.\n%\n%% RELATED PAPERS\n%\n% [1] Ji, S. and Ye, J. An Accelerated Gradient Method for Trace Norm Minimization, ICML 2009\n%\n%% RELATED FUNCTIONS\n% Least_Trace, init_opts\n\n%% Code starts here\nfunction [W, C, funcVal] = Logistic_Trace(X, Y, rho1, opts)\n\nif nargin <3\n error('\\n Inputs: X, Y, and rho1 should be specified!\\n');\nend\nX = multi_transpose(X);\n\nif nargin <4\n opts = [];\nend\n\n% initialize options.\nopts=init_opts(opts);\n\nif isfield(opts, 'rho_L2')\n rho_L2 = opts.rho_L2;\nelse\n rho_L2 = 0;\nend\n\ntask_num = length (X);\ndimension = size(X{1}, 1);\nfuncVal = [];\n\n%initialize a starting point\nC0_prep = zeros(1, task_num);\nfor t_idx = 1: task_num\n m1 = nnz(Y{t_idx} == 1);\n m2 = nnz(Y{t_idx} == -1);\n if ( m1==0 || m2==0 )\n C0_prep(t_idx) = 0;\n else\n C0_prep(t_idx) = log(m1/m2);\n end\nend\n\nif opts.init==2\n W0 = zeros(dimension, task_num);\n C0 = zeros(1, task_num);\nelseif opts.init== 0\n W0 = randn(dimension, task_num);\n C0 = C0_prep;\nelse\n if isfield(opts,'W0')\n W0=opts.W0;\n if (nnz(size(W0)-[dimension, task_num]))\n error('\\n Check the input .W0');\n end\n else\n W0 = zeros(dimension, task_num);\n end\n if isfield(opts,'C0')\n C0=opts.C0;\n else\n C0=C0_prep;\n end\nend\n\n\n\nbFlag=0; % this flag tests whether the gradient step only changes a little\n\n\nWz= W0;\nCz= C0;\nWz_old = W0;\nCz_old = C0;\n\nt = 1;\nt_old = 0;\niter = 0;\ngamma = 1;\ngamma_inc = 2;\n\nwhile iter < opts.maxIter\n alpha = (t_old - 1) /t;\n \n Ws = (1 + alpha) * Wz - alpha * Wz_old;\n Cs = (1 + alpha) * Cz - alpha * Cz_old;\n \n % compute function value and gradients of the search point\n [gWs, gCs, Fs ] = gradVal_eval(Ws, Cs);\n \n % the Armijo Goldstein line search scheme\n while true\n [Wzp Wzp_tn] = trace_projection(Ws - gWs/gamma, 2 * rho1 / gamma);\n Czp = Cs - gCs/gamma;\n Fzp = funVal_eval (Wzp, Czp);\n \n delta_Wzp = Wzp - Ws;\n delta_Czp = Czp - Cs;\n nrm_delta_Wzp = norm(delta_Wzp, 'fro')^2;\n nrm_delta_Czp = norm(delta_Czp, 'fro')^2;\n r_sum = (nrm_delta_Wzp+nrm_delta_Czp)/2;\n \n % Fzp_gamma = Fs + trace(delta_Wzp' * gWs)...\n % + trace(delta_Czp' * gCs)...\n % + gamma/2 * nrm_delta_Wzp ...\n % + gamma/2 * nrm_delta_Czp;\n Fzp_gamma = Fs + sum(sum(delta_Wzp .* gWs))...\n + sum(sum(delta_Czp .* gCs))...\n + gamma/2 * nrm_delta_Wzp ...\n + gamma/2 * nrm_delta_Czp;\n \n if (r_sum <=1e-20)\n bFlag=1; % this shows that, the gradient step makes little improvement\n break;\n end\n \n if (Fzp <= Fzp_gamma)\n break;\n else\n gamma = gamma * gamma_inc;\n end\n end\n \n Wz_old = Wz;\n Cz_old = Cz;\n Wz = Wzp;\n Cz = Czp;\n \n %funcVal = cat(1, funcVal, Fzp + rho1 * sum( svd(Wzp, 0) ));\n funcVal = cat(1, funcVal, Fzp + rho1 * Wzp_tn);\n \n if (bFlag)\n % fprintf('\\n The program terminates as the gradient step changes the solution very small.');\n break;\n end\n \n % test stop condition.\n switch(opts.tFlag)\n case 0\n if iter>=2\n if (abs( funcVal(end) - funcVal(end-1) ) <= opts.tol)\n break;\n end\n end\n case 1\n if iter>=2\n if (abs( funcVal(end) - funcVal(end-1) ) <=...\n opts.tol* funcVal(end-1))\n break;\n end\n end\n case 2\n if ( funcVal(end)<= opts.tol)\n break;\n end\n case 3\n if iter>=opts.maxIter\n break;\n end\n end\n \n iter = iter + 1;\n t_old = t;\n t = 0.5 * (1 + (1+ 4 * t^2)^0.5);\n \nend\n\nW = Wzp;\nC = Czp;\n\n% private functions\n function [grad_W, grad_C, funcVal] = gradVal_eval(W, C)\n grad_W = zeros(dimension, task_num);\n grad_C = zeros(1, task_num);\n lossValVect = zeros (1 , task_num);\n if opts.pFlag\n parfor i = 1:task_num\n [ grad_W(:, i), grad_C(:, i), lossValVect(:, i)] = unit_grad_eval( W(:, i), C(i), X{i}, Y{i});\n end\n else\n for i = 1:task_num\n [ grad_W(:, i), grad_C(:, i), lossValVect(:, i)] = unit_grad_eval( W(:, i), C(i), X{i}, Y{i});\n end\n end\n grad_W = grad_W+ rho_L2 * 2 * W;\n % here when computing function value we do not include\n % l1 norm.\n funcVal = sum(lossValVect) + rho_L2 * norm(W, 'fro')^2;\n end\n\n function [funcVal] = funVal_eval (W, C )\n funcVal = 0;\n if opts.pFlag\n parfor i = 1: task_num\n funcVal = funcVal + unit_funcVal_eval( W(:, i), C(i), X{i}, Y{i});\n end\n else\n for i = 1: task_num\n funcVal = funcVal + unit_funcVal_eval( W(:, i), C(i), X{i}, Y{i});\n end\n end\n % here when computing function value we do not include\n % l1 norm.\n funcVal = funcVal + rho_L2 * norm(W, 'fro')^2;\n end\n\n\nend\n\nfunction [ grad_w, grad_c, funcVal ] = unit_grad_eval( w, c, x, y)\n%gradient and logistic evaluation for each task\nm = length(y);\nweight = ones(m, 1)/m;\nweighty = weight.* y;\naa = -y.*(x'*w + c);\nbb = max( aa, 0);\nfuncVal = weight'* ( log( exp(-bb) + exp(aa-bb) ) + bb );\npp = 1./ (1+exp(aa));\nb = -weighty.*(1-pp);\ngrad_c = sum(b);\ngrad_w = x * b;\nend\n\nfunction [ funcVal ] = unit_funcVal_eval( w, c, x, y)\n%function value evaluation for each task\nm = length(y);\nweight = ones(m, 1)/m;\naa = -y.*(x'*w + c);\nbb = max( aa, 0);\nfuncVal = weight'* ( log( exp(-bb) + exp(aa-bb) ) + bb );\nend", "meta": {"author": "jiayuzhou", "repo": "MALSAR", "sha": "fb9751594983df020ddc4f7e4a40520ee7c37989", "save_path": "github-repos/MATLAB/jiayuzhou-MALSAR", "path": "github-repos/MATLAB/jiayuzhou-MALSAR/MALSAR-fb9751594983df020ddc4f7e4a40520ee7c37989/MALSAR/functions/low_rank/Logistic_Trace.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.48761010607136296}} {"text": "% Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9)\n%\n% Copyright (C) 1993-2011, by Peter I. Corke\n%\n% This file is part of The Robotics Toolbox for MATLAB (RTB).\n% \n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with RTB. If not, see .\n%\n% http://www.petercorke.com\nfunction t = q2tr(q)\n\n q = double(q);\n s = q(1);\n x = q(2);\n y = q(3);\n z = q(4);\n\n r = [ 1-2*(y^2+z^2) 2*(x*y-s*z) 2*(x*z+s*y)\n 2*(x*y+s*z) 1-2*(x^2+z^2) 2*(y*z-s*x)\n 2*(x*z-s*y) 2*(y*z+s*x) 1-2*(x^2+y^2) ];\n t = eye(4,4);\n t(1:3,1:3) = r;\n t(4,4) = 1;\nendfunction\n", "meta": {"author": "petercorke", "repo": "robotics-toolbox-matlab", "sha": "bd7a9d75176c660f43fc799b24d838f70b02250c", "save_path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab/robotics-toolbox-matlab-bd7a9d75176c660f43fc799b24d838f70b02250c/Octave/@Quaternion/q2tr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4875791825430054}} {"text": "% SP_BSPLINE_FLUID: Construct different pair of B-Splines spaces on the physical domain for fluid problems.\n%\n% [spv, spp] = sp_bspline_fluid (elem_name, knots, nsub, ...\n% degreep, regularity, msh)\n%\n% INPUTS:\n%\n% elem_name: the name of the element. Right now 'TH' (Taylor-Hood), \n% 'NDL' (Nedelec, 2nd family), 'RT' (Raviart-Thomas) and\n% 'SG' (SubGrid) are supported.\n% knots: knot vector of the coarse geometry.\n% nsub: number of subdivisions of each interval.\n% degreep: degree of the pressure space along each parametric direction\n% regularity: continuity of the pressure space along each parametric direction\n% msh: msh object containing (in the field msh.qn) the points \n% along each parametric direction in the parametric \n% domain at which to evaluate, i.e. quadrature points \n% or points for visualization (see msh_cartesian).\n%\n% OUTPUT:\n%\n% spv: object representing the discrete velocity function space (see sp_vector)\n% spp: object representing the discrete pressure function space (see sp_scalar)\n%\n% For more details, see:\n% A. Buffa, C. de Falco, G. Sangalli, \n% IsoGeometric Analysis: Stable elements for the 2D Stokes equation\n% Internat. J. Numer. Methods Fluids, 2011\n%\n% A. Bressan, G. Sangalli,\n% Isogeometric discretizations of the Stokes problem: stability\n% analysis by the macroelement technique\n% IMA J. Numer. Anal., 2013.\n%\n% Copyright (C) 2009, 2010, 2011 Carlo de Falco\n% Copyright (C) 2011, 2015 Rafael Vazquez\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\nfunction [spv, spp] = sp_bspline_fluid (element_name, ...\n knots, nsub_p, degree_p, regularity_p, msh)\n\n% Construction of the knot vectors and the discrete space for the velocity\nswitch (lower (element_name))\n case {'th'}\n knotsp = kntrefine (knots, nsub_p-1, degree_p, regularity_p);\n spp = sp_bspline (knotsp, degree_p, msh);\n \n degree_v = degree_p + 1;\n regularity_v = regularity_p;\n nsub_v = nsub_p;\n knots_v = kntrefine (knots, nsub_v-1, degree_v, regularity_v);\n scalar_space = sp_bspline (knots_v, degree_v, msh);\n for idim = 1:msh.ndim\n scalar_spaces{idim} = scalar_space;\n end\n spv = sp_vector (scalar_spaces, msh);\n clear scalar_spaces scalar_space\n\n case {'sg'}\n knotsp = kntrefine (knots, nsub_p-1, degree_p, regularity_p);\n spp = sp_bspline (knotsp, degree_p, msh);\n \n degree_v = degree_p + 1;\n regularity_v = regularity_p+1;\n nsub_v = 2*nsub_p;\n knots_v = kntrefine (knots, nsub_v-1, degree_v, regularity_v);\n scalar_space = sp_bspline (knots_v, degree_v, msh);\n for idim = 1:msh.ndim\n scalar_spaces{idim} = scalar_space;\n end\n spv = sp_vector (scalar_spaces, msh);\n clear scalar_spaces scalar_space\n\n case {'ndl'}\n% In this case the regularity is assigned first in the velocity space\n degree_h1 = degree_p + 1;\n regularity_h1 = regularity_p + 1;\n knots_h1 = kntrefine (knots, nsub_p-1, degree_h1, regularity_h1);\n [knots_hdiv, degree_hdiv] = knt_derham (knots_h1, degree_h1, 'Hdiv');\n\n degree_v = degree_h1;\n for idim = 1:msh.ndim\n knots_v{idim} = knots_hdiv{idim}{idim};\n for jdim = setdiff (1:msh.ndim, idim)\n knots_v{jdim} = sort ([knots_hdiv{idim}{jdim}, unique(knots_hdiv{idim}{jdim})]);\n end\n scalar_spaces{idim} = sp_bspline (knots_v, degree_v, msh);\n end\n spv = sp_vector (scalar_spaces, msh, 'div-preserving');\n clear scalar_spaces\n \n [knotsp, degp] = knt_derham (knots_h1, degree_h1, 'L2');\n spp = sp_bspline (knotsp, degp, msh, 'integral-preserving');\n\n case {'rt'}\n% In this case the regularity is assigned first in the velocity space\n degree_h1 = degree_p + 1;\n regularity_h1 = regularity_p + 1;\n knots_h1 = kntrefine (knots, nsub_p-1, degree_h1, regularity_h1);\n\n [knots_v, degree_v] = knt_derham (knots_h1, degree_h1, 'Hdiv');\n for idim = 1:msh.ndim\n scalar_spaces{idim} = sp_bspline (knots_v{idim}, degree_v{idim}, msh);\n end\n spv = sp_vector (scalar_spaces, msh, 'div-preserving');\n clear scalar_spaces\n\n [knotsp, degp] = knt_derham (knots_h1, degree_h1, 'L2');\n spp = sp_bspline (knotsp, degp, msh, 'integral-preserving');\n\n% if (nargout == 3)\n% PI = b2nst__ (spp, knotsp, degree_p, msh);\n% end\n otherwise\n error ('sp_bspline_fluid: unknown element type')\nend\n\nend\n\n", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/space/sp_bspline_fluid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6187804337438502, "lm_q1q2_score": 0.48755640700022085}} {"text": " function [Gauss,terms,logp,comptime] = laplacedegenerate_ep(y,X,K,varargin)\n\n% specialized version of our fast variant of\n% Expectation Propagation for Logistic Regression (2 classes) with a (correlated) Laplace prior\n% in the degenerate case, i.e., when the number of features >> number of samples\n% (also works when number of samples > number of features, but then less stable!!!)\n%\n% input:\n% labels = an N x 1 vector of class labels [1,2]\n% examples = an N x M matrix of input data\n% K = the prior precision matrix of size M x M\n%\n% Note: the bias term should be explicitly added to K and the examples!\n%\n% regression parameters refers to betas\n% auxiliary variables refers to u and v whose precision matrix auxK = inv(Lambda) couples the features.\n%\n% we have a precision matrix of the form\n%\n% | K_beta |\n% | K_u |\n% | K_v |\n%\n% priorGauss: struct with fields\n%\n% hatK diagonal of precision matrix (number of samples x 1);\n% (initially zero)\n% diagK diagonal of precision matrix (number of features x 1)\n% (initially zero)\n% \n% precision matrix of regression parameters K_beta = A' hatK A + diagK\n%\n% h canonical mean (number of features x 1)\n% (initially zero)\n%\n% auxK precision matrix of auxiliary variables (number of features x number of features; sparse)\n% (contains the covariance structure of interest)\n%\n% A feature matrix (number of samples x number of features)\n%\n% terms: struct with fields\n%\n% hatK as priorGauss\n% diagK as priorGauss\n% hath canonical mean (number of samples x 1)\n% h canonical mean (number of features x 1)\n% canonical mean of regression parameters = h + A' hath\n% auxK as priorGauss, but then only diagonal elements (number of features x 1)\n%\n% opt: struct with fields (all optional, defaults in brackets)\n%\n% maxstepsize maximum step size [1]\n% fraction fraction or power for fractional/power EP [1]\n% niter maximum number of iterations [100]\n% tol convergence criterion [1e-5]\n% nweights number of points for numerical integration [20]\n% temperature temperature for simulated annealing [1]\n% verbose give output during run [1]\n%\n% Gauss: struct with fields as in priorGauss plus\n%\n% hatB diagonal of projected covariance (number of samples x 1)\n% hatB = A Covariance A'\n% hatn projected mean (number of samples x 1)\n% hatn = A m\n% diagC diagonal of covariance matrix of regression parameters (number of features x 1)\n% auxC diagonal of covariance matrix of auxiliary variables (number of features x 1)\n%\n%\n% logp: estimated marginal loglikelihood (implementation doubtful...)\n%\n% comptime: computation time\n\n%% initialization\n\n% parse opt \nopt = [];\nfor i=1:2:length(varargin)\n opt.(varargin{i}) = varargin{i+1};\nend\n\nif ~isfield(opt,'maxstepsize'), opt.maxstepsize = 1; end\nif ~isfield(opt,'fraction'), opt.fraction = 0.95; end\nif ~isfield(opt,'niter'), opt.niter = 1000; end\nif ~isfield(opt,'tol'), opt.tol = 1e-5; end\nif ~isfield(opt,'nweights'), opt.nweights = 50; end\nif ~isfield(opt,'temperature'), opt.temperature = 1; end\nif ~isfield(opt,'lambda'), opt.lambda = 1; end\nif ~isfield(opt,'verbose'), opt.verbose = 1; end\n\nif opt.verbose\n fprintf('starting EP\\n');\nend\n\ntic\n\n[nsamples,nfeatures] = size(X);\n\n%% create priorGauss and terms\n\nA = X.*repmat(y,1,nfeatures);\n\n% construct Gaussian representation\npriorGauss.A = A;\npriorGauss.hatK = zeros(nsamples,1);\npriorGauss.h = zeros(nfeatures,1);\npriorGauss.diagK = zeros(nfeatures,1);\npriorGauss.auxK = K;\n\n% compute additional terms for the EP free energy\n[cholK,dummy,S] = chol(K,'lower');\nLogPriorRestAux2 = (2*sum(log(full(diag(cholK))))); % -nfeatures*log(2*pi)); % redundant MvG\n\n% construct term representation\nterms.hatK = ones(nsamples,1)/10;\nterms.hath = zeros(nsamples,1);\nterms.diagK = ones(nfeatures,1)./(10*opt.lambda);\nterms.auxK = zeros(nfeatures,1);\nterms.h = zeros(nfeatures,1);\n\n%% precompute points and weights for numerical integration\n\n[xhermite,whermite] = gausshermite(opt.nweights);\nxhermite = xhermite(:); % nhermite x 1\nwhermite = whermite(:); % nhermite x 1\n\n[xlaguerre,wlaguerre] = gausslaguerre(opt.nweights);\nxlaguerre = xlaguerre(:); % nlaguerre x 1\nwlaguerre = wlaguerre(:); % nlaguerre x 1\n\n% divide all canonical parameters by the temperature\nif opt.temperature ~= 1,\n [priorGauss,terms] = correct_for_temperature(priorGauss,terms,opt.temperature);\nend\n\n\n%% build initial Gauss\n\n% add terms to prior\nGauss = update_Gauss(priorGauss,terms); \nGauss = canonical_to_moments(Gauss);\n[myGauss,ok] = project_all(Gauss,terms,opt.fraction);\nif ~ok,\n error('improper cavity distributions\\n');\nend\n\nprior = Gauss; % save prior Gauss\n\n%% enter the iterations \n\nlogp = 0;\nlogpold = 2*opt.tol;\nchange = 0;\nteller = 0;\nstepsize = opt.maxstepsize;\n\nwhile abs(logp-logpold) > stepsize*opt.tol && teller < opt.niter,\n \n teller = teller+1;\n logpold = logp;\n oldchange = change;\n \n % compute the new term approximation by applying an adf update on all the cavity approximations\n [fullterms,logreglogz,crosslogz] = ...\n adfupdate_all(myGauss,terms,xhermite,whermite,xlaguerre,wlaguerre,opt.fraction,opt.temperature);\n\n ok = 0;\n ok1 = 1;\n ok2 = 1;\n \n while ~ok,\n \n % try to replace the old term approximations by the new term approximations and check whether the new Gauss is still fine\n \n [newGauss,newterms,ok1] = try_update(Gauss,fullterms,terms,stepsize);\n %[newGauss,newterms,ok1] = try_update(Gauss,fullterms,terms,0.5);\n \n \n if ok1, \n % compute all cavity approximations needed for the next EP updates and check whether they are all fine \n [newGauss,myGauss,logZappx,ok2] = try_project(newGauss,newterms,opt.fraction);\n end\n \n ok = (ok1 & ok2);\n if ok, % accept\n \n terms = newterms;\n Gauss = newGauss;\n stepsize = min(opt.maxstepsize,stepsize*1.9);\n \n else % try with smaller stepsize\n \n stepsize = stepsize/2;\n if ~ok1,\n fprintf('improper full covariance: lowering stepsize to %g\\n',stepsize');\n elseif ~ok2,\n fprintf('improper cavity covariance: lowering stepsize to %g\\n',stepsize');\n end\n if stepsize < 1e-10,\n warning('Cannot find an update that leads to proper cavity approximations');\n teller = opt.niter;\n break;\n end\n\n end\n\n end\n \n % compute marginal moments\n \n if ok,\n \n % compute marginal loglikelihood\n \n %logp = sum(logz) + sum(crosslogz) + logdet/2 + contribQ; \n% CorrTermCross1 = (myGauss.m.^2)./myGauss.diagC - (newGauss.m.^2)./newGauss.diagC + log(myGauss.diagC/newGauss.diagC);\n%\t CorrTermCross2 = log(myGauss.auxC/newGauss.auxC);\n% CorrTerm = 0.5*CorrTermCross1 + 0.5*(CorrTermCross2 + CorrTermCross2);\n \n logp = (sum(crosslogz) + sum(logreglogz))./opt.fraction + logZappx + LogPriorRestAux2; \n \n if opt.verbose\n fprintf('%d: %g (stepsize: %g)\\n',teller,logp,stepsize);\n end\n \n % check whether marginal loglikelihood is going up and down, if so, lower stepsize\n \n change = logp-logpold;\n if change*oldchange < 0, % possibly cycling\n stepsize = stepsize/2;\n end\n oldchange = change;\n end\n\nend\n\ncomptime = toc;\n\nif opt.verbose\n fprintf('EP finished in %s seconds\\n',num2str(comptime));\nend\n\nGauss.prior = prior;\n\n%%% END MAIN\n\n\n%%%%%%%%%\n%\n% compute the cavity approximations that result when subtracting a fraction of the term approximations \n\nfunction [myGauss,ok] = project_all(Gauss,terms,fraction)\n\nif nargin < 3,\n fraction = 1;\nend\n\n% take out and project in moment form\n\n% (1) regression parameters\n\n[myGauss.hatB,myGauss.hatn] = ...\n rank_one_update(Gauss.hatB,Gauss.hatn,-fraction*terms.hatK,-fraction*terms.hath);\n\n% (2) cross terms between regression parameters and auxiliary parameters\n\n[myGauss.diagC,myGauss.m] = ...\n rank_one_update(Gauss.diagC,Gauss.m,-fraction*terms.diagK,-fraction*terms.h);\n\n myGauss.auxC = rank_one_update(Gauss.auxC,[],-fraction*terms.auxK);\n\n% check whether all precision matrices are strictly positive definite\n\nif nargout > 1,\n ok = (all(myGauss.hatB > 0) & all(myGauss.diagC > 0) & all(myGauss.auxC > 0));\nend\n\n\n%%%%%%%%%\n%\n% compute the new term approximation by applying an adf update on all the cavity approximations\n\nfunction [fullterms,logreglogz,crosslogz] = ...\n adfupdate_all(myGauss,terms,xhermite,whermite,xlaguerre,wlaguerre,fraction,temperature)\n\nif nargin < 8,\n temperature = 1;\nend\nif nargin < 7,\n fraction = 1;\nend\n\n%% (1) regression parameters\n\noldm = myGauss.hatn;\noldC = myGauss.hatB;\nsqrtC = sqrt(oldC);\nnsamples = length(oldm);\nnhermite = length(whermite);\n\n% translate and scale the sample points to get the correct mean and variance\n\nx = repmat(oldm,1,nhermite) + sqrtC*xhermite';\n\n% compute the terms at the sample points\n\ng = logist(x); % returns - log (1 + exp(-x)) with special attention for very small and very large x\n\n% correct for fraction and temperature and incorporate the sample weights\n\ng = fraction*g/temperature + log(repmat(whermite',nsamples,1));\nmaxg = max(g,[],2);\ng = g-repmat(maxg,1,nhermite);\nexpg = exp(g);\ndenominator = sum(expg,2);\nneww = expg./repmat(denominator,1,nhermite);\n\n% compute the moments\n\nEx = sum(x.*neww,2);\nExx = sum(x.^2.*neww,2); \nnewm = Ex;\nnewC = Exx-Ex.^2;\n\n% derive the term approximation from the change in mean and variance\n\n[fullterms.hatK,fullterms.hath,logzextra] = compute_termproxy(newC,newm,oldC,oldm,fraction);\n\n% contributions to marginal loglikelihood\nlogreglogz = maxg + log(denominator) + logzextra;\n\n%% (2) cross terms between regression parameters and auxiliary variables\n\noldm = myGauss.m;\noldC = myGauss.diagC;\noldlambda = myGauss.auxC;\nnfeatures = length(oldm);\nnlaguerre = length(wlaguerre);\n\n% this part heavily relies on the accompanying note\n% basic idea:\n% - the cavity approximation on U is an exponential distribution\n% - we have analytical formulas for the moments of x conditioned upon U\n% - marginal moments can then be computed through numerical integration with Gauss-Laguerre\n\n% translate and scale the sample points to get the correct mean\n\nU = 2*oldlambda*xlaguerre'; % nfeatures x nlaguerre\n\nmm = repmat(oldm,1,nlaguerre);\nCC = repmat(oldC,1,nlaguerre);\n\n% compute the partition function (integral over x) given U and turn this into weights required for computing the marginal moments\n\ng = (1-fraction)*log(U)/2 - fraction*mm.^2./(U + fraction*CC)/2 - log(U+ fraction*CC)/2;\n\ng = bsxfun(@plus,g,log(wlaguerre'));\nmaxg = max(g,[],2);\ng = bsxfun(@minus,g,maxg);\nexpg = exp(g);\n\ndenominator = sum(expg,2);\n\nneww = bsxfun(@rdivide,expg,denominator);\n\n% compute the marginal moments through numerical integration\n\nExgU = mm.*U./(U + fraction*CC);\nEx = sum(ExgU.*neww,2);\n\nExxgU = ExgU.^2 + CC.*U./(U+fraction*CC);\nExx = sum(ExxgU.*neww,2);\nEU = sum(U.*neww,2);\n\nnewm = Ex;\nnewC = Exx-Ex.^2;\nnewlambda = EU/2;\n\n% derive the term approximation from the change in mean and variance\n\n[fullterms.diagK,fullterms.h,logzextra1] = compute_termproxy(newC,newm,oldC,oldm,fraction);\n[fullterms.auxK,dummy,logzextra2] = compute_termproxy(newlambda,zeros(nfeatures,1),oldlambda,zeros(nfeatures,1),fraction);\n\ncrosslogz = maxg + log(denominator) + logzextra1 + 2*logzextra2;\n% multiplied the last term by two\n\n\n%%%%%%%%%%\n%\n% compute the moments corresponding to the canonical parameters\n\nfunction [Gauss,logp] = canonical_to_moments(Gauss)\n\n[nsamples,nfeatures] = size(Gauss.A);\n\n%% (1) regression parameters\n\nif nsamples > nfeatures, % in the non-degenerate case, this direct route is more stable and faster\n \n scaledA = Gauss.A.*(repmat(Gauss.hatK,1,nfeatures));\n K = Gauss.A'*scaledA + diag(Gauss.diagK);\n [C,logdet1] = invert_chol(K);\n Gauss.m = C*Gauss.h;\n Gauss.hatB = zeros(nsamples,1); % only need diagonal\n for k=1:nsamples,\n Gauss.hatB(k) = Gauss.A(k,:)*C*Gauss.A(k,:)';\n end\n Gauss.diagC = diag(C);\n Gauss.hatn = Gauss.A*Gauss.m;\n \nelse\n \n % this part heavily relies on the appendix of the accompanying note\n % basic idea:\n % - the precision matrix K is of the form A' hatK A + diagK, where both hatK and diagK are diagonal matrices\n % - apply Woodbury's formula to replace inverting an (nfeat x nfeat) matrix by an (nsample x nsample) alternative\n % - projections of the covariance matrix and the mean onto the feature matrix then follow immediately\n \n scaledA = bsxfun(@rdivide,Gauss.A,Gauss.diagK');\n W = Gauss.A*scaledA';\n W = (W + W')/2; % make symmetric\n [Q,logdet1] = invert_chol(diag(1./Gauss.hatK) + W);\n\n Gauss.hatB = zeros(nsamples,1);\n for k=1:nsamples,\n Gauss.hatB(k) = W(k,k) - W(k,:)*Q*W(:,k);\n end\n\n Gauss.m = Gauss.h./Gauss.diagK - scaledA'*(Q*(scaledA*Gauss.h));\n Gauss.hatn = Gauss.A*Gauss.m;\n \n Gauss.diagC = 1./Gauss.diagK;\n\n% for i=1:nfeatures,\n% Gauss.diagC(i) = Gauss.diagC(i) - scaledA(:,i)'*Q*scaledA(:,i);\n% end\n\n % adriana's recipe\n z = scaledA' * Q; for i=1:size(z), Gauss.diagC(i) = Gauss.diagC(i) - z(i,:) * scaledA(:,i); end\n \n logdet1 = logdet1 + sum(log(Gauss.diagK)) + sum(log(Gauss.hatK)); \n \nend\n\n% compute quadratic term (BC)\n\nqterm = sum(Gauss.m .* Gauss.diagK .* Gauss.m); % = m' * diagK * m\nqterm = qterm + sum(Gauss.hatn .* Gauss.hatK .* Gauss.hatn);\n\nlogp1 = 0.5*(qterm - logdet1);\n\n\n%% (2) auxiliary variables; i.e., wrt scale mixture representation of\n% Laplace prior\n\n% this is (by far) the most expensive step when nsamples << nfeatures\n% and the precision matrix of the auxiliary variables is non-diagonal\n\n[auxC,logdet2] = invert_chol(Gauss.auxK); % only need diagonal terms\nGauss.auxC = full(diag(auxC)); % turn into full vector\nlogp2 = 0.5*( - logdet2);\nlogp = logp1 + 2*logp2;\n\n%%%%%%%%%%\n%\n% take out the old term proxies and add the new termproxies and check whether the resulting Gaussian is still normalizable\n\nfunction [newGauss,newterms,ok] = try_update(Gauss,fullterms,terms,stepsize)\n\nif nargin < 4,\n stepsize = 1;\nend\n\n% take out the old term proxies\n\nnewGauss = update_Gauss(Gauss,terms,-1);\n\n% compute the new term proxies as a weighted combi of the old ones and the \"full\" (stepsize 1) term proxies\n\nnewterms = combine_terms(fullterms,terms,stepsize);\n\n% add the new term proxies\n\nnewGauss = update_Gauss(newGauss,newterms,1);\n\n[L,check,dummy] = chol(newGauss.auxK,'lower'); % check whether full covariance matrix is ok\n % note that this is bit inefficient, since we redo the Cholesky later when everything is fine\n\nok = (check == 0 & all(newGauss.hatK > 0) & all(newGauss.diagK > 0)); % perhaps a bit too strong???\n\n\n%%%%%%%%%%%%\n%\n% compute the moment form of the current Gauss and all cavity approximations and check whether they are fine\n\nfunction [Gauss,myGauss,logdet,ok] = try_project(Gauss,terms,fraction)\n\nif nargin < 3,\n fraction = 1;\nend\n\n[Gauss,logdet] = canonical_to_moments(Gauss);\n[myGauss,ok] = project_all(Gauss,terms,fraction);\n\n%%%%%%%%%%\n%\n% if we use a temperature < 1, to get closer to the MAP solution, we have to change the prior and initial term proxies accordingly\n\nfunction [Gauss,terms] = correct_for_temperature(Gauss,terms,temperature)\n\n% note: choose temperature small to implement MAP-like behavior\n\nGauss.hatK = Gauss.hatK/temperature;\nGauss.h = Gauss.h/temperature;\nGauss.auxK = Gauss.auxK/temperature;\nGauss.diagK = Gauss.diagK/temperature;\n\n\nterms.hatK = terms.hatK/temperature;\nterms.hath = terms.hath/temperature;\nterms.diagK = terms.diagK/temperature;\nterms.auxK = terms.auxK/temperature;\nterms.h = terms.h/temperature;\n\n%%%%%%%%%%\n%\n% invert a positive definite matrix using Cholesky factorization\n\nfunction [invA,logdet] = invert_chol(A)\n\nif issparse(A)\n \n if 0 % matlab version; slower but useful in case of mex problems\n \n [L,dummy,S] = chol(sparse(A),'lower'); % now A = S*(L*L')*S' and (L*L') = S'*A*S\n \n n = length(L);\n invdiagL2 = 1./spdiags(L,0).^2;\n \n invA = A;\n for i=n:-1:1,\n I = i+find(L(i+1:n,i));\n invA(I,i) = -(invA(I,I)*L(I,i))/L(i,i);\n invA(i,I) = invA(I,i)';\n invA(i,i) = invdiagL2(i) - (invA(i,I)*L(I,i))/L(i,i);\n end\n \n invA = S*invA*S';\n \n else\n \n [L,dummy,S] = chol(sparse(A),'lower'); % now A = S*(L*L')*S' and (L*L') = S'*A*S\n \n if dummy\n error('matrix is not p.d.');\n end\n \n invA = fastinvc(L);\n invA = S*invA*S';\n end\n \nelse\n \n [L,dummy] = chol(A,'lower');\n \n if dummy\n error('matrix is not p.d.');\n end\n\n invA = inv(A);\n \nend\n\nif nargout > 1,\n logdet = 2*sum(log(full(diag(L))));\nend\n\n%%%%%%%%%%\n%\n% compute the term proxy when [oldC,oldm] changes to [newC,newm]\n\nfunction [K,h,logz] = compute_termproxy(newC,newm,oldC,oldm,fraction)\n\nif nargin < 5,\n fraction = 1;\nend\n\nK = (1./newC - 1./oldC)/fraction;\nh = (newm./newC - oldm./oldC)/fraction;\nlogz = oldm.^2./oldC/2 - newm.^2./newC/2 + log(full(oldC./newC))/2 ;\n\n\n%%%%%%%%%%\n%\n% Sherman-Morrison formula to compute the change from [oldC,oldm] to [newC,newm] when we add [K,h] to the corresponding canonical parameters\n\nfunction [newC,newm] = rank_one_update(oldC,oldm,K,h)\n\ndummy = K.*oldC;\noneminusdelta = 1./(1+dummy);\nnewC = oneminusdelta.*oldC;\n\nif nargout > 1,\n newm = oneminusdelta.*(oldm + h.*oldC);\nend\n\n\n%%%%%%%%%%%\n%\n% general procedure for a weighted combi of the fields of two structures\n\nfunction terms = combine_terms(terms1,terms2,stepsize)\n\nnames1 = fieldnames(terms1);\nnames2 = fieldnames(terms2);\nnames = intersect(names1,names2);\n\nterms = struct;\nfor i=1:length(names) \n terms.(names{i}) = stepsize*terms1.(names{i}) + (1-stepsize)*terms2.(names{i});\nend\n\n\n%%%%%%%%%%%\n%\n% updates the Gaussian representation with new term proxies\n\nfunction Gauss = update_Gauss(Gauss,terms,const)\n\nif nargin < 3,\n const = 1;\nend\n\nGauss.h = Gauss.h + const*Gauss.A'*terms.hath + const*terms.h;\nGauss.hatK = Gauss.hatK + const*terms.hatK;\nGauss.diagK = Gauss.diagK + const*terms.diagK;\n\n% get diagonal elements\ndiagidx = 1:(size(Gauss.auxK,1)+1):numel(Gauss.auxK);\nGauss.auxK(diagidx) = Gauss.auxK(diagidx) + const*terms.auxK';\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/bayesianlogreg/laplacedegenerate_ep.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4875564070002208}} {"text": "classdef TREE3 < PROBLEM\n% \n% The time-varying ratio error estimation problem\n% T --- 1000 --- Length of data (related to the number of variables)\n\n%------------------------------- Reference --------------------------------\n% C. He, R. Cheng, C. Zhang, Y. Tian, Q. Chen, and X. Yao, Evolutionary\n% large-scale multiobjective optimization for ratio error estimation of\n% voltage transformers, IEEE Transactions on Evolutionary Computation,\n% 2020, 24(5): 868-881.\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(Access = private)\n Data; % Dataset\n Mean; % Mean values of the dataset\n end\n methods\n %% Default settings of the problem\n function Setting(obj)\n % Load data\n T = obj.ParameterSet(1000);\n CallStack = dbstack('-completenames');\n load(fullfile(fileparts(CallStack(1).file),'Dataset_TREE.mat'),'Dataset');\n obj.Data = Dataset.TREE3(1:min(max(T,10),end),:);\n % Set the numbers of objectives and decision variables\n K = 6;\n obj.M = 2;\n obj.D = T*K;\n % Set the upper and lower boundaries\n Lower = zeros(T,K);\n Upper = zeros(T,K);\n obj.Mean = zeros(T,K);\n for i = 1 : 3\n Lower(:,i) = min(obj.Data(:,i:3:end*0.5),[],2)/1.01;\n Upper(:,i) = max(obj.Data(:,i:3:end*0.5),[],2)/0.99;\n Lower(:,i+3) = min(obj.Data(:,end*0.5+i:3:end),[],2)/1.01;\n Upper(:,i+3) = max(obj.Data(:,end*0.5+i:3:end),[],2)/0.99;\n obj.Mean(:,i) = mean(obj.Data(:,i:3:end*0.5),2);\n obj.Mean(:,i+3) = mean(obj.Data(:,end*0.5+i:3:end),2);\n end\n % The decision variables are the offset of the mean values of\n % the dataset\n obj.lower = reshape(Lower-obj.Mean,1,[]);\n obj.upper = reshape(Upper-obj.Mean,1,[]);\n obj.encoding = ones(1,obj.D);\n end\n %% Generate initial solutions\n function Population = Initialization(obj,N)\n if nargin < 2; N = obj.N; end\n PopDec = obj.Mean(:)'.*(rand(N,obj.D)*0.008-0.004);\n PopDec = min(max(PopDec,repmat(obj.lower,N,1)),repmat(obj.upper,N,1));\n Population = obj.Evaluation(PopDec);\n end\n %% Calculate objective values\n function PopObj = CalObj(obj,PopDec)\n N = size(PopDec,1);\n KP = size(obj.Data,2);\n [T,K] = size(obj.Mean);\n PopDec = reshape(PopDec,N,T,K) + repmat(reshape(obj.Mean,1,T,K),N,1,1);\n PopObj = zeros(N,obj.M);\n % First objective\n eA1 = abs(repmat(reshape(obj.Data(:,1:end*0.5),1,T,KP/2),N,1,1)./repmat(PopDec(:,:,1:3),1,1,KP/6)-1);\n eA2 = abs(repmat(reshape(obj.Data(:,end*0.5+1:end),1,T,KP/2),N,1,1)./repmat(PopDec(:,:,4:6),1,1,KP/6)-1);\n eA = cat(3,eA1,eA2);\n PopObj(:,1) = sum(sum(eA,3),2);\n % Second objective\n Delta = std(eA(:,2:end,:)-eA(:,1:end-1,:),0,2);\n PopObj(:,2) = sum(reshape(Delta,N,[]),2);\n end\n %% Calculate constraint violations\n function PopCon = CalCon(obj,PopDec)\n N = size(PopDec,1);\n [T,K] = size(obj.Mean);\n PopDec = reshape(PopDec,N,T,K) + repmat(reshape(obj.Mean,1,T,K),N,1,1);\n PopCon = TREE_CalCon(PopDec,2);\n end\n %% Generate a point for hypervolume calculation\n function R = GetOptimum(obj,~)\n X = zeros(1,obj.D);\n X(1:2:end) = obj.lower(1:2:end);\n X(2:2:end) = obj.upper(2:2:end);\n R = obj.CalObj(X);\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/TREE/TREE3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4875564008373683}} {"text": "function preconfun = preconhessiansolve(problem, options)\n% Preconditioner based on the inverse Hessian, by solving linear systems.\n%\n% function preconfun = preconhessiansolve(problem)\n% function preconfun = preconhessiansolve(problem, options)\n%\n% Input:\n%\n% A Manopt problem structure (already containing the manifold and enough\n% information to compute the Hessian of the cost) and an options structure\n% (optional, currently ignored). Notice that if the Hessian is not positive\n% definite, then its inverse is not positive definite either and this\n% preconditioner is not suitable.\n%\n% If the Hessian cannot be computed on 'problem', a warning is issued. An\n% approximation of the Hessian will be used instead, and the present\n% preconditioner will attempt to invert that (although it may not be a\n% linear operator). If no approximate Hessian is provided either, a generic\n% approximation is used. Behavior is unspecified.\n%\n% Output:\n% \n% Returns a function handle, encapsulating a generic preconditioner of the\n% Hessian based on solving linear systems of the form:\n% Hessian(x)[preconfun(x, xdot)] = xdot,\n% where x is the point on the manifold, xdot is the input to the\n% preconditioner (a tangent vector) and preconfun(x, xdot) is returned\n% (also a tangent vector). The solve may be approximate.\n% \n% The returned preconfun has this calling pattern:\n% \n% function precxdot = preconfun(x, xdot)\n% function precxdot = preconfun(x, xdot, storedb)\n% function precxdot = preconfun(x, xdot, storedb, key)\n% \n% x is a point on the manifold problem.M, xdot is a tangent vector to that\n% manifold at x, storedb is a StoreDB object, and key is the StoreDB key to\n% point x.\n%\n% Usage:\n%\n% Typically, the user will set problem.M and other fields to define the\n% cost, the gradient and the Hessian (typically, problem.cost, problem.grad\n% and problem.hess, or problem.egrad and problem.ehess). Then, to use this\n% generic purpose Hessian preconditioner:\n%\n% problem.precon = preconhessiansolve(problem, options);\n%\n% Passing that problem structure to the conjugategradients solver\n% (which uses preconditioning) configured in steepest descent mode results\n% in a type of Riemannian Newton method.\n%\n% See also: conjugategradients\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, April 9, 2015.\n% Contributors: \n% Change log: \n\n % Check availability of the Hessian, or at least of an approximation.\n if ~canGetHessian(problem) && ~canGetApproxHessian(problem)\n % Note: we do not give a warning if an approximate Hessian is\n % explicitly given in the problem description, as in that case the\n % user seems to be aware of the issue.\n warning('manopt:getHessian:approx', ...\n ['No Hessian provided. Using an FD approximation instead.\\n' ...\n 'To disable this warning: warning(''off'', ''manopt:getHessian:approx'')']);\n problem.approxhess = approxhessianFD(problem);\n end\n\n % Set local defaults here, and merge with user options, if any.\n localdefaults = struct();\n if ~exist('options', 'var') || isempty(options)\n options = struct();\n end\n options = mergeOptions(localdefaults, options);\n\n % Build and return the function handle here. This extra construct via\n % funhandle makes it possible to make storedb and key optional.\n preconfun = @funhandle;\n function precxdot = funhandle(x, xdot, storedb, key)\n % Allow omission of the key, and even of storedb.\n if ~exist('key', 'var')\n if ~exist('storedb', 'var')\n storedb = StoreDB();\n end\n key = storedb.getNewKey();\n end \n precxdot = hessiansolvehelper(options, problem, x, xdot, ...\n storedb, key);\n end\n \nend\n\n\nfunction precxdot = hessiansolvehelper(options, problem, x, xdot, storedb, key)\n% This function does the actual work.\n \n % Exclude the case where xdot is zero\n norm_xdot = problem.M.norm(x, xdot);\n if norm_xdot < eps\n precxdot = problem.M.zerovec(x);\n return;\n end\n \n % Get a shorthand for the Hessian of the cost on M at x.\n hessian = @(u) getHessian(problem, x, u, storedb, key);\n \n % Setup an optimization problem on the tangent space to problem.M at x.\n M = problem.M;\n tgtspace = tangentspacefactory(M, x);\n prblm.M = tgtspace;\n prblm.cost = @cost;\n prblm.grad = @grad;\n prblm.hess = @(u, udot) 2*hessian(hessian(udot))/norm_xdot;\n \n function [f, store] = cost(u, store)\n if ~isfield(store, 'residue')\n Hu = hessian(u);\n store.residue = M.lincomb(x, 1, Hu, -1, xdot);\n end\n f = M.norm(x, store.residue).^2 / norm_xdot;\n end\n function [g, store] = grad(u, store)\n if ~isfield(store, 'residue')\n Hu = hessian(u);\n store.residue = M.lincomb(x, 1, Hu, -1, xdot);\n end\n g = 2 * hessian(store.residue) / norm_xdot;\n end\n \n % checkgradient(prblm); pause;\n % checkhessian(prblm); pause;\n \n localdefaults.solver = @trustregions;\n localdefaults.verbosity = 0;\n % Merge local defaults with user options, if any.\n if ~exist('options', 'var') || isempty(options)\n options = struct();\n end\n options = mergeOptions(localdefaults, options);\n \n % Solve the linear system by solving the optimization problem.\n precxdot = manoptsolve(prblm, M.zerovec(), options);\n \nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/solvers/preconditioners/preconhessiansolve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.48734375601983376}} {"text": "function a = sec(a)\n%SEC Gradient secant sec(a)\n%\n\n% written 10/16/98 S.M. Rump\n% modified 10/14/00 S.M. Rump use Tony's trick\n% modified 03/22/04 S.M. Rump improved performance\n% modified 04/04/04 S.M. Rump set round to nearest for safety\n% accelaration for sparse input\n% modified 04/06/05 S.M. Rump rounding unchanged\n% modified 09/28/08 S.M. Rump check for rounding to nearest improved\n% modified 10/08/08 S.M. Rump improved sparse multiplication: not using intval data type\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 N = getappdata(0,'INTLAB_GRADIENT_NUMVAR');\n\n ax = tan(a.x(:));\n a.x = sec(a.x);\n ax = a.x(:) .* ax;\n if issparse(a.dx)\n sizeax = size(a.dx,1);\n [ia,ja,sa] = find(a.dx);\n % take care of scalar a.x: cures Matlab V6.0 bug\n % a=7; i=[1 1]; x=a(i), b=sparse(a); y=b(i) yields row vector x but column vector y\n ax = ax(ia); \n if isa(a.x,'intval')\n adx = times(ax(:),sa(:),0);\n if adx.complex\n a.dx = intval( sparse(ia,ja,adx.mid,sizeax,N) , sparse(ia,ja,adx.rad,sizeax,N) , 'midrad' );\n else\n a.dx = intval( sparse(ia,ja,adx.inf,sizeax,N) , sparse(ia,ja,adx.sup,sizeax,N) , 'infsup' );\n end\n else\n a.dx = sparse(ia,ja,ax(:).*sa(:),sizeax,N);\n end\n else\n a.dx = a.dx .* ax(:,ones(1,N));\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/gradient/@gradient/sec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.6584174871563662, "lm_q1q2_score": 0.4873437435112955}} {"text": "function [samples, logp, diagn] = hmc_nuts(f, theta0, opt)\n%HMC_NUTS No-U-Turn Sampler (NUTS)\n%\n% Description\n% [SAMPLES, LOGP, DIAGN] = HMC_NUTS(f, theta0, opt)\n% Implements the No-U-Turn Sampler (NUTS), specifically,\n% algorithm 6 from the NUTS paper (Hoffman & Gelman, 2011). Runs\n% opt.Madapt steps of burn-in, during which it adapts the step\n% size parameter epsilon, then starts generating samples to\n% return.\n% \n% f(theta) should be a function that returns the log probability its\n% gradient evaluated at theta. I.e., you should be able to call\n% [logp grad] = f(theta).\n%\n% opt.epsilon is a step size parameter.\n% opt.M is the number of samples to generate.\n% opt.Madapt is the number of steps of burn-in/how long to run\n% the dual averaging algorithm to fit the step size\n% epsilon. Note that there is no need to provide\n% opt.epsilon if doing adaptation.\n% opt.theta0 is a 1-by-D vector with the desired initial setting\n% of the parameters.\n% opt.delta should be between 0 and 1, and is a target HMC\n% acceptance probability. Defaults to 0.8 if\n% unspecified.\n%\n% \n% The returned variable \"samples\" is an (M+Madapt)-by-D matrix\n% of samples generated by NUTS, including burn-in samples.\n%\n% Note that when used from gp_mc, opt.M and opt.Madapt are both 0 or\n% 1 (hmc_nuts returns only one sample to gp_mc). Number of epsilon \n% adaptations should be set in hmc options structure hmc_opt.nadapt, in \n% gp_mc(... ,'hmc_opt', hmc_opt).\n%\n% The returned structure diagn includes step-size vector\n% epsilon, number of rejected samples and dual averaging\n% parameters so its possible to continue adapting step-size\n% parameter.\n\n% Copyright (c) 2011, Matthew D. Hoffman\n% Copyright (c) 2012, Ville Tolvanen\n% All rights reserved.\n% \n\n% Redistribution and use in source and binary forms, with or\n% without modification, are permitted provided that the following\n% conditions are met:\n% \n% Redistributions of source code must retain the above copyright\n% notice, this list of conditions and the following disclaimer.\n%\n% Redistributions in binary form must reproduce the above copyright\n% notice, this list of conditions and the following disclaimer in\n% the documentation and/or other materials provided with the\n% distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND\n% CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n% INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n% DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n% CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n% SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n% LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n% USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n% AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n% LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n% ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n% POSSIBILITY OF SUCH DAMAGE.\n\nglobal nfevals;\nnfevals = 0;\n\nif ~isfield(opt, 'delta')\n delta = 0.8;\nelse\n delta = opt.delta;\nend\nif ~isfield(opt, 'M')\n M = 1;\nelse\n M = opt.M;\nend\nif ~isfield(opt, 'Madapt')\n Madapt = 0;\nelse\n Madapt = opt.Madapt;\nend\n\ndiagn.rej = 0;\nassert(size(theta0, 1) == 1);\n\nD = length(theta0);\nsamples = zeros(M+Madapt, D);\n\n[logp grad] = f(theta0);\nsamples(1, :) = theta0;\n\n% Parameters to the dual averaging algorithm.\ngamma = 0.05;\nt0 = 10;\nkappa = 0.75;\n% Initialize dual averaging algorithm.\nepsilonbar = 1;\nHbar = 0;\n\nif isfield(opt, 'epsilon') && ~isempty(opt.epsilon)\n epsilon = opt.epsilon(end);\n \n % Hbar & epsilonbar are needed when doing adaptation of step-length\n if isfield(opt, 'Hbar') && ~isempty(opt.Hbar)\n Hbar = opt.Hbar;\n end\n if isfield(opt, 'epsilonbar') && ~isempty(opt.epsilonbar)\n epsilonbar=opt.epsilonbar;\n else\n epsilonbar=opt.epsilon;\n end\n mu = log(10*opt.epsilon(1));\nelse\n % Choose a reasonable first epsilon by a simple heuristic.\n epsilon = find_reasonable_epsilon(theta0, grad, logp, f);\n mu = log(10*epsilon);\n \n opt.epsilon = epsilon;\n opt.epsilonbar = epsilonbar;\n opt.Hbar = Hbar;\nend\n\nfor m = 2:M+Madapt+1,\n% m\n % Resample momenta.\n r0 = randn(1, D);\n % Joint log-probability of theta and momenta r.\n joint = logp - 0.5 * (r0 * r0');\n % Resample u ~ uniform([0, exp(joint)]).\n % Equivalent to (log(u) - joint) ~ exponential(1).\n logu = joint - exprnd(1);\n % Initialize tree.\n thetaminus = samples(m-1, :);\n thetaplus = samples(m-1, :);\n rminus = r0;\n rplus = r0;\n gradminus = grad;\n gradplus = grad;\n % Initial height j = 0.\n j = 0;\n % If all else fails, the next sample is the previous sample.\n samples(m, :) = samples(m-1, :);\n % Initially the only valid point is the initial point.\n n = 1;\n rej = 0;\n % Main loop---keep going until the criterion s == 0.\n s = 1;\n while (s == 1)\n % Choose a direction. -1=backwards, 1=forwards.\n v = 2*(rand() < 0.5)-1;\n % Double the size of the tree.\n if (v == -1)\n [thetaminus, rminus, gradminus, tmp, tmp, tmp, thetaprime, gradprime, logpprime, nprime, sprime, alpha, nalpha] = ...\n build_tree(thetaminus, rminus, gradminus, logu, v, j, epsilon, f, joint);\n else\n [tmp, tmp, tmp, thetaplus, rplus, gradplus, thetaprime, gradprime, logpprime, nprime, sprime, alpha, nalpha] = ...\n build_tree(thetaplus, rplus, gradplus, logu, v, j, epsilon, f, joint);\n end\n % Use Metropolis-Hastings to decide whether or not to move to a\n % point from the half-tree we just generated.\n if ((sprime == 1) && (rand() < nprime/n))\n samples(m, :) = thetaprime;\n logp = logpprime;\n grad = gradprime;\n else\n rej = rej + 1;\n end\n % Update number of valid points we've seen.\n n = n + nprime;\n % Decide if it's time to stop.\n s = sprime && stop_criterion(thetaminus, thetaplus, rminus, rplus);\n % Increment depth.\n j = j + 1;\n end\n \n % Do adaptation of epsilon if we're still doing burn-in.\n eta = 1 / (length(opt.epsilon) + t0);\n Hbar = (1 - eta) * Hbar + eta * (delta - alpha / nalpha);\n if (m <= Madapt+1)\n epsilon = exp(mu - sqrt(m-1)/gamma * Hbar);\n eta = (length(opt.epsilon))^-kappa;\n epsilonbar = exp((1 - eta) * log(epsilonbar) + eta * log(epsilon));\n else\n epsilon = epsilonbar;\n end\n opt.epsilon(end+1) = epsilon;\n opt.epsilonbar = epsilonbar;\n opt.Hbar = Hbar;\n diagn.rej = diagn.rej + rej;\nend\n\ndiagn.opt = opt;\nend\n\nfunction [thetaprime, rprime, gradprime, logpprime] = leapfrog(theta, r, grad, epsilon, f)\nrprime = r + 0.5 * epsilon * grad;\nthetaprime = theta + epsilon * rprime;\n[logpprime, gradprime] = f(thetaprime);\nrprime = rprime + 0.5 * epsilon * gradprime;\nglobal nfevals;\nnfevals = nfevals + 1;\nend\n\nfunction criterion = stop_criterion(thetaminus, thetaplus, rminus, rplus)\nthetavec = thetaplus - thetaminus;\ncriterion = (thetavec * rminus' >= 0) && (thetavec * rplus' >= 0);\nend\n\n% The main recursion.\nfunction [thetaminus, rminus, gradminus, thetaplus, rplus, gradplus, thetaprime, gradprime, logpprime, nprime, sprime, alphaprime, nalphaprime] = ...\n build_tree(theta, r, grad, logu, v, j, epsilon, f, joint0)\nif (j == 0)\n % Base case: Take a single leapfrog step in the direction v.\n [thetaprime, rprime, gradprime, logpprime] = leapfrog(theta, r, grad, v*epsilon, f);\n joint = logpprime - 0.5 * (rprime * rprime');\n % Is the new point in the slice?\n nprime = logu < joint;\n % Is the simulation wildly inaccurate?\n sprime = logu - 1000 < joint;\n % Set the return values---minus=plus for all things here, since the\n % \"tree\" is of depth 0.\n thetaminus = thetaprime;\n thetaplus = thetaprime;\n rminus = rprime;\n rplus = rprime;\n gradminus = gradprime;\n gradplus = gradprime;\n % Compute the acceptance probability.\n alphaprime = min(1, exp(logpprime - 0.5 * (rprime * rprime') - joint0));\n nalphaprime = 1;\nelse\n % Recursion: Implicitly build the height j-1 left and right subtrees.\n [thetaminus, rminus, gradminus, thetaplus, rplus, gradplus, thetaprime, gradprime, logpprime, nprime, sprime, alphaprime, nalphaprime] = ...\n build_tree(theta, r, grad, logu, v, j-1, epsilon, f, joint0);\n % No need to keep going if the stopping criteria were met in the first\n % subtree.\n if (sprime == 1)\n if (v == -1)\n [thetaminus, rminus, gradminus, tmp, tmp, tmp, thetaprime2, gradprime2, logpprime2, nprime2, sprime2, alphaprime2, nalphaprime2] = ...\n build_tree(thetaminus, rminus, gradminus, logu, v, j-1, epsilon, f, joint0);\n else\n [tmp, tmp, tmp, thetaplus, rplus, gradplus, thetaprime2, gradprime2, logpprime2, nprime2, sprime2, alphaprime2, nalphaprime2] = ...\n build_tree(thetaplus, rplus, gradplus, logu, v, j-1, epsilon, f, joint0);\n end\n % Choose which subtree to propagate a sample up from.\n if (rand() < nprime2 / (nprime + nprime2))\n thetaprime = thetaprime2;\n gradprime = gradprime2;\n logpprime = logpprime2;\n end\n % Update the number of valid points.\n nprime = nprime + nprime2;\n % Update the stopping criterion.\n sprime = sprime && sprime2 && stop_criterion(thetaminus, thetaplus, rminus, rplus);\n % Update the acceptance probability statistics.\n alphaprime = alphaprime + alphaprime2;\n nalphaprime = nalphaprime + nalphaprime2;\n end\nend\nend\n\nfunction epsilon = find_reasonable_epsilon(theta0, grad0, logp0, f)\nepsilon = 0.1;\nr0 = randn(1, length(theta0));\n% Figure out what direction we should be moving epsilon.\n[tmp, rprime, tmp, logpprime] = leapfrog(theta0, r0, grad0, epsilon, f);\nacceptprob = exp(logpprime - logp0 - 0.5 * (rprime * rprime' - r0 * r0'));\n\n% Here we presume that energy function returns NaN, if energy cannot be\n% evaluated at the suggested hyperparameters so that we need smalled epsilon\nif isnan(acceptprob)\n acceptprob=0;\nend\na = 2 * (acceptprob > 0.5) - 1;\n% Keep moving epsilon in that direction until acceptprob crosses 0.5.\nwhile (acceptprob^a > 2^(-a))\n epsilon = epsilon * 2^a;\n [tmp, rprime, tmp, logpprime] = leapfrog(theta0, r0, grad0, epsilon, f);\n acceptprob = exp(logpprime - logp0 - 0.5 * (rprime * rprime' - r0 * r0'));\nend\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/mc/hmc_nuts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.48730007937938397}} {"text": "function [groups, orphans, R, C] = connectedComponents(model, type, figures, files)\n% Assuming two reactions are connected if they share metabolites, calculates the connected components\n% in the stoichiometric matrix, that is, the sets of reactions that share a set of metabolites\n%\n% USAGE:\n%\n% [groups, orphans, R, C] = connectedComponents(model, type, figures)\n%\n% INPUT:\n% model:\n%\n% OPTIONAL INPUTS:\n% type: {('allComponents'), 'largestComponent'}\n% figures: Will generate plots of the grouping algorithm as it creates block diagonal\n% groups in from top left to bottom right in `W`.\n% files: Indicator, whether several files containing indicator\n% matrices are generated.\n% OUTPUTS:\n% groups: a structure array (the number of distinct groups is length(groups)) with fields:\n%\n% * `groups(i).num_els` - number of reactions in group `i`.\n% * `groups(i).block` - sub-block identity of group `i`.\n% * `groups(i).elements` - reactions of W that are in group `i`.\n% * `groups(i).degrees` - degrees of connection for each reaction in group `i`.\n% orphans: elements of W that were not in any group, becasue they did not meet the constraints.\n% R: reaction adjacency\n% C: compound adjacency\n%\n% All components require:\n% Connected Component Analysis on an Undirected Graph by Tristan Ursell\n% http://www.mathworks.com/matlabcentral/fileexchange/35442-connected-component-analysis-on-an-undirected-graph.\n%\n% Largest component requires:\n% gaimc : Graph Algorithms In Matlab Code by David Gleich\n% http://www.mathworks.com/matlabcentral/fileexchange/24134-gaimc-graph-algorithms-in-matlab-code.\n%\n% .. Author:\n% - Ronan Fleming, 2012\n% - Thomas Pfau May 2017, Speedup and addition of files indicator\n\nif ~exist('type','var')\n type='allComponents';\nend\nif ~exist('figures','var')\n figures=0;\nend\nif ~exist('files','var')\n files=0;\nend\n\nmodel=findSExRxnInd(model);\n\n\n%stoichiometric matrix\nS=model.S;\n%dont include exchange reactions\nS(:,~model.SIntRxnBool)=0;\n\n[m,n]=size(S);\n\n%binary form\nB=sparse(m,n);\nB(S~=0)=1;\n\n%Compound adjacency\nC1=B*B';\n\n%number of reactions a species participates in\nnReactionsSpeciesParticipatesIn=diag(C1,0);\n\n%take out connections by cofactors\n[nReactionsSpeciesParticipatesInSorted,IX] = sort(nReactionsSpeciesParticipatesIn,'descend');\n%model.mets(IX(1:80))\n\n% %omit reactions connected by cofactors\n% omitMet=false(m,1);\n% for i=1:m\n% metAbbr=model.mets{i};\n% if strcmp(metAbbr(1:2),'h[')\n% omitMet(i)=1;\n% continue;\n% end\n% if strcmp(metAbbr(1:3),'k[')\n% omitMet(i)=1;\n% continue;\n% end\n% if length(metAbbr)>3\n% if strcmp(metAbbr(1:3),'pi[')\n% omitMet(i)=1;\n% continue;\n% end\n% if strcmp(metAbbr(1:3),'cl[')\n% omitMet(i)=1;\n% continue;\n% end\n% if strcmp(metAbbr(1:3),'o2[')\n% omitMet(i)=1;\n% continue;\n% end\n% end\n%\n% if length(metAbbr)>4\n% if strcmp(metAbbr(1:4),'na1[')\n% omitMet(i)=1;\n% continue;\n% end\n% if strcmp(metAbbr(1:4),'h2o[')\n% omitMet(i)=1;\n% continue;\n% end\n% if strcmp(metAbbr(1:4),'co2[')\n% omitMet(i)=1;\n% continue;\n% end\n% if strcmp(metAbbr(1:4),'atp[')\n% omitMet(i)=1;\n% continue;\n% end\n% if strcmp(metAbbr(1:4),'adp[')\n% omitMet(i)=1;\n% continue;\n% end\n% if strcmp(metAbbr(1:4),'utp[')\n% omitMet(i)=1;\n% continue;\n% end\n% if strcmp(metAbbr(1:4),'gtp[')\n% omitMet(i)=1;\n% continue;\n% end\n% if strcmp(metAbbr(1:4),'gdp[')\n% omitMet(i)=1;\n% continue;\n% end\n% if strcmp(metAbbr(1:4),'amp[')\n% omitMet(i)=1;\n% continue;\n% end\n% if strcmp(metAbbr(1:4),'nad[')\n% omitMet(i)=1;\n% continue;\n% end\n% if strcmp(metAbbr(1:4),'fad[')\n% omitMet(i)=1;\n% continue;\n% end\n% if strcmp(metAbbr(1:4),'coa[')\n% omitMet(i)=1;\n% continue;\n% end\n% if strcmp(metAbbr(1:4),'ppi[')\n% omitMet(i)=1;\n% continue;\n% end\n% if strcmp(metAbbr(1:4),'nh4[')\n% omitMet(i)=1;\n% continue;\n% end\n% if strcmp(metAbbr(1:4),'ACP[')\n% omitMet(i)=1;\n% continue;\n% end\n% if strcmp(metAbbr(1:4),'thf[')\n% omitMet(i)=1;\n% continue;\n% end\n% if strcmp(metAbbr(1:4),'crn[')\n% omitMet(i)=1;\n% continue;\n% end\n% end\n%\n% if length(metAbbr)>5\n% if strcmp(metAbbr(1:5),'nadh[')\n% omitMet(i)=1;\n% continue;\n% end\n% if strcmp(metAbbr(1:5),'fadh[')\n% omitMet(i)=1;\n% continue;\n% end\n% if strcmp(metAbbr(1:5),'nadp[')\n% omitMet(i)=1;\n% continue;\n% end\n% end\n%\n% if length(metAbbr)>6\n% if strcmp(metAbbr(1:6),'nadph[')\n% omitMet(i)=1;\n% continue;\n% end\n% if strcmp(metAbbr(1:6),'accoa[')\n% omitMet(i)=1;\n% continue;\n% end\n% end\n%\n% end\n%\n% %omit these metabolites\n% B(omitMet,:)=0;\n\n%Reaction adjacency\nR1=B'*B;\n\n%number of species in a reaction\nnMolecularSpeciesInReaction=diag(R1,0);\n\nR=R1;\n%Set the diagonal to 0\nR(logical(eye(size(R1,1)))) = 0;\n\nif files\n R2=triu(R);\n fid=fopen('reactionAdjacencyOtherThanCofactors.txt','w');\n for j=1:n\n fprintf(fid,'%s\\t',model.rxns{j});\n end\n fprintf(fid,'\\n');\n for j=1:n\n fprintf(fid,'%s\\t',model.rxns{j});\n for k=1:n\n fprintf(fid,'%u\\t',full(R2(j,k)));\n end\n fprintf(fid,'\\n');\n end\n fclose(fid);\nend\n\n\nC=C1;\n%Set the diagonal to 0\nC(logical(eye(size(C1,1)))) = 0;\n\nif strcmp(type,'largestComponent')\n if ~exist('largest_component')\n error('Install gamic and add it to your path. (http://www.mathworks.com/matlabcentral/fileexchange/24134-gaimc-graph-algorithms-in-matlab-code)')\n end\n [Acc,p] = largest_component(R);\n degree=sum(Acc);\n groups(1).num_els=nnz(degree);\n groups(1).block='largest';\n groups(1).elements=find(p);\n groups(1).degrees=degree;\n orphans=[];\nelse\n if figures==1\n [groups,orphans]=graph_analysis(R,'plot',1);\n else\n [groups,orphans]=graph_analysis(R);\n end\n\nend\n\nif files\n fid=fopen('reactionsNotConnectedByAnything.txt','w');\n bool=model.SIntRxnBool;\n bool(groups.elements) = 0;\n for j=1:n\n if bool(j)\n fprintf(fid,'%s\\n',model.rxns{j});\n end\n end\n fclose(fid);\nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/topology/connectedComponents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.48728403650563723}} {"text": "function hf_out = lhs_operation_gpu(hf, samplesf, reg_filter, sample_weights)\n\n% This is the left-hand-side operation in Conjugate Gradient\n\n% Get sizes\nnum_features = length(hf);\nfilter_sz = zeros(num_features,2);\nfor k = 1:num_features\n filter_sz(k,:) = [size(hf{k},1), size(hf{k},2)];\nend\n[~, k1] = max(filter_sz(:,1)); % Index for the feature block with the largest spatial size\nblock_inds = 1:num_features;\nblock_inds(k1) = [];\noutput_sz = [size(hf{k1},1), 2*size(hf{k1},2)-1];\n\n% Compute the operation corresponding to the data term in the optimization\n% (blockwise matrix multiplications)\n%implements: A' diag(sample_weights) A f\n\n% sum over all features and feature blocks\nsh = sum(bsxfun(@times, samplesf{k1}, hf{k1}), 3); % assumes the feature with the highest resolution is first\npad_sz = cell(1,1,num_features);\nfor k = block_inds\n pad_sz{k} = (output_sz - [size(hf{k},1), 2*size(hf{k},2)-1]) / 2;\n \n sh(1+pad_sz{k}(1):end-pad_sz{k}(1), 1+pad_sz{k}(2):end,1,:) = ...\n sh(1+pad_sz{k}(1):end-pad_sz{k}(1), 1+pad_sz{k}(2):end,1,:) + sum(bsxfun(@times, samplesf{k}, hf{k}), 3);\nend\n\n% weight all the samples and take conjugate\nsh = conj(bsxfun(@times,sample_weights,sh));\n\n% multiply with the transpose\nhf_out = cell(1,1,num_features);\nhf_out{k1} = conj(sum(bsxfun(@times, sh, samplesf{k1}), 4));\nfor k = block_inds\n hf_out{k} = conj(sum(bsxfun(@times, sh(1+pad_sz{k}(1):end-pad_sz{k}(1), 1+pad_sz{k}(2):end,1,:), samplesf{k}), 4));\nend\n\n% compute the operation corresponding to the regularization term (convolve\n% each feature dimension with the DFT of w, and the tramsposed operation)\n% add the regularization part\n% hf_conv = cell(1,1,num_features);\nfor k = 1:num_features\n reg_pad = min(size(reg_filter{k},2)-1, size(hf{k},2)-1);\n \n % add part needed for convolution\n hf_conv = cat(2, hf{k}, conj(rot90(hf{k}(:, end-reg_pad:end-1, :), 2)));\n \n % do first convolution\n hf_conv = convn(hf_conv, reg_filter{k});\n \n % do final convolution and put toghether result\n hf_out{k} = hf_out{k} + convn(hf_conv(:,1:end-reg_pad,:), reg_filter{k}, 'valid');\nend\n\nend", "meta": {"author": "martin-danelljan", "repo": "ECO", "sha": "27e8ae565cd63ec14bafcaad8b5b993bec8f3e69", "save_path": "github-repos/MATLAB/martin-danelljan-ECO", "path": "github-repos/MATLAB/martin-danelljan-ECO/ECO-27e8ae565cd63ec14bafcaad8b5b993bec8f3e69/implementation/training/lhs_operation_gpu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219505, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.48728403650563723}} {"text": "function a = sqrt(a)\n%SQRT Gradient square root sqrt(a)\n%\n\n% written 10/16/98 S.M. Rump\n% modified 10/14/00 S.M. Rump use Tony's trick\n% modified 04/04/04 S.M. Rump set round to nearest for safety\n% accelaration for sparse input\n% modified 04/06/05 S.M. Rump rounding unchanged\n% modified 09/28/08 S.M. Rump check for rounding to nearest improved\n% modified 10/08/08 S.M. Rump improved sparse multiplication: not using intval data type\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 N = getappdata(0,'INTLAB_GRADIENT_NUMVAR');\n\n wng = warning;\n warning off\n \n a.x = sqrt(a.x);\n % use full(a.x(:)): cures Matlab V6.0 bug\n % a=7; i=[1 1]; x=a(i), b=sparse(a); y=b(i) yields row vector x but column vector y\n % ax is full anyway\n ax = 1./(2*full(a.x(:)));\n if issparse(a.dx)\n sizeax = size(a.dx,1);\n [ia,ja,sa] = find(a.dx);\n if isa(a.x,'intval')\n adx = times(ax(ia),sa,0);\n if adx.complex\n a.dx = intval( sparse(ia,ja,adx.mid,sizeax,N) , sparse(ia,ja,adx.rad,sizeax,N) , 'midrad' );\n else\n a.dx = intval( sparse(ia,ja,adx.inf,sizeax,N) , sparse(ia,ja,adx.sup,sizeax,N) , 'infsup' );\n end\n else\n a.dx = sparse(ia,ja,ax(ia).*sa,sizeax,N);\n end\n else\n a.dx = a.dx .* ax(:,ones(1,N));\n end\n \n warning(wng)\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/gradient/@gradient/sqrt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.48717556320583116}} {"text": "function [pkx_final, cluster_final, LogL_final] = LCGMM(X, k, W, options)\n% Local Consistent Gaussian Mixture Model (LCGMM)\n%\n% where\n% X\n% Notation:\n% X ... (nSmp x mFea) observed data matrix \n% nSmp ... number of samples\n% mFea ... number of features \n%\n% K ... number of clusters\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% pkx ... P(z|x)\n% R ... covariance matrix\n% mu ... mean\n% \n%\n% References:\n% [1] Jialu Liu, Deng Cai, Xiaofei He, \"Gaussian Mixture Model with \n% Local Consistency\", AAAI 2010. \n% [2] Jialu Liu, \"Notes on Local Consistent Gaussian Mixture Model(LCGMM)\", \n% Online available at http://relau.com/jialuliu/technical_notes/LCGMM.pdf \n% [accessed 27-Dec-2011]. \n%\n% version 2.0 --Dec/2011 \n% version 1.0 --Dec/2009 \n%\n% Written by Jialu Liu (remenberl AT gmail.com)\n% Deng Cai (dengcai AT gmail.com)\n%\nZERO_OFFSET = 1e-200;\n\ndifferror = 1e-7;\nif isfield(options,'error')\n differror = options.error;\nend\n\nlambda = 0.1;\nif isfield(options,'lambda')\n lambda = options.lambda;\nend\n\nnRepeat = 5;\nif isfield(options,'nRepeat')\n nRepeat = options.nRepeat;\nend\n\nmaxIter = 100;\nif isfield(options,'maxIter')\n maxIter = options.maxIter;\nend\n\nminIterOrig = 5;\nif isfield(options,'minIter')\n minIterOrig = options.minIter;\nend\nminIter = minIterOrig-1;\n\nmeanFitRatio = 0.1;\nif isfield(options,'meanFitRatio')\n meanFitRatio = options.meanFitRatio;\nend\nmeanFitControl = 1;\nif isfield(options,'meanFitControl')\n meanFitControl = options.meanFitControl;\nend\n\n\nif ~isfield(options,'InitWay')\n options.InitWay = 'kmeans';\nend\n\nshow = 0;\nif isfield(options,'show')\n show = options.show;\nend\n\ndebug = 0;\nif isfield(options,'debug')\n debug = options.debug;\nend\n\n\n\n% init mixture\n[nSmp mFea] = size(X);\n\nif lambda > 0\n DCol = full(sum(W,2));\n D = spdiags(DCol,0,nSmp,nSmp);\n L = D - W;\nend\n\n[cluster,pkx,LogL] = GMM_init(X,k,options);\nmeanFit = LogL/10;\n\n\ntryNo = 0;\nselectInit = 1;\nnIter = 0;\nwhile tryNo < nRepeat\n tryNo = tryNo+1;\n maxErr = 1;\n retry = 0;\n while(maxErr > differror || maxErr==-1)\n % EM iteration\n alertFlag = 0;\n for kidx=1:k\n % compute pi\n cluster(kidx).pb = sum(pkx(:,kidx));\n if cluster(kidx).pb < 1e-20\n retry = 1;\n break;\n end\n % compute Tk\n if lambda > 0\n Tk = 1 - lambda * sum(bsxfun(@minus, pkx(:,kidx), pkx(:,kidx)') .* W, 2) ./ (pkx(:,kidx) + ZERO_OFFSET);\n else\n Tk = ones(nSmp, 1);\n end\n \n if min(Tk) < 0 && alertFlag == 0 && debug == 1\n alertFlag = 1;\n disp('The covariance matrix might not be positive semidefinate since lambda is too big such that some value of Tik is negative.');\n end\n \n % compute mean\n cluster(kidx).mu = ((pkx(:,kidx) .* Tk)' * X) / cluster(kidx).pb;\n \n % compute covariance matrix\n Y1 = X-repmat(cluster(kidx).mu,nSmp,1); \n Y2 = bsxfun(@times,sqrt(pkx(:,kidx) .* Tk), Y1);\n R = (Y2'*Y2) /cluster(kidx).pb;\n %for elemetns in Tk which are negative\n Y3 = bsxfun(@times,sqrt(pkx(:,kidx) .* (-(Tk<0) .* Tk)), Y1);\n R = R - 2 * (Y3'*Y3) /cluster(kidx).pb;\n \n %\n clear Y2;\n R = max(R,R');\n \n \n detR = det(R);\n if detR <= 0\n retry = 1;\n break;\n end\n \n cluster(kidx).cov = R;\n const = -(mFea*log(2*pi) + log(detR))/2;\n \n Y2 = R\\Y1';\n Y2 = -Y2'/2;\n pkx(:,kidx) = dot(Y1,Y2,2)+const;\n clear Y1 Y2 R;\n end\n \n if retry\n break;\n end\n \n llmax=max(pkx,[],2);\n pkx =exp( pkx-repmat(llmax,1,k) );\n pkx = pkx.*repmat([cluster(:).pb],nSmp,1);\n ss = sum(pkx,2);\n llnew = sum(log(ss)+llmax);\n pkx = pkx./(repmat(ss,1,k));\n \n % compute new likelihood\n if lambda > 0\n llnew = llnew - sum(sum((log(pkx' + ZERO_OFFSET) * L).* pkx')) * lambda / 2;\n end\n \n LogL = [LogL llnew]; \n %\n nIter = nIter + 1;\n\n meanFit = meanFitRatio*meanFit + (1-meanFitRatio)*llnew;\n maxErr = (llnew-meanFit)/meanFit;\n if show\n if length(LogL) > 1\n disp(['tryNo: ',num2str(tryNo),' Iteration: ',num2str(nIter),' LogL: ',num2str(LogL(end)),' deltaLogL: ',num2str(LogL(end)-LogL(end-1)),' maxErr:',num2str(maxErr)]);\n else\n disp(['tryNo: ',num2str(tryNo),' Iteration: ',num2str(nIter),' LogL: ',num2str(LogL(end)),' maxErr:',num2str(maxErr)]);\n end\n end\n if nRepeat > 1 && selectInit\n maxErr = 1;\n end\n if ~meanFitControl\n maxErr = 1;\n end\n if nIter > minIter\n if selectInit\n maxErr = 0;\n else\n if nIter >= maxIter\n maxErr = 0;\n end\n end\n end\n end\n \n if retry && ~(tryNo == nRepeat && nIter >= nIter_final)\n tryNo = tryNo - 1;\n [cluster,pkx,LogL] = GMM_init(X,k,options);\n meanFit = LogL/10;\n nIter = 0;\n continue;\n end\n \n if tryNo == 1\n pkx_final = pkx;\n cluster_final = cluster;\n LogL_final = LogL;\n nIter_final = nIter;\n else\n if LogL(end) > LogL_final(end)\n pkx_final = pkx;\n cluster_final = cluster;\n LogL_final = LogL;\n nIter_final = nIter;\n end\n end\n \n if selectInit\n if tryNo < nRepeat\n [cluster,pkx,LogL] = GMM_init(X,k,options);\n meanFit = LogL/10;\n nIter = 0;\n else\n tryNo = tryNo - 1;\n selectInit = 0;\n pkx = pkx_final;\n cluster = cluster_final;\n LogL = LogL_final;\n nIter = nIter_final;\n meanFit = LogL(end)/10;\n end\n end\nend\n\n\n\nfunction [cluster,pkx,llnew] = GMM_init(X,k,options)\n ZERO_OFFSET = 1e-200;\n [nSmp, mFea] = size(X);\n if strcmpi(options.InitWay,'kmeans')\n kmeansres = litekmeans(X,k,'maxIter',10);\n residx = unique(kmeansres);\n for kidx=1:k\n smpidx = kmeansres==residx(kidx);\n cluster(kidx).mu = mean(X(smpidx,:),1);\n cluster(kidx).pb = 1/k;\n end\n else\n permutation = randperm(nSmp);\n nSmpClass = floor(nSmp/k);\n for kidx=1:k\n cluster(kidx).mu = mean(X(permutation((kidx-1)*nSmpClass+1:kidx*nSmpClass),:),1);\n cluster(kidx).pb = 1/k;\n end\n end\n\n R = (nSmp-1)*cov(X)/nSmp;\n R = max(R,R');\n\n % EM iteration\n\n pkx=zeros(nSmp,k);\n detR = det(R);\n if detR <= 0\n error('The covariance matrix is not positive definite. Use PCA to reduce the dimensions first!');\n end\n const = -(mFea*log(2*pi) +log(detR))/2;\n for kidx=1:k\n Y1=X-repmat(cluster(kidx).mu,nSmp,1);\n Y2 = R\\Y1';\n Y2 = -Y2'/2;\n pkx(:,kidx) = dot(Y1,Y2,2)+const;\n clear Y1 Y2;\n end\n clear R;\n llmax=max(pkx,[],2);\n pkx =exp( pkx-repmat(llmax,1,k) );\n pkx = pkx.*repmat([cluster(:).pb],nSmp,1);\n ss = sum(pkx,2);\n llnew = sum(log(ss)+llmax);\n pkx = pkx./(repmat(ss,1,k));\n", "meta": {"author": "ZJULearning", "repo": "MatlabFunc", "sha": "97504df0f597c1980ab76ddc0c9c5d669043c6c9", "save_path": "github-repos/MATLAB/ZJULearning-MatlabFunc", "path": "github-repos/MATLAB/ZJULearning-MatlabFunc/MatlabFunc-97504df0f597c1980ab76ddc0c9c5d669043c6c9/Clustering/LCGMM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.48714332245737285}} {"text": "%IRECTIFY Rectify stereo image pair\n%\n% [OUT1,OUT2] = IRECTIFY(F, M, IM1, IM2) is a rectified pair of images\n% corresponding to IM1 and IM2. F (3x3) is the fundamental matrix relating \n% the two views and M is a FeatureMatch object containing point correspondences \n% between the images.\n%\n% [OUT1,OUT2,H1,H2] = IRECTIFY(F, M, IM1, IM2) as above but also returns\n% the homographies H1 and H2 that warp IM1 to OUT1 and IM2 to OUT2 respectively.\n%\n% Notes::\n% - The resulting image pair are epipolar aligned, equivalent to the view\n% if the two original camera axes were parallel.\n% - Rectified images are required for dense stereo matching.\n% - The effect of lense distortion is not removed, use the camera calibration\n% toolbox to unwarp each image prior to rectification.\n% - The resulting images may have negative disparity.\n% - Some output pixels may have no corresponding input pixels and will be\n% set to NaN.\n%\n% See also FeatureMatch, ISTEREO, HOMWARP, CentralCamera.\n\n\n% Copyright (C) 1993-2011, by Peter I. Corke\n%\n% This file is part of The Machine Vision Toolbox for Matlab (MVTB).\n% \n% MVTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% MVTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with MVTB. If not, see .\n\nfunction [Img1_new, Img2_new, H12,H21] = irectify(F, m, Img1, Img2)\n% http://se.cs.ait.ac.th/cvwiki/matlab:tutorial:rectification\n\nF12 = F';\n\n[rows,cols,depth] = size(Img1);\n\n% Get homographies.\n\nx1 = e2h( m.p1 );\nx2 = e2h( m.p2 );\n\n[H12,H21,bSwap] = rectify_homographies( F12, x1, x2, rows, cols );\n\n[w1,off1] = homwarp(H12, Img1, 'full');\n[w2,off2] = homwarp(H21, Img2, 'full');\n\n% fix the vertical alignment of the images by padding\ndy = off1(2) - off2(2);\nif dy < 0\n w1 = ipad(w1, 'b', -dy);\n w2 = ipad(w2, 't', -dy);\nelse\n w1 = ipad(w1, 't', dy);\n w2 = ipad(w2, 'b', dy);\nend\n\n[w1,w2] = itrim(w1, w2);\n\nif nargout == 0\n stdisp(w1, w2)\nelse\n Img1_new = w1;\n Img2_new = w2;\nend\n\n\n\n%-----------------------------------------------------------------------------\n\nfunction [H1,H2,bSwap] = rectify_homographies( F, x1, x2, rows, cols )\n\n % F: a fundamental matrix\n\n % x1 and x2: corresponding points such that x1_i' * F * x2_i = 0\n\n % Initialize\n\n H1 = [];\n H2 = [];\n bSwap = 0;\n\n % Center of image\n\n cy = round( rows/2 );\n cx = round( cols/2 );\n\n % Fix F to be rank 2 to numerical accuracy\n\n [U,D,V] = svd( F );\n D(3,3) = 0;\n F = U*D*V';\n\n % Get epipole. e12 is the epipole in image 1 for camera 2.\n\n e12 = null( F' ); % Epipole in image 1 for camera 2\n e21 = null( F ); % Epipole in image 2 for camera 1\n\n % Put epipoles in front of camera\n\n if e12 < 0, e12 = -e12; end;\n if e21 < 0, e21 = -e21; end;\n\n % Make sure the epipoles are inside the images\n\n check_epipoles_in_image( e12, e21, rows, cols );\n\n % Check that image 1 is to the left of image 2\n\n% if e12(1)/e12(3) < cx\n% fprintf( 1, 'Swapping left and right images...\\n' );\n% tmp = e12;\n% e12 = e21;\n% e21 = tmp;\n% F = F';\n% bSwap = 1;\n% end;\n\n % Now we have\n % F' * e12 = 0, \n % F * e21 = 0,\n\n % Let's get the rectifying homography Hprime for image 1 first\n\n Hprime = map_to_infinity( e12, cx, cy );\n e12_new = Hprime * e12;\n % Normalize Hprime so that Hprime*eprime = (1,0,0)'\n Hprime = Hprime / e12_new(1);\n e12_new = Hprime * e12;\n fprintf( 1, 'Epipole 1/2 mapped to infinity: (%g, %g, %g)\\n', e12_new );\n\n % Get canonical camera matrices for F12 and compute H0, one possible\n % rectification homography for image 2\n\n [P,Pprime] = get_canonical_cameras( F );\n M = Pprime(:,1:3);\n H0 = Hprime * M;\n\n % Test that F12 is a valid F for P,Pprime\n\n test_p_f( P, Pprime, F );\n\n % Now we need to find H so that the epipolar lines match\n % each other, i.e., inv(H)' * l = inv(Hprime)' * lprime\n % and the disparity is minimized, i.e.,\n % min \\sum_i d(H x_i, Hprime xprime_i)^2\n\n % Transform data initially according to Hprime (img 1) and H0 (img 2)\n\n x1hat = Hprime * x1;\n x1hat = x1hat ./ repmat( x1hat(3,:), 3, 1 );\n x2hat = H0 * x2;\n x2hat = x2hat ./ repmat( x2hat(3,:), 3, 1 );\n rmse_x = sqrt( mean( (x1hat(1,:) - x2hat(1,:) ).^2 ));\n rmse_y = sqrt( mean( (x1hat(2,:) - x2hat(2,:) ).^2 ));\n fprintf( 1, 'Before Ha, RMSE for corresponding points in Y: %g X: %g\\n', ...\n rmse_y, rmse_x );\n\n % Estimate [ a b c ; 0 1 0 ; 0 0 1 ] aligning H, Hprime\n\n n = size(x1,2);\n A = [ x2hat(1,:)', x2hat(2,:)', ones(n,1) ];\n b = x1hat(1,:)';\n abc = A\\b;\n HA = [ abc' ; 0 1 0 ; 0 0 1 ];\n H = HA*H0;\n x2hat = H * x2;\n x2hat = x2hat ./ repmat( x2hat(3,:), 3, 1 );\n rmse_x = sqrt( mean(( x1hat(1,:) - x2hat(1,:) ).^2 ));\n rmse_y = sqrt( mean(( x1hat(2,:) - x2hat(2,:) ).^2 ));\n fprintf( 1, 'After Ha, RMSE for corresponding points in Y: %g X: %g\\n', ...\n rmse_y, rmse_x );\n\n % Return the homographies as appropriate\n\n if bSwap\n H1 = H;\n H2 = Hprime;\n else\n H1 = Hprime;\n H2 = H;\n end;\n\n%-----------------------------------------------------------------------------\n\nfunction check_epipoles_in_image( e1, e2, rows, cols )\n\n % Check whether given epipoles are in the image or not\n\n if abs( e1(3) ) < 1e-6 & abs( e2(3) ) < 1e-6, return; end;\n\n e1 = e1 / e1(3);\n e2 = e2 / e2(3);\n if ( e1(1) <= cols & e1(1) >= 1 & e1(2) <= rows & e1(2) >= 1 ) | ...\n ( e2(1) <= cols & e2(1) >= 1 & e2(2) <= rows & e2(2) >= 1 )\n err_msg = sprintf( 'epipole (%g,%g) or (%g,%g) is inside image', ...\n e1(1:2), e2(1:2) );\n error( [ err_msg, ' -- homography does not work in this case!' ] );\n end;\n\n%-----------------------------------------------------------------------------\n\nfunction [P,Pprime] = get_canonical_cameras( F )\n\n % Get the \"canonical\" cameras for given fundamental matrix\n % according to Hartley and Zisserman (2004), p256, Result 9.14\n\n % But ensure that the left 3x3 submatrix of Pprime is nonsingular\n % using Result 9.15, that the general form is\n % [ skewsym( e12 ) * F + e12 * v', k * e12 ] where v is an arbitrary\n % 3-vector and k is an arbitrary scalar\n\n P = [ 1 0 0 0\n 0 1 0 0\n 0 0 1 0 ];\n\n e12 = null( F' );\n M = skew( e12 ) * F + e12 * [1 1 1];\n Pprime = [ M, e12 ];\n\n%-----------------------------------------------------------------------------\n\nfunction test_p_f( P, Pprime, F )\n\n % Test that camera matrices Pprime and P are consistent with\n % fundamental matrix F\n % Meaning (Pprime*X)' * F * (P*X) = 0, for all X in 3space\n\n % Get the epipole in camera 1 for camera 2\n\n C2 = null( P );\n eprime = Pprime * C2;\n\n % Construct F from Pprime, P, and eprime\n\n Fhat = skew( eprime ) * Pprime * pinv( P );\n\n % Check that it's close to F\n\n alpha = Fhat(:)\\F(:);\n if norm( alpha*Fhat-F ) > 1e-10\n fprintf( 1, 'Warning: supplied camera matrices are inconsistent with F\\n' );\n else\n fprintf( 1, 'Supplied camera matrices OK\\n' );\n end;\n\n%-----------------------------------------------------------------------------\n\nfunction H = map_to_infinity( x, cx, cy )\n\n % Given a point and the desired origin (point of minimum projective\n % distortion), compute a homograph H = G*R*T taking the point to the\n % origin, rotating it to align with the X axis, then mapping it to\n % infinity.\n\n % First map cx,cy to the origin\n\n T = [ 1 0 -cx\n 0 1 -cy\n 0 0 1 ];\n x = T * x;\n\n % Now rotate the translated x to align with the X axis.\n\n cur_angle = atan2( x(2), x(1) );\n R = [ cos( -cur_angle ), -sin( -cur_angle ), 0\n sin( -cur_angle ), cos( -cur_angle ), 0\n 0, 0, 1 ];\n x = R * x;\n\n % Now the transformation G mapping x to infinity\n\n if abs( x(3)/norm(x) ) < 1e-6\n % It's already at infinity\n G = eye(3)\n else\n f = x(1)/x(3);\n G = [ 1 0 0\n 0 1 0\n -1/f 0 1 ];\n end;\n\n H = G*R*T;\n", "meta": {"author": "petercorke", "repo": "machinevision-toolbox-matlab", "sha": "2d791168c19c5e56acef74d22eafd227b4b58e42", "save_path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab/machinevision-toolbox-matlab-2d791168c19c5e56acef74d22eafd227b4b58e42/irectify.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.4869283981977793}} {"text": "function matches_refined = refine_matches(...\n part, model, part_ind, model_ind, C_init, options)\n\nF = part_ind;\nG = model_ind;\n\nk = options.k;\n\nW = zeros(k);\nfor i=1:k\n for j=1:k\n slope = 1;\n direction = [1 slope];\n direction = direction./norm(direction);\n W(i,j) = exp(-0.03*sqrt(i.^2 + j.^2))*norm(cross([direction 0], [i,j, 0]-[1 1 0]));\n end\nend\nd=ones(1,k);\nD = repmat(d,k,1);\n\nmu1 = 1e-2; % diagonal mask\nmu2 = 1e1; % orthogonality\n\nfor iter=1:options.refine_iters\n \n A = part.evecs'*part.S*F;\n B = model.evecs'*model.S*G;\n \n manifold = euclideanfactory(k,k);\n problem = {};\n \n problem.M = manifold;\n \n problem.cost = @(C) (...\n sum(sum((C*A-B).^2).^0.5) + ...\n mu1 * norm(C.*W,'fro')^2 + ...\n mu2 * (norm(C'*C,'fro')^2 - sum(diag(C'*C).^2) + sum((diag(C'*C) - d').^2) ));\n \n problem.egrad = @(C) (...\n norm_21_gradient(C,A,B) + ...\n mu1 * 2 * C.*W.*W + ...\n mu2 * 4*(C*C'*C - C.*D ));\n \n options.verbosity = 2;\n% options.maxiter = 5e3;\n% C_refined = conjugategradient(problem, C_init, options);\n options.maxiter = 3e2;\n C_refined = trustregions(problem, C_init, options);\n \n% figure,colormap(bluewhitered)\n% subplot(121),imagesc(C_init),colorbar,axis image\n% subplot(122),imagesc(C_refined),colorbar,axis image\n \n [matches_refined, ~] = flann_search(...\n model.evecs', ...\n C_refined*part.evecs', ...\n 1, struct());\n \n% [matches_init, ~] = flann_search(...\n% model.evecs', ...\n% C_init*part.evecs', ...\n% 1, struct());\n \n% colors = create_colormap(model,model);\n% figure\n% subplot(231), colormap(colors), plot_scalar_map(model, 1:model.n), axis off, view([0 90]), freeze_colors\n% subplot(232), colormap(colors(matches_init,:)), plot_scalar_map(part, 1:part.n), axis off, view([0 90]), freeze_colors\n% subplot(233), colormap(colors(matches_refined,:)), plot_scalar_map(part, 1:part.n), axis off, view([0 90])\n% subplot(234), colormap(colors), plot_scalar_map(model, 1:model.n), axis off, view([-180 -90]), freeze_colors\n% subplot(235), colormap(colors(matches_init,:)), plot_scalar_map(part, 1:part.n), axis off, view([-180 -90]), freeze_colors\n% subplot(236), colormap(colors(matches_refined,:)), plot_scalar_map(part, 1:part.n), axis off, view([-180 -90])\n \n C_init = C_refined;\n \n fps = fps_euclidean(part.VERT, 1e3, randi(part.n));\n F = sparse(fps, 1:length(fps), 1, part.n, length(fps));\n G = sparse(matches_refined(fps), 1:length(fps), 1, model.n, length(fps));\n \nend\n\nend\n", "meta": {"author": "OshriHalimi", "repo": "unsupervised_learning_of_dense_shape_correspondence", "sha": "440643d633a6db3f947ac71a247c8083cb3aeadc", "save_path": "github-repos/MATLAB/OshriHalimi-unsupervised_learning_of_dense_shape_correspondence", "path": "github-repos/MATLAB/OshriHalimi-unsupervised_learning_of_dense_shape_correspondence/unsupervised_learning_of_dense_shape_correspondence-440643d633a6db3f947ac71a247c8083cb3aeadc/Tools/demo_upscaling/refine_matches.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4867578135467367}} {"text": "function [A, b, x, ProbInfo] = PRblurdefocus(varargin) \n% PRblurdefocus Image deblurring problem with a defocus point spread function\n%\n% [A, b, x, ProbInfo] = PRblurdefocus\n% [A, b, x, ProbInfo] = PRblurdefocus(n)\n% [A, b, x, ProbInfo] = PRblurdefocus(n, options)\n% [A, b, x, ProbInfo] = PRblurdefocus(options)\n%\n% Input:\n% n - size of the image. Can be either a scalar n (in this case \n% the size is n x n) or a vector [nrow, ncol] (in this case the\n% size is (nrow x ncol).\n% Default: n = 256.\n% options - Structure containing the following optional fields:\n% trueImage : test image of size n, of type numeric, 2-D only,\n% or character string indicating\n% 'pattern1' : geometrical image\n% 'pattern2' : geometrical image\n% 'ppower' : random image with patterns of nonzero pixels\n% 'smooth' : very smooth image\n% 'dot2' : two small Gaussian shaped dots, e.g., a\n% binary star\n% 'dotk' : n/2 small Gaussian shaped dots, e.g., stars\n% (placement is random, reset using rng(0))\n% 'satellite' : satellite test image\n% 'hst' : image of the Hubble space telescope\n% Default: 'hst'.\n% This image is then stored in the output vector x.\n% BlurLevel : If choosing one of the built-in PSFs, this sets the\n% severity of the blur to one of the following:\n% 'mild'\n% 'medium'\n% 'severe'\n% Default is 'medium'\n% BC : Specify boundary condition:\n% 'zero'\n% 'periodic'\n% 'reflective' (or 'neumann' or 'reflexive')\n% Default: 'reflective'\n% Note that in this case an extended (or padded) test image\n% is blurred using 'zero' boundary conditions, and then the \n% central subimage of size n is extracted from the exact and\n% the blurred image. No inverse crime is committed, \n% i.e., A*x ~= b.\n% CommitCrime: To get an exact system Ax = b (i.e., commit the inverse\n% crime), set this to:\n% 'on'\n% Default is 'off' (do not commit the inverse crime).\n%\n% Output: \n% A - blurring matrix (psfMatrix class)\n% b - blurred vector (i.e., blurred image with stacked columns)\n% x - image vector, i.e., exact (unknown) image with stacked columns\n% ProbInfo - structure whose fields contain information about problem:\n% problemType : kind of test problem generated\n% (in this case: 'deblurring')\n% xType : solution type (in this case 'image2D')\n% bType : data type (in this case 'image2D')\n% xSize : size of image x\n% bSize : size of image b\n% psf : point spread function\n%\n% See also: PRblur, PRblurgauss, PRblurmotion, PRblurrotation,\n% PRblurshake, PRblurspeckle, PRdiffusion, PRinvinterp2, PRnmr,\n% PRseismic, PRspherical, PRtomo, PRnoise, PRshowb, PRshowx, fspecial\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('trueImage', 'hst', 'BlurLevel', 'medium', ...\n 'BC', 'reflective', 'CommitCrime', 'off');\n \n% If input is 'defaults,' return the default options in X\nif nargin == 1 && nargout <= 1 && strcmp(varargin,'defaults')\n A = defaultopt;\n return;\nend\n\n% Check for acceptable number of optional input arguments\nswitch length(varargin)\n case 0\n n = []; options = [];\n case 1\n if isa(varargin{1}, 'double')\n n = varargin{1}; options = [];\n else\n n = []; options = varargin{1};\n end\n case 2\n if isa(varargin{1}, 'double')\n n = varargin{1}; options = varargin{2};\n else\n n = varargin{2}; options = varargin{1};\n end\n otherwise\n error('Too many input parameters')\nend\n\nif isempty(options)\n options = defaultopt;\nend\n\noptions = PRset(defaultopt, options);\noptions = PRset(options, 'PSF', 'defocus');\n[A, b, x, ProbInfo] = PRblur(n, options);", "meta": {"author": "jnagy1", "repo": "IRtools", "sha": "040ef13d27873b6391aedd4ec06c453e1add9066", "save_path": "github-repos/MATLAB/jnagy1-IRtools", "path": "github-repos/MATLAB/jnagy1-IRtools/IRtools-040ef13d27873b6391aedd4ec06c453e1add9066/PRcodes/PRblurdefocus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.4866519269286485}} {"text": "function zi = interp2_mine(varargin)\n%INTERP2 2-D interpolation (table lookup).\n% ZI = INTERP2(X,Y,Z,XI,YI) interpolates to find ZI, the values of the\n% underlying 2-D function Z at the points in matrices XI and YI.\n% Matrices X and Y specify the points at which the data Z is given.\n%\n% XI can be a row vector, in which case it specifies a matrix with\n% constant columns. Similarly, YI can be a column vector and it \n% specifies a matrix with constant rows. \n%\n% ZI = INTERP2(Z,XI,YI) assumes X=1:N and Y=1:M where [M,N]=SIZE(Z).\n% ZI = INTERP2(Z,NTIMES) expands Z by interleaving interpolates between\n% every element, working recursively for NTIMES. INTERP2(Z) is the\n% same as INTERP2(Z,1).\n%\n% ZI = INTERP2(...,METHOD) specifies alternate methods. The default\n% is linear interpolation. Available methods are:\n%\n% 'nearest' - nearest neighbor interpolation\n% 'linear' - bilinear interpolation\n% 'spline' - spline interpolation\n% 'cubic' - bicubic interpolation as long as the data is\n% uniformly spaced, otherwise the same as 'spline'\n%\n% For faster interpolation when X and Y are equally spaced and monotonic,\n% use the syntax ZI = INTERP2(...,*METHOD).\n%\n% ZI = INTERP2(...,METHOD,EXTRAPVAL) specificies a method and a scalar \n% value for ZI outside of the domain created by X and Y. Thus, ZI will\n% equal EXTRAPVAL for any value of YI or XI which is not spanned by Y \n% or X respectively. A method must be specified for EXTRAPVAL to be used,\n% the default method is 'linear'.\n%\n% All the interpolation methods require that X and Y be monotonic and\n% plaid (as if they were created using MESHGRID). If you provide two\n% monotonic vectors, interp2 changes them to a plaid internally. \n% X and Y can be non-uniformly spaced.\n%\n% For example, to generate a coarse approximation of PEAKS and\n% interpolate over a finer mesh:\n% [x,y,z] = peaks(10); [xi,yi] = meshgrid(-3:.1:3,-3:.1:3);\n% zi = interp2(x,y,z,xi,yi); mesh(xi,yi,zi)\n%\n% Class support for inputs X, Y, Z, XI, YI: \n% float: double, single\n%\n% See also INTERP1, INTERP3, INTERPN, MESHGRID, TriScatteredInterp.\n\n% Copyright 1984-2011 The MathWorks, Inc.\n% $Revision: 5.33.4.24 $ $Date: 2011/05/17 02:32:27 $\n\n% error(nargchk(1,7,nargin,'struct')); % allowing for an ExtrapVal\n\nbypass = false;\nuniform = true;\nif (nargin > 1)\n if nargin == 7 && ~isnumeric(varargin{end})\n error(message('MATLAB:interp2:extrapvalNotNumeric'));\n end\n if ischar(varargin{end})\n narg = nargin-1;\n method = [varargin{end} ' ']; % Protect against short string.\n if strncmpi(method,'s',1) || strncmpi(method, '*s', 2)\n ExtrapVal = 'extrap'; % Splines can extrapolate\n else\n ExtrapVal = nan; % setting default ExtrapVal as NAN\n end\n index = 1; %subtract off the elements not in method\n elseif ischar(varargin{end-1}) && isnumeric(varargin{end})\n narg = nargin-2;\n method = [ varargin{end-1} ' '];\n ExtrapVal = varargin{end}; % user specified ExtrapVal\n index = 2; % subtract off the elements not in method and ExtrapVal\n else\n narg = nargin;\n method = 'linear';\n ExtrapVal = nan; % protecting default\n index = 0;\n end\n if strncmpi(method,'*',1) % Direct call bypass.\n if (narg ==5 || narg ==3)\n xitemp = varargin{end-index - 1};\n yitemp = varargin{end-index};\n if isrow(xitemp) && iscolumn(yitemp)\n varargin{end-index - 1} = repmat(xitemp, [size(yitemp,1), 1]);\n varargin{end-index} = repmat(yitemp, [1, size(xitemp,2)]);\n elseif iscolumn(xitemp) && isrow(yitemp)\n varargin{end-index - 1} = repmat(xitemp', [size(yitemp, 2), 1]);\n varargin{end-index} = repmat(yitemp', [1, size(xitemp,1)]);\n end\n end\n if strcmpi(method(2),'l') || strcmpi(method(2:4),'bil') \n % bilinear interpolation.\n zi = linear(ExtrapVal, varargin{1:end-index});\n return\n elseif strcmpi(method(2),'c') || strcmpi(method(2:4),'bic') \n % bicubic interpolation\n zi = cubic(ExtrapVal, varargin{1:end-index});\n return\n elseif strcmpi(method(2),'n') \n % Nearest neighbor interpolation\n zi = nearest(ExtrapVal, varargin{1:end-index});\n return\n elseif strcmpi(method(2),'s') \n % spline interpolation\n method = 'spline'; bypass = true;\n else\n error(message('MATLAB:interp2:InvalidMethod', deblank( method )));\n end\n elseif strncmpi(method,'s',1), % Spline interpolation\n method = 'spline'; bypass = true;\n end\nelse\n narg = nargin;\n method = 'linear';\n ExtrapVal = nan; % default ExtrapVal is NaN\nend\n\n% if narg==1, % interp2(z), % Expand Z\n% [nrows,ncols] = size(varargin{1});\n% xi = 1:.5:ncols; yi = (1:.5:nrows)';\n% x = 1:ncols; y = 1:nrows;\n% [msg,x,y,z,xi,yi] = xyzchk(x,y,varargin{1},xi,yi);\n% \n% elseif narg==2. % interp2(z,n), Expand Z n times\n% [nrows,ncols] = size(varargin{1});\n% ntimes = floor(varargin{2}(1));\n% xi = 1:1/(2^ntimes):ncols; yi = (1:1/(2^ntimes):nrows)';\n% x = 1:ncols; y = 1:nrows;\n% [msg,x,y,z,xi,yi] = xyzchk(x,y,varargin{1},xi,yi);\n% \n% elseif narg==3, % interp2(z,xi,yi)\n% [nrows,ncols] = size(varargin{1});\n% x = 1:ncols; y = 1:nrows;\n% [msg,x,y,z,xi,yi] = xyzchk(x,y,varargin{1:3});\n% \n% elseif narg==4,\n% error(message('MATLAB:interp2:nargin'));\n\n% elseif narg==5, % linear(x,y,z,xi,yi)\n% [msg,x,y,z,xi,yi] = xyzchk(varargin{1:5});\n% \n% end\nx = varargin{1};\ny = varargin{2};\nz = varargin{3};\nxi = varargin{4};\nyi = varargin{5};\n\n% if ~isempty(msg)\n% error(message(msg.identifier));\n% end\n\n%\n% Check for plaid data.\n%\nxx = x(1,:); yy = y(:,1);\n% if (size(x,2)>1 && ~isequal(repmat(xx,size(x,1),1),x)) || ...\n% (size(y,1)>1 && ~isequal(repmat(yy,1,size(y,2)),y)),\n% error(message('MATLAB:interp2:meshgrid'));\n% end\n\n%\n% Check for non-equally spaced data. If so, map (x,y) and\n% (xi,yi) to matrix (row,col) coordinate system.\n%\nif ~bypass,\n xx = xx.'; % Make sure it's a column.\n dx = diff(xx); dy = diff(yy);\n xdiff = max(abs(diff(dx))); if isempty(xdiff), xdiff = 0; end\n ydiff = max(abs(diff(dy))); if isempty(ydiff), ydiff = 0; end\n if (xdiff > eps(class(xx))*max(abs(xx))) || (ydiff > eps(class(yy))*max(abs(yy)))\n if any(dx < 0), % Flip orientation of data so x is increasing.\n x = fliplr(x); y = fliplr(y); z = fliplr(z);\n xx = flipud(xx); dx = -flipud(dx);\n end\n if any(dy < 0), % Flip orientation of data so y is increasing.\n x = flipud(x); y = flipud(y); z = flipud(z);\n yy = flipud(yy); dy = -flipud(dy);\n end\n\n if any(dx<=0) || any(dy<=0),\n error(message('MATLAB:interp2:XorYNotMonotonic'));\n end\n\n % Bypass mapping code for cubic\n if ~strncmp(method(1),'c',1)\n % Determine the nearest location of xi in x\n [xxi,j] = sort(xi(:));\n [~,i] = sort([xx;xxi]);\n ui(i) = 1:length(i);\n ui = (ui(length(xx)+1:end)-(1:length(xxi)))';\n ui(j) = ui;\n\n % Map values in xi to index offset (ui) via linear interpolation\n ui(ui<1) = 1;\n ui(ui>length(xx)-1) = length(xx)-1;\n ui = ui + (xi(:)-xx(ui))./(xx(ui+1)-xx(ui));\n\n % Determine the nearest location of yi in y\n [yyi,j] = sort(yi(:));\n [~,i] = sort([yy;yyi(:)]);\n vi(i) = 1:length(i);\n vi = (vi(length(yy)+1:end)-(1:length(yyi)))';\n vi(j) = vi;\n\n % Map values in yi to index offset (vi) via linear interpolation\n vi(vi<1) = 1;\n vi(vi>length(yy)-1) = length(yy)-1;\n vi = vi + (yi(:)-yy(vi))./(yy(vi+1)-yy(vi));\n\n [x,y] = meshgrid(ones(class(x)):size(x,2),ones(class(y)):size(y,1));\n xi(:) = ui; yi(:) = vi;\n else\n uniform = false;\n end\n end\nend\n\n% Now do the interpolation based on method.\nif strncmpi(method,'l',1) || strncmpi(method,'bil',3) % bilinear interpolation.\n zi = linear(ExtrapVal,x,y,z,xi,yi);\n\nelseif strncmpi(method,'c',1) || strncmpi(method,'bic',3) % bicubic interpolation\n if uniform\n zi = cubic(ExtrapVal,x,y,z,xi,yi);\n else\n zi = spline2(x,y,z,xi,yi,ExtrapVal);\n end\n\nelseif strncmpi(method,'n',1) % Nearest neighbor interpolation\n zi = nearest(ExtrapVal,x,y,z,xi,yi);\n\nelseif strncmpi(method,'s',1) % Spline interpolation\n % A column is removed from z if it contains a NaN.\n % Orient to preserve as much data as possible.\n [inan, jnan] = find(isnan(z));\n ncolnan = length(unique(jnan));\n nrownan = length(unique(inan));\n if ncolnan > nrownan\n zi = spline2(y',x',z',yi,xi,ExtrapVal);\n else\n zi = spline2(x,y,z,xi,yi,ExtrapVal);\n end\nelse\n error(message('MATLAB:interp2:InvalidMethod', deblank( method )));\n\nend\n\n%------------------------------------------------------\nfunction F = linear(ExtrapVal,arg1,arg2,arg3,arg4,arg5)\n%LINEAR 2-D bilinear data interpolation.\n% ZI = LINEAR(EXTRAPVAL,X,Y,Z,XI,YI) uses bilinear interpolation to\n% find ZI, the values of the underlying 2-D function in Z at the points\n% in matrices XI and YI. Matrices X and Y specify the points at which\n% the data Z is given. X and Y can also be vectors specifying the\n% abscissae for the matrix Z as for MESHGRID. In both cases, X\n% and Y must be equally spaced and monotonic.\n%\n% Values of EXTRAPVAL are returned in ZI for values of XI and YI that are\n% outside of the range of X and Y.\n%\n% If XI and YI are vectors, LINEAR returns vector ZI containing\n% the interpolated values at the corresponding points (XI,YI).\n%\n% ZI = LINEAR(EXTRAPVAL,Z,XI,YI) assumes X = 1:N and Y = 1:M, where\n% [M,N] = SIZE(Z).\n%\n% ZI = LINEAR(EXTRAPVAL,Z,NTIMES) returns the matrix Z expanded by\n% interleaving bilinear interpolates between every element, working\n% recursively for NTIMES. LINEAR(EXTRAPVAL,Z) is the same as\n% LINEAR(EXTRAPVAL,Z,1).\n%\n% See also INTERP2, CUBIC.\n\nif nargin==2 % linear(extrapval,z), Expand Z\n [nrows,ncols] = size(arg1);\n s = 1:.5:ncols; lengths = length(s);\n t = (1:.5:nrows)'; lengtht = length(t);\n s = repmat(s,lengtht,1);\n t = repmat(t,1,lengths);\n \nelseif nargin==3 % linear(extrapval,z,n), Expand Z n times\n [nrows,ncols] = size(arg1);\n ntimes = floor(arg2);\n s = 1:1/(2^ntimes):ncols; lengths = length(s);\n t = (1:1/(2^ntimes):nrows)'; lengtht = length(t);\n s = repmat(s,lengtht,1);\n t = repmat(t,1,lengths);\n\nelseif nargin==4 % linear(extrapval,z,s,t), No X or Y specified.\n [nrows,ncols] = size(arg1);\n s = arg2; t = arg3;\n\nelseif nargin==5\n error(message('MATLAB:interp2:linear:nargin'));\n\nelseif nargin==6 % linear(extrapval,x,y,z,s,t), X and Y specified.\n [nrows,ncols] = size(arg3);\n mx = numel(arg1); my = numel(arg2);\n if (mx ~= ncols || my ~= nrows) && ~isequal(size(arg1),size(arg2),size(arg3))\n error(message('MATLAB:interp2:linear:XYZLengthMismatch'));\n end\n if nrows < 2 || ncols < 2\n error(message('MATLAB:interp2:linear:sizeZ'));\n end\n s = 1 + (arg4-arg1(1))/(arg1(end)-arg1(1))*(ncols-1);\n t = 1 + (arg5-arg2(1))/(arg2(end)-arg2(1))*(nrows-1);\n\nend\n\nif nrows < 2 || ncols < 2\n error(message('MATLAB:interp2:linear:sizeZsq'));\nend\nif ~isequal(size(s),size(t))\n error(message('MATLAB:interp2:linear:XIandYISizeMismatch'));\nend\n\n% Check for out of range values of s and set to 1\nsout = find((s<1)|(s>ncols));\nif ~isempty(sout), s(sout) = 1; end\n\n% Check for out of range values of t and set to 1\ntout = find((t<1)|(t>nrows));\nif ~isempty(tout), t(tout) = 1; end\n\n% Matrix element indexing\nndx = floor(t)+floor(s-1)*nrows;\n\n% Compute intepolation parameters, check for boundary value.\nif isempty(s), d = s; else d = find(s==ncols); end\ns(:) = (s - floor(s));\nif ~isempty(d), s(d) = s(d)+1; ndx(d) = ndx(d)-nrows; end\n\n% Compute intepolation parameters, check for boundary value.\nif isempty(t), d = t; else d = find(t==nrows); end\nt(:) = (t - floor(t));\nif ~isempty(d), t(d) = t(d)+1; ndx(d) = ndx(d)-1; end\n\n% Now interpolate.\nonemt = 1-t;\nif nargin==6,\n F = ( arg3(ndx).*(onemt) + arg3(ndx+1).*t ).*(1-s) + ...\n ( arg3(ndx+nrows).*(onemt) + arg3(ndx+(nrows+1)).*t ).*s;\nelse\n F = ( arg1(ndx).*(onemt) + arg1(ndx+1).*t ).*(1-s) + ...\n ( arg1(ndx+nrows).*(onemt) + arg1(ndx+(nrows+1)).*t ).*s;\nend\n\n% Now set out of range values to ExtrapVal.\nif ~isempty(sout), F(sout) = ExtrapVal; end\nif ~isempty(tout), F(tout) = ExtrapVal; end\n\n%------------------------------------------------------\nfunction F = cubic(ExtrapVal,arg1,arg2,arg3,arg4,arg5)\n%CUBIC 2-D bicubic data interpolation.\n% CUBIC(...) is the same as LINEAR(....) except that it uses\n% bicubic interpolation.\n%\n% This function needs about 7-8 times SIZE(XI) memory to be available.\n%\n% See also LINEAR.\n\n% Based on \"Cubic Convolution Interpolation for Digital Image\n% Processing\", Robert G. Keys, IEEE Trans. on Acoustics, Speech, and\n% Signal Processing, Vol. 29, No. 6, Dec. 1981, pp. 1153-1160.\n\nif nargin==2, % cubic(extrapval,z), Expand Z\n [nrows,ncols] = size(arg1);\n s = 1:.5:ncols; lengths = length(s);\n t = (1:.5:nrows)'; lengtht = length(t);\n s = repmat(s,lengtht,1);\n t = repmat(t,1,lengths);\n \nelseif nargin==3, % cubic(extrapval,z,n), Expand Z n times\n [nrows,ncols] = size(arg1);\n ntimes = floor(arg2);\n s = 1:1/(2^ntimes):ncols; lengths = length(s);\n t = (1:1/(2^ntimes):nrows)'; lengtht = length(t);\n s = repmat(s,lengtht,1);\n t = repmat(t,1,lengths);\n\nelseif nargin==4, % cubic(extrapval,z,s,t), No X or Y specified.\n [nrows,ncols] = size(arg1);\n s = arg2; t = arg3;\n\nelseif nargin==5,\n error(message('MATLAB:interp2:cubic:nargin'));\n\nelseif nargin==6, % cubic(extrapval,x,y,z,s,t), X and Y specified.\n [nrows,ncols] = size(arg3);\n mx = numel(arg1); my = numel(arg2);\n if (mx ~= ncols || my ~= nrows) && ~isequal(size(arg1),size(arg2),size(arg3))\n error(message('MATLAB:interp2:cubic:XYZLengthMismatch'));\n end\n if nrows < 3 || ncols < 3\n error(message('MATLAB:interp2:cubic:sizeZ'));\n end\n s = 1 + (arg4-arg1(1))/(arg1(end)-arg1(1))*(ncols-1);\n t = 1 + (arg5-arg2(1))/(arg2(end)-arg2(1))*(nrows-1);\n\nend\n\nif nrows < 3 || ncols < 3\n error(message('MATLAB:interp2:cubic:sizeZsq'));\nend\nif ~isequal(size(s),size(t)),\n error(message('MATLAB:interp2:cubic:XIandYISizeMismatch'));\nend\n\n% Check for out of range values of s and set to 1\nsout = find((s<1)|(s>ncols));\nif ~isempty(sout), s(sout) = 1; end\n\n% Check for out of range values of t and set to 1\ntout = find((t<1)|(t>nrows));\nif ~isempty(tout), t(tout) = 1; end\n\n% Matrix element indexing\nndx = floor(t)+floor(s-1)*(nrows+2);\n\n% Compute intepolation parameters, check for boundary value.\nif isempty(s), d = s; else d = find(s==ncols); end\ns(:) = (s - floor(s));\nif ~isempty(d), s(d) = s(d)+1; ndx(d) = ndx(d)-nrows-2; end\n\n% Compute intepolation parameters, check for boundary value.\nif isempty(t), d = t; else d = find(t==nrows); end\nt(:) = (t - floor(t));\nif ~isempty(d), t(d) = t(d)+1; ndx(d) = ndx(d)-1; end\n\nif nargin==6,\n % Expand z so interpolation is valid at the boundaries.\n zz = zeros(size(arg3)+2);\n zz(1,2:ncols+1) = 3*arg3(1,:)-3*arg3(2,:)+arg3(3,:);\n zz(2:nrows+1,2:ncols+1) = arg3;\n zz(nrows+2,2:ncols+1) = 3*arg3(nrows,:)-3*arg3(nrows-1,:)+arg3(nrows-2,:);\n zz(:,1) = 3*zz(:,2)-3*zz(:,3)+zz(:,4);\n zz(:,ncols+2) = 3*zz(:,ncols+1)-3*zz(:,ncols)+zz(:,ncols-1);\n nrows = nrows+2; %also ncols = ncols+2;\nelse\n % Expand z so interpolation is valid at the boundaries.\n zz = zeros(size(arg1)+2);\n zz(1,2:ncols+1) = 3*arg1(1,:)-3*arg1(2,:)+arg1(3,:);\n zz(2:nrows+1,2:ncols+1) = arg1;\n zz(nrows+2,2:ncols+1) = 3*arg1(nrows,:)-3*arg1(nrows-1,:)+arg1(nrows-2,:);\n zz(:,1) = 3*zz(:,2)-3*zz(:,3)+zz(:,4);\n zz(:,ncols+2) = 3*zz(:,ncols+1)-3*zz(:,ncols)+zz(:,ncols-1);\n nrows = nrows+2; %also ncols = ncols+2;\nend\n\n% Now interpolate using computationally efficient algorithm.\nt0 = ((2-t).*t-1).*t;\nt1 = (3*t-5).*t.*t+2;\nt2 = ((4-3*t).*t+1).*t;\nt(:) = (t-1).*t.*t;\nF = ( zz(ndx).*t0 + zz(ndx+1).*t1 + zz(ndx+2).*t2 + zz(ndx+3).*t ) ...\n .* (((2-s).*s-1).*s);\nndx(:) = ndx + nrows;\nF(:) = F + ( zz(ndx).*t0 + zz(ndx+1).*t1 + zz(ndx+2).*t2 + zz(ndx+3).*t ) ...\n .* ((3*s-5).*s.*s+2);\nndx(:) = ndx + nrows;\nF(:) = F + ( zz(ndx).*t0 + zz(ndx+1).*t1 + zz(ndx+2).*t2 + zz(ndx+3).*t ) ...\n .* (((4-3*s).*s+1).*s);\nndx(:) = ndx + nrows;\nF(:) = F + ( zz(ndx).*t0 + zz(ndx+1).*t1 + zz(ndx+2).*t2 + zz(ndx+3).*t ) ...\n .* ((s-1).*s.*s);\nF(:) = F/4;\n\n% Now set out of range values to ExtrapVal.\nif ~isempty(sout), F(sout) = ExtrapVal; end\nif ~isempty(tout), F(tout) = ExtrapVal; end\n\n%------------------------------------------------------\nfunction F = nearest(ExtrapVal,arg1,arg2,arg3,arg4,arg5)\n%NEAREST 2-D Nearest neighbor interpolation.\n% ZI = NEAREST(EXTRAPVAL,X,Y,Z,XI,YI) uses nearest neighbor interpolation\n% to find ZI, the values of the underlying 2-D function in Z at the points\n% in matrices XI and YI. Matrices X and Y specify the points at which\n% the data Z is given. X and Y can also be vectors specifying the\n% abscissae for the matrix Z as for MESHGRID. In both cases, X\n% and Y must be equally spaced and monotonic.\n%\n% Values of EXTRAPVAL are returned in ZI for values of XI and YI that are\n% outside of the range of X and Y.\n%\n% If XI and YI are vectors, NEAREST returns vector ZI containing\n% the interpolated values at the corresponding points (XI,YI).\n%\n% ZI = NEAREST(EXTRAPVAL,Z,XI,YI) assumes X = 1:N and Y = 1:M, where\n% [M,N] = SIZE(Z).\n%\n% F = NEAREST(EXTRAPVAL,Z,NTIMES) returns the matrix Z expanded by\n% interleaving interpolates between every element. NEAREST(EXTRAPVAL,Z)\n% is the same as NEAREST(EXTRAPVAL,Z,1).\n%\n% See also INTERP2, LINEAR, CUBIC.\n\nif nargin==2, % nearest(z), Expand Z\n [nrows,ncols] = size(arg1);\n u = 1:.5:ncols; lengthu = length(u);\n v = (1:.5:nrows)'; lengthv = length(v);\n u = repmat(u,lengthv,1);\n v = repmat(v,1,lengthu);\n\nelseif nargin==3, % nearest(z,n), Expand Z n times\n [nrows,ncols] = size(arg1);\n ntimes = floor(arg2);\n u = 1:1/(2^ntimes):ncols; lengthu = length(u);\n v = (1:1/(2^ntimes):nrows)'; lengthv = length(v);\n u = repmat(u,lengthv,1);\n v = repmat(v,1,lengthu);\n\nelseif nargin==4, % nearest(z,u,v)\n [nrows,ncols] = size(arg1);\n u = arg2; v = arg3;\n\nelseif nargin==5,\n error(message('MATLAB:interp2:nearest:nargin'));\n\nelseif nargin==6, % nearest(x,y,z,u,v), X and Y specified.\n [nrows,ncols] = size(arg3);\n mx = numel(arg1); my = numel(arg2);\n if (mx ~= ncols || my ~= nrows) && ...\n ~isequal(size(arg1),size(arg2),size(arg3))\n error(message('MATLAB:interp2:nearest:XYZLengthMismatch'));\n end\n if nrows > 1 && ncols > 1\n u = 1 + (arg4-arg1(1))/(arg1(mx)-arg1(1))*(ncols-1);\n v = 1 + (arg5-arg2(1))/(arg2(my)-arg2(1))*(nrows-1);\n else\n u = 1 + (arg4-arg1(1));\n v = 1 + (arg5-arg2(1));\n end\nend\n\nif ~isequal(size(u),size(v))\n error(message('MATLAB:interp2:nearest:XIandYISizeMismatch'));\nend\n\n% Check for out of range values of u and set to 1\nuout = (u<.5)|(u>=ncols+.5);\nanyuout = any(uout(:));\nif anyuout, u(uout) = 1; end\n\n% Check for out of range values of v and set to 1\nvout = (v<.5)|(v>=nrows+.5);\nanyvout = any(vout(:));\nif anyvout, v(vout) = 1; end\n\n% Interpolation parameters\nu = round(u); v = round(v);\n\n% Now interpolate\nndx = v+(u-1)*nrows;\nif nargin==6,\n F = arg3(ndx);\nelse\n F = arg1(ndx);\nend\n\n% Now set out of range values to ExtrapVal.\nif anyuout, F(uout) = ExtrapVal; end\nif anyvout, F(vout) = ExtrapVal; end\n\n%----------------------------------------------------------\nfunction F = spline2(varargin)\n%2-D spline interpolation\n\n% Determine abscissa vectors\nvarargin{1} = varargin{1}(1,:);\nvarargin{2} = varargin{2}(:,1).';\n\n%\n% Check for plaid data.\n%\nxi = varargin{4}; yi = varargin{5};\nxxi = xi(1,:); yyi = yi(:,1);\n\nif ~isequal(repmat(xxi,size(xi,1),1),xi) || ...\n ~isequal(repmat(yyi,1,size(yi,2)),yi)\n F = splncore(varargin(2:-1:1),varargin{3},varargin(5:-1:4));\nelse\n F = splncore(varargin(2:-1:1),varargin{3},{yyi(:).' xxi},'gridded');\nend\n\nExtrapVal = varargin{6};\n% Set out-of-range values to ExtrapVal\nif isnumeric(ExtrapVal)\n d = xi < min(varargin{1}) | xi > max(varargin{1}) | ...\n yi < min(varargin{2}) | yi > max(varargin{2});\n F(d) = ExtrapVal;\nend\n", "meta": {"author": "TadasBaltrusaitis", "repo": "OpenFace", "sha": "3d4b5cf8d96138be42bed229447f36cbb09a5a29", "save_path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace", "path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace/OpenFace-3d4b5cf8d96138be42bed229447f36cbb09a5a29/matlab_version/fitting/interp2_mine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239133, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.4866018253943721}} {"text": "function [y,ysup] = erfc_rnd(x,rnd)\n% input x real non-negative column vector\n% rnd -1 y = lower bound for erf(x)\n% 1 y = upper bound for erf(x)\n% [] [y,ysup] inclusion of erf(x)\n% rounding may be altered after leaving erfc_rnd\n\n% written 05/30/13 S.M. Rump\n%\n\n xmax = hex2num('403b369a6244e684'); % ~27.2: erfc(x)=xmax\n \n y = x;\n if isempty(rnd)\n ysup = x;\n end\n \n index = ( x<-0.5 ); % Use 2-erfc(-x)\n if any(index) % x in [-inf,-0.5)\n if isempty(rnd)\n [yindex,ysupindex] = erfc_rnd(-x(index),-rnd);\n setround(-1)\n y(index) = 2 - ysupindex;\n setround(1)\n ysup(index) = 2 - yindex;\n else\n yindex = erfc_rnd(-x(index),-rnd);\n setround(rnd)\n y(index) = 2 - yindex;\n end\n end\n Index = index; % store finished indices\n \n index = ( ~Index ) & ( x<0 ); % first method\n if any(index) % x in [-0.5,0)\n if isempty(rnd)\n [yindex,ysupindex] = erf_rnd1(-x(index),rnd,6);\n setround(-1)\n y(index) = 1 + yindex;\n setround(1)\n ysup(index) = 1 + ysupindex;\n else\n yindex = erf_rnd1(-x(index),rnd,6);\n setround(rnd)\n y(index) = 1 + yindex;\n end\n end\n Index = Index | index; % store finished indices\n \n index = ( ~Index ) & ( x<=0.5 ); % first method\n if any(index) % x in [0,0.5]\n if isempty(rnd)\n [yindex,ysupindex] = erf_rnd1(x(index),rnd,6);\n setround(-1)\n y(index) = 1 - ysupindex;\n setround(1)\n ysup(index) = 1 - yindex;\n else\n yindex = erf_rnd1(x(index),-rnd,6);\n setround(rnd)\n y(index) = 1 - yindex;\n end\n end\n Index = Index | index; % store finished indices\n \n index = ( ~Index ) & ( x<=7 ); % second method\n if any(index) % x in (0.5,7]\n yindex = erfc_rnd2(x(index));\n if rnd==-1\n y(index) = yindex.inf;\n elseif rnd==1\n y(index) = yindex.sup;\n else\n y(index) = yindex.inf;\n ysup(index) = yindex.sup;\n end\n end\n Index = Index | index; % store finished indices\n \n index = ( ~Index ) & ( x<=10 ); % third method\n if any(index) % x in (7,10]\n if isempty(rnd)\n [y(index),ysup(index)] = erfc_rnd3(x(index),rnd,16);\n else\n y(index) = erfc_rnd3(x(index),rnd,16);\n end\n end\n Index = Index | index; % store finished indices\n \n index = ( ~Index ) & ( x<=xmax ); % third method\n if any(index) % x in (10,xmax]\n if isempty(rnd)\n [y(index),ysup(index)] = erfc_rnd3(x(index),rnd,10);\n else\n y(index) = erfc_rnd3(x(index),rnd,10);\n end\n end\n \n index = ( x>xmax );\n if any(index) % x in (xmax,inf]\n if isempty(rnd) % inclusion [y,ysup] of erfc(x)\n y(index) = 0;\n ysup(index) = hex2num('0000000000000001'); % subrealmin\n elseif rnd==1 % y upper bound for erfc(x)\n y(index) = hex2num('0000000000000001'); % subrealmin\n else % y lower bound for erfc(x)\n y(index) = 0;\n end\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/intval/@intval/private/erfc_rnd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920068519376, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.48655104294350776}} {"text": "function [W, info] = MTFLC_ADMM(X, y, lambda1, lambda2, opts)\n%\n% Multi-Task Feature Learning with Calibration - ADMM\n%\n% OBJECTIVE\n% min_W { sum_i^m ||Xi wi - yi|| + lambda1 ||W||_{1,2} + lambda2/2 ||W||_F^2 }\n%\n% We use ADMM to solve the problem.\n%\n% INPUT\n% X - cell array of {n_i by d matrices} by m\n% y - cell array of {n_i by 1 vectors} by m\n% lambda1 - regularization parameter of the l2,1 norm penalty\n% lambda2 - regularization parameter of the Fro norm penalty\n%\n% OUTPUT\n% W - task weights: d by t.\n% funcVal - the funcion value.\n%\n% Author: Jiayu Zhou\n\n%% Initialization\nif(nargin<5), opts = []; end\n\nopts = setOptsDefault( opts, 'verbose', 1); \nopts = setOptsDefault( opts, 'maxIter', 10000);\nopts = setOptsDefault( opts, 'tol', 1e-4);\nverbose = opts.verbose;\n\ninnerOpts = [];\ninnerOpts = setOptsDefault( innerOpts, 'maxIter', 5000);\ninnerOpts = setOptsDefault( innerOpts, 'tol', 1e-8);\ninnerOpts = setOptsDefault( innerOpts, 'tFlag', 1);\n\nif verbose > 0\n fprintf('ADMM Config: [MaxIter %u][Tol %.4g]\\n', opts.maxIter, opts.tol);\n fprintf('ADMM Subsolver Config: [MaxIter %u][Tol %.4g]\\n', innerOpts.maxIter, innerOpts.tol);\nend\n\nm = length(X); % task number\nd = size(X{1}, 2); % dimension.\n\nfuncVal = zeros(opts.maxIter, 1);\n\n% init for variables.\nTh = cell(m, 1); % each element is n_i by 1\nfor tt = 1:m\n Th{tt} = L2proj(randn(size(X{tt}, 1), 1));\nend\nZ = Th; % this initialization indicates that w_init = 0.\nW = zeros(d, m);\n\nrho = 1; rhoInc = 1;\n\n%% Computation\nif verbose == 1; fprintf('Iteration: '); end\nfor iter = 1: opts.maxIter\n \n % Update W\n innerOpts.init = W;\n [W, innerInfo] = MTFLC_ADMM_WSolver(X, y, Th, Z, rho, lambda1, lambda2, innerOpts); %#ok\n \n % Update Z (the same size as Tht)\n for t = 1: m\n vt = Th{t} / rho + y{t} - X{t} * W(:, t);\n vtNrm = sqrt(sum(vt.^2));\n Z{t} = max(0, 1- 1/(rho * vtNrm)) * vt;\n end\n \n % Update theta\n for t = 1: m\n Th{t} = Th{t} + rho * (y{t} - Z{t} - X{t} * W(:, t));\n end\n \n %if verbose >=2, fprintf('Th: %.4f\\n', augLagObjective(W, Th, Z)); end\n \n % Update rho\n rho = rho * rhoInc;\n \n funcVal(iter) = augLagObjective(W, Th, Z);\n if verbose == 1; fprintf('\\b\\b\\b\\b\\b%5i',iter); end\n \n % check stop criteria\n if (iter >1)\n diffW = sum(sum((W - W_old).^2));\n diffZ = 0; diffTh = 0;\n for t = 1: m\n diffZ = diffZ + sum((Z{t} - Z_old{t}) .^2);\n diffTh = diffTh + sum((Th{t} - Th_old{t}).^2);\n end\n \n if verbose>1\n fprintf('Iter: Fv: %.4f Fv+L: %.4f dW %.4g, dZ %.4g, dTh %.4g\\n', ...\n primalObjective(W), funcVal(iter), diffW, diffZ, diffTh);\n end\n \n if( max(diffW, max(diffZ, diffTh)) < opts.tol)\n break;\n end\n end\n \n W_old = W; Z_old = Z; Th_old = Th;\nend\nif verbose == 1; fprintf('\\n'); end\n\n%% Output\ninfo.funcVal = funcVal(1: iter);\n% use the last to show the 'real' objective without aug Lagrange.\ninfo.funcVal(end + 1) = primalObjective(W);\n% NOTE: the primal should be the same as augmented when converged.\n\n\n%% Nested Functions\n function fvP = primalObjective(W)\n % primal objective (without augmented terms)\n % P(W) sum_i^m ||Xi wi - yi|| + lambda1 ||W||_{1,2} + lambda2/2 ||W||_F^2\n \n fvP = lambda1 * L21norm(W) + lambda2 /2 * sum(sum(W.^2));\n for i = 1: m\n fvP = fvP + sqrt(sum((X{i} * W(:, i) - y{i}).^2));\n end\n end\n\n function fvP = augLagObjective(W, Th, Z)\n % primal objective with augmented Lagrange terms.\n % P(W) sum_i^m ||Xi wi - yi|| + lambda1 ||W||_{1,2} + lambda2/2 ||W||_F^2\n % + sum_i^m {Th_i' (y_i - z_i - X_i w_i) + 2 ||y_i - z_i - X_i w_i||^2/rho }\n \n fvP = lambda1 * L21norm(W) + lambda2 /2 * sum(sum(W.^2));\n for i = 1: m\n fvP = fvP + sqrt(sum((X{i} * W(:, i) - y{i}).^2)); % loss\n ti = y{i} - Z{i} - X{i} * W(:, i);\n fvP = fvP + Th{i}' * ti; % dual\n fvP = fvP + 2 * sum(ti.^2) / rho; % augment term.\n end\n end\n\nend\n\nfunction [Xnrm] = L21norm(X)\n% ||X||_{1,2} = sum_i ||X^i||_2\nXnrm = sum(sqrt(sum(X.^2, 2)));\nend\n\nfunction [x] = L2proj(x)\nnrm = sqrt(sum(x.^2));\nx = x ./ max(1, nrm) ;\nend\n\n", "meta": {"author": "jiayuzhou", "repo": "MALSAR", "sha": "fb9751594983df020ddc4f7e4a40520ee7c37989", "save_path": "github-repos/MATLAB/jiayuzhou-MALSAR", "path": "github-repos/MATLAB/jiayuzhou-MALSAR/MALSAR-fb9751594983df020ddc4f7e4a40520ee7c37989/MALSAR/functions/calibration/MTFLC_ADMM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812552, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4865469252001073}} {"text": "function [ spect, frqs ] = LTASS( speech_folder_OR_vec, nfft, fs )\n% Computes the Long-Term Average Speech Spectrum from a folder of speech files or vector of speech samples\n%\n% Syntax:\t[ spect, frqs ] = LTASS( speech_folder_OR_vec, nfft )\n%\n% Inputs:\n% \tspeech_folder_OR_vec - The path to the folder containing the speech\n% files OR a vector of concatenated speech signals\n% \tnfft - The number of FFT points used to compute the LTASS\n% \tfs - The sampling frequency to use (if not provided then the sampling\n% frequency of the file is used)\n%\n% Outputs:\n% \tspect - The LTASS spectrum\n% \tfrqs - The frequency vector for the spectrum\n\n% Author: Jacob Donley\n% University of Wollongong\n% Email: jrd089@uowmail.edu.au\n% Copyright: Jacob Donley 2017\n% Date: 17 June 2016\n% Revision: 0.4 (30 March 2017)\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif isa(speech_folder_OR_vec,'char') % if a character array (string)\n % Just incase this function tries to call getAllFiles within a class folder we\n % should create a function handle for getAllFiles regardless\n inf = dbstack('-completenames');\n funcName = 'getAllFiles';\n funcPath = inf.file;\n classDirs = getClassDirs(funcPath);\n getAllFiles_ = str2func([classDirs funcName]);\n \n %% Start LTASS\n files = getAllFiles_(speech_folder_OR_vec);\n speech=[];\n F = length(files);\n for file = 1:F\n try\n [audioSig,fs_] = audioread(files{file});\n if nargin < 3, fs = fs_; end\n audioSig = audioSig ./ rms(audioSig(:));\n catch err\n if strcmp(err.identifier, 'MATLAB:audiovideo:audioread:FileTypeNotSupported')\n continue; % Skip unsupported files\n end\n end\n speech = [speech; audioSig];\n end\n if nargin < 2\n nfft = numel(speech);\n end\n if logical(mod(nfft,2)) % if isodd( nfft )\n nfft = nfft-1; % Force nfft to be even so that pwelch returns normalised frequencies [0,...,1]\n end\n\nelse\n speech = speech_folder_OR_vec;\nend\n\n%%\nwin_=rectwin(nfft);\novlap = 0;\n\n[spect,frqs]=pwelch(speech,win_,nfft*ovlap,nfft,fs,'power'); % Power spectrum\nspect = sqrt(spect); % Magnitude spectrum\n\nend\n\nfunction classDirs = getClassDirs(FullPath)\nclassDirs = '';\nclasses = strfind(FullPath,'+');\nfor c = 1:length(classes)\n clas = FullPath(classes(c):end);\n stp = strfind(clas,filesep);\n classDirs = [classDirs clas(2:stp(1)-1) '.'];\nend\nend", "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/SoundZone_Tools-master/SoundZone_Tools-master/LTASS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.4864541021335409}} {"text": "function [ output_im ] = patch_sew(input_patches, output_sz, patch_stsz)\n% function [ output_im ] = patch_sew(input_patches, output_sz, patch_stsz)\n% Combine evenly spaced patches into a single image, averaging at voxels\n% in more than one patch. Allows for the input of patches from multiple\n% output images (assuming each image has been divided into similarly \n% sized and spaced patches.\n% \n% Note: patch_create and patch_sew differ from im2col and col2im by \n% allowing a custom stride, and were designed to output a stack of 2d \n% patches for direct input to a 2d neural network.\n%\n% Inputs:\n% input_patches [nlin_patch, ncol_patch, npatch] stack of input patches\n% output size 2x1 dimensions of output 2D image (or images)\n% patch_stsz 1x1 step size btwn patches (stride)\n%\n% Outputs:\n% output_im [nlin, ncol, nims] sewed together images\n%\n% Melissa Haskell, University of Michigan, 2021-09-08\n\nif nargin < 3, ir_usage, end\n\n%% Find patch size and determine the indices of each patch using createpatches\n\npatch_sz = size(input_patches,1);\n\n% input 2D image to get number of patches for 2d image of that size\n[~, patch_indices] = patch_create(zeros(output_sz), patch_sz, patch_stsz);\n\n%% Calculate total number of images and initialize output\n\nnpatch_per_image = size(patch_indices,3);\nnpatch = size(input_patches,3);\nnrow = output_sz(1);\nncol = output_sz(2);\nnims = npatch / npatch_per_image;\noutput_im = zeros(nrow,ncol,nims);\n\n%% Sew all the patches together\nfor ii = 1:nims\n psf_img = zeros(nrow, ncol); % for tracking how many patches are at each voxel\n sum_img = zeros(nrow, ncol); % for adding all the patch values together\n for jj = 1:npatch_per_image\n \n patch_indx = (ii-1)*npatch_per_image + jj;\n patch = reshape(input_patches(:,:,patch_indx),[patch_sz, patch_sz]);\n \n ind_2dim = patch_indices(:,:,jj);\n r1 = ind_2dim(1); c1 = ind_2dim(2); \n r2 = ind_2dim(3); c2 = ind_2dim(4);\n \n psf_img(r1:r2,c1:c2) = psf_img(r1:r2,c1:c2) + 1;\n sum_img(r1:r2,c1:c2) = sum_img(r1:r2,c1:c2) + patch;\n \n end\n % scale summation image by the psf image\n output_im(:,:,ii) = sum_img ./ (psf_img + 1e-12);\nend\n\n\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/utilities/patch_sew.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.4864540875814478}} {"text": "function [dWdB, dWdD, dWdS, dWdalpha, dWdgParam, dWdn] = gpsimMapWGradient(model, ...\n k)\n% GPSIMMAPWGRADIENT Compute the gradients of W with respect to the parameters of the k-th gene.\n% FORMAT\n% DESC computes the gradients of W with respect to the parameters of the k-th gene given\n% Gaussian process for use in a single input motif protein network.\n% ARG model : the model for which the log likelihood is computed.\n% ARG k : the k-th gene. \n% RETURN dWdB : the gradients of W w.r.t the model paramter Bk.\n% RETURN dWdD : the gradients of W w.r.t the model paramter Dk.\n% RETURN dWdS : the gradients of W w.r.t the model paramter Sk.\n% RETURN dWdalpha : the gradients of W w.r.t the model paramter alpha_k.\n% RETURN dWdgParam : the gradients of W w.r.t the model paramter gamma_k\n% RETURN dWdn : the gradients of W w.r.t the general noise variance of the k-gene.\n%\n% SEEALSO : gpsimMapCreate, gpsimMapLogLikelihood,\n% gpsimMapGradient, gpsimMapFunctionalLogLikeGradients\n%\n% COPYRIGHT : Pei Gao, Magnus Rattray and Neil D. Lawrence, 2008\n\n% GPSIM \n \nintPoints = model.times_index(1)+1:(model.numMapPts);\nstep2 = model.step*model.step;\nS2 = model.S.*model.S;\nnumData = length(model.t);\n\n[w1, w2] = size(model.W);\n\ndWdB = zeros(w1, w2);\ndWdD = zeros(w1, w2);\ndWdS = zeros(w1, w2);\ndWdalpha = [];\ndWdgParam = [];\ndWdn = [];\ndWdalpha = [];\nif model.ngParam > 0\n ngParamk = model.ngParam/model.numGenes;\n dWdgParam= zeros(w1, w2, ngParamk);\n gInd = k;\nelse\n gInd = 1;\nend\n\n% check if it's multiple g(f).\nif isfield(model, 'isGroupNonlinearity') && strcmp(model.nonLinearity{k}, ...\n 'repression')\n dWdalpha = zeros(w1, w2);\nend\n\n\nif isfield(model, 'includeNoise') && model.includeNoise\n noiseMat = ones(numData, 1)*model.noiseVar;\n yvar = model.yvar + noiseMat;\n dWdn = zeros(w1, w2);\nelse\n yvar = model.yvar;\nend\n\nfor p = intPoints\n for i=1:numData\n arg = model.t(i)-model.mapt(p);\n if arg >= 0\n ind = i + (k-1)*numData;\n beta_ik=1/yvar(ind);\n \n [dxdB dxdD dxdS dxdalpha dxdgParam] = gpsimXGradient(model, i, k);\n\n dWdB(p, p)=dWdB(p, p)+beta_ik*model.g_grad2(p,gInd)*dxdB* ...\n exp(-model.D(k)*arg+log(model.S(k)) +log(model.step));\n \n if isfield(model, 'isGroupNonlinearity') \n if strcmp(model.nonLinearity{k}, 'repression')\n dWdalpha(p,p) = dWdalpha(p, p)+beta_ik*model.g_grad2(p,gInd)* ...\n dxdalpha*exp(-model.D(k)*arg+log(model.S(k)) +log(model.step));\n end\n end\n \n factor = model.ypred(model.times_index(i), k)-model.y(ind);\n\n dWdD(p, p) = dWdD(p, p)+model.step*beta_ik*model.g_grad2(p,gInd)* ...\n (dxdD-factor*arg)*exp(-model.D(k)*arg+log(model.S(k))) ;\n\n dWdS(p, p) = dWdS(p, p)+model.step*beta_ik*exp(-model.D(k)* ...\n arg)*(dxdS*model.S(k)*model.g_grad2(p,gInd)+ ...\n factor*model.g_grad2(p,gInd));\n\n if model.ngParam > 0\n for gParamInd = 1:ngParamk\n dWdgParam(p, p, gParamInd)= dWdgParam(p, p, gParamInd)+ ...\n model.step*beta_ik*exp(-model.D(k)*arg)* ...\n (dxdgParam(gParamInd)*model.S(k)*model.g_grad2(p, ...\n gInd)+ factor*model.S(k)*model.dggrad2(p,gInd));\n end\n end\n \n if isfield(model,'includeNoise') && model.includeNoise\n dWdn(p, p) = dWdn(p, p)-2*sqrt(model.noiseVar(k))* ...\n beta_ik^2*factor*model.g_grad2(p,gInd)*exp(-model.D(k)*arg+ ...\n log(model.step)+ ...\n log(model.S(k)));\n end\n end\n end\nend\n\nfor p = intPoints\n for q = intPoints\n for i = 1:numData\n arg1 = model.t(i)-model.mapt(p);\n arg2 = model.t(i)-model.mapt(q);\n if arg1 >= 0 && arg2 >= 0\n ind = i + (k-1)*numData;\n beta_ik = 1/yvar(ind);\n\n dWdD(p,q) = dWdD(p,q)-beta_ik*model.g_grad(p,gInd)* ...\n model.g_grad(q,gInd)*(arg1+arg2)*exp(-model.D(k)*(arg1+arg2)+ ...\n log(S2(k))+log(step2));\n\n dWdS(p,q) = dWdS(p,q)+2*beta_ik*model.S(k)* model.g_grad(q,gInd)* ...\n model.g_grad(p,gInd) * exp(-model.D(k)*(arg1+arg2)+log(step2));\n\n if model.ngParam > 0\n for gParamInd = 1:ngParamk\n dWdgParam(p, q, gParamInd)= dWdgParam(p, q, gParamInd)+beta_ik*(model.dggrad(q,gInd)*model.g_grad(p,gInd)+model.g_grad(q,gInd)*model.dggrad(p,gInd))*exp(-model.D(k)*(arg1+arg2)+log(S2(k))+log(step2));\n end\n end\n \n if isfield(model, 'includeNoise') && model.includeNoise\n dWdn(p, q) = dWdn(p, q)-2*sqrt(model.noiseVar(k))* ...\n beta_ik^2*model.g_grad(p,gInd)*model.g_grad(q,gInd)*exp(- ...\n model.D(k)*(arg1+arg2)+log(step2)+log(S2(k)));\n end\n end\n end\n end\nend\n\n\n\n\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/gpsim/gpsimMapWGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240930029118, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4864086530864653}} {"text": "function suborder = tetrahedron_ncc_suborder ( rule, suborder_num )\n\n%*****************************************************************************80\n%\n%% TETRAHEDRON_NCC_SUBORDER returns the suborders for an NCC rule.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 January 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Peter Silvester,\n% Symmetric Quadrature Formulae for Simplexes,\n% Mathematics of Computation,\n% Volume 24, Number 109, January 1970, pages 95-100.\n%\n% Parameters:\n%\n% Input, integer RULE, the index of the rule.\n%\n% Input, integer SUBORDER_NUM, the number of suborders of the rule.\n%\n% Output, integer SUBORDER(SUBORDER_NUM), the suborders of the rule.\n%\n if ( rule == 1 )\n suborder(1:suborder_num) = [ ...\n 1 ];\n elseif ( rule == 2 )\n suborder(1:suborder_num) = [ ...\n 4 ];\n elseif ( rule == 3 )\n suborder(1:suborder_num) = [ ...\n 4, 6 ];\n elseif ( rule == 4 )\n suborder(1:suborder_num) = [ ...\n 4, 12, 4 ];\n elseif ( rule == 5 )\n suborder(1:suborder_num) = [ ...\n 4, 12, 6, 12, 1 ];\n elseif ( rule == 6 )\n suborder(1:suborder_num) = [ ...\n 4, 12, 12, 12, 12, 4 ];\n elseif ( rule == 7 )\n suborder(1:suborder_num) = [ ...\n 4, 12, 12, 12, 6, 24, 4, 4, 6 ];\n\n else\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TETRAHEDRON_NCC_SUBORDER - Fatal error!\\n' );\n fprintf ( 1, ' Illegal RULE = %d\\n', rule );\n error ( 'TETRAHEDRON_NCC_SUBORDER - 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/tetrahedron_ncc_rule/tetrahedron_ncc_suborder.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879991, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.48635128907902725}} {"text": "function waic = gp_waic(gp, x, y, varargin)\n%GP_WAIC The widely applicable information criterion (WAIC) for GP model\n% \n% Description\n% WAIC = GP_WAIC(GP, X, Y) evaluates WAIC defined by\n% Watanabe(2010) given a Gaussian process model GP, training\n% inputs X and training outputs Y. Instead of Bayes loss we\n% compute the Bayes utility which is just the negative of loss\n% used by Watanabe.\n% \n% WAIC is evaluated as follows when using the variance form\n% \n% WAIC(n) = BUt(n) - V/n\n% \n% where BUt(n) is Bayesian training utility, V is functional variance\n% and n is the number of training inputs.\n%\n% BUt = mean(log(p(yt | xt, x, y)))\n% V = sum(E[log(p(y|th))^2] - E[log(p(y|th))]^2)\n%\n% When using the Gibbs training loss, WAIC is evaluated as follows\n%\n% WAIC(n) = BUt(n) - 2*(BUt(n) - GUt(n))\n%\n% where BUt(n) is as above and GUt is Gibbs training utility\n%\n% GUt(n) = E_th[mean(log(p(y|th)))].\n% \n% GP can be a Gaussian process structure, a record structure\n% from GP_MC or an array of GPs from GP_IA.\n%\n% OPTIONS is optional parameter-value pair\n% method - Method to evaluate waic, 'V' = Variance method, 'G' = Gibbs\n% training utility method (default = 'V')\n% form - Return form, 'mean' returns the mean value and 'all'\n% returns the values for all data points (default = 'mean')\n% z - optional observed quantity in triplet (x_i,y_i,z_i)\n% Some likelihoods may use this. For example, in case of \n% Poisson likelihood we have z_i=E_i, that is, expected value \n% for ith case. \n%\n% See also\n% GP_DIC, DEMO_MODELASSESMENT1, DEMO_MODELASSESMENT2\n%\n% References\n% \n% Watanabe(2010). Equations of states in singular statistical\n% estimation. Neural Networks 23 (2010), 20-34\n%\n% Watanabe(2010). Asymptotic Equivalance of Bayes Cross Validation and\n% Widely applicable Information Criterion in Singular Learning Theory.\n% Journal of Machine Learning Research 11 (2010), 3571-3594.\n% \n%\n\n% Copyright (c) 2011-2013 Ville Tolvanen\n\n ip=inputParser;\n ip.FunctionName = 'GP_WAIC';\n ip.addRequired('gp',@(x) isstruct(x) || iscell(x));\n ip.addRequired('x', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\n ip.addRequired('y', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\n ip.addParamValue('method', 'V', @(x) ismember(x,{'V' 'G'}))\n ip.addParamValue('form', 'mean', @(x) ismember(x,{'mean','all'}))\n ip.addParamValue('z', [], @(x) isreal(x) && all(isfinite(x(:))))\n ip.parse(gp, x, y, varargin{:});\n method=ip.Results.method;\n form=ip.Results.form;\n % pass these forward\n options=struct();\n z = ip.Results.z;\n if ~isempty(ip.Results.z)\n options.zt=ip.Results.z;\n options.z=ip.Results.z;\n end\n \n [tn, nin] = size(x);\n \n % ====================================================\n if isstruct(gp) % Single GP or MCMC solution\n switch gp.type\n case {'FULL' 'VAR' 'DTC' 'SOR'}\n tstind = [];\n case {'FIC' 'CS+FIC'}\n tstind = 1:tn;\n case 'PIC'\n tstind = gp.tr_index;\n end\n\n if isfield(gp, 'etr')\n % MCMC solution\n [Ef, Varf, BUt] = gpmc_preds(gp,x,y, x, 'yt', y, 'tstind', tstind, options);\n BUt=log(mean(exp(BUt),2));\n GUt = zeros(tn,1);\n Elog = zeros(tn,1);\n Elog2 = zeros(tn,1);\n \n nsamples = length(gp.edata);\n if strcmp(gp.type, 'PIC')\n tr_index = gp.tr_index;\n gp = rmfield(gp, 'tr_index');\n else\n tr_index = [];\n end\n \n %Ef = zeros(tn, nsamples);\n %Varf = zeros(tn, nsamples);\n sigma2 = zeros(tn, nsamples);\n for j = 1:nsamples\n Gp = take_nth(gp,j);\n if strcmp(gp.type, 'FIC') | strcmp(gp.type, 'PIC') || strcmp(gp.type, 'CS+FIC') || strcmp(gp.type, 'VAR') || strcmp(gp.type, 'DTC') || strcmp(gp.type, 'SOR')\n Gp.X_u = reshape(Gp.X_u,length(Gp.X_u)/nin,nin);\n end\n Gp.tr_index = tr_index;\n\n gp_array{j} = Gp;\n %[Ef(:,j), Varf(:,j)] = gp_pred(Gp, x, y, x, 'yt', y, 'tstind', tstind, options);\n if isfield(gp.lik.fh,'trcov')\n sigma2(:,j) = repmat(Gp.lik.sigma2,1,tn);\n end\n end\n \n if isequal(method,'V')\n % Evaluate WAIC using the Variance method\n \n if isfield(gp.lik.fh,'trcov')\n % Gaussian likelihood\n for i=1:tn\n% fmin = mean(Ef(i,:) - 9*sqrt(Varf(i,:)));\n% fmax = mean(Ef(i,:) + 9*sqrt(Varf(i,:)));\n% Elog(i) = quadgk(@(f) mean(multi_npdf(f,Ef(i,:),(Varf(i,:))) ...\n% .*bsxfun(@minus,-bsxfun(@rdivide,(repmat((y(i)-f),nsamples,1)).^2,(2.*sigma2(i,:))'), 0.5*log(2*pi*sigma2(i,:))').^2), fmin, fmax);\n% Elog2(i) = quadgk(@(f) mean(multi_npdf(f,Ef(i,:),(Varf(i,:))) ...\n% .*bsxfun(@minus,-bsxfun(@rdivide,(repmat((y(i)-f),nsamples,1)).^2,(2.*sigma2(i,:))'), 0.5*log(2*pi*sigma2(i,:))')), fmin, fmax);\n% \n m = Ef(i,:);\n s2 = Varf(i,:);\n m0 = 1; m1 = m; m2 = m.^2 + s2; m3 = m.*(m.^2+3*s2);\n m4 = m.^4+6.*m.^2.*s2+3*s2.^2;\n Elog2(i) = mean((-0.5.*log(2.*pi.*sigma2(i,:)) - y(i).^2./(2.*sigma2(i,:))).*m0 - 1./(2.*sigma2(i,:)) .* m2 + y(i)./sigma2(i,:) .* m1);\n Elog(i) = mean((1/4 .* m4 - y(i) .* m3 + (3.*y(i).^2./2+0.5.*log(2.*pi.*sigma2(i,:)).*sigma2(i,:)) .* m2 ...\n - (y(i).^3 + y(i).*log(2.*pi.*sigma2(i,:)).*sigma2(i,:)) .* m1 + (y(i).^4./4 + 0.5.*y(i).^2.*log(2.*pi.*sigma2(i,:)).*sigma2(i,:) ...\n + 0.25.*log(2.*pi.*sigma2(i,:)).^2.*sigma2(i,:).^2) .* m0) ./ sigma2(i,:).^2);\n end\n Elog2 = Elog2.^2;\n Vn = (Elog-Elog2);\n if strcmp(form, 'mean')\n Vn = mean(Vn);\n BUt = mean(BUt);\n end\n waic = BUt - Vn;\n else\n % non-Gaussian likelihood\n for i=1:tn\n if ~isempty(z)\n z1 = z(i);\n else\n z1 = [];\n end\n if ~isequal(gp.lik.type, 'Coxph')\n fmin = mean(Ef(i,:) - 9*sqrt(Varf(i,:)));\n fmax = mean(Ef(i,:) + 9*sqrt(Varf(i,:)));\n Elog(i) = quadgk(@(f) mean(multi_npdf(f,Ef(i,:),(Varf(i,:))) ...\n .*llvec(gp_array, y(i), f, z1).^2), fmin, fmax);\n Elog2(i) = quadgk(@(f) mean(multi_npdf(f,Ef(i,:),(Varf(i,:))) ...\n .*llvec(gp_array, y(i), f, z1)), fmin, fmax);\n else\n ntime = size(gp.lik.xtime,1);\n for i2=1:nsamples\n % Use MC to integrate over latents\n ns = 10000;\n Sigma_tmp = diag(Varf([1:ntime ntime+i],i2));\n f = mvnrnd(Ef([1:ntime ntime+i],i2), Sigma_tmp, ns);\n tmp2(i2) = 1/ns * sum(llvec(gp_array{i2}, y(i,:), f', z1));\n tmp(i2) = 1/ns * sum((llvec(gp_array{i2}, y(i,:), f', z1)).^2);\n end\n Elog2(i)=mean(tmp2);\n Elog(i)=mean(tmp);\n end\n end\n Elog2 = Elog2.^2;\n Vn = (Elog-Elog2);\n if strcmp(form, 'mean')\n Vn = mean(Vn);\n BUt = mean(BUt);\n end\n waic = BUt - Vn;\n end\n \n else\n % Evaluate WAIC using the expected value form via Gibbs training\n % loss\n \n if isfield(gp.lik.fh,'trcov')\n % Gaussian likelihood\n for i=1:tn\n fmin = mean(Ef(i,:) - 9*sqrt(Varf(i,:)));\n fmax = mean(Ef(i,:) + 9*sqrt(Varf(i,:)));\n GUt(i) = quadgk(@(f) mean(multi_npdf(f,Ef(i,:),(Varf(i,:))) ...\n .*bsxfun(@minus,-bsxfun(@rdivide,(repmat((y(i)-f),nsamples,1)).^2,(2.*sigma2(i,:))'), 0.5*log(2*pi*sigma2(i,:))')), fmin, fmax);\n end\n if strcmp(form, 'mean')\n GUt = mean(GUt);\n BUt = mean(BUt);\n end\n waic = BUt-2*(BUt-GUt);\n else\n % non-Gaussian likelihood\n for i=1:tn\n if ~isempty(z)\n z1 = z(i);\n else\n z1 = [];\n end\n fmin = mean(Ef(i,:) - 9*sqrt(Varf(i,:)));\n fmax = mean(Ef(i,:) + 9*sqrt(Varf(i,:)));\n GUt(i) = quadgk(@(f) mean(multi_npdf(f,Ef(i,:),(Varf(i,:))) ...\n .*llvec(gp_array, y(i), f, z1)), fmin, fmax);\n end\n if strcmp(form, 'mean')\n GUt = mean(GUt);\n BUt = mean(BUt);\n end\n waic = BUt-2*(BUt-GUt);\n end\n end\n \n \n else\n % A single GP solution\n [Ef, Varf, BUt] = gp_pred(gp, x, y, x, 'yt', y, 'tstind', tstind, options);\n\n GUt = zeros(tn,1);\n Elog = zeros(tn,1);\n Elog2 = zeros(tn,1);\n\n if isequal(method,'V')\n % Estimate WAIC with variance form\n \n if isfield(gp.lik.fh,'trcov')\n % Gaussian likelihood\n sigma2 = gp.lik.sigma2;\n \n for i=1:tn\n \n % Analytical moments for Gaussian distribution\n \n m0 = 1; m1 = Ef(i); m2 = Ef(i)^2 + Varf(i); m3 = Ef(i)*(Ef(i)^2+3*Varf(i));\n m4 = Ef(i)^4+6*Ef(i)^2*Varf(i)+3*Varf(i)^2;\n \n Elog2(i) = (-0.5*log(2*pi*sigma2) - y(i).^2./(2.*sigma2))*m0 - 1./(2.*sigma2) * m2 + y(i)./sigma2 * m1;\n Elog(i) = (1/4 * m4 - y(i) * m3 + (3*y(i).^2./2+0.5*log(2*pi*sigma2).*sigma2) * m2 ...\n - (y(i).^3 + y(i).*log(2*pi*sigma2).*sigma2) * m1 + (y(i).^4/4 + 0.5*y(i).^2*log(2*pi*sigma2).*sigma2 ...\n + 0.25*log(2*pi*sigma2).^2.*sigma2.^2) * m0) ./ sigma2.^2;\n \n end\n Elog2 = Elog2.^2;\n Vn = Elog-Elog2;\n if strcmp(form,'mean')\n BUt = mean(BUt);\n Vn = mean(Vn);\n end\n waic = BUt - Vn;\n\n else\n % Non-Gaussian likelihood\n for i=1:tn\n if ~isempty(z)\n z1 = z(i);\n else\n z1 = [];\n end\n if ~isequal(gp.lik.type, 'Coxph')\n fmin = Ef(i)-9*sqrt(Varf(i));\n fmax = Ef(i)+9*sqrt(Varf(i));\n Elog(i) = quadgk(@(f) norm_pdf(f, Ef(i), sqrt(Varf(i))).*llvec(gp, y(i), f, z1).^2 ,...\n fmin, fmax);\n Elog2(i) = quadgk(@(f) norm_pdf(f, Ef(i), sqrt(Varf(i))).*llvec(gp, y(i), f, z1) ,...\n fmin, fmax);\n else\n % Use MC to integrate over latents\n ntime = size(gp.lik.xtime,1);\n ns = 10000;\n Sigma_tmp = Varf([1:ntime ntime+i], [1:ntime ntime+i]);\n Sigma_tmp = (Sigma_tmp + Sigma_tmp') ./ 2;\n f = mvnrnd(Ef([1:ntime ntime+i]), Sigma_tmp, ns);\n Elog2(i) = 1/ns * sum(llvec(gp, y(i,:), f', z1));\n Elog(i) = 1/ns * sum((llvec(gp, y(i,:), f', z1)).^2);\n end\n end\n Elog2 = Elog2.^2;\n Vn = Elog-Elog2;\n if strcmp(form, 'mean')\n Vn = mean(Vn);\n BUt = mean(BUt);\n end\n waic = BUt - Vn;\n \n end\n \n else\n % WAIC using the expected value form via Gibbs training loss GUt\n \n if isfield(gp.lik.fh,'trcov')\n % Gaussian likelihood\n sigma2 = gp.lik.sigma2;\n for i=1:tn\n if Varf(i) maxsubs\n warning('quad_moments: Reached the limit on the maximum number of intervals in use.');\n break\n end\n midpoints(ndx) = []; \n subs = reshape([subs(1,:); midpoints; midpoints; subs(2,:)],2,[]); % Divide the remaining subintervals in half\n end\n \n % Scale moments\n m_0 = Ifx;\n m_1 = Ifx1./Ifx;\n m_2 = Ifx2./Ifx;\n m_3 = Ifx3./Ifx;\n m_4 = Ifx4./Ifx;\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/gp/gp_waic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.6442250928250376, "lm_q1q2_score": 0.4863351845942938}} {"text": "function [out] = RFT_main(X,options,verbose)\n% applies RFT to an input 1D-field X sampled on a regular lattice\n% function [out] = RFT_main(X,options,verbose)\n% RFT (Random Field Theory) allows one to derive the FWE-corrected p-values\n% on some topological features of the field (e.g., local peaks and\n% upcrossing thresholds), under the assumption of non-independance\n% between neighbouring positions on the lattice.\n% IN:\n% - X: Lx1 vector of sampled RF\n% - options: structure containing the set-inducing thresholds, i.e.:\n% .u: height threshold (cluster-level inference, default=2.33)\n% .k: extent threshold (set-level inference, default=6)\n% .R: sampled RF of residuals (for smoothness estimation). If empty,\n% then the smoothness is estimated directly on X.\n% .type: type of RF. Can be set to 'norm' (normal, default), 't'\n% (Student) or 'F' (Fisher).\n% .dof: degrees of freedom (only relevant for 't' or 'F' fields).\n% - verbose: a verbose flag\n% OUT:\n% - out: a structure containing the following fields:\n% .peaks: summary stats of peak-level inference, i.e.:\n% .ind: npx1 vector of local maxima indices\n% .val: npx1 vector of local maxima values\n% .prft: npx1 vector of local maxima corrected p-values\n% .punc: npx1 vector of local maxima uncorrected p-values\n% where np is the number of local maxima on the field.\n% .clusters: summary stats of cluster-level inference, i.e.:\n% .ind: ncx1 cell-array of sets of indices\n% .k: ncx1 vector of clusters' spatial extent\n% .prft: ncx1 vector of clusters' corrected p-values\n% where nc is the number of upcrossing clusters on the field.\n% .set: summary stats of set-level inference, i.e.:\n% .c: number of upcrossing threshold with a size bigger than k\n% .prft: set-level p-value\n% .xc: the height threshold that corresponds to the nominal FWER\n% .Em: expected number of clusters (under H0)\n% .En: expected number of voxels per cluster (under H0)\n% .fwhm: the estimated smoothness of the field\n\ntry,options;catch,options=[];end\ntry,verbose;catch,verbose=0;end\n\nOUTSTR = cell(0);\nOUTSTR{1} = ['Date: ',datestr(clock)];\nif verbose\n disp(' ')\n disp('-- 1D-RFT analysis --')\n disp(OUTSTR{1}) \nend\n\nif isempty(options)\n options.FWER = 0.05;\n options.u = VBA_spm_invNcdf(0.99,0,1);\n options.k = 6;\n options.R = [];\n options.type = 'norm';\n options.dof = NaN; % only relevant for 't' or 'F' fields\n options.mask = [];\n if verbose\n disp(['Using default set-inducing thresholds (X>',num2str(options.u,'%3.2f'),', k>',num2str(options.k),').'])\n end\nelse\n if ~isfield(options,'FWER')\n options.FWER = 0.05;\n end\n if ~isfield(options,'k')\n options.k = 6;\n if verbose\n disp(['Using default set-inducing threshold (k>',num2str(options.k),').'])\n end\n end\n if ~isfield(options,'R')\n options.R = [];\n if verbose\n disp(['Estimating smoothness on statistical map.'])\n end\n end\n if ~isfield(options,'type')\n options.type = 'norm';\n end\n if ~isfield(options,'dof')\n if ~isequal(options.type,'norm')\n disp('RFT: error: must provide valid degrees of freedom!')\n out = [];\n else\n options.dof = NaN;\n end\n end\n if ~isfield(options,'u')\n switch options.type\n case 'norm'\n options.u = VBA_spm_invNcdf(0.99,0,1);\n case 't'\n options.u = VBA_spm_invTcdf(0.99,options.dof);\n case 'F'\n options.u = VBA_spm_invFcdf(0.99,options.dof(1),options.dof(2));\n end\n if verbose\n disp(['Using default cluster-inducing threshold (X>',num2str(options.u,'%3.2f'),').'])\n end\n end\n if ~isfield(options,'mask')\n options.mask = [];\n end\nend\n\nif ~isempty(options.mask)\n if length(options.mask)~=length(X) || ~isequal(VBA_vec(unique(options.mask)),[0;1])\n disp(['RFT-1D: error: invalid mask provided!'])\n out = [];\n return\n end\nend\n\nout.options = options;\nout.verbose = verbose;\n\nX = VBA_vec(X);\nif isempty(options.mask)\n L = length(X);\nelse\n L = length(find(options.mask==1));\nend\n\n% estimate smoothness\nif ~isempty(options.R)\n out.fwhm = RFT_smoothness(options.R);\nelse\n out.fwhm = RFT_smoothness(X);\nend\nOUTSTR{2} = ['Search volume: L=',num2str(L)];\nOUTSTR{3} = ['Estimated smoothness: FWHM=',num2str(out.fwhm,'%3.1f')];\nOUTSTR{4} = ['Number of resels: R=',num2str(L./out.fwhm,'%3.1f')];\nif verbose\n disp(OUTSTR{2})\n disp(OUTSTR{3})\n disp(OUTSTR{4})\nend\n\n% estimate critical height threshold (peak-level)\ngridu = 0:1e-3:10;\npgrid = RFT_Pval(gridu',0,1,out.fwhm,L,options.type,options.dof);\nd = abs(options.FWER-pgrid);\nout.xc = gridu(find(d==min(d)));\nOUTSTR{5} = ['Critical height threshold [peak-level]: X>',num2str(out.xc,'%3.2f'),' (test size: FWER=',num2str(round(options.FWER*100)),'%)'];\nif verbose\n disp(OUTSTR{5})\nend\n\n% peak- level inference\npeaks.ind = RFT_localmax(X);\npeaks.val = X(peaks.ind);\npeaks.prft = RFT_Pval(peaks.val,0,1,out.fwhm,L,options.type,options.dof);\nswitch options.type\n case 'norm'\n peaks.punc = 1-VBA_spm_Ncdf(peaks.val,0,1);\n case 't'\n peaks.punc = 1-VBA_spm_Tcdf(peaks.val,options.dof);\n case 'F'\n peaks.punc = 1-VBA_spm_Fcdf(peaks.val,options.dof(1),options.dof(2));\nend\n\n% cluster-level inference\n[clusters.ind,clusters.imax] = RFT_clusters(X,options.u,0);\nnc = length(clusters.ind);\nclusters.k = [];\nclusters.prft = [];\nfor i=1:nc\n clusters.k(i) = length(clusters.ind{i});\n clusters.prft(i) = RFT_Pval(options.u,clusters.k(i),1,out.fwhm,L,options.type,options.dof);\nend\n\n% set-level inference\nif nc>0\n bigC = find(clusters.k>=options.k);\nelse\n bigC = [];\nend\nset.c = length(bigC);\nset.prft = RFT_Pval(options.u,options.k,set.c,out.fwhm,L,options.type,options.dof);\n\n% E[number of voxel per cluster] and E[number of clusters]\nout.Em = RFT_expectedTopo(options.u,L,out.fwhm,1,options.type,options.dof);\nswitch options.type\n case 'norm'\n P0 = 1-VBA_spm_Ncdf(options.u,0,1);\n case 't'\n P0 = 1-VBA_spm_Tcdf(options.u,options.dof);\n case 'F'\n P0 = 1-VBA_spm_Fcdf(options.u,options.dof(1),options.dof(2));\nend\nout.En = L.*P0./out.Em;\n\nOUTSTR{6} = ['Expected voxels per cluster [cluster-level]: E[k|H0]=',num2str(out.En,'%3.1f')];\nOUTSTR{7} = ['Expected number of clusters [set-level]: E[c|H0]=',num2str(out.Em,'%3.1f')];\nif verbose\n disp(OUTSTR{6})\n disp(OUTSTR{7})\nend\n\nOUTSTR{8} = ['Number of local peaks =',num2str(length(peaks.prft)),];\nOUTSTR{9} = ['Number of upcrossing clusters =',num2str(nc),' (X>',num2str(options.u,'%3.2f'),')'];\nOUTSTR{10} = ['RFT [set-level]: p=',num2str(set.prft,'%3.3f'),' (c=',num2str(set.c),')'];\nif verbose\n disp(OUTSTR{8})\n disp(OUTSTR{9})\n disp(OUTSTR{10})\nend\n\n\n\n% wrap-up results\nout.peaks = peaks;\nout.clusters = clusters;\nout.set = set;\nout.OUTSTR = OUTSTR;\n\n\n% order peak-pval of clusters' maxima\ninc = ismember(peaks.ind,clusters.imax);\n[ps,is] = sort(peaks.prft(inc==1),'ascend');\nSTR.loc = cell(0);\nSTR.unc = cell(0);\nSTR.peak = cell(0);\nSTR.cluster = cell(0);\nfor i=1:nc % for all clusters\n % find local maxima that belong to each cluster\n ic = is(i);\n ip = find(ismember(peaks.ind,clusters.ind{ic})==1);\n % sort peak-pvalues in each cluster\n [pval,iop] = sort(peaks.prft(ip),'ascend');\n % aggregate info Re: local maxima per (ordered) cluster\n nt = length(STR.loc);\n for j=1:length(ip)\n STR.loc{nt+j} = num2str(peaks.ind(ip(iop(j))));\n STR.unc{nt+j} = num2str(peaks.punc(ip(iop(j))),'%3.3f');\n STR.peak{nt+j} = [num2str(peaks.prft(ip(iop(j))),'%3.3f'),' (',num2str(peaks.val(ip(iop(j))),'%3.2f'),')'];\n if j==1\n STR.cluster{nt+j} = [num2str(clusters.prft(ic),'%3.3f'),' (',num2str(clusters.k(ic)),')'];\n end\n end\nend\nSTR.set = [num2str(set.prft,'%3.3f'),' (',num2str(set.c),')'];\nout.STR = STR;\n\n% display results\nif verbose\n [out] = RFT_ReDisplay(X,out);\nend\n\n", "meta": {"author": "MBB-team", "repo": "VBA-toolbox", "sha": "01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414", "save_path": "github-repos/MATLAB/MBB-team-VBA-toolbox", "path": "github-repos/MATLAB/MBB-team-VBA-toolbox/VBA-toolbox-01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414/modules/random_field_theory/RFT_main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4862455984309629}} {"text": "function [sys,x0,str,ts] = quadrotor_dynamics(t,x,u,flag, quad, x0, groundflag)\n % Flyer2dynamics lovingly coded by Paul Pounds, first coded 12/4/04\n % A simulation of idealised X-4 Flyer II flight dynamics.\n % version 2.0 2005 modified to be compatible with latest version of Matlab\n % version 3.0 2006 fixed rotation matrix problem\n % version 4.0 4/2/10, fixed rotor flapping rotation matrix bug, mirroring\n % version 5.0 8/8/11, simplified and restructured\n % version 6.0 25/10/13, fixed rotation matrix/inverse wronskian definitions, flapping cross-product bug\n\n warning off MATLAB:divideByZero\n \n global groundFlag;\n \n % New in version 2:\n % - Generalised rotor thrust model\n % - Rotor flapping model\n % - Frame aerodynamic drag model\n % - Frame aerodynamic surfaces model\n % - Internal motor model\n % - Much coolage\n \n % Version 1.3\n % - Rigid body dynamic model\n % - Rotor gyroscopic model\n % - External motor model\n \n %ARGUMENTS\n % u Reference inputs 1x4\n % tele Enable telemetry (1 or 0) 1x1\n % crash Enable crash detection (1 or 0) 1x1\n % init Initial conditions 1x12\n \n %INPUTS\n % u = [N S E W]\n % NSEW motor commands 1x4\n \n %CONTINUOUS STATES\n % z Position 3x1 (x,y,z)\n % v Velocity 3x1 (xd,yd,zd)\n % n Attitude 3x1 (Y,P,R)\n % o Angular velocity 3x1 (wx,wy,wz)\n % w Rotor angular velocity 4x1\n %\n % Notes: z-axis downward so altitude is -z(3)\n \n %CONTINUOUS STATE MATRIX MAPPING\n % x = [z1 z2 z3 n1 n2 n3 z1 z2 z3 o1 o2 o3 w1 w2 w3 w4]\n \n %INITIAL CONDITIONS\n n0 = [0 0 0]; % n0 Ang. position initial conditions 1x3\n v0 = [0 0 0]; % v0 Velocity Initial conditions 1x3\n o0 = [0 0 0]; % o0 Ang. velocity initial conditions 1x3\n init = [x0 n0 v0 o0]; % x0 is the passed initial position 1x3\n groundFlag = groundflag;\n\n %CONTINUOUS STATE EQUATIONS\n % z` = v\n % v` = g*e3 - (1/m)*T*R*e3\n % I*o` = -o X I*o + G + torq\n % R = f(n)\n % n` = inv(W)*o\n \n % Dispatch the flag.\n %\n switch flag\n case 0\n [sys,x0,str,ts]=mdlInitializeSizes(init, quad); % Initialization\n case 1\n sys = mdlDerivatives(t,x,u, quad); % Calculate derivatives\n case 3\n sys = mdlOutputs(t,x, quad); % Calculate outputs\n case { 2, 4, 9 } % Unused flags\n sys = [];\n otherwise\n error(['Unhandled flag = ',num2str(flag)]); % Error handling\n end\nend % End of flyer2dynamics\n\n%==============================================================\n% mdlInitializeSizes\n% Return the sizes, initial conditions, and sample times for the\n% S-function.\n%==============================================================\n%\nfunction [sys,x0,str,ts] = mdlInitializeSizes(init, quad)\n %\n % Call simsizes for a sizes structure, fill it in and convert it\n % to a sizes array.\n %\n sizes = simsizes;\n sizes.NumContStates = 12;\n sizes.NumDiscStates = 0;\n sizes.NumOutputs = 12;\n sizes.NumInputs = 4;\n sizes.DirFeedthrough = 0;\n sizes.NumSampleTimes = 1;\n sys = simsizes(sizes);\n %\n % Initialize the initial conditions.\n x0 = init;\n %\n % str is an empty matrix.\n str = [];\n %\n % Generic timesample\n ts = [0 0];\n \n if quad.verbose\n disp(sprintf('t\\t\\tz1\\t\\tz2\\t\\tz3\\t\\tn1\\t\\tn2\\t\\tn3\\t\\tv1\\t\\tv2\\t\\tv3\\t\\to1\\t\\to2\\t\\to3\\t\\tw1\\t\\tw2\\t\\tw3\\t\\tw4\\t\\tu1\\t\\tu2\\t\\tu3\\t\\tu4'))\n end\nend % End of mdlInitializeSizes.\n\n\n%==============================================================\n% mdlDerivatives\n% Calculate the state derivatives for the next timestep\n%==============================================================\n%\nfunction sys = mdlDerivatives(t,x,u, quad)\n global a1s b1s groundFlag\n \n %CONSTANTS\n %Cardinal Direction Indicies\n N = 1; % N 'North' 1x1\n E = 2; % S 'South' 1x1\n S = 3; % E 'East' 1x1\n W = 4; % W 'West' 1x1\n \n \n D(:,1) = [quad.d;0;quad.h]; % Di Rotor hub displacements 1x3\n D(:,2) = [0;quad.d;quad.h];\n D(:,3) = [-quad.d;0;quad.h];\n D(:,4) = [0;-quad.d;quad.h];\n \n %Body-fixed frame references\n e1 = [1;0;0]; % ei Body fixed frame references 3x1\n e2 = [0;1;0];\n e3 = [0;0;1];\n \n %EXTRACT ROTOR SPEEDS FROM U\n w = u(1:4);\n \n %EXTRACT STATES FROM X\n z = x(1:3); % position in {W}\n n = x(4:6); % RPY angles {W}\n v = x(7:9); % velocity in {W}\n o = x(10:12); % angular velocity in {W}\n \n %PREPROCESS ROTATION AND WRONSKIAN MATRICIES\n phi = n(1); % yaw\n the = n(2); % pitch\n psi = n(3); % roll\n \n % rotz(phi)*roty(the)*rotx(psi)\n R = [cos(the)*cos(phi) sin(psi)*sin(the)*cos(phi)-cos(psi)*sin(phi) cos(psi)*sin(the)*cos(phi)+sin(psi)*sin(phi); %BBF > Inertial rotation matrix\n cos(the)*sin(phi) sin(psi)*sin(the)*sin(phi)+cos(psi)*cos(phi) cos(psi)*sin(the)*sin(phi)-sin(psi)*cos(phi);\n -sin(the) sin(psi)*cos(the) cos(psi)*cos(the)];\n \n \n %Manual Construction\n % Q3 = [cos(phi) -sin(phi) 0;sin(phi) cos(phi) 0;0 0 1]; % RZ %Rotation mappings\n % Q2 = [cos(the) 0 sin(the);0 1 0;-sin(the) 0 cos(the)]; % RY\n % Q1 = [1 0 0;0 cos(psi) -sin(psi);0 sin(psi) cos(psi)]; % RX\n % R = Q3*Q2*Q1 %Rotation matrix\n %\n % RZ * RY * RX\n iW = [0 sin(psi) cos(psi); %inverted Wronskian\n 0 cos(psi)*cos(the) -sin(psi)*cos(the);\n cos(the) sin(psi)*sin(the) cos(psi)*sin(the)] / cos(the);\n if any(w == 0)\n % might need to fix this, preculudes aerobatics :(\n % mu becomes NaN due to 0/0\n error('quadrotor_dynamics: not defined for zero rotor speed');\n end\n \n %ROTOR MODEL\n for i=[N E S W] %for each rotor\n %Relative motion\n \n Vr = cross(o,D(:,i)) + v;\n mu = sqrt(sum(Vr(1:2).^2)) / (abs(w(i))*quad.r); %Magnitude of mu, planar components\n lc = Vr(3) / (abs(w(i))*quad.r); %Non-dimensionalised normal inflow\n li = mu; %Non-dimensionalised induced velocity approximation\n alphas = atan2(lc,mu);\n j = atan2(Vr(2),Vr(1)); %Sideslip azimuth relative to e1 (zero over nose)\n J = [cos(j) -sin(j);\n sin(j) cos(j)]; %BBF > mu sideslip rotation matrix\n \n %Flapping\n beta = [((8/3*quad.theta0 + 2*quad.theta1)*mu - 2*(lc)*mu)/(1-mu^2/2); %Longitudinal flapping\n 0;];%sign(w) * (4/3)*((Ct/sigma)*(2*mu*gamma/3/a)/(1+3*e/2/r) + li)/(1+mu^2/2)]; %Lattitudinal flapping (note sign)\n beta = J'*beta; %Rotate the beta flapping angles to longitudinal and lateral coordinates.\n a1s(i) = beta(1) - 16/quad.gamma/abs(w(i)) * o(2);\n b1s(i) = beta(2) - 16/quad.gamma/abs(w(i)) * o(1);\n \n %Forces and torques\n T(:,i) = quad.Ct*quad.rho*quad.A*quad.r^2*w(i)^2 * [-cos(b1s(i))*sin(a1s(i)); sin(b1s(i));-cos(a1s(i))*cos(b1s(i))]; %Rotor thrust, linearised angle approximations\n Q(:,i) = -quad.Cq*quad.rho*quad.A*quad.r^3*w(i)*abs(w(i)) * e3; %Rotor drag torque - note that this preserves w(i) direction sign\n tau(:,i) = cross(T(:,i),D(:,i)); %Torque due to rotor thrust\n end\n \n %RIGID BODY DYNAMIC MODEL\n dz = v;\n dn = iW*o;\n \n dv = quad.g*e3 + R*(1/quad.M)*sum(T,2);\n \n % vehicle can't fall below ground\n if groundFlag && (z(3) > 0)\n z(3) = 0;\n dz(3) = 0;\n end\n do = inv(quad.J)*(cross(-o,quad.J*o) + sum(tau,2) + sum(Q,2)); %row sum of torques\n sys = [dz;dn;dv;do]; %This is the state derivative vector\nend % End of mdlDerivatives.\n\n\n%==============================================================\n% mdlOutputs\n% Calculate the output vector for this timestep\n%==============================================================\n%\nfunction sys = mdlOutputs(t,x, quad)\n \n %TELEMETRY\n if quad.verbose\n disp(sprintf('%0.3f\\t',t,x))\n end\n \n % compute output vector as a function of state vector\n % z Position 3x1 (x,y,z)\n % v Velocity 3x1 (xd,yd,zd)\n % n Attitude 3x1 (Y,P,R)\n % o Angular velocity 3x1 (Yd,Pd,Rd)\n \n n = x(4:6); % RPY angles\n phi = n(1); % yaw\n the = n(2); % pitch\n psi = n(3); % roll\n \n \n % rotz(phi)*roty(the)*rotx(psi)\n R = [cos(the)*cos(phi) sin(psi)*sin(the)*cos(phi)-cos(psi)*sin(phi) cos(psi)*sin(the)*cos(phi)+sin(psi)*sin(phi); %BBF > Inertial rotation matrix\n cos(the)*sin(phi) sin(psi)*sin(the)*sin(phi)+cos(psi)*cos(phi) cos(psi)*sin(the)*sin(phi)-sin(psi)*cos(phi);\n -sin(the) sin(psi)*cos(the) cos(psi)*cos(the)];\n \n iW = [0 sin(psi) cos(psi); %inverted Wronskian\n 0 cos(psi)*cos(the) -sin(psi)*cos(the);\n cos(the) sin(psi)*sin(the) cos(psi)*sin(the)] / cos(the);\n \n % return velocity in the body frame\n sys = [ x(1:6);\n inv(R)*x(7:9); % translational velocity mapped to body frame\n iW*x(10:12)]; % RPY rates mapped to body frame\n %sys = [x(1:6); iW*x(7:9); iW*x(10:12)];\n %sys = x;\nend\n% End of mdlOutputs.\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/simulink/quadrotor_dynamics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4862316839162263}} {"text": "function options = rbfcreate(x, y, varargin)\n%RBFCREATE Creates an RBF interpolation\n% OPTIONS = RBFSET(X, Y, 'NAME1',VALUE1,'NAME2',VALUE2,...) creates an \n% radial base function interpolation \n% \n% RBFCREATE with no input arguments displays all property names and their\n% possible values.\n% \n%RBFCREATE PROPERTIES\n% \n\n%\n% Alex Chirokov, alex.chirokov@gmail.com\n% 16 Feb 2006\ntic;\n% Print out possible values of properties.\nif (nargin == 0) & (nargout == 0)\n fprintf(' x: [ dim by n matrix of coordinates for the nodes ]\\n');\n fprintf(' y: [ 1 by n vector of values at nodes ]\\n');\n fprintf(' RBFFunction: [ gaussian | thinplate | cubic | multiquadrics | {linear} ]\\n');\n fprintf(' RBFConstant: [ positive scalar ]\\n');\n fprintf(' RBFSmooth: [ positive scalar {0} ]\\n');\n fprintf(' Stats: [ on | {off} ]\\n');\n fprintf('\\n');\n return;\nend\nNames = [\n 'RBFFunction '\n 'RBFConstant '\n 'RBFSmooth '\n 'Stats '\n];\n[m,n] = size(Names);\nnames = lower(Names);\n\noptions = [];\nfor j = 1:m\n options.(deblank(Names(j,:))) = [];\nend\n\n%**************************************************************************\n%Check input arrays \n%**************************************************************************\n[nXDim nXCount]=size(x);\n[nYDim nYCount]=size(y);\n\nif (nXCount~=nYCount)\n error(sprintf('x and y should have the same number of rows'));\nend;\n\nif (nYDim~=1)\n error(sprintf('y should be n by 1 vector'));\nend;\n\noptions.('x') = x;\noptions.('y') = y;\n%**************************************************************************\n%Default values \n%**************************************************************************\noptions.('RBFFunction') = 'linear';\noptions.('RBFConstant') = (prod(max(x')-min(x'))/nXCount)^(1/nXDim); %approx. average distance between the nodes \noptions.('RBFSmooth') = 0;\noptions.('Stats') = 'off';\n\n%**************************************************************************\n% Argument parsing code: similar to ODESET.m\n%**************************************************************************\n\ni = 1;\n% A finite state machine to parse name-value pairs.\nif rem(nargin-2,2) ~= 0\n error('Arguments must occur in name-value pairs.');\nend\nexpectval = 0; % start expecting a name, not a value\nwhile i <= nargin-2\n arg = varargin{i};\n \n if ~expectval\n if ~isstr(arg)\n error(sprintf('Expected argument %d to be a string property name.', i));\n end\n \n lowArg = lower(arg);\n j = strmatch(lowArg,names);\n if isempty(j) % if no matches\n error(sprintf('Unrecognized property name ''%s''.', arg));\n elseif length(j) > 1 % if more than one match\n % Check for any exact matches (in case any names are subsets of others)\n k = strmatch(lowArg,names,'exact');\n if length(k) == 1\n j = k;\n else\n msg = sprintf('Ambiguous property name ''%s'' ', arg);\n msg = [msg '(' deblank(Names(j(1),:))];\n for k = j(2:length(j))'\n msg = [msg ', ' deblank(Names(k,:))];\n end\n msg = sprintf('%s).', msg);\n error(msg);\n end\n end\n expectval = 1; % we expect a value next\n \n else\n options.(deblank(Names(j,:))) = arg;\n expectval = 0; \n end\n i = i + 1;\nend\n\nif expectval\n error(sprintf('Expected value for property ''%s''.', arg));\nend\n\n \n%**************************************************************************\n% Creating RBF Interpolatin\n%**************************************************************************\n\nswitch lower(options.('RBFFunction'))\n case 'linear' \n options.('rbfphi') = @rbfphi_linear;\n case 'cubic'\n options.('rbfphi') = @rbfphi_cubic;\n case 'multiquadric'\n options.('rbfphi') = @rbfphi_multiquadrics;\n case 'thinplate'\n options.('rbfphi') = @rbfphi_thinplate;\n case 'gaussian'\n options.('rbfphi') = @rbfphi_gaussian;\n otherwise\n options.('rbfphi') = @rbfphi_linear;\nend\n\nphi = options.('rbfphi');\n\nA=rbfAssemble(x, phi, options.('RBFConstant'), options.('RBFSmooth'));\n\nb=[y'; zeros(nXDim+1, 1)]; \n\n%inverse\nrbfcoeff=A\\b;\n\n%SVD\n% [U,S,V] = svd(A);\n% \n% for i=1:1:nXCount+1\n% if (S(i,i)>0) S(i,i)=1/S(i,i); end; \n% end; \n% rbfcoeff = V*S'*U*b;\n\n\noptions.('rbfcoeff') = rbfcoeff;\n\n\nif (strcmp(options.('Stats'),'on'))\n fprintf('%d point RBF interpolation was created in %e sec\\n', length(y), toc); \n fprintf('\\n');\nend;\n\nfunction [A]=rbfAssemble(x, phi, const, smooth)\n[dim n]=size(x);\nA=zeros(n,n);\nfor i=1:n\n for j=1:i\n r=norm(x(:,i)-x(:,j));\n temp=feval(phi,r, const);\n A(i,j)=temp;\n A(j,i)=temp;\n end\n A(i,i) = A(i,i) - smooth;\nend\n% Polynomial part\nP=[ones(n,1) x'];\nA = [ A P\n P' zeros(dim+1,dim+1)];\n\n%**************************************************************************\n% Radial Base Functions\n%************************************************************************** \nfunction u=rbfphi_linear(r, const)\nu=r;\n\nfunction u=rbfphi_cubic(r, const)\nu=r.*r.*r;\n\nfunction u=rbfphi_gaussian(r, const)\nu=exp(-0.5*r.*r/(const*const));\n\nfunction u=rbfphi_multiquadrics(r, const)\nu=sqrt(1+r.*r/(const*const));\n\nfunction u=rbfphi_thinplate(r, const)\nu=r.*r.*log(r+1);", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/rbfinterp/rbfcreate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.4859305056585046}} {"text": "function [y,ty]=v_correlogram(x,inc,nw,nlag,m,fs)\n%V_CORRELOGRAM calculate correlogram [y,ty]=(x,inc,nw,nlag,m,fs)\n% Usage:\n% do_env=1; do_hp=1; % flags to control options\n% [b,a,fx,bx,gd]=v_gammabank(25,fs,'',[80 5000]); % determine v_filterbank\n% y=v_filterbank(b,a,s,gd); % filter signal s\n% if do_env\n% [bl,al]=butter(3,2*800/fs);\n% y=filter(bl,al,v_teager(y,1),[],1); % low pass envelope @ 800 Hz\n% end\n% if do_hp\n% y=filter(fir1(round(16e-3*fs),2*64/fs,'high'),1,y,[],1); % HP filter @ 64 Hz\n% end\n% v_correlogram(y,round(10e-3*fs),round(16e-3*fs),round(12e-3*fs),'',fs);\n%\n% Inputs:\n% x(*,chan) is the output of a filterbank (e.g. v_filterbank)\n% with one column per filter channel\n% inc frame increment in samples\n% nw window length in samples [or window function]\n% nlag number of lags to calculate\n% m mode string:\n% 'h' = Hamming window\n% fs sample freq (affects only plots)\n%\n% Outputs:\n% y(lag,chan,frame) is v_correlogram. Lags are 1:nlag samples\n% ty is time of the window energy centre for each frame\n% x(n) is at time n\n%\n% For each channel, the calculated correlation for frame n comprises\n% y(t+1,*,n+1)=(win.*x(n*inc+(1:nw))'*x(n*inc+t+(1:nw))/sqrt(win'*abs(x(n*inc+(1:nw))).^2 * win'*abs(x(n*inc+t+(1:nw))).^2)\n% This corresponds to the expression in (1.7) of [1] but incorporating the normalization from (1) of [2].\n%\n% Future planned mode options:\n% 'd' = subtract DC component\n% 'n' = unnormalized\n% 'v' = variable analysis window proportional to lag\n% 'p' = output the peaks only\n%\n% Refs:\n% [1]\tD. Wang and G. J. Brown. Fundamentals of computational auditory scene analysis.\n% In D. Wang and G. Brown, editors, Computational Auditory Scene Analysis: Principles,\n% Algorithms, and Applications, chapter 1. Wiley, Oct. 2006. doi: 10.1109/9780470043387.ch1\n% [2]\tS. Granqvist and B. Hammarberg. The correlogram: a visual display of periodicity. J. Acoust. Soc. Amer., 114: 2934, 2003.\n\n% Copyright (C) Mike Brookes 2011-2018\n% Version: $Id: v_correlogram.m 10867 2018-09-21 17:35:59Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nmemsize=v_voicebox('memsize'); \t% set memory size to use\n[nx,nc]=size(x); % number of sampes and channels\nif nargin<6\n fs=1; % default sample frequency is 1 Hz\n if nargin<5\n m='h'; % default analysis window is Hamming\n if nargin<4\n nlag=[];\n if nargin<3\n nw=[];\n if nargin<2\n inc=[];\n end\n end\n end\n end\nend\nif ~numel(inc)\n inc=128; % default frame hop is 128 samples\nend\nif ~numel(nw)\n nw=inc; % default analysis window length is the fame increment\nend\nnwin=length(nw);\nif nwin>1 % nw specifies the window function explicitly\n win=nw(:);\nelse % nw gives the window length\n nwin=nw;\n if any(m=='h')\n win=v_windows(3,nwin)'; % Hamming window\n else\n win=ones(nwin,1); % window function\n end\nend\nif ~numel(nlag)\n nlag=nwin;\nend\nnwl=nwin+nlag-1;\nnt=pow2(nextpow2(nwl)); % transform length\nnf=floor((nx-nwl+inc)/inc); % number of frames\ni1=repmat((1:nwl)',1,nc)+repmat(0:nx:nx*nc-1,nwl,1);\nnb=min(nf,max(1,floor(memsize/(16*nwl*nc)))); % chunk size for calculating\nnl=ceil(nf/nb); % number of chunks\njx0=nf-(nl-1)*nb; % size of first chunk in frames\nwincg=(1:nwin)*win.^2/(win'*win); % determine window centre of energy\nfwin=conj(fft(win,nt,1)); % conjugate fft of window\ny=zeros(nlag,nc,nf);\n% first do partial chunk\njx=jx0;\nx2=zeros(nwl,nc*jx);\nx2(:)=x(repmat(i1(:),1,jx)+repmat((0:jx-1)*inc,nwl*nc,1));\n% the next line was previously: v=ifft(conj(fft(x2(1:nwin,:),nt,1)).*fft(x2,nt,1));\nv=ifft(conj(fft(x2(1:nwin,:).*repmat(win(:),1,nc*jx),nt,1)).*fft(x2,nt,1)); % v(1:nlag,:) contains second half of xcorr(x2) output\nw=max(real(ifft(fwin(:,ones(1,nc*jx)).*fft(x2.*conj(x2),nt,1))),0); % v(1:nlag,:) contains second half of xcorr(|x2|^2,win) output\nw=sqrt(w(1:nlag,:).*w(ones(nlag,1),:));\nif isreal(x)\n y(:,:,1:jx)=reshape(real(v(1:nlag,:))./w,nlag,nc,jx); % note: some values may be NaN is x=0 throughout the window\nelse\n y(:,:,1:jx)=reshape(conj(v(1:nlag,:))./w,nlag,nc,jx);\nend\n% now do remaining chunks\nx2=zeros(nwl,nc*nb);\nfor il=2:nl\n ix=jx+1; % first frame in this chunk\n jx=jx+nb; % last frame in this chunk\n x2(:)=x(repmat(i1(:),1,nb)+repmat((ix-1:jx-1)*inc,nwl*nc,1));\n % the next line was previously: v=ifft(conj(fft(x2(1:nwin,:),nt,1)).*fft(x2,nt,1));\n v=ifft(conj(fft(x2(1:nwin,:).*repmat(win(:),1,nc*nb),nt,1)).*fft(x2,nt,1));\n w=max(real(ifft(fwin(:,ones(1,nc*nb)).*fft(x2.*conj(x2),nt,1))),0);\n w=sqrt(w(1:nlag,:).*w(ones(nlag,1),:));\n if isreal(x)\n y(:,:,ix:jx)=reshape(real(v(1:nlag,:))./w,nlag,nc,nb);\n else\n y(:,:,ix:jx)=reshape(conj(v(1:nlag,:))./w,nlag,nc,nb);\n end\nend\nty=(0:nf-1)'*inc+wincg; % calculate times of window centres\nif ~nargout\n imagesc(ty/fs,(1:nlag)/fs,squeeze(mean(abs(y),2)));\n if nargin<6\n us='samp';\n else\n us='s';\n end\n xlabel(['Time (' v_xticksi us ')']);\n ylabel(['Lag (' v_yticksi us ')']);\n axis 'xy';\n v_colormap('v_thermliny');\n colorbar;\n v_cblabel('Mean Correlation');\n title('Summary Correlogram');\nend\n\n\n", "meta": {"author": "ImperialCollegeLondon", "repo": "sap-voicebox", "sha": "28f2654b7584f724277ec81de533debe28ff51ac", "save_path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox", "path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox/sap-voicebox-28f2654b7584f724277ec81de533debe28ff51ac/voicebox/v_correlogram.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.48592339572087545}} {"text": "function segment_length = p11_boundary_segment_length ( segment_index, h )\n\n%*****************************************************************************80\n%\n%% P11_BOUNDARY_SEGMENT_LENGTH returns boundary segment lengths in problem 11.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer 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, 'P11_BOUNDARY_SEGMENT_LENGTH - Fatal error!' );\n fprintf ( 1, ' Nonpositive H = %f\\n', h );\n error ( 'P11_BOUNDARY_SEGMENT_LENGTH - Fatal error!' );\n end\n\n if ( segment_index == 1 )\n\n n = round ( 4.0 / h );\n n = max ( n, 5 );\n segment_length = n + mod ( 4 - mod ( n - 1, 4 ), 4 );\n\n else\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'P11_BOUNDARY_SEGMENT_LENGTH - Fatal error!' );\n fprintf ( 1, ' Illegal SEGMENT_INDEX = %d\\n', segment_index );\n error ( 'P11_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/p11_boundary_segment_length.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.48560065299016947}} {"text": "function [omega,u,eqn,info] = fourCurl3P2(node,elem,bdFlag,pde,option)\n\n%% fourCurl3P2: the fourth order curl problem in 3D\n%\n% [w,u,eqn,info] = fourCurl3P2(node,elem,bdFlag,pde,option)\n% uses the first P2 elements to approximate the velocity u and\n% the stream function w. \n%\n% We solve the following equations:\n% -w + curl curl u = 0 \n% curl curl w + u = f\n% u\\times n = (curl u )\\times n = 0 on \\partial \\Omega\n%\n% please check fourCurl3doc for details.\n%\n% Lin Zhong, June 2013.\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\n\n%% Set up optional input arguments\nif ~exist('bdFlag','var'), bdFlag = []; end\nif ~exist('option','var'), option = []; end\n\n%% Sort elem to asend ordering\nelemunSort = elem;\n[elem,bdFlag] = sortelem3(elemunSort,bdFlag);\n\n%% Construct Data Structure\n[Dlambda,volume] = gradbasis3(node,elem);\nvolume = abs(volume);\n%---------------------------------------------%\n% locEdge = [1 2; 1 3; 1 4; 2 3; 2 4; 3 4];\n% locFace = [2 3 4; 1 3 4; 1 2 4; 1 2 3];\nlocBasesIdx = [1 2 0; 1 3 0; 1 4 0; 2 3 0; 2 4 0; 3 4 0; ... % phi\n 1 2 0; 1 3 0; 1 4 0; 2 3 0; 2 4 0; 3 4 0; ... % psi\n 3 2 4; 3 1 4; 2 1 4; 2 1 3; ...\n 4 2 3; 4 1 3; 4 1 2; 3 1 2]; % chi\n \n%---------------------------------------------%\n[elem2edge,edge] = dof3edge(elem);\n[elem2face,face] = dof3face(elem);\n%---------------------------------------------%\nNE = size(edge,1);\nNF = size(face,1);\nNT = size(elem,1);\nNdof = 2*(NE+NF);\n%---------------------------------------------%\nelem2dof = [elem2edge elem2edge+NE elem2face+2*NE elem2face+2*NE+NF];\nface2edge = zeros(NF,3,'int32');\nface2edge(elem2face(:,1),:) = elem2edge(:,[4 5 6]);\nface2edge(elem2face(:,2),:) = elem2edge(:,[2 3 6]);\nface2edge(elem2face(:,3),:) = elem2edge(:,[1 3 5]);\nface2edge(elem2face(:,4),:) = elem2edge(:,[1 2 4]);\n\ntic;\n\n%% Assemble Matrix\nDiDjcross = zeros(NT,3,4,4);\nfor i = 1:4\n for j = i+1:4 \n DiDjcross(:,:,i,j) = mycross(Dlambda(:,:,i),Dlambda(:,:,j),2);\n DiDjcross(:,:,j,i) = -DiDjcross(:,:,i,j);\n end\nend\nDiDj = zeros(NT,4,4);\nfor i = 1:4\n for j = i:4 \n DiDj(:,i,j) = dot(Dlambda(:,:,i),Dlambda(:,:,j),2);\n DiDj(:,j,i) = DiDj(:,i,j);\n end\nend\n\nii = zeros(210*NT,1); jj = zeros(210*NT,1); \nindex = 0;\nfor i = 1:20\n for j = i:20\n ii(index+1:index+NT) = double(elem2dof(:,i));\n jj(index+1:index+NT) = double(elem2dof(:,j));\n i1 = locBasesIdx(i,1); i2 = locBasesIdx(i,2); i3 = locBasesIdx(i,3);\n j1 = locBasesIdx(j,1); j2 = locBasesIdx(j,2); j3 = locBasesIdx(j,3);\n Aij = zeros(NT,1); Mij = zeros(NT,1); \n %% curl-curl matrix\n if (i<=6) && (j<=6)\n Aij = 4*dot(DiDjcross(:,:,i1,i2),DiDjcross(:,:,j1,j2),2);\n end\n if (i<=6) && (j>12)\n Aij = dot(DiDjcross(:,:,i1,i2),...\n DiDjcross(:,:,j1,j3)-DiDjcross(:,:,j1,j2)+2*DiDjcross(:,:,j2,j3),2)/2;\n end\n if (i>12) && (j>12)\n % curl chi_i = Dlambda_{i1}mycross phi_{i2,i3} + lambda_{i1}curl phi_{i2,i3}\n % curl chi_j = Dlambda_{j1}mycross phi_{j2,j3} + lambda_{j1}curl phi_{j2,j3}\n % (Dlambda_{i1}mycross phi_{i2,i3}) dot (Dlambda_{j1}mycross phi_{j2,j3})\n temp11 = ((1+(i2==j2))*dot(DiDjcross(:,:,i1,i3),DiDjcross(:,:,j1,j3),2) ...\n - (1+(i2==j3))*dot(DiDjcross(:,:,i1,i3),DiDjcross(:,:,j1,j2),2) ...\n - (1+(i3==j2))*dot(DiDjcross(:,:,i1,i2),DiDjcross(:,:,j1,j3),2) ...\n + (1+(i3==j3))*dot(DiDjcross(:,:,i1,i2),DiDjcross(:,:,j1,j2),2))/20;\n % lambda_{i1}curl phi_{i2,i3} dot lambda_{j1}curl phi_{j2,j3}\n temp22 = (1+(i1==j1))/5*dot(DiDjcross(:,:,i2,i3),DiDjcross(:,:,j2,j3),2);\n % Dlambda_{i1}mycross phi_{i2,i3} dot lambda_{j1}curl phi_{j2,j3}\n temp12 = dot( (1+(j1==i2))*DiDjcross(:,:,i1,i3) ...\n - (1+(j1==i3))*DiDjcross(:,:,i1,i2), ...\n DiDjcross(:,:,j2,j3),2)/10; \n % Dlambda_{j1}mycross phi_{j2,j3} dot lambda_{i1}curl phi_{i2,i3}\n temp21 = dot( (1+(i1==j2))*DiDjcross(:,:,j1,j3) ...\n - (1+(i1==j3))*DiDjcross(:,:,j1,j2), ...\n DiDjcross(:,:,i2,i3),2)/10; \n Aij = temp11 + temp22 + temp12 + temp21;\n end\n if (i<=6) && (j<=6)\n % block 1: (phi_i,phi_j)\n Mij = 1/20*((1+(i1==j1))*DiDj(:,i2,j2) ...\n - (1+(i1==j2))*DiDj(:,i2,j1) ...\n - (1+(i2==j1))*DiDj(:,i1,j2) ...\n + (1+(i2==j2))*DiDj(:,i1,j1));\n end\n if (i<=6) && (7<=j) && (j<=12)\n % block 2: (psi_j,phi_i)\n Mij = 1/20*( (1+(j1==i1))*DiDj(:,j2,i2) ...\n - (1+(j1==i2))*DiDj(:,j2,i1) ...\n + (1+(j2==i1))*DiDj(:,j1,i2) ...\n - (1+(j2==i2))*DiDj(:,j1,i1));\n\n end\n if (7<=i) && (i<=12) && (7<=j) && (j<=12)\n % block 3: (psi_j,psi_i)\n Mij = 1/20*((1+(i1==j1))*DiDj(:,i2,j2) ...\n + (1+(i1==j2))*DiDj(:,i2,j1) ...\n + (1+(i2==j1))*DiDj(:,i1,j2) ...\n + (1+(i2==j2))*DiDj(:,i1,j1));\n end\n if (i<=6) && (j>12)\n % block 4: (chi_j,phi_i)\n Mij = intlambda([j1,i1,j2],3)*DiDj(:,i2,j3) ...\n -intlambda([j1,i1,j3],3)*DiDj(:,i2,j2) ...\n -intlambda([j1,i2,j2],3)*DiDj(:,i1,j3) ...\n +intlambda([j1,i2,j3],3)*DiDj(:,i1,j2); \n end\n if (7<=i) && (i<=12) && (j>12)\n % block 5: (chi_j,psi_i)\n Mij = intlambda([j1,i1,j2],3)*DiDj(:,i2,j3) ...\n -intlambda([j1,i1,j3],3)*DiDj(:,i2,j2) ...\n +intlambda([j1,i2,j2],3)*DiDj(:,i1,j3) ...\n -intlambda([j1,i2,j3],3)*DiDj(:,i1,j2); \n end\n if (i>12) && (j>12)\n % block 6: (chi_j,chi_i)\n Mij = intlambda([i1,j1,i2,j2],3)*DiDj(:,i3,j3) ...\n -intlambda([i1,j1,i2,j3],3)*DiDj(:,i3,j2) ...\n -intlambda([i1,j1,i3,j2],3)*DiDj(:,i2,j3) ...\n +intlambda([i1,j1,i3,j3],3)*DiDj(:,i2,j2); \n end\n Aij = Aij.*volume;\n Mij = Mij.*volume;\n sA(index+1:index+NT) = Aij;\n sM(index+1:index+NT) = Mij;\n index = index + NT;\n end\nend\nclear curlBasis_i curlBasis_j basis_i basis_j\ndiagIdx = (ii == jj); upperIdx = ~diagIdx;\nA = sparse(ii(diagIdx),jj(diagIdx),sA(diagIdx),Ndof,Ndof);\nAU = sparse(ii(upperIdx),jj(upperIdx),sA(upperIdx),Ndof,Ndof);\nA = A + AU + AU';\nM = sparse(ii(diagIdx),jj(diagIdx),sM(diagIdx),Ndof,Ndof);\nMU = sparse(ii(upperIdx),jj(upperIdx),sM(upperIdx),Ndof,Ndof);\nM = M + MU + MU';\nclear AU MU\n\n% Whole matrix\nbigA = [-M A; A M];\n\n%% Righthand side\nf = zeros(Ndof,1);\nif ~isfield(pde,'f') || (isfield(pde,'f') && isreal(pde.f) && all(pde.f==0))\n pde.f = [];\nend\nif ~isfield(option,'fquadorder')\n option.fquadorder = 4; % default order is 4\nend\nif isfield(pde,'f') && ~isempty(pde.f)\n [lambda,w] = quadpts3(option.fquadorder); % quadrature order is 4\n nQuad = size(lambda,1);\n bt = zeros(NT,20);\n for p = 1:nQuad\n % quadrature points in the x-y-z coordinate\n pxyz = lambda(p,1)*node(elem(:,1),:) ...\n + lambda(p,2)*node(elem(:,2),:) ... \n + lambda(p,3)*node(elem(:,3),:) ... \n + lambda(p,4)*node(elem(:,4),:);\n fp = pde.f(pxyz);\n for k = 1:20\n k1 = locBasesIdx(k,1); \n k2 = locBasesIdx(k,2); \n k3 = locBasesIdx(k,3);\n % evaluate basis at quadrature points\n if k<=6\n % phi_k = lambda_{k1}Dlambda_{k2} - lambda_{k2}Dlambda_{k1};\n basis_k = (lambda(p,k1)*Dlambda(:,:,k2) ...\n -lambda(p,k2)*Dlambda(:,:,k1));\n elseif k<=12\n % psi_k = lambda_{k1}Dlambda_{k2} + lambda_{k2}Dlambda_{k1};\n basis_k = (lambda(p,k1)*Dlambda(:,:,k2) ...\n +lambda(p,k2)*Dlambda(:,:,k1));\n else\n % chi_k = lambda_{k1}phi_{k2,k3}; \n basis_k = lambda(p,k1)*(lambda(p,k2)*Dlambda(:,:,k3) ...\n -lambda(p,k3)*Dlambda(:,:,k2));\n end \n rhs = dot(basis_k,fp,2);\n bt(:,k) = bt(:,k) + w(p)*rhs;\n end\n end\n bt = bt.*repmat(volume,1,20);\n f = accumarray(elem2dof(:),bt(:),[Ndof 1]);\nend\nclear pxy fp bt rhs basis_k\n\nbigf = [zeros(Ndof,1); f];\nassembleTime = toc;\n\n%% Boundary condition\n% Find Dirichlet boundary dof: fixedDof\nif isempty(bdFlag) && ~isempty(pde.g_D) && isempty(pde.g_N)\n % Dirichlet boundary condition only\n bdFlag = setboundary3(node,elem,'Dirichlet');\nend\nisBdDof = false(Ndof,1);\n\nif ~isempty(bdFlag)\n %% Dirichlet boundary condition on edge dofs\n % Find boundary faces, edges and nodes\n isBdFace = false(NF,1);\n isBdFace(elem2face(bdFlag(:,1) == 1,1)) = true;\n isBdFace(elem2face(bdFlag(:,2) == 1,2)) = true;\n isBdFace(elem2face(bdFlag(:,3) == 1,3)) = true;\n isBdFace(elem2face(bdFlag(:,4) == 1,4)) = true;\n% boundaryFace = face(isBdFace,:);\n bdFace2edge = face2edge(isBdFace,:);\n isBdEdge = false(NE,1);\n isBdEdge(bdFace2edge(:)) = true;\n edgeBdDof = [find(isBdEdge); NE + find(isBdEdge)];\n% bdEdge = edge(isBdEdge,:);\n% isBdNode(bdEdge) = true;\n% bdNode = find(isBdNode);\n faceBdDof = 2*NE + [find(isBdFace); NF+find(isBdFace)];\n% edgeIdxMap = zeros(NE,1);\n% edgeIdxMap(isBdEdge) = 1:size(bdEdge,1);\n% bdFace2edge = edgeIdxMap(bdFace2edge);\n isBdDof(edgeBdDof) = true;\n isBdDof(faceBdDof) = true;\nend\n\nfreeDof = ~isBdDof;\n\nif any(freeDof)\n idx = [true(Ndof,1); freeDof];\n bigA_bd= bigA(idx,idx);\n bigf_bd = bigf(idx);\nend\n\n%% Solve\nt = cputime;\nbigu = bigA_bd\\bigf_bd;\nomega = bigu(1:Ndof);\nu = zeros(Ndof,1);\nu(freeDof) = bigu(Ndof+1:end);\ninfo.solverTime = cputime -t;\ndisplay(info.solverTime);\n\n%% Output information\neqn = struct('elem2edge',elem2edge,'elem2face',elem2face,'face2edge',face2edge,'A',A,'edge',edge,'face',face,'M',M,'f',f);\ninfo.assembleTime = assembleTime;\nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/equation/fourCurl3P2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.48551265455647713}} {"text": "clear all\n % Desemnarea variabilei x ca si simbolica\nx=sym('x');\n\t\t% Incarcarea functiei de integrat\nF=1/x \n % Calcularea integralei nedefinite\nI1=int(F)\n % Calcularea integralei definite intre limitele 1 si 2\nI2=int(F,1,2)", "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/12/Ex_12_5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.5660185351961016, "lm_q1q2_score": 0.48551263809239076}} {"text": "% RES = reconWpyr(PYR, INDICES, FILT, EDGES, LEVS, BANDS)\n%\n% Reconstruct image from its separable orthonormal QMF/wavelet pyramid\n% representation, as created by buildWpyr.\n%\n% PYR is a vector containing the N pyramid subbands, ordered from fine\n% to coarse. INDICES is an Nx2 matrix containing the sizes of\n% each subband. This is compatible with the MatLab Wavelet toolbox.\n%\n% FILT (optional) can be a string naming a standard filter (see\n% namedFilter), or a vector which will be used for (separable)\n% convolution. Default = 'qmf9'. EDGES specifies edge-handling,\n% and defaults to 'reflect1' (see corrDn).\n%\n% LEVS (optional) should be a vector of levels to include, or the string\n% 'all' (default). 1 corresponds to the finest scale. The lowpass band\n% corresponds to wpyrHt(INDICES)+1.\n%\n% BANDS (optional) should be a vector of bands to include, or the string\n% 'all' (default). 1=horizontal, 2=vertical, 3=diagonal. This is only used\n% for pyramids of 2D images.\n\n% Eero Simoncelli, 6/96.\n\nfunction res = reconWpyr(pyr, ind, filt, edges, levs, bands)\n\nif (nargin < 2)\n error('First two arguments (PYR INDICES) are required');\nend\n\n%%------------------------------------------------------------\n%% OPTIONAL ARGS:\n\nif (exist('filt') ~= 1)\n filt = 'qmf9';\nend\n\nif (exist('edges') ~= 1)\n edges= 'reflect1';\nend\n\nif (exist('levs') ~= 1)\n levs = 'all';\nend\n\nif (exist('bands') ~= 1)\n bands = 'all';\nend\n\n%%------------------------------------------------------------\n\nmaxLev = 1+wpyrHt(ind);\nif strcmp(levs,'all')\n levs = [1:maxLev]';\nelse\n if (any(levs > maxLev))\n error(sprintf('Level numbers must be in the range [1, %d].', maxLev));\n end\n levs = levs(:);\nend\n\nif strcmp(bands,'all')\n bands = [1:3]';\nelse\n if (any(bands < 1) | any(bands > 3))\n error('Band numbers must be in the range [1,3].');\n end\n bands = bands(:);\nend\n\nif isstr(filt)\n filt = namedFilter(filt);\nend\n\nfilt = filt(:);\nhfilt = modulateFlip(filt);\n\n%% For odd-length filters, stagger the sampling lattices:\nif (mod(size(filt,1),2) == 0)\n\tstag = 2;\nelse\n\tstag = 1;\nend\n\n%% Compute size of result image: assumes critical sampling (boundaries correct)\nres_sz = ind(1,:);\nif (res_sz(1) == 1)\n loind = 2;\n res_sz(2) = sum(ind(:,2));\nelseif (res_sz(2) == 1)\t\n loind = 2;\n res_sz(1) = sum(ind(:,1));\nelse\n loind = 4;\n res_sz = ind(1,:) + ind(2,:); %%horizontal + vertical bands.\n hres_sz = [ind(1,1), res_sz(2)];\n lres_sz = [ind(2,1), res_sz(2)];\nend\n\t\n\n%% First, recursively collapse coarser scales:\nif any(levs > 1) \n\n if (size(ind,1) > loind)\n nres = reconWpyr( pyr(1+sum(prod(ind(1:loind-1,:)')):size(pyr,1)), ...\n\tind(loind:size(ind,1),:), filt, edges, levs-1, bands);\n else\n nres = pyrBand(pyr, ind, loind); \t% lowpass subband\n end\n\n if (res_sz(1) == 1)\n res = upConv(nres, filt', edges, [1 2], [1 stag], res_sz);\n elseif (res_sz(2) == 1)\n res = upConv(nres, filt, edges, [2 1], [stag 1], res_sz);\n else\n ires = upConv(nres, filt', edges, [1 2], [1 stag], lres_sz); \n res = upConv(ires, filt, edges, [2 1], [stag 1], res_sz);\n end\n \nelse\n\n res = zeros(res_sz);\n\nend\n\n\t\n%% Add in reconstructed bands from this level:\nif any(levs == 1)\n if (res_sz(1) == 1)\n upConv(pyrBand(pyr,ind,1), hfilt', edges, [1 2], [1 2], res_sz, res);\n elseif (res_sz(2) == 1)\n upConv(pyrBand(pyr,ind,1), hfilt, edges, [2 1], [2 1], res_sz, res);\n else\n if any(bands == 1) % horizontal\n ires = upConv(pyrBand(pyr,ind,1),filt',edges,[1 2],[1 stag],hres_sz);\n upConv(ires,hfilt,edges,[2 1],[2 1],res_sz,res); %destructively modify res\n end\n if any(bands == 2) % vertical\n ires = upConv(pyrBand(pyr,ind,2),hfilt',edges,[1 2],[1 2],lres_sz);\n upConv(ires,filt,edges,[2 1],[stag 1],res_sz,res); %destructively modify res\n end\n if any(bands == 3) % diagonal\n ires = upConv(pyrBand(pyr,ind,3),hfilt',edges,[1 2],[1 2],hres_sz);\n upConv(ires,hfilt,edges,[2 1],[2 1],res_sz,res); %destructively modify res\n end\n end\nend\n \n", "meta": {"author": "jbhuang0604", "repo": "SelfExSR", "sha": "8f6dd8c1d20cb7e8792a7177b4f6fd677633f598", "save_path": "github-repos/MATLAB/jbhuang0604-SelfExSR", "path": "github-repos/MATLAB/jbhuang0604-SelfExSR/SelfExSR-8f6dd8c1d20cb7e8792a7177b4f6fd677633f598/quant_eval/ifcvec_release/matlabPyrTools/reconWpyr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.48537825852173044}} {"text": "function tapas_ehgf_jget_plotTraj(r)\n% Plots the estimated trajectories for the HGF perceptual model for\n% the JGET project\n% Usage example: est = tapas_fitModel(responses, inputs); tapas_ehgf_plotTraj(est);\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2013-2020 Christoph Mathys, TNU, UZH & ETHZ\n%\n% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or .\n\n% Optional plotting of standard deviations (true or false)\nplotsd = true;\n\n% Set up display\nscrsz = get(0,'screenSize');\nouterpos = [0.2*scrsz(3),0.2*scrsz(4),0.8*scrsz(3),0.8*scrsz(4)];\nfigure(...\n 'OuterPosition', outerpos,...\n 'Name', 'HGF trajectories');\n\n% Time axis\nif size(r.u,2) > 1 && ~isempty(find(strcmp(fieldnames(r.c_prc),'irregular_intervals'))) && r.c_prc.irregular_intervals\n t = r.u(:,end)';\nelse\n t = ones(1,size(r.u,1));\nend\n\nts = cumsum(t);\nts = [0, ts];\n\n% Do we know the generative parameters?\nif size(r.u,2) > 2\n genpar = true;\n mean = r.u(:,2);\n sd = r.u(:,3);\nelse\n genpar = false;\nend\n\n% Number of levels\ntry\n l = r.c_prc.n_levels;\ncatch\n l = length(r.p_prc.p)/8;\nend\n\n% Upper levels\nfor j = 1:l-1\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Left subplot (x) %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n subplot(l+1,2,2*j-1);\n\n if plotsd == true\n upperprior = r.p_prc.mux_0(l-j+1) +1.96*sqrt(r.p_prc.sax_0(l-j+1));\n lowerprior = r.p_prc.mux_0(l-j+1) -1.96*sqrt(r.p_prc.sax_0(l-j+1));\n upper = [upperprior; r.traj.mux(:,l-j+1)+1.96*sqrt(r.traj.sax(:,l-j+1))];\n lower = [lowerprior; r.traj.mux(:,l-j+1)-1.96*sqrt(r.traj.sax(:,l-j+1))];\n \n plot(0, upperprior, 'ob', 'LineWidth', 1);\n hold all;\n plot(0, lowerprior, 'ob', 'LineWidth', 1);\n fill([ts, fliplr(ts)], [(upper)', fliplr((lower)')], ...\n 'b', 'EdgeAlpha', 0, 'FaceAlpha', 0.15);\n end\n plot(ts, [r.p_prc.mux_0(l-j+1); r.traj.mux(:,l-j+1)], 'b', 'LineWidth', 1.5);\n hold all;\n plot(0, r.p_prc.mux_0(l-j+1), 'ob', 'LineWidth', 1.5); % prior\n xlim([0 ts(end)]);\n title(['Posterior expectation of x_' num2str(l-j+1)], 'FontWeight', 'bold');\n ylabel(['\\mu x_', num2str(l-j+1)]);\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Right subplot (alpha) %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n subplot(l+1,2,2*j);\n\n if plotsd == true\n upperprior = r.p_prc.mua_0(l-j+1) +1.96*sqrt(r.p_prc.saa_0(l-j+1));\n lowerprior = r.p_prc.mua_0(l-j+1) -1.96*sqrt(r.p_prc.saa_0(l-j+1));\n upper = [upperprior; r.traj.mua(:,l-j+1)+1.96*sqrt(r.traj.saa(:,l-j+1))];\n lower = [lowerprior; r.traj.mua(:,l-j+1)-1.96*sqrt(r.traj.saa(:,l-j+1))];\n \n plot(0, upperprior, 'ob', 'LineWidth', 1);\n hold all;\n plot(0, lowerprior, 'ob', 'LineWidth', 1);\n fill([ts, fliplr(ts)], [(upper)', fliplr((lower)')], ...\n 'b', 'EdgeAlpha', 0, 'FaceAlpha', 0.15);\n end\n plot(ts, [r.p_prc.mua_0(l-j+1); r.traj.mua(:,l-j+1)], 'b', 'LineWidth', 1.5);\n hold all;\n plot(0, r.p_prc.mua_0(l-j+1), 'ob', 'LineWidth', 1.5); % prior\n xlim([0 ts(end)]);\n title(['Posterior expectation of \\alpha_' num2str(l-j+1)], 'FontWeight', 'bold');\n ylabel(['\\mu \\alpha_', num2str(l-j+1)]);\nend\n\n\n% Input level\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Left subplot (x) %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nsubplot(l+1,2,2*l-1);\n\nif plotsd == true\n upperprior = r.p_prc.mux_0(1) +1.96*sqrt(r.p_prc.sax_0(1));\n lowerprior = r.p_prc.mux_0(1) -1.96*sqrt(r.p_prc.sax_0(1));\n upper = [upperprior; r.traj.mux(:,1)+1.96*sqrt(r.traj.sax(:,1))];\n lower = [lowerprior; r.traj.mux(:,1)-1.96*sqrt(r.traj.sax(:,1))];\n \n plot(0, upperprior, 'or', 'LineWidth', 1);\n hold all;\n plot(0, lowerprior, 'or', 'LineWidth', 1);\n fill([ts, fliplr(ts)], [(upper)', fliplr((lower)')], ...\n 'r', 'EdgeAlpha', 0, 'FaceAlpha', 0.15);\nend\nplot(ts, [r.p_prc.mux_0(1); r.traj.mux(:,1)], 'r', 'LineWidth', 1.5);\nhold all;\nplot(0, r.p_prc.mux_0(1), 'or', 'LineWidth', 1.5); % prior\nplot(ts(2:end), r.u(:,1), '.', 'Color', [0 0.6 0]); % inputs\nif genpar\n plot(ts(2:end), mean, '-', 'Color', 'k', 'LineWidth', 1); % mean of input distribution\n plot(ts(2:end), mean +1.96.*sd, '--', 'Color', 'k', 'LineWidth', 1); % 95% interval of input distribution\n plot(ts(2:end), mean -1.96.*sd, '--', 'Color', 'k', 'LineWidth', 1); % 95% interval of input distribution\nend\nxlim([0 ts(end)]);\ntitle(['Input u (green) and posterior expectation of x_1 (red) for \\kappa_x=', ...\n num2str(r.p_prc.kax), ', \\omega_x=', num2str(r.p_prc.omx)], 'FontWeight', 'bold');\nylabel('u, \\mu x_1');\nhold off;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Right subplot (alpha) %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nsubplot(l+1,2,2*l);\n\nif plotsd == true\n upperprior = r.p_prc.mua_0(1) +1.96*sqrt(r.p_prc.saa_0(1));\n lowerprior = r.p_prc.mua_0(1) -1.96*sqrt(r.p_prc.saa_0(1));\n upper = [upperprior; r.traj.mua(:,1)+1.96*sqrt(r.traj.saa(:,1))];\n lower = [lowerprior; r.traj.mua(:,1)-1.96*sqrt(r.traj.saa(:,1))];\n\n transupperprior = sqrt(exp(r.p_prc.kau *upperprior +r.p_prc.omu));\n translowerprior = sqrt(exp(r.p_prc.kau *lowerprior +r.p_prc.omu));\n transupper = sqrt(exp(r.p_prc.kau *upper +r.p_prc.omu));\n translower = sqrt(exp(r.p_prc.kau *lower +r.p_prc.omu));\n\n plot(0, transupperprior, 'or', 'LineWidth', 1);\n hold all;\n plot(0, translowerprior, 'or', 'LineWidth', 1);\n fill([ts, fliplr(ts)], [(transupper)', fliplr((translower)')], ...\n 'r', 'EdgeAlpha', 0, 'FaceAlpha', 0.15);\nend\ntransmuaprior = sqrt(exp(r.p_prc.kau *r.p_prc.mua_0(1) +r.p_prc.omu));\nplot(ts, [transmuaprior; sqrt(exp(r.p_prc.kau *r.traj.mua(:,1) +r.p_prc.omu))], 'r', 'LineWidth', 1.5);\nhold all;\nplot(0, transmuaprior, 'or', 'LineWidth', 1.5); % prior\nif genpar\n plot(ts(2:end), sd, '--', 'Color', 'k', 'LineWidth', 1);\nend\nxlim([0 ts(end)]);\ntitle(['Belief on noise (red) for \\kappa_\\alpha=', ...\n num2str(r.p_prc.kaa), ', \\omega_\\alpha=', num2str(r.p_prc.oma)], 'FontWeight', 'bold');\nylabel('\\mu \\alpha_1');\nhold off;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Decision model %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nsubplot(l+1,2,2*l+1);\n\nif plotsd == true\n upper = r.traj.muxhat(:,1)+1.96*sqrt(r.p_obs.ze +r.traj.saxhat(:,1));\n lower = r.traj.muxhat(:,1)-1.96*sqrt(r.p_obs.ze +r.traj.saxhat(:,1));\n\n fill([ts(2:end), fliplr(ts(2:end))], [(upper)', fliplr((lower)')], ...\n 'r', 'EdgeAlpha', 0, 'FaceAlpha', 0.15);\n hold all;\nend\nplot(ts(2:end), r.traj.muxhat(:,1), 'Color', [153/256 17/256 153/256], 'LineWidth', 1.5);\nhold all;\nplot(ts(2:end), r.y(:,1), '.', 'Color', [1 0.65 0], 'MarkerSize', 15); % responses\nif genpar\n plot(ts(2:end), mean, '-', 'Color', 'k', 'LineWidth', 1); % mean of input distribution\n plot(ts(2:end), mean +1.96.*sd, '--', 'Color', 'k', 'LineWidth', 1); % 95% interval of input distribution\n plot(ts(2:end), mean -1.96.*sd, '--', 'Color', 'k', 'LineWidth', 1); % 95% interval of input distribution\nend\nxlim([1 ts(end)]);\ntitle('Decision model: prediction of decision (purple) and decision (orange)', 'FontWeight', 'bold');\nylabel('y, \\^{\\mu} x_1');\nxlabel({'Trial number', ' '}); % A hack to get the relative subplot sizes right\nhold off;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Learning rate %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif genpar\nsubplot(l+1,2,2*l+2);\n[AX, H1, H2 ] = plotyy(ts(2:end), mean, ts(2:end), r.traj.lrx(:,1));\nhold all;\nylim(AX(1), [min(mean -1.96.*sd-3), max(mean +1.96.*sd+3)]);\nplot(AX(1), ts(2:end), mean +1.96.*sd, '--', 'Color', 'k', 'LineWidth', 1.1); % 95% interval of input distribution\nplot(AX(1), ts(2:end), mean -1.96.*sd, '--', 'Color', 'k', 'LineWidth', 1.1); % 95% interval of input distribution\nset(H1, 'Color', 'k', 'LineWidth', 1.1);\nset(H2, 'Color', [178/256, 34/256, 34/256], 'LineWidth', 1.5);\nset(AX(1), 'YColor', 'k');\nset(AX(2), 'YColor', 'k');\nxlim(AX(1), [1 ts(end)]);\nxlim(AX(2), [1 ts(end)]);\ntitle('Learning rate (bordeaux) and input sampling distribution (black)', 'FontWeight', 'bold');\nylabel(AX(1), 'Input');\nylabel(AX(2), '\\^{\\pi}_u/\\pi_x');\nxlabel('Trial number');\nhold off;\nend\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/HGF/tapas_ehgf_jget_plotTraj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.48525736174643314}} {"text": "function [ abd, rcond, z, info ] = spbco ( abd, lda, n, m )\n\n%*****************************************************************************80\n%\n%% SPBCO factors a real symmetric positive definite banded matrix.\n%\n% Discussion:\n%\n% SPBCO also estimates the condition of the matrix.\n%\n% If RCOND is not needed, SPBFA is slightly faster.\n%\n% To solve A*X = B, follow SPBCO by SPBSL.\n%\n% To compute inverse(A)*C, follow SPBCO by SPBSL.\n%\n% To compute determinant(A), follow SPBCO by SPBDI.\n%\n% Band storage:\n%\n% If A is a symmetric positive definite band matrix, the following \n% program segment will set up the input.\n%\n% m = (band width above diagonal)\n% do j = 1, n\n% i1 = max (1, j-m)\n% do i = i1, j\n% k = i-j+m+1\n% abd(k,j) = a(i,j)\n% end do\n% end do\n%\n% This uses M + 1 rows of A, except for the M by M upper left triangle, \n% which is ignored.\n%\n% For example, if the original matrix is\n%\n% 11 12 13 0 0 0\n% 12 22 23 24 0 0\n% 13 23 33 34 35 0\n% 0 24 34 44 45 46\n% 0 0 35 45 55 56\n% 0 0 0 46 56 66\n%\n% then N = 6, M = 2 and ABD should contain\n%\n% * * 13 24 35 46\n% * 12 23 34 45 56\n% 11 22 33 44 55 66\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 June 2009\n%\n% Author:\n%\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Dongarra, Moler, Bunch and Stewart,\n% LINPACK User's Guide,\n% SIAM, (Society for Industrial and Applied Mathematics),\n% 3600 University City Science Center,\n% Philadelphia, PA, 19104-2688.\n% ISBN 0-89871-172-X\n%\n% Parameters:\n%\n% Input, real ABD(LDA,N), the matrix to be factored. The columns of the \n% upper triangle are stored in the columns of ABD and the diagonals of \n% the upper triangle are stored in the rows of ABD. \n%\n% Input, integer LDA, the leading dimension of the array ABD.\n% M+1 <= LDA is required.\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, integer M, the number of diagonals above the main diagonal.\n%\n% Output, real ABD(LDA,N), an upper triangular matrix R, stored in band form,\n% so that A = R'*R. If INFO /= 0, the factorization is not complete.\n%\n% Output, real RCOND, an estimate of the reciprocal condition\n% of A. For the system A*X = B, relative perturbations in A and B of size \n% EPSILON may cause relative perturbations in X of size EPSILON/RCOND.\n% If RCOND is so small that the logical expression\n% 1.0 + RCOND == 1.0\n% is true, then A may be singular to working precision. In particular, \n% RCOND is zero if exact singularity is detected or the estimate underflows.\n%\n% Output, real Z(N), a work vector whose contents are usually\n% unimportant. If A is singular to working precision, then Z is an\n% approximate null vector in the sense that\n% norm(A*Z) = RCOND * norm(A) * norm(Z).\n% If INFO /= 0, Z is unchanged.\n%\n% Output, integer INFO, error flag.\n% 0, for normal return.\n% K, signals an error condition. The leading minor of order K is not \n% positive definite.\n%\n\n%\n% Find the norm of A.\n%\n for j = 1 : n\n\n l = min ( j, m+1 );\n mu = max ( m+2-j, 1 );\n z(j) = sasum ( l, abd(mu:mu+l-1,j), 1 );\n k = j - l;\n for i = mu : m\n k = k + 1;\n z(k) = z(k) + abs ( abd(i,j) );\n end\n\n end\n\n anorm = max ( z(1:n) );\n%\n% Factor.\n%\n [ abd, info ] = spbfa ( abd, lda, n, m );\n\n if ( info ~= 0 )\n return\n end\n%\n% RCOND = 1/(norm(A)*(estimate of norm(inverse(A)))).\n%\n% Estimate = norm(Z)/norm(Y) where A*Z = Y and A*Y = E.\n%\n% The components of E are chosen to cause maximum local\n% growth in the elements of W where R'*W = E.\n%\n% The vectors are frequently rescaled to avoid overflow.\n%\n% Solve R' * W = E.\n%\n ek = 1.0;\n z(1:n) = 0.0;\n\n for k = 1 : n\n\n if ( z(k) ~= 0.0 )\n ek = - abs ( ek ) * r4_sign ( z(k) );\n end\n\n if ( abd(m+1,k) < abs ( ek - z(k) ) )\n s = abd(m+1,k) / abs ( ek - z(k) );\n z(1:n) = s * z(1:n);\n ek = s * ek;\n end\n\n wk = ek - z(k);\n wkm = -ek - z(k);\n s = abs ( wk );\n sm = abs ( wkm );\n wk = wk / abd(m+1,k);\n wkm = wkm / abd(m+1,k);\n j2 = min ( k+m, n );\n i = m + 1;\n\n if ( k+1 <= j2 )\n\n for j = k+1 : j2\n i = i - 1;\n sm = sm + abs ( z(j) + wkm * abd(i,j) );\n z(j) = z(j) + wk * abd(i,j);\n s = s + abs ( z(j) );\n end\n\n if ( s < sm )\n\n t = wkm - wk;\n wk = wkm;\n i = m + 1;\n\n for j = k+1 : j2\n i = i - 1;\n z(j) = z(j) + t * abd(i,j);\n end\n\n end\n\n end\n\n z(k) = wk;\n\n end\n\n z(1:n) = z(1:n) / sasum ( n, z(1:n), 1 );\n%\n% Solve R * Y = W.\n%\n for k = n : -1 : 1\n\n if ( abd(m+1,k) < abs ( z(k) ) )\n s = abd(m+1,k) / abs ( z(k) );\n z(1:n) = s * z(1:n);\n end\n\n z(k) = z(k) / abd(m+1,k);\n lm = min ( k-1, m );\n la = m + 1 - lm;\n lb = k - lm;\n t = -z(k);\n z(lb:lb+lm-1) = z(lb:lb+lm-1) + t * abd(la:la+lm-1,k)';\n\n end\n\n z(1:n) = z(1:n) / sasum ( n, z(1:n), 1 );\n\n ynorm = 1.0;\n%\n% Solve R' * V = Y.\n%\n for k = 1 : n\n\n lm = min ( k-1, m );\n la = m + 1 - lm;\n lb = k - lm;\n\n z(k) = z(k) - sdot ( lm, abd(la:la+lm-1,k), 1, z(lb:lb+lm-1), 1 );\n\n if ( abd(m+1,k) < abs ( z(k) ) )\n s = abd(m+1,k) / abs ( z(k) );\n z(1:n) = s * z(1:n);\n ynorm = s * ynorm;\n end\n\n z(k) = z(k) / abd(m+1,k);\n\n end\n\n s = 1.0 / sasum ( n, z(1:n), 1 );\n z(1:n) = s * z(1:n);\n ynorm = s * ynorm;\n%\n% Solve R * Z = W.\n%\n for k = n : -1 : 1\n\n if ( abd(m+1,k) < abs ( z(k) ) )\n s = abd(m+1,k) / abs ( z(k) );\n z(1:n) = s * z(1:n);\n ynorm = s * ynorm;\n end\n\n z(k) = z(k) / abd(m+1,k);\n lm = min ( k-1, m );\n la = m + 1 - lm;\n lb = k - lm;\n t = -z(k);\n z(lb:lb+lm-1) = z(lb:lb+lm-1) + t * abd(la:la+lm-1,k)';\n\n end\n%\n% Make ZNORM = 1.0.\n%\n s = 1.0 / sasum ( n, z(1:n), 1 );\n z(1:n) = s * z(1:n);\n ynorm = s * ynorm;\n\n if ( anorm ~= 0.0 )\n rcond = ynorm / anorm;\n else\n rcond = 0.0;\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_s/spbco.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.4852508409997785}} {"text": "function [w,u] = biharmonicP3(node,elem,pde,bdFlag,option)\n% [w,u] = biharmonicP1(node,elem,pde,bdFlag) produces the mixed cubic finite element\n% approximation of the biharmonic equation, where w = laplace u\n% See also biharmonicP1, biharmonicP2, biharmonicP3.\n% Created by Jie Zhou.\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nif nargin<5, option = []; end\ntic;\n%% Construct Data Structure\n[elem2dof,elem2edge,edge,fixedDof,freeDof] = dofP3(elem); \nN = size(node,1); NT = size(elem,1); NE=size(edge,1); Ndof = N+2*NE+NT;\n%% Compute geometric quantities and gradient of local basis\n[Dlambda,area] = gradbasis(node,elem);\n\n%% Assemble stiffness matrix\n% Since Dphi_i*Dphi_j is quadratic, numerical quadrature rule is used here\nif ~isfield(option,'quadorder')\n option.quadorder = 6; % default order\nend\n[lambda, weight] = quadpts(option.quadorder);\nnQuad = size(lambda,1);\nii = zeros(55*NT,1); jj = zeros(55*NT,1); sA = zeros(55*NT,nQuad);sB = zeros(55*NT,nQuad);\nindex = 0;\nfor i = 1:10\n for j = i:10\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\nfor p = 1:nQuad\n % Dphi at quadrature points\n Dphi(:,:,1) = (27/2*lambda(p,1)*lambda(p,1)-9*lambda(p,1)+1).*Dlambda(:,:,1); \n Dphi(:,:,2) = (27/2*lambda(p,2)*lambda(p,2)-9*lambda(p,2)+1).*Dlambda(:,:,2); \n Dphi(:,:,3) = (27/2*lambda(p,3)*lambda(p,3)-9*lambda(p,3)+1).*Dlambda(:,:,3);\n Dphi(:,:,4) = 9/2*((3*lambda(p,2)*lambda(p,2)-lambda(p,2)).*Dlambda(:,:,3)+...\n lambda(p,3)*(6*lambda(p,2)-1).*Dlambda(:,:,2)); \n Dphi(:,:,5) = 9/2*((3*lambda(p,3)*lambda(p,3)-lambda(p,3)).*Dlambda(:,:,2)+...\n lambda(p,2)*(6*lambda(p,3)-1).*Dlambda(:,:,3)); \n Dphi(:,:,6) = 9/2*((3*lambda(p,3)*lambda(p,3)-lambda(p,3)).*Dlambda(:,:,1)+...\n lambda(p,1)*(6*lambda(p,3)-1).*Dlambda(:,:,3)); \n Dphi(:,:,7) = 9/2*((3*lambda(p,1)*lambda(p,1)-lambda(p,1)).*Dlambda(:,:,3)+...\n lambda(p,3)*(6*lambda(p,1)-1).*Dlambda(:,:,1)); \n Dphi(:,:,8) = 9/2*((3*lambda(p,1)*lambda(p,1)-lambda(p,1)).*Dlambda(:,:,2)+...\n lambda(p,2)*(6*lambda(p,1)-1).*Dlambda(:,:,1)); \n Dphi(:,:,9) = 9/2*((3*lambda(p,2)*lambda(p,2)-lambda(p,2)).*Dlambda(:,:,1)+...\n lambda(p,1)*(6*lambda(p,2)-1).*Dlambda(:,:,2)); \n Dphi(:,:,10) = 27*(lambda(p,1)*lambda(p,2)*Dlambda(:,:,3)+lambda(p,1)*lambda(p,3)*Dlambda(:,:,2)+...\n lambda(p,3)*lambda(p,2)*Dlambda(:,:,1)); \n phi(:,1) = 0.5*(3*lambda(:,1)-1).*(3*lambda(:,1)-2).*lambda(:,1); \n phi(:,2) = 0.5*(3*lambda(:,2)-1).*(3*lambda(:,2)-2).*lambda(:,2); \n phi(:,3) = 0.5*(3*lambda(:,3)-1).*(3*lambda(:,3)-2).*lambda(:,3);\n phi(:,4) = 9/2*lambda(:,3).*lambda(:,2).*(3*lambda(:,2)-1); \n phi(:,5) = 9/2*lambda(:,3).*lambda(:,2).*(3*lambda(:,3)-1); \n phi(:,6) = 9/2*lambda(:,1).*lambda(:,3).*(3*lambda(:,3)-1); \n phi(:,7) = 9/2*lambda(:,1).*lambda(:,3).*(3*lambda(:,1)-1); \n phi(:,8) = 9/2*lambda(:,1).*lambda(:,2).*(3*lambda(:,1)-1);\n phi(:,9) = 9/2*lambda(:,1).*lambda(:,2).*(3*lambda(:,2)-1); \n phi(:,10) = 27*lambda(:,1).*lambda(:,2).*lambda(:,3); \n index = 0;\n for i = 1:10\n for j = i:10\n Bij = 0;\n Aij = 0;\n Bij = Bij + weight(p)*dot(Dphi(:,:,i),Dphi(:,:,j),2);\n Aij = Aij + weight(p)*dot(phi(p,i),phi(p,j),2);\n Bij = Bij.*area;\n Aij = Aij.*area;\n ii(index+1:index+NT) = double(elem2dof(:,i)); \n jj(index+1:index+NT) = double(elem2dof(:,j));\n sB(index+1:index+NT,p) = Bij;\n sA(index+1:index+NT,p) = Aij; \n index = index + NT;\n end\n end\nend\n\nsA = sum(sA,2);\nsB = sum(sB,2);\nclear Aij Bij\ndiagIdx = (ii == jj); upperIdx = ~diagIdx;\nB = sparse(ii(diagIdx),jj(diagIdx),sB(diagIdx),Ndof,Ndof);\nA = sparse(ii(diagIdx),jj(diagIdx),sA(diagIdx),Ndof,Ndof);\n% A = spdiags(accumarray(ii(diagIdx),sA(diagIdx),[Ndof 1]),0,Ndof,Ndof);\nBU = sparse(ii(upperIdx),jj(upperIdx),sB(upperIdx),Ndof,Ndof);\nAU = sparse(ii(upperIdx),jj(upperIdx),sA(upperIdx),Ndof,Ndof);\nB = B + BU + BU';\nA = A + AU + AU';\n\n \n \n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% % subfunction Dphi\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% function s = Dphi(p,i) % gradient of basis phi\n% switch i\n% case 1\n% s =(27/2*lambda(p,1)*lambda(p,1)-9*lambda(p,1)+1).*Dlambda(:,:,1); \n% case 2\n% s =(27/2*lambda(p,2)*lambda(p,2)-9*lambda(p,2)+1).*Dlambda(:,:,2); \n% case 3\n% s =(27/2*lambda(p,3)*lambda(p,3)-9*lambda(p,3)+1).*Dlambda(:,:,3);\n% case 4\n% s =9/2*((3*lambda(p,2)*lambda(p,2)-lambda(p,2)).*Dlambda(:,:,3)+...\n% lambda(p,3)*(6*lambda(p,2)-1).*Dlambda(:,:,2)); \n% case 5\n% s =9/2*((3*lambda(p,3)*lambda(p,3)-lambda(p,3)).*Dlambda(:,:,2)+...\n% lambda(p,2)*(6*lambda(p,3)-1).*Dlambda(:,:,3)); \n% \n% case 6\n% s =9/2*((3*lambda(p,3)*lambda(p,3)-lambda(p,3)).*Dlambda(:,:,1)+...\n% lambda(p,1)*(6*lambda(p,3)-1).*Dlambda(:,:,3)); \n% case 7\n% s =9/2*((3*lambda(p,1)*lambda(p,1)-lambda(p,1)).*Dlambda(:,:,3)+...\n% lambda(p,3)*(6*lambda(p,1)-1).*Dlambda(:,:,1)); \n% case 8\n% s =9/2*((3*lambda(p,1)*lambda(p,1)-lambda(p,1)).*Dlambda(:,:,2)+...\n% lambda(p,2)*(6*lambda(p,1)-1).*Dlambda(:,:,1)); \n% \n% case 9\n% s =9/2*((3*lambda(p,2)*lambda(p,2)-lambda(p,2)).*Dlambda(:,:,1)+...\n% lambda(p,1)*(6*lambda(p,2)-1).*Dlambda(:,:,2)); \n% case 10\n% s = 27*(lambda(p,1)*lambda(p,2)*Dlambda(:,:,3)+lambda(p,1)*lambda(p,3)*Dlambda(:,:,2)+...\n% lambda(p,3)*lambda(p,2)*Dlambda(:,:,1));\n% \n% end\n% end\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% \n% \n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% % subfunction phi\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% function s = phi(p,i) % gradient of basis phi\n% switch i\n% case 1\n% s = 0.5*(3*lambda(p,1)-1).*(3*lambda(p,1)-2).*lambda(p,1); \n% case 2\n% s = 0.5*(3*lambda(p,2)-1).*(3*lambda(p,2)-2).*lambda(p,2); \n% case 3\n% s = 0.5*(3*lambda(p,3)-1).*(3*lambda(p,3)-2).*lambda(p,3);\n% case 4\n% s = 9/2*lambda(p,3).*lambda(p,2).*(3*lambda(p,2)-1); \n% case 5\n% s = 9/2*lambda(p,3).*lambda(p,2).*(3*lambda(p,3)-1); \n% case 6\n% s = 9/2*lambda(p,1).*lambda(p,3).*(3*lambda(p,3)-1); \n% case 7\n% s = 9/2*lambda(p,1).*lambda(p,3).*(3*lambda(p,1)-1); \n% case 8\n% s = 9/2*lambda(p,1).*lambda(p,2).*(3*lambda(p,1)-1);\n% case 9\n% s = 9/2*lambda(p,1).*lambda(p,2).*(3*lambda(p,2)-1); \n% case 10\n% s = 27*lambda(p,1).*lambda(p,2).*lambda(p,3); \n% end\n% end\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%% Assemble right hand side by high order quadrature rule\n% To reduce the effect of the error introduced by the numerical quadrature,\n% the load term is computed using the 3rd order qudrature rule.\nb = zeros(Ndof,1);\nu = zeros(Ndof,1);\nw = zeros(Ndof,1);\n\nif ~isfield(option,'fquadorder')\n option.fquadorder = 6; % 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,w] = quadpts(option.fquadorder);\n nQuad = size(lambda,1);\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% phi(:,6) = 4*lambda(:,1).*lambda(:,2);\n bt = zeros(NT,10);\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 if isfield(pde,'f') && isnumeric(pde.f)\n fp = pde.f; % piecewise constant \n else\n fp = pde.f(pxy); % function handle\n end\n for j = 1:10\n bt(:,j) = bt(:,j) + w(p)*phi(p,j)*fp;\n end\n end\n bt = bt.*repmat(area,1,10);\n b = accumarray(elem2dof(:),bt(:),[Ndof 1]); \nend\n\n[b1,u] = getbdP3(b);\n% b1 is the first part of the right sides, b is the second part of right sides\n\n function [b1,u] = getbdP3(b)\n %% Boundary conditions for Poisson equation: P3 quadratic FEM.\n %\n % The set up of boundary condition consists of two parts: \n %\n\n %\n % Modify the right hand side b. The Neumann boundary integral is added\n % to b. For Dirichlet boundary ndoes, b(fixedDof) is the evaluation of\n % pde.g_D.\n %\n % Special attentation should be given for the pure Neumann boundary\n % condition. To enforce the compatible condition, the vector b should have\n % mean value zero. To avoid a singular matrix, the 1st node is chosen as\n % fixedDof. \n %\n % The order of assigning Neumann and Dirichlet boundary condition is\n % important to get the right setting at the intersection nodes of Dirichlet\n % and Neumann boundary edges.\n\n u = zeros(Ndof,1);\n\n %% Part 1: Find boundary edges and modify the load b \n % Neumann boundary condition\n if ~isfield(option,'gNquadorder')\n option.gNquadorder = 6; \n end \n b1 = zeros(Ndof,1);\n [lambdagN,weightgN] = quadpts1(option.gNquadorder);\n idxN = (bdFlag(:) == 1); % all Neumann edges in bdFlag \n Neumannidx = elem2edge(idxN ); % index of Neumann and Robin edges\n % since boundary integral is also needed for Robin edges\n Neumann = edge(Neumannidx,:);\n \n nQuadgN = size(lambdagN,1);\n % quadratic bases (1---3---4--2)\n bdphi = zeros(nQuadgN,4); \n bdphi(:,1) = 0.5*(3*lambdagN(:,1)-1).*(3*lambdagN(:,1)-2).*lambdagN(:,1); \n bdphi(:,2) = 0.5*(3*lambdagN(:,2)-1).*(3*lambdagN(:,2)-2).*lambdagN(:,2);\n bdphi(:,3) = 9/2*lambdagN(:,1).*lambdagN(:,2).*(3*lambdagN(:,1)-1);\n bdphi(:,4) = 9/2*lambdagN(:,1).*lambdagN(:,2).*(3*lambdagN(:,2)-1);\n % length of edge\n \n el = sqrt(sum((node(Neumann(:,1),:) - node(Neumann(:,2),:)).^2,2));\n ge = zeros(size(Neumann,1),4);\n for pp = 1:nQuadgN\n ppxy = lambdagN(pp,1)*node(Neumann(:,1),:) ...\n + lambdagN(pp,2)*node(Neumann(:,2),:);\n gNu = pde.g_N(ppxy);\n ge(:,1) = ge(:,1) + weightgN(pp)*gNu*bdphi(pp,1);\n ge(:,2) = ge(:,2) + weightgN(pp)*gNu*bdphi(pp,2);\n ge(:,3) = ge(:,3) + weightgN(pp)*gNu*bdphi(pp,3); \n ge(:,4) = ge(:,4) + weightgN(pp)*gNu*bdphi(pp,4);\n end\n ge = ge.*repmat(el,1,4);\n b1(1:N) = accumarray(Neumann(:), [ge(:,1); ge(:,2)],[N,1]);\n b1(N+2*Neumannidx-1) = b1(N+2*Neumannidx-1) + ge(:,3);\n b1(N+2*Neumannidx) = b1(N+2*Neumannidx) + ge(:,4);\n\n %% Part 2: Find Dirichlet boundary edges and compute the boundary value\n % Dirichlet boundary conditions\n \n isDirichlet(elem2edge(bdFlag(:)==1)) = true;\n % interpolation\n idx = (fixedDof > N); % index of edge nodes\n u(fixedDof(~idx)) = pde.g_D(node(fixedDof(~idx),:)); % bd value at vertex dofs\n % for P3, we should divide the points of edge into two parts. \n bdEdgeIdx = fixedDof(idx) - N;\n % First parts, the points * is in 1---*------2\n bdEdgeMid = node(edge(isDirichlet,1),:)+(node(edge(isDirichlet,2),:) ...\n - node(edge(isDirichlet,1),:))/3;\n u(N + bdEdgeIdx(1:2:end)) = pde.g_D(bdEdgeMid);\n % Second parts, the points * is in 1------*---2 \n bdEdgeMid = node(edge(isDirichlet,1),:)+2*(node(edge(isDirichlet,2),:)...\n - node(edge(isDirichlet,1),:))/3; \n u(N + bdEdgeIdx(2:2:end)) = pde.g_D(bdEdgeMid);\n % modify the right hand side\n b1 = b1 - B*u;\n %b1(fixedDof) = u(fixedDof);\n\n end % end of getbdP3\n\nB(:,fixedDof)=[];\nNu = Ndof-size(fixedDof,1);\n\n\nb(fixedDof) = [];\n bigA = [A, B; ...\n B', sparse(Nu,Nu)];\n bigF = [b1; -b];\n% Solver\n%bigU=PFGMRES(bigA, bigF,sparse(Ndof+Nu,1), Ndof, 10, 1e-6, [],[]);\ntic;\nbigU=bigA\\bigF;\ntoc;\n% norm(bigA*bigU-bigF)\n% norm(bigA*[p;u(freeDof)]-bigF)\n w=bigU(1:Ndof);\n u(freeDof)=bigU(Ndof+1:Ndof+Nu);\n\nend % end of function PoissonP2", "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/equation/biharmonicP3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.48508944257515846}} {"text": "function q = ch_qnormlz(q)\n% å››å…ƒę•°å½’äø€åŒ–\n q = q/norm(q);\n if(q(1)<0)\n q(1) = -q(1);\n q(2) = -q(2);\n q(3) = -q(3);\n q(4) = -q(4);\n end", "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/lib/rotation/ch_qnormlz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.48508943878247035}} {"text": "function I = domIntegral6(data)\n%+========================================================================+\n%| |\n%| OPENDOM - LIBRARY FOR NUMERICAL INTEGRATION |\n%| openDom is part of the GYPSILAB toolbox for Matlab |\n%| |\n%| COPYRIGHT : Matthieu Aussal & Francois Alouges (c) 2017-2018. |\n%| PROPERTY : Centre de Mathematiques Appliquees, Ecole polytechnique, |\n%| route de Saclay, 91128 Palaiseau, France. All rights reserved. |\n%| LICENCE : This program is free software, distributed in the hope that|\n%| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use, |\n%| redistribute and/or modify it under the terms of the GNU General Public|\n%| License, as published by the Free Software Foundation (version 3 or |\n%| later, http://www.gnu.org/licenses). For private use, dual licencing |\n%| is available, please contact us to activate a \"pay for remove\" option. |\n%| CONTACT : matthieu.aussal@polytechnique.edu |\n%| francois.alouges@polytechnique.edu |\n%| WEBSITE : www.cmap.polytechnique.fr/~aussal/gypsilab Ā Ā Ā Ā  |\n%| |\n%| Please acknowledge the gypsilab toolbox in programs or publications in |\n%| which you use it. |\n%|________________________________________________________________________|\n%| '&` | |\n%| # | FILE : domIntegral6.m |\n%| # | VERSION : 0.61 |\n%| _#_ | AUTHOR(S) : Matthieu Aussal |\n%| ( # ) | CREATION : 14.03.2017 |\n%| / 0 \\ | LAST MODIF : 05.09.2019 |\n%| ( === ) | SYNOPSIS : Numerical integation with 6 input arguments |\n%| `---' | |\n%+========================================================================+\n\n%%% H-MATRIX BOUNDARY ELEMENT OPERATOR --> \\int_{mesh(x)} \\int_{mesh(y)} psi(x)' f(x,y) psi(y) dxdy\nif isa(data{1},'dom') && isa(data{2},'dom')\n % Domain with quadrature\n Xdom = data{1};\n [X,Wx] = Xdom.qud;\n Nx = size(X,1);\n Wx = spdiags(Wx,0,Nx,Nx);\n \n % Domain with quadrature\n Ydom = data{2};\n [Y,Wy] = Ydom.qud;\n Ny = size(Y,1);\n Wy = spdiags(Wy,0,Ny,Ny);\n \n % Finite element matrix with integration\n u = data{3};\n Mu = u.uqm(Xdom);\n if iscell(Mu)\n Mu{1} = Mu{1}' * Wx;\n Mu{2} = Mu{2}' * Wx;\n Mu{3} = Mu{3}' * Wx;\n else\n Mu = Mu' * Wx;\n end\n \n % Green kernel\n green = data{4};\n \n % Finite element matrix with integration\n v = data{5};\n Mv = v.uqm(Ydom);\n if iscell(Mv)\n Mv{1} = Wy * Mv{1};\n Mv{2} = Wy * Mv{2};\n Mv{3} = Wy * Mv{3};\n else\n Mv = Wy * Mv;\n end\n \n % Accuracy\n tol = data{6};\n \n % H-Matrix Integration\n if iscell(Mu) && ~iscell(green) && ~iscell(Mv)\n I{1} = hmx(u.unk,v.unk,Mu{1},X,green,Y,Mv,tol);\n I{2} = hmx(u.unk,v.unk,Mu{2},X,green,Y,Mv,tol);\n I{3} = hmx(u.unk,v.unk,Mu{3},X,green,Y,Mv,tol);\n \n elseif ~iscell(Mu) && iscell(green) && ~iscell(Mv)\n I{1} = hmx(u.unk,v.unk,Mu,X,green{1},Y,Mv,tol);\n I{2} = hmx(u.unk,v.unk,Mu,X,green{2},Y,Mv,tol);\n I{3} = hmx(u.unk,v.unk,Mu,X,green{3},Y,Mv,tol);\n \n elseif ~iscell(Mu) && ~iscell(green) && iscell(Mv)\n I{1} = hmx(u.unk,v.unk,Mu,X,green,Y,Mv{1},tol);\n I{2} = hmx(u.unk,v.unk,Mu,X,green,Y,Mv{2},tol);\n I{3} = hmx(u.unk,v.unk,Mu,X,green,Y,Mv{3},tol);\n \n else\n I = hmx(u.unk,v.unk,Mu,X,green,Y,Mv,tol);\n end\n\n\n%%% FFM BOUNDARY ELEMENT INTEGRATION --> \\int_{mesh(y)} f(x,y) psi(y) dy\nelseif isnumeric(data{1}) && isa(data{2},'dom')\n % Evaluation points \n X = data{1};\n Nx = size(X,1);\n Mx = speye(Nx,Nx);\n \n % Domain with quadrature\n Ydom = data{2};\n [Y,Wy] = Ydom.qud;\n Ny = size(Y,1);\n Wy = spdiags(Wy,0,Ny,Ny);\n \n % Green kernel\n green = data{3};\n \n % Wave number\n k = data{4};\n \n % Integrated finite element matrix\n v = data{5};\n Mv = v.uqm(Ydom);\n if iscell(Mv)\n Mv{1} = Wy * Mv{1};\n Mv{2} = Wy * Mv{2};\n Mv{3} = Wy * Mv{3};\n else\n Mv = Wy * Mv;\n end\n \n % Accuracy\n tol = data{6};\n \n % Fast & Furious integration\n if iscell(Mv) && iscell(green)\n I = ffm(Mx,X,green{1},k,Y,Mv{1},tol) + ...\n ffm(Mx,X,green{2},k,Y,Mv{2},tol) + ...\n ffm(Mx,X,green{3},k,Y,Mv{3},tol);\n \n elseif iscell(Mv) && ~iscell(green)\n I{1} = ffm(Mx,X,green,k,Y,Mv{1},tol);\n I{2} = ffm(Mx,X,green,k,Y,Mv{2},tol);\n I{3} = ffm(Mx,X,green,k,Y,Mv{3},tol);\n \n elseif ~iscell(Mv) && iscell(green)\n I{1} = ffm(Mx,X,green{1},k,Y,Mv,tol);\n I{2} = ffm(Mx,X,green{2},k,Y,Mv,tol);\n I{3} = ffm(Mx,X,green{3},k,Y,Mv,tol);\n \n else\n I = ffm(Mx,X,green,k,Y,Mv,tol);\n end\n\n \n%%% FFM BOUNDARY ELEMENT INTEGRATION --> \\int_{mesh(x)} psi(x)' f(x,y) dx\nelseif isa(data{1},'dom') && isnumeric(data{2})\n % Domain with quadrature\n Xdom = data{1};\n [X,Wx] = Xdom.qud;\n Nx = size(X,1);\n Wx = spdiags(Wx,0,Nx,Nx);\n \n % Evaluation points\n Y = data{2};\n Ny = size(Y,1);\n My = speye(Ny,Ny);\n \n % Integrated finite element matrix\n u = data{3};\n Mu = u.uqm(Xdom);\n if iscell(Mu)\n Mu{1} = Mu{1}' * Wx;\n Mu{2} = Mu{2}' * Wx;\n Mu{3} = Mu{3}' * Wx;\n else\n Mu = Mu' * Wx;\n end \n \n % Green kernel\n green = data{4};\n \n % Wave number\n k = data{5};\n\n % Accuracy\n tol = data{6};\n \n % Fast & Furious integration\n if iscell(Mu) && iscell(green)\n I = ffm(Mu{1},X,green{1},k,Y,My,tol) + ...\n ffm(Mu{2},X,green{2},k,Y,My,tol) + ...\n ffm(Mu{3},X,green{3},k,Y,My,tol) ;\n \n elseif iscell(Mu) && ~iscell(green)\n I{1} = ffm(Mu{1},X,green,k,Y,My,tol);\n I{2} = ffm(Mu{2},X,green,k,Y,My,tol);\n I{3} = ffm(Mu{3},X,green,k,Y,My,tol);\n \n elseif ~iscell(Mu) && iscell(green)\n I{1} = ffm(Mu,X,green{1},k,Y,My,tol);\n I{2} = ffm(Mu,X,green{2},k,Y,My,tol);\n I{3} = ffm(Mu,X,green{3},k,Y,My,tol);\n \n else\n I = ffm(Mu,X,green,k,Y,My,tol);\n end\n\n \nelse\n error('domIntegral6.m : unavailable case')\nend\nend\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/gypsilabModified/openDom/domIntegral6.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4850686000011511}} {"text": "\nfunction [u v] = coarse_to_fine(I1, I2, settings, show_flow, h)\n\n[M N] = size(I1);\n\n% computes the maximum number of pyramid levels; the coarsest image should\n% have a width or height around 10\npyramid_levels = min(...\n ceil(log(10/M)/log(settings.pyramid_factor)), ...\n ceil(log(10/N)/log(settings.pyramid_factor)));\n\npyrI1 = cell(pyramid_levels, 1);\npyrI2 = cell(pyramid_levels, 1);\n\npyrI1{1} = I1;\npyrI2{1} = I2;\n\n% build the pyramids\nfor i = 2:pyramid_levels\n pyrI1{i} = imresize(I1, (settings.pyramid_factor)^(i-1), settings.resampling_method);\n pyrI2{i} = imresize(I2, (settings.pyramid_factor)^(i-1), settings.resampling_method); \nend\n\n% start coarse to fine processing\nfor level = pyramid_levels:-1:1;\n \n [M N] = size(pyrI1{level});\n if level == pyramid_levels\n \n % initialization \n u = zeros(M, N);\n v = zeros(M, N);\n \n pu = zeros(M, N, 2);\n pv = zeros(M, N, 2);\n \n else \n % previous dimensions\n [Mp Np] = size(pyrI1{level+1}); \n \n % upsample the flow to next level\n u = imresize(u, [M N], settings.resampling_method) * N/Np; \n v = imresize(v, [M N], settings.resampling_method) * M/Mp;\n\n pu_tmp = pu;\n pv_tmp = pv;\n \n pu = zeros(M, N, 2);\n pv = zeros(M, N, 2);\n \n for i=1:2\n pu(:,:,i) = imresize(pu_tmp(:,:,i), [M N], settings.resampling_method);\n pv(:,:,i) = imresize(pv_tmp(:,:,i), [M N], settings.resampling_method);\n end\n end \n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % solve the optical flow on the current level\n [u, v, pu, pv] = solve_flow_on_level(u, v, pu, pv, pyrI1{level}, pyrI2{level}, settings, level, show_flow, h); \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \nend", "meta": {"author": "thomas-koehler", "repo": "SupER", "sha": "d8c6f2e4b26db002ff55bc2beba18639f1d0bb49", "save_path": "github-repos/MATLAB/thomas-koehler-SupER", "path": "github-repos/MATLAB/thomas-koehler-SupER/SupER-d8c6f2e4b26db002ff55bc2beba18639f1d0bb49/matlab/algorithms/SRAlgorithms/VSRnet/external_functions/CLG-TV-matlab/coarse_to_fine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.48502870747995996}} {"text": "function [update] = ...\n polynomial_expansion_registration3d(moving, fixed, varargin)\n% POLYNOMIAL_EXPANSION_REGISTRATION3D Estimates a displacement field using polynomial expansion\n%\n% INPUT ARGUMENTS\n% moving - Moving image\n% fixed - Fixed image\n% \n% OPTIONAL INPUT ARGUMENTS\n% 'signalModel' - Local signal model to use when computing the\n% polynomial expansion transformation\n% 'linear' (deafult), 'quadratic'\n%\n% 'transformationModel' - Transformation model for estimating the\n% displacement field\n% translation, affine, non-rigid (default)\n%\n% 'multiModal' - Set wheteher to perform multi-modal or\n% uni-modal image registration\n% false (default), true\n%\n% 'numberOfChannels' - Number of channels to use in when computing\n% the entropy (based on channel coding). This\n% is only relevant if multiModal is set to\n% true.\n% Default value is 8\n%\n% OUTPUT ARGUMENTS\n% update\n% displacementUpdate - Estimated update field\n% certaintyUpdate - Certainty related to the estimated update field\n% transformationMatrix - Estimate transformation matrix (only if \n% transformation model is set to translation or affine)\n\n\n% Copyright (c) 2012 Daniel Forsberg\n% danne.forsberg@outlook.com\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 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%% Setup default parameters\n% linear, quadratic\nsignalModel = 'linear';\n\n% translation, affine, non-rigid\ntransformationModel = 'non-rigid';\nmultiModal = false;\n\n% Only valid for multi-modal registration\nnumberOfChannels = 16;\n\n% Only valid for non-rigid registration\nsigma = 1.5;\nalpha = 0.01;\n\n% Overwrites default parameter\nfor k=1:2:length(varargin)\n eval([varargin{k},'=varargin{',int2str(k+1),'};']);\nend;\n\n%% Perform polynomial expansion\nif strcmp(signalModel,'quadratic')\n [A_moving, b_moving, c_moving] = make_Abc_fast(moving);\n [A_fixed, b_fixed, c_fixed] = make_Abc_fast(fixed);\n \n A = (A_moving + A_fixed)/2;\n delta_b = b_fixed - b_moving;\nelse\n [b_moving, c_moving] = make_bc_fast(moving);\n [b_fixed, c_fixed] = make_bc_fast(fixed);\n if multiModal\n b = b_fixed;\n \n [delta_c mask] = estimate_delta_c(c_fixed,c_moving,numberOfChannels);\n delta_c(mask ~= 1) = 0;\n mask = repmat(mask,[1 1 1 3]);\n b(mask ~= 1) = 0;\n else\n b = (b_moving + b_fixed)/2;\n \n delta_c = c_fixed - c_moving;\n end \nend\n\nif strcmp(signalModel,'quadratic')\n switch transformationModel\n case 'translation'\n [G, h] = build_G_h_quadratic3d(A, delta_b, transformationModel);\n d = G \\ h;\n update.transformationMatrix = eye(4);\n update.transformationMatrix(1:3,4) = d;\n case {'rigid','affine'}\n [G, h] = build_G_h_quadratic3d(A, delta_b, transformationModel);\n p = G \\ h;\n \n update.transformationMatrix = eye(4);\n update.transformationMatrix(1:3,1:4) = [1+p(1) p(2) p(3) p(10);...\n p(4) 1+p(5) p(6) p(11);...\n p(7) p(8) 1+p(9) p(12)];\n case 'non-rigid'\n A11 = A(:,:,:,5);\n A12 = 2*A(:,:,:,4);\n A13 = 2*A(:,:,:,8);\n A21 = 2*A(:,:,:,2);\n A22 = A(:,:,:,1);\n A23 = 2*A(:,:,:,7);\n A31 = 2*A(:,:,:,6);\n A32 = 2*A(:,:,:,3);\n A33 = A(:,:,:,9);\n B1 = delta_b(:,:,:,2);\n B2 = delta_b(:,:,:,1);\n B3 = delta_b(:,:,:,3);\n \n % Set the elements of the equation system\n G11 = A11.^2 + A21.^2 + A31.^2;\n G12 = A11.*A12 + A21.*A22 + A31.*A32;\n G13 = A11.*A13 + A21.*A23 + A31.*A33;\n G22 = A12.^2 + A22.^2 + A32.^2;\n G23 = A12.*A13 + A22.*A23 + A32.*A33;\n G33 = A13.^2 + A23.^2 + A33.^2;\n H1 = A11.*B1 + A21.*B2 + A31.*B3;\n H2 = A12.*B1 + A22.*B2 + A32.*B3;\n H3 = A13.*B1 + A23.*B2 + A33.*B3;\n \n % Smooth the elements of the equation system\n G11 = gauss_smoothing(G11, sigma);\n G12 = gauss_smoothing(G12, sigma);\n G13 = gauss_smoothing(G13, sigma);\n G22 = gauss_smoothing(G22, sigma);\n G23 = gauss_smoothing(G23, sigma);\n G33 = gauss_smoothing(G33, sigma);\n H1 = gauss_smoothing(H1, sigma);\n H2 = gauss_smoothing(H2, sigma);\n H3 = gauss_smoothing(H3, sigma);\n \n % Add alpha*identity matrix for stability\n scaleFactor = max([G11(:); G22(:); G33(:)]);\n G11 = G11 + alpha * scaleFactor;\n G22 = G22 + alpha * scaleFactor;\n G33 = G33 + alpha * scaleFactor;\n \n det = G33.*G12.^2 - 2*G12.*G13.*G23 + G22.*G13.^2 + G11.*G23.^2 - G11.*G22.*G33;\n \n % Estimate the displacement field\n update.displacement = cell(3,1);\n update.displacement{1} = removenan((H1.*(G23.^2 - G22.*G33) - ...\n H3.*(G12.*G23 - G13.*G22) - ...\n H2.*(G13.*G23 - G12.*G33))./(det + eps));\n update.displacement{2} = removenan((H2.*(G13.^2 - G11.*G33) - ...\n H3.*(G12.*G13 - G11.*G23) - ...\n H1.*(G13.*G23 - G12.*G33))./(det + eps));\n update.displacement{3} = removenan((H3.*(G12.^2 - G11.*G22) - ...\n H2.*(G12.*G13 - G11.*G23) - ...\n H1.*(G12.*G23 - G13.*G22))./(det + eps));\n \n % Estimate a certainty\n update.certainty = sqrt(b_fixed(:,:,:,2).^2 + b_fixed(:,:,:,1).^2 + b_fixed(:,:,:,3).^2);\n end\nelse\n switch transformationModel\n case 'translation'\n [G, h] = build_G_h_linear3d(b, delta_c, transformationModel);\n d = G \\ h;\n update.transformationMatrix = eye(4);\n update.transformationMatrix(1:3,4) = d;\n case {'rigid','affine'}\n [G, h] = build_G_h_linear3d(b, delta_c, transformationModel);\n p = G \\ h;\n \n update.transformationMatrix = eye(4);\n update.transformationMatrix(1:3,1:4) = [1+p(1) p(2) p(3) p(10);...\n p(4) 1+p(5) p(6) p(11);...\n p(7) p(8) 1+p(9) p(12)];\n case 'non-rigid'\n % Set the elements of the equation system\n % Set the elements of the equation system\n G11 = b(:,:,:,2) .* b(:,:,:,2);\n G12 = b(:,:,:,2) .* b(:,:,:,1);\n G13 = b(:,:,:,2) .* b(:,:,:,3);\n G22 = b(:,:,:,1) .* b(:,:,:,1);\n G23 = b(:,:,:,1) .* b(:,:,:,3);\n G33 = b(:,:,:,3) .* b(:,:,:,3);\n H1 = b(:,:,:,2) .* delta_c;\n H2 = b(:,:,:,1) .* delta_c;\n H3 = b(:,:,:,3) .* delta_c;\n \n % Smooth the elements of the equation system\n G11 = gauss_smoothing(G11, sigma);\n G12 = gauss_smoothing(G12, sigma);\n G13 = gauss_smoothing(G13, sigma);\n G22 = gauss_smoothing(G22, sigma);\n G23 = gauss_smoothing(G23, sigma);\n G33 = gauss_smoothing(G33, sigma);\n H1 = gauss_smoothing(H1, sigma);\n H2 = gauss_smoothing(H2, sigma);\n H3 = gauss_smoothing(H3, sigma);\n \n % Add alpha*identity matrix for stability\n scaleFactor = max([G11(:); G22(:); G33(:)]);\n G11 = G11 + alpha * scaleFactor;\n G22 = G22 + alpha * scaleFactor;\n G33 = G33 + alpha * scaleFactor;\n \n det = G33.*G12.^2 - 2*G12.*G13.*G23 + G22.*G13.^2 + G11.*G23.^2 - G11.*G22.*G33;\n \n % Estimate the displacement field\n update.displacement = cell(3,1);\n update.displacement{1} = removenan((H1.*(G23.^2 - G22.*G33) - ...\n H3.*(G12.*G23 - G13.*G22) - ...\n H2.*(G13.*G23 - G12.*G33))./(det + eps));\n update.displacement{2} = removenan((H2.*(G13.^2 - G11.*G33) - ...\n H3.*(G12.*G13 - G11.*G23) - ...\n H1.*(G13.*G23 - G12.*G33))./(det + eps));\n update.displacement{3} = removenan((H3.*(G12.^2 - G11.*G22) - ...\n H2.*(G12.*G13 - G11.*G23) - ...\n H1.*(G12.*G23 - G13.*G22))./(det + eps));\n \n % Estimate a certainty\n update.certainty = sqrt(b(:,:,:,2).^2 + b(:,:,:,1).^2 + b(:,:,:,3).^2);\n end\nend\n", "meta": {"author": "fordanic", "repo": "image-registration", "sha": "36c23d5da1f035b07c66a04fe5bac20de1bd1c74", "save_path": "github-repos/MATLAB/fordanic-image-registration", "path": "github-repos/MATLAB/fordanic-image-registration/image-registration-36c23d5da1f035b07c66a04fe5bac20de1bd1c74/registration/polynomial-expansion/polynomial_expansion_registration3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4850287016455469}} {"text": "function [parameters,ll,Ht,VCV,scores] = gogarch(data,p,q,gjrType,type,startingVals,options)\n% OGARCH(p,q) and GOGARCH(p,q) multivarate volatility model estimation\n%\n% USAGE:\n% [PARAMETERS] = rarch(DATA,P,Q)\n% [PARAMETERS,LL,HT,VCV,SCORES] = gogarch(DATA,P,Q,GJRTYPE,TYPE,STARTINGVALS,OPTIONS)\n%\n% INPUTS:\n% DATA - A T by K matrix of zero mean residuals -OR-\n% K by K by T array of covariance estimators (e.g. realized covariance)\n% P - Positive, scalar integer representing the number of symmetric innovations. Can\n% also be a K by 1 vector with lag lengths for each series.\n% Q - Non-negative, scalar integer representing the number of conditional covariance\n% lags Can also be a K by 1 vector with lag lengths for each series.\n % GJRTYPE - [OPTIONAL] Either 1 (TARCH/AVGARCH) or 2 (GJR-GARCH/GARCH/ARCH). Can also be a K \n% by 1 vector containing the model type for each for each series. Default is 2.\n% TYPE - [OPTIONAL] String, one of 'GOGARCH' (Default) or 'OGARCH'\n% STARTINGVALS - [OPTIONAL] Vector of starting values to use. See parameters and COMMENTS.\n% OPTIONS - [OPTIONAL] Options to use in the model optimization (fmincon)\n%\n% OUTPUTS:\n% PARAMETERS - Estimated parameters in the order:\n% OGARCH:\n% [vol(1) ... vol(K)]\n% GOGARCH:\n% [phi(1) ... phi(K(K-1)/2) vol(1) ... vol(K)]\n% where vol(i) = [alpha(i,1) ... alpha(i,P(i)) beta(i,1) ... beta(i,Q(i))]\n% LL - The log likelihood at the optimum\n% HT - A [K K T] dimension matrix of conditional covariances\n% VCV - A numParams^2 square matrix of robust parameter covariances (A^(-1)*B*A^(-1)/T)\n% SCORES - A T by numParams matrix of individual scores\n%\n% COMMENTS:\n% The orthonormal matrix is constructed from K(K-1)/2 angles using PHI2U\n%\n%\n% EXAMPLES:\n% % OGARCH(1,1)\n% parameters = gogarch(data,1,1,[],'OGARCH')\n% % GOGARCH(1,1)\n% parameters = gogarch(data,1,1)\n%\n% See also BEKK, RARCH, DCC, TARCH, PHI2U\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 1 Date: 4/15/2012\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Argument Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nswitch nargin\n case 3\n gjrType = [];\n type = [];\n startingVals = [];\n options = [];\n case 4\n type = [];\n startingVals = [];\n options = [];\n case 5\n startingVals = [];\n options = [];\n case 6\n options = [];\n case 7\n % Nothing\n otherwise\n error('3 to 7 inputs required.')\nend\n\nif ndims(data)==3\n [k,~,T] = size(data);\nelse\n [T,k] = size(data);\n temp = zeros(k,k,T);\n for t=1:T\n temp(:,:,t) = data(t,:)'*data(t,:);\n end\n data = temp;\nend\n\nif isscalar(p)\n p = ones(k,1)*p;\nend\nif isscalar(q)\n q = ones(k,1)*q;\nend\n\nif isempty(gjrType)\n gjrType = 2;\nend\nif isscalar(gjrType)\n gjrType = ones(k,1)*gjrType;\nend\n\nif isempty(type)\n type = 'gogarch';\nend\ntype = lower(type);\nif ~ismember(type,{'gogarch','ogarch'})\n error('TYPE must be either ''GoGARCH'' or ''OGARCH''');\nend\nif strcmpi(type,'gogarch')\n isGogarch = true;\nelse\n isGogarch = false;\nend\n\n\nif ~isempty(startingVals)\n count = sum(p) + sum(q);\n if isGogarch\n count = count + k*(k-1)/2;\n end\n if length(startingVals)~=count\n error('STARTINGVALS does not have the correct number of parameters.')\n end\n if isGogarch\n if any(startingVals(1:k*(k-1)/2))>pi || any(startingVals(1:k*(k-1)/2))<0\n error('STARTGINVALS 1 to K*(K-1)/2 must be between 0 and 3.141592')\n end\n end\nend\n\nif isempty(options)\n options = optimset('fmincon');\n options.Display = 'iter';\n options.Diagnostics = 'on';\n options.Algorithm = 'sqp';\nelse\n try\n optimset(options);\n catch ME\n error('OPTIONS does not appear to be a valid options structure.')\n end\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Preliminary Estimation\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nS = mean(data,3);\n[P,L] = eig(S);\nP = P';\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Starting Values\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif isempty(startingVals)\n startingOptions = optimset('fminunc');\n startingOptions.TolFun = 1e-005;\n startingOptions.TolX = 1e-005;\n startingOptions.Display = 'none';\n startingOptions.LargeScale ='off';\n startingOptions.MaxFunEvals = 400*(max(p)+max(q));\n \n \n Zinv = L^(-0.5)*P';\n stdData = zeros(k,k,T);\n for t=1:T\n stdData(:,:,t) = Zinv*data(:,:,t)*Zinv';\n end\n volParams = cell(k,1);\n V = zeros(T,k);\n for i=1:k\n volData = sqrt(squeeze(stdData(i,i,:)));\n [temp,~,V(:,i)] = tarch(volData,p(i),0,q(i),[],gjrType(i),[],startingOptions);\n volParams{i} = temp(2:(1+p(i)+q(i)));\n end\n if isGogarch\n startingVals = zeros(1,k*(k-1)/2)+.0001;\n end\n for i=1:k\n startingVals = [startingVals volParams{i}']; %#ok\n end\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% OGARCH\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nw = .06*.94.^(0:sqrt(T));\nw = w/sum(w);\nif isGogarch\n offset = k*(k-1)/2;\nelse\n offset = 0;\nend\nparameters = startingVals;\nogarchOptions = optimset('fmincon');\nif isGogarch\n ogarchOptions.Display = 'off';\nelse\n ogarchOptions.Display = 'iter';\nend\nogarchOptions.Algorithm = 'sqp';\nfor i=1:k\n if gjrType==1\n backCast = w*abs(volData(1:length(w)));\n else\n backCast = w*(volData(1:length(w))).^2;\n end\n count = p(i) + q(i);\n LB = zeros(count,1);\n UB = LB + 1;\n A = ones(1,count);\n b = 1;\n volStart = parameters(offset + (1:count));\n volData = sqrt(squeeze(stdData(i,i,:)));\n parameters(offset + (1:count)) = fmincon(@ogarch_likelihood,volStart,A,b,[],[],LB,UB,[],ogarchOptions,volData,p(i),q(i),gjrType(i),backCast);\n offset = offset + count;\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% GOGARCH\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif isGogarch\n v = length(startingVals);\n LB = zeros(1,v);\n UB = LB + 1;\n LB(1:(k*(k-1)/2)) = 1e-6;\n UB(1:(k*(k-1)/2)) = .99998*pi;\n A = zeros(k,v);\n b = .99998*ones(1,k);\n offset = k*(k-1)/2;\n for i=1:k\n count = p(i)+q(i);\n Ai = ones(1,count);\n A(i,offset + (1:count)) = Ai;\n offset = offset + count;\n end\n parameters = fmincon(@gogarch_likelihood,startingVals,A,b,[],[],LB,UB,[],options,data,p,q,gjrType,P,L,false,false);\n [ll,~,Ht] = gogarch_likelihood(parameters,data,p,q,gjrType,P,L,false,false);\nelse\n [ll,~,Ht] = gogarch_likelihood(parameters,data,p,q,gjrType,P,L,true,false);\nend\nll = -ll;\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Inference\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nk2 = k*(k+1)/2;\nv = k2+length(parameters);\nscores = zeros(T,v);\ncount = 1;\nfor j=1:k\n for i=j:k\n scores(:,count) = squeeze(data(i,j,:) - S(i,j));\n count = count + 1;\n end\nend\n[~,s] = gradient_2sided(@gogarch_likelihood,parameters',data,p,q,gjrType,P,L,~isGogarch,false);\nscores(:,k2+1:v) = s;\nB = covnw(scores,ceil(1.2*T^(1/3)));\nA = zeros(v);\nA(1:k2,1:k2) = -eye(k2);\nm = length(parameters);\nparameters = [vech(S)' parameters]';\ntemp = hessian_2sided_nrows(@gogarch_likelihood,parameters,m,data,p,q,gjrType,P,L,~isGogarch,true);\nA((k2+1):v,:) = temp/T;\nAinv = A\\eye(v);\nVCV = Ainv*B*Ainv'/T;", "meta": {"author": "bashtage", "repo": "mfe-toolbox", "sha": "9622b6c546bc6d649fd9bf0a36a7fcd53872e04a", "save_path": "github-repos/MATLAB/bashtage-mfe-toolbox", "path": "github-repos/MATLAB/bashtage-mfe-toolbox/mfe-toolbox-9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/multivariate/gogarch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.48501304856749794}} {"text": "function voronoiStats=getVoronoiStats(Fv_cell,Vv,np,numBins)\n\n%Replace infinite entries by NaN\nVv(isinf(Vv))=NaN;\n\n%Allocate memory for structure\nvoronoiStats.ellipse=nan(numel(Fv_cell),5);\nvoronoiStats.ellipticity=nan(numel(Fv_cell),1);\nvoronoiStats.circularity=nan(numel(Fv_cell),1);\nvoronoiStats.angle=nan(numel(Fv_cell),1);\nvoronoiStats.area=nan(numel(Fv_cell),1);\nvoronoiStats.radii=cell(numel(Fv_cell),1);\nvoronoiStats.minRad=nan(numel(Fv_cell),1);\nvoronoiStats.maxRad=nan(numel(Fv_cell),1);\nvoronoiStats.meanRad=nan(numel(Fv_cell),1);\n\n%Loop through cells to compute statistics\nfor q=1:1:numel(Fv_cell);\n \n %Get current Voronoi cell\n fv=Fv_cell{q};\n vv=Vv(fv,:);\n \n if ~isnan(vv(:))\n %Compute ellips and ellipticity\n [A] = ellipseFit(vv,2,np);\n \n a=A(3); b=A(4);\n if b\n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/getVoronoiStats.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.48499252952584243}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% q = solve_spherical_wrist(robot, q, T, wrist)\t\n% Solves the inverse kinematic problem for a spherical wrist\n% robot: robot structure.\n% q: vector containing the values of the joints 1, 2 and 3.\n% T: orientation of the last reference system.\n% wrist: select -1 or 1 for two possible solutions (wrist up, wrist down)\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 .\n\nfunction q = solve_spherical_wrist(robot, q, T, wrist, method)\n\nswitch method\n \n %algebraic solution\n case 'algebraic'\n T01=dh(robot, q, 1);\n T12=dh(robot, q, 2);\n T23=dh(robot, q, 3);\n \n Q=inv(T23)*inv(T12)*inv(T01)*T;\n \n %detect the degenerate case when q(5)=0, this leads to zeros\n % in Q13, Q23, Q31 and Q32 and Q33=1\n thresh=1e-12;\n %detect if q(5)==0\n % this happens when cos(q5) in the matrix Q is close to 1\n if abs(Q(3,3)-1)>thresh \n %normal solution\n if wrist==1 %wrist up\n q(4)=atan2(-Q(2,3),-Q(1,3)); \n q(6)=atan2(-Q(3,2),Q(3,1)); \n %q(5)=atan2(-Q(3,2)/sin(q(6)),Q(3,3));\n else %wrist down\n q(4)=atan2(-Q(2,3),-Q(1,3))-pi; \n q(6)=atan2(-Q(3,2),Q(3,1))+pi; \n %q(5)=atan2(-Q(3,2)/sin(q(6)),Q(3,3));\n end\n if abs(cos(q(6)+q(4)))>thresh \n cq5=(Q(1,1)+Q(2,2))/cos(q(4)+q(6))-1;\n end\n if abs(sin(q(6)+q(4)))>thresh\n cq5=(-Q(1,2)+Q(2,1))/sin(q(4)+q(6))-1;\n end\n if abs(sin(q(6)))>thresh\n sq5=-Q(3,2)/sin(q(6));\n end\n if abs(cos(q(6)))>thresh\n sq5=Q(3,1)/cos(q(6));\n end\n q(5)=atan2(sq5,cq5);\n \n else %degenerate solution, in this case, q4 cannot be determined,\n % so q(4)=0 is assigned\n if wrist==1 %wrist up\n q(4)=0;\n q(5)=0;\n q(6)=atan2(-Q(1,2)+Q(2,1),Q(1,1)+Q(2,2));\n else %wrist down\n q(4)=-pi;\n q(5)=0;\n q(6)=atan2(-Q(1,2)+Q(2,1),Q(1,1)+Q(2,2))+pi;\n end \n \n end \n \n %geometric solution \n case 'geometric' \n % T is the noa matrix defining the position/orientation of the end\n % effector's reference system\n vx6=T(1:3,1);\n vz5=T(1:3,3); % The vector a z6=T(1:3,3) is coincident with z5\n \n % Obtain the position and orientation of the system 3\n % using the already computed joints q1, q2 and q3\n T01=dh(robot, q, 1);\n T12=dh(robot, q, 2);\n T23=dh(robot, q, 3);\n T03=T01*T12*T23;\n \n vx3=T03(1:3,1);\n vy3=T03(1:3,2);\n vz3=T03(1:3,3);\n \n % find z4 normal to the plane formed by z3 and a\n vz4=cross(vz3, vz5);\t% end effector's vector a: T(1:3,3)\n \n % in case of degenerate solution,\n % when vz3 and vz6 are parallel--> then z4=0 0 0, choose q(4)=0 as solution\n if norm(vz4) <= 0.000001\n if wrist == 1 %wrist up\n q(4)=0;\n else\n q(4)=-pi; %wrist down\n end\n else\n %this is the normal and most frequent solution\n cosq4=wrist*dot(-vy3,vz4);\n sinq4=wrist*dot(vx3,vz4);\n q(4)=atan2(sinq4, cosq4);\n end\n %propagate the value of q(4) to compute the system 4\n T34=dh(robot, q, 4);\n T04=T03*T34;\n vx4=T04(1:3,1);\n vy4=T04(1:3,2);\n \n % solve for q5 \n cosq5=dot(vy4,vz5);\n sinq5=dot(-vx4,vz5);\n q(5)=atan2(sinq5, cosq5);\n \n %propagate now q(5) to compute T05\n T45=dh(robot, q, 5);\n T05=T04*T45;\n vx5=T05(1:3,1);\n vy5=T05(1:3,2);\n \n % solve for q6\n cosq6=dot(vx6,vx5);\n sinq6=dot(vx6,vy5);\n q(6)=atan2(sinq6, cosq6); \n \n \n \n otherwise\n disp('no method specified in solve_spherical_wrist');\nend\n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/lib/kinematics/solve_spherical_wrist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733963661418, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.48494247200357965}} {"text": "%NULIBSVC Trainable classifier: LIBSVM, nu-algorithme\n% \n% \t[W,J,NU] = NULIBSVC(A,KERNEL,NU)\n% \t[W,J,NU] = A*NULIBSVC([],KERNEL,NU)\n% \t[W,J,NU] = A*NULIBSVC(KERNEL,NU)\n%\n% INPUT\n% A\t Dataset\n% KERNEL Mapping to compute kernel by A*MAP(A,KERNEL)\n% or string to compute kernel by FEVAL(KERNEL,A,A)\n% or cell array with strings and parameters to compute kernel by\n% FEVAL(KERNEL{1},A,A,KERNEL{2:END})\n% Default: linear kernel.\n% NU nu value, upperbound error.\n% Default NU is derived from 1-NN error.\n%\n% OUTPUT\n% W Mapping: Support Vector Classifier\n% J Object idences of support objects. Can be also obtained as W{4}\t\t\t\n% NU Actual nu_value used\n%\n% DESCRIPTION\n% Optimizes a support vector classifier for the dataset A by the libsvm\n% package, see http://www.csie.ntu.edu.tw/~cjlin/libsvm/. LIBSVC calls the\n% svmtrain routine of libsvm for training. Classifier execution for a\n% test dataset B may be done by D = B*W; In D posterior probabilities are\n% given as computed by svmpredict using the '-b 1' option. \n% \n% The kernel may be supplied in KERNEL by\n% - an untrained mapping, e.g. a call to PROXM like W = LIBSVC(A,PROXM([],'R',1))\n% - a string with the name of the routine to compute the kernel from A\n% - a cell-array with this name and additional parameters.\n% This will be used for the evaluation of a dataset B by B*W or PRMAP(B,W) as\n% well. \n%\n% If KERNEL = 0 (or not given) it is assumed that A is already the \n% kernelmatrix (square). In this also a kernel matrix should be supplied at \n% evaluation by B*W or PRMAP(B,W). However, the kernel has to be computed with \n% respect to support objects listed in J (the order of objects in J does matter).\n% \n% REFERENCES\n% R.-E. Fan, P.-H. Chen, and C.-J. Lin. Working set selection using the second order \n% information for training SVM. Journal of Machine Learning Research 6, 1889-1918, 2005\n%\n% SEE ALSO (PRTools Guide) \n% MAPPINGS, DATASETS, LIBSVC, SVC, PROXM\n\n% Copyright: R.P.W. Duin, r.p.w.duin@37steps.com\n% Faculty EWI, Delft University of Technology\n% P.O. Box 5031, 2600 GA Delft, The Netherlands\n \nfunction [W,J,NU] = nulibsvc(varargin)\n\t\t\n\tchecktoolbox('libsvm');\n\n mapname = 'nuLIBSVM';\n argin = shiftargin(varargin,{'prmapping','char','cell'});\n argin = setdefaults(argin,[],proxm([],'p',1),[],[]);\n \n if mapping_task(argin,'definition')\n \n W = define_mapping(argin,'untrained',mapname);\n \n\telseif mapping_task(argin,'training')\t\t\t% Train a mapping.\n\n [a,kernel,NU] = check_for_old_call(argin);\t\n\t\tif isempty(NU), NU = 2*min(max(testk(a,1),0.01),(0.8*min(classsizes(a))/size(a,1))); end\n\t\t%opt = ['-s 0 -t 4 -b 1 -c ',num2str(NU)];\n opt = ['-s 1 -t 4 -b 1 -n ',num2str(NU), ' -q'];\n\t\tislabtype(a,'crisp');\n\t\tisvaldset(a,1,2); % at least 1 object per class, 2 classes\n\t\t[m,k,c] = getsize(a);\n\t\tnlab = getnlab(a); \n\t\n\t\tK = compute_kernel(a,a,kernel);\n\t\tK = min(K,K'); % make sure kernel is symmetric\n\t\tK = [[1:m]' K]; % as libsvm wants it\n\t % call libsvm\n\t\tu = svmtrain(nlab,K,opt);\n\t\tif isempty(u)\n\t\t\tprwarning(1,'nulibsvc: no solution for SVM, pseudo-inverse will be used')\n\t\t\tW = lkc(prdataset(K(:,2:end),getlabels(a)),0);\n\t\t\tJ = [1:m]';\n\t\t\treturn\n\t\tend\n\t\t % Store the results:\n \tJ = full(u.SVs); \n if isequal(kernel,0)\n s = [];\n in_size = length(J);\n % in_size = 0; % to allow old and new style calls\n else\n s = a(J,:);\n in_size = k;\n end\n\n lablist = getlablist(a); \n W = prmapping(mfilename,'trained',{u,s,kernel,J,opt},lablist(u.Label,:),in_size,c);\n\t\t\n\t\tW = setname(W,mapname);\n\t\tW = setcost(W,a);\n\t\t\t\n else % Evaluation\n\n [a,W] = deal(argin{1:2});\n [u,s,kernel,J,opt] = getdata(W);\n\t\tm = size(a,1);\n\t\t\n\t\tK = compute_kernel(a,s,kernel);\n k = size(K,2);\n if k ~= length(J)\n if isequal(kernel,0)\n if (k > length(J)) & (k >= max(J))\n % precomputed kernel; old style call\n prwarning(1,'Old style execution call: The precomputed kernel was calculated on a test set and the whole training set!') \n else\n error('Inappropriate precomputed kernel!\\nFor the execution the kernel matrix should be computed on a test set and the set of support objects');\n end \n else\n error('Kernel matrix has the wrong number of columns');\n end\n else \n % kernel was computed with respect to the support objects\n % we make an approprite correction in the libsvm structure\n u.SVs = sparse((1:length(J))');\n end \n K = [[1:m]' K]; % as libsvm wants it\n %[lab,acc,d] = svmpredict(getnlab(a),K,u,'-b 1');\n [lab,acc,d] = svmpredict(ones(m,1),K,u,'-b 1');\n\t\tW = setdat(a,d,W);\n\n\tend\n\n return;\n\nfunction K = compute_kernel(a,s,kernel)\n\n\t% compute a kernel matrix for the objects a w.r.t. the support objects s\n\t% given a kernel description\n\n\tif isstr(kernel) % routine supplied to compute kernel\n\t\tK = feval(kernel,a,s);\n\telseif iscell(kernel)\n\t\tK = feval(kernel{1},a,s,kernel{2:end});\n\telseif ismapping(kernel)\n\t\tK = a*prmap(s,kernel);\n\telseif kernel == 0 % we have already a kernel\n\t\tK = a;\n\telse\n\t\terror('Do not know how to compute kernel matrix')\n\tend\n\t\t\n\tK = +K;\n\t\t\nreturn\n\nfunction [a,kernel,NU] = check_for_old_call(argin)\n\n[a,kernel,NU,par] = deal(argin{:});\nif ischar(kernel) && exist(kernel,'file') ~= 2\n kernel = proxm(kernel,NU);\n NU = par;\nend\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/prtools/nulibsvc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.48489068744587427}} {"text": " function back = my_cbct_back(proj, cg, ig, varargin)\n% function back = cbct_back(proj, cg, ig, varargin)\n%|\n%| cone-beam backprojector for feldkamp.m\n%| in\n%|\tproj\t[ns nt na]\tcone-beam projection views\n%| option\n%|\t'use_mex' 1|2|3\t\tdefault: 1 mex with loop in mex\n%|\t\t\t\t\t2 mex with loop in matlab\n%|\t\t\t\t\t3 mex with \"st\" data order (slower)\n%|\t\t\t\t\t0 no mex; use matlab\n%|\t'ia_skip'\t\tdefault: 1\n%|\t'offset_source'\t\tdefault: 0\n%|\t'nthread'\t\tdefault: jf('ncore')\n%| out\n%|\tback\t[nx ny nz]\tback projection result\n%|\n%| Copyright 2004-8-28 Jeff Fessler, University of Michigan\n\nif nargin == 1 && streq(proj, 'test'), cbct_back_test, return, end\nif nargin < 3, help(mfilename), error(mfilename), end\n\narg.ia_skip = 1;\narg.use_mex = 1;\narg.offset_source = 0;\narg.nthread = jf('ncore');\narg.back_call = @fdk_mex_call;\narg.scale_dang = true;\narg = vararg_pair(arg, varargin);\n\nif arg.use_mex\n\tif cg.pitch ~= 0 || any(cg.source_zs ~= 0)\n\t\tfail('helix not yet supported')\n\tend\n\tback = cbct_back_mex(proj, cg.ns, cg.nt, cg.na, ...\n\t\tcg.ds, cg.dt, cg.offset_s, cg.offset_t, arg.offset_source, ...\n\t\tcg.dsd, cg.dso, cg.dfs, cg.orbit, cg.orbit_start, ...\n\t\tig.mask_or, ig.nz, ig.dx, ig.dy, ig.dz, ...\n\t\t[ig.offset_x ig.offset_y ig.offset_z], ...\n\t\targ.ia_skip, arg.scale_dang, ...\n\t\targ.use_mex, arg.nthread, arg.back_call);\n\nelse\n\n\tback = cbct_back_mat(proj, cg, cg.ns, cg.nt, cg.na, ...\n\t\tcg.ds, cg.dt, cg.offset_s, cg.offset_t, arg.offset_source, ...\n\t\tcg.dsd, cg.dso, cg.dfs, cg.orbit, cg.orbit_start, ...\n\t\tcg.source_zs, ...\n\t\tig.mask_or, ig.nz, ig.dx, ig.dy, ig.dz, ...\n\t\t[ig.offset_x ig.offset_y ig.offset_z], ...\n\t\targ.ia_skip, arg.scale_dang);\nend\n\nend % cbct_back()\n\n\n%\n% cbct_back_mex()\n% mex backprojector\n%\nfunction img = cbct_back_mex(proj, ns, nt, na, ...\n\tds, dt, offset_s, offset_t, offset_source, ...\n\tdsd, dso, dfs, orbit, orbit_start, ...\n\tmask, nz, dx, dy, dz, offset_xyz, ia_skip, scale_dang, ...\n\tuse_mex, nthread, back_call)\n\n[nx ny] = size(mask);\nia_list = 1:ia_skip:na;\nbetas = deg2rad(orbit_start + orbit * [0:na-1] / na); % [na] source angles\nproj = single(proj);\nnthread = int32(nthread);\n\nswitch use_mex\ncase 1 % loop in mex\n\tproj = permute(proj, [2 1 3]); % sta -> tsa\n\timg = back_call('fdk,ts,back', ...\n\t\t\tint32([nx ny nz]), [dx dy dz], ...\n\t\t\toffset_xyz, uint8(mask), ...\n\t\t\tdso, dsd, dfs, [ds dt], [offset_s offset_t], ...\n\t\t\tproj(:,:,ia_list), betas(ia_list), nthread);\n%\timg = double6(img);\n\timg = permute(img, [2 3 1]); % zxy -> xyz\n\ncase 2 % loop in matlab (for testing)\n\tproj = permute(proj, [2 1 3]); % sta -> tsa\n\timg = 0;\n\tfor ia=ia_list\n\t\tticker(mfilename, ia, na)\n\t\t% note: 2006-5-30: replaced -dy with dy\n\t\ttmp = back_call('fdk,ts,back', ...\n\t\t\tint32([nx ny nz]), [dx dy dz], ...\n\t\t\toffset_xyz, uint8(mask), ...\n\t\t\tdso, dsd, dfs, [ds dt], [offset_s offset_t], ...\n\t\t\tproj(:,:,ia), betas(ia), nthread);\n%\t\ttmp = double6(tmp);\n\t\timg = img + tmp;\n\tend\n\timg = permute(img, [2 3 1]); % zxy -> xyz\n\ncase 3 % fdk,st (for testing only - slower!)\n\twarn 'fdk,st does not handle projection view edges completely' \n\timg = back_call('fdk,st,back', ...\n\t\t\tint32([nx ny nz]), [dx dy dz], ...\n\t\t\toffset_xyz, uint8(mask), ...\n\t\t\tdso, dsd, dfs, [ds dt], [offset_s offset_t], ...\n\t\t\tproj(:,:,ia_list), betas(ia_list), nthread);\n%\timg = double6(img);\n\notherwise\n\tfail 'bug'\nend\n\nif scale_dang % final \"\\der angle\" scale:\n\timg = (0.5 * deg2rad(abs(orbit)) / (na/ia_skip)) * img;\nend\n\nend % cbct_back_mex()\n\n\n%\n% cbct_back_mat()\n% matlab backprojector (slower)\n%\nfunction img = cbct_back_mat(proj, cg, ns, nt, na, ...\n\tds, dt, offset_s, offset_t, offset_source, ...\n\tdsd, dso, dfs, orbit, orbit_start, ...\n\tsource_zs, ...\n\tmask, nz, dx, dy, dz, offset_xyz, ia_skip, scale_dang)\n\nif any(source_zs ~= 0)\n\twarn('helix not yet tested')\nend\n\n[nx ny] = size(mask);\nbetas = deg2rad(orbit_start + orbit * [0:na-1] / na); % [na] source angles\n\n% precompute as much as possible\nwx = (nx-1)/2 + offset_xyz(1);\nwy = (ny-1)/2 + offset_xyz(2);\nwz = (nz-1)/2 + offset_xyz(3);\n[xc yc] = ndgrid(([0:nx-1] - wx) * dx, ([0:ny-1] - wy) * dy);\nzc = ([0:nz-1] - wz) * dz;\n\nif 0 % limit back-projection to FOV? removed 2008-10-9\n\trr = sqrt(xc.^2 + yc.^2); % [nx,ny]\n\tsmax = ((ns-1)/2-abs(offset_s)) * ds; % maximum detector s coordinate\n\n\tif isinf(dfs)\n\t\tgamma_max = atan(smax/dsd);\n\telseif dfs == 0\n\t\tgamma_max = smax / dsd;\n\tend\n\n\trmax = dso * sin(gamma_max);\n\tmask = mask & (rr < rmax);\nend\nclear wx wy wz rr smax rmax\n\nxc = xc(mask); % [np] pixels within mask\nyc = yc(mask);\n\nws = (ns+1)/2 + offset_s; % trick: +1 because matlab starts from 1\nwt = (nt+1)/2 + offset_t;\n\n% loop over slices\nimg = zeros([size(mask) nz]);\nsdim = [ns+3 nt+3]; % trick: extra zeros saves indexing in loop\nproj1 = zeros(sdim);\nticker reset\n\n% Greg Handy stuff:\nnum_turns = orbit/360;\nhalfNumAngles = round((na/num_turns)/2);\nmyPitch = cg.pitch * cg.nt * dso / dsd * cg.dt;\nh = myPitch / (2*pi);\ndist = .5 * myPitch;\nzindex = 1;\n\nfor iz=1:nz\n\n\t% Greg Handy stuff:\n\t% Just trying to limit the number of angles used\n\tlower_limit = zc(iz) - dist;\n\n\t% enter into the acceptable range for the z-slices\n\twhile zindex < size(cg.source_zs,1)+1 && cg.source_zs(zindex) < lower_limit \n\t\tzindex = zindex + 1;\n\tend\n\tlowerA = zindex - halfNumAngles;\n\tupperA = zindex + halfNumAngles;\n\t\n\t% a check to prevent error; images without enough views will be poor \n\tif lowerA <= 0\n\t\tlowerA = 1;\n\tend\n\tif upperA > na\n\t\tupperA = na;\n\tend\n\n\t% loop over each projection angle\n\timg2 = 0;\n\tfor ia=lowerA:ia_skip:upperA\n\t\tticker(mfilename, [iz ia], [nz na])\n\t\tbeta = betas(ia);\n\n\t\tx_beta = +xc * cos(beta) + yc * sin(beta);\n\t\ty_betas = dso - (-xc * sin(beta) + yc * cos(beta));\n\n\t\t% detector indices\n\t\tif isinf(dsd) || isinf(dso) % par\n\t\t\tmag = ones(size(y_betas));\n\t\telse\n\t\t\tmag = dsd ./ y_betas;\n\t\tend\n\n\t\tif isinf(dfs) ... % flat\n\t\t\t|| isinf(dsd) || isinf(dso) % par\n\t\t\tsprime = mag .* x_beta;\n\t\telseif (dfs == 0) % arc\n\t\t\tr_loop = x_beta - offset_source;\n\t\t\tsprime = dsd * atan2(r_loop, y_betas);\n\t\tend\n\n\t\ttprime = mag * (zc(iz) - source_zs(ia));\n\t\tbs = sprime / ds + ws;\n\t\tbt = tprime / dt + wt;\n\n\t\t% bi-linear interpolation:\n\t\tis = floor(bs); % left bin\n\t\tit = floor(bt);\n\n\t\twr = bs - is;\t% left weight\n\t\twl = 1 - wr;\t% right weight\n\t\twu = bt - it;\t% upper weight\n\t\twd = 1 - wu;\t% lower weight\n\n\t\tibad = (is < 0) | (is > ns) | (it < 0) | (it > nt);\n\t\tis(ibad) = ns+1; % trick! point at harmless zeros\n\t\tit(ibad) = nt+1;\n\n\t\tproj1(1+[1:ns],1+[1:nt]) = proj(:,:,ia); % trick: left side\n\t\tp1 =\twl .* proj1(sub2ind(sdim, is+1,it+1)) + ...\n\t\t\twr .* proj1(sub2ind(sdim, is+2,it+1));\n\t\tp2 =\twl .* proj1(sub2ind(sdim, is+1,it+2)) + ...\n\t\t\twr .* proj1(sub2ind(sdim, is+2,it+2));\n\n\t\tp0 = wu .* p1 + wd .* p2; % vertical interpolation\n\n\t\tif isinf(dfs) ... % flat\n\t\t\t|| isinf(dsd) || isinf(dso) % par\n\t\t\tp0 = p0 .* mag.^2; % back-projection weighting for flat\n\t\telseif dfs == 0 % arc\n\t\t\tp0 = p0 .* (dsd.^2) ./ (r_loop.^2 + y_betas.^2);\n\t\tend\n\n\t\timg2 = img2 + p0;\n\tend % ia\n\n\timg(:,:,iz) = embed(img2, mask);\nend % iz\n\nif scale_dang % final \"\\der angle\" scale:\n\timg = (0.5 * deg2rad(abs(orbit)) / (na*ia_skip)) * img;\nend\n\nend % cbct_back_mat()\n\n\n%\n% fdk_mex_call()\n%\nfunction out = fdk_mex_call(varargin)\nif exist('fdk_mex') == 3\n\tprintm 'using fdk_mex'\n\tout = fdk_mex(varargin{:});\nelseif exist('jf_mex') == 3\n\tout = jf_mex(varargin{:});\nelse\n\tfail('bug: neither fdk_mex nor jf_mex found')\nend\nend % fdk_mex_call()\n\n\n%\n% cbct_back_test()\n% compare various versions to check consistency\n%\nfunction cbct_back_test\n\ndown = 8; % fast test\n% todo: test parallel, flat, arc\n%cg = ct_geom('ge1', 'nt', 800, 'na', 50*down, 'dsd', inf, 'down', down);\ncg = ct_geom('ge1', 'nt', 800, 'na', 50*down, 'down', down);\n%cg.dt = -cg.dt; % todo: handle this case\nig = image_geom('nx', 512, 'ny', 496, 'nz', 480, 'fov', 500, ...\n\t'mask', 'all-but-edge', 'down', down);\n\nell = [ ... % somewhat realistic phantom object\n\t[30 10 10\t150 150 280\t0 0 1000]; % 30cm diam\n\t[80 10 10\t50 50 30\t0 0 300]; % bone-like inserts\n\t[-10 -40 75\t40 40 40\t0 0 600];\n\t[-10 80 -20\t30 30 30\t0 0 600];\n];\n\nif 1\n\tproj = ellipsoid_proj(cg, ell);\n\tproj = fdk_filter(proj, 'ramp', cg.dsd, cg.dfs, cg.ds);\nelse\n\tproj = cg.zeros;\n\tproj(:,:,9) = 1;\nend\n% im clf, im(proj, 'true projections'), cbar, return\n\nif 0 % zero outer edges of projection for comparing ,st to ,ts\n\tproj([1 cg.ns], :, :) = 0;\n\tproj(:, [1 cg.nt], :) = 0;\n\tf.compare_st = true;\nelse\n\tf.compare_st = false;\nend\n\n\tia_skip = 3; % stress test and makes it faster too\n\targs = {proj, cg, ig, 'ia_skip', ia_skip, 'scale_dang', 0};\nif 1\n\tback0 = cbct_back(args{:}, 'use_mex', 0);\n%\tim(back0), return\nend\n\nif exist('jf_mex') == 3\n\tfor ii = 1:3\n\t\tuse_mex = ii;\n\t\tprintm('testing jf_mex with use_mex=%d', use_mex)\n\t\tback1{ii} = cbct_back(args{:}, ...\n\t\t\t'use_mex', use_mex, 'back_call', @jf_mex);\n\tend\n\tprintm('mpd mex1 vs mat: %g%%', max_percent_diff(back1{1}, back0))\n\tprintm('mpd mex1 vs mex2: %g%%', max_percent_diff(back1{1}, back1{2}))\n\tif f.compare_st % only if edges are zeroed\n\tprintm('mpd mex1 vs mex3: %g%%', max_percent_diff(back1{1}, back1{3}))\n\tend\nend\n\nif exist('fdk_mex') == 3\n\tprintm('found fdk_mex:\\n %s', which('fdk_mex'))\n\tback2 = cbct_back(args{:}, 'use_mex', 1, 'back_call', @fdk_mex);\n\tprintm('mpd jf_mex vs fdk_mex: %g%%', max_percent_diff(back1{1}, back2))\n\n\tif 1\n\t\tim plc 1 3\n\t\tiz = 1:ig.nz;\n\t\tim(1, back1{1}(:,:,iz))\n\t\tim(2, back2(:,:,iz))\n\t\terr = back2(:,:,iz) - back1{1}(:,:,iz);\n\t\tim(3, err)\n\tend\nend\n\nend % cbct_back_test()\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/contrib/handy-greg/my_cbct_back.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.48489068146627706}} {"text": "function [aVal,aJacob,aHess,papt]=aPolarCoordTurn2DOmega(x,tauInv,tauAccelInv)\n%%APOLARCOORDTURN2DOMEGA The continuous-time drift function for a 2D\n% coordinated turn model with the velocity expressed in terms of\n% a heading angle and a speed rather than in terms of a Cartesian\n% velocity vector. Additionally a turn rate is part of the state\n% (unlike in aPolarLin2D) and a linear acceleration term can be\n% given, which acts in the direction of motion. The turn rate and\n% linear acceleration can optionally have time constants\n% associated with them, like in the Singer model, modelling a\n% tendancy to eventually return to non-accelerating, straight-\n% line motion.\n%\n%INPUTS: xState The 5X1 or 6X1 target state for 2D motion. If there is no\n% linear acceleration (acceleration along the direction of\n% motion), then the state is [xPos;yPos;theta;v;omega],\n% where (xPos,yPos) are the Cartesian position, theta is the\n% angle of the velocity vector in radians counterclockwise\n% from the x axis, v is the speed, and omega is the turn\n% rate, typically in radians per second. If a linear\n% acceleration component is provided, then the state is\n% [xPos;yPos;theta;v;omega,al].\n% tauInv The inverse of the correlation time constant tau for the\n% turn rate in seconds. tauInv must be positive. The default\n% if omitted or an empty matrix is passed is 0.\n% tauAccelInv The inverse of the correlation time constant for the linear\n% acceleration in seconds. This parameter is not used if\n% there is no linear acceleration. the default if omitted or\n% an empty matrix is passed is 0.\n%\n%OUTPUTS: aVal The 5X1 (or 6X1 with linear acceleration) time-derivative of\n% the state. \n% aJacob The 5X5 (or 6X6) matrix of partial derivatives of aVals\n% such that aJacob(:,k) is the partial derivative of\n% aVals(:,k) with respect to x(k).\n% aHess The 5X5X5 (or 6X6X6) matrix of second derivatives of aVals\n% such that aHess(:,k1,k2) is the second partial derivative of\n% aVals with respect to x(k1) and x(k2).\n% papt The 5X1 or 6X1 derivative with resect to time of aVals.\n% This is all zeros, because the model is time invariant.\n%\n%The basic 2D coordinated turn model in Cartesian coordinates is described\n%in Section VA of [1]. When the turn rate is something that must be\n%estimated, it is assumed that the continuous-time turn rate model is\n%omegaDot=-(1/tauTurn)*Omega+noise\n%Note that the ordering of the state elements assumed by this function\n%differs from the ordering of the state elements assumed in [1].\n%\n%The 2D coordinates turn model in Cartesian coordinates is also described\n%in Chapter 4.2.3 of [2].\n%\n%The corresponding diffusion matrix is given by the function DCoordTurn2D.\n%The corresponding discrete-time functions are FCoordTurn2D and\n%QCoordTurn. However, note that the discrete-time functions are\n%direct-discrete models and not discretizations of the continuous-time\n%models as the propagated PDF does not remain Gaussian over time.\n%\n%REFERENCES:\n%[1] X. R. Li and V. P. Jilkov, \"Survey of maneuvering target tracking.\n% Part I: Dynamic models,\" IEEE Transactions on Aerospace and Electronic\n% Systems, vol. 39, no. 4, pp. 1333-1364, Oct. 2003.\n%[2] S. Blackman and R. Popoli, Design and Analysis of Modern Tracking\n% Systems. Norwood, MA: Artech House, 1999.\n%\n%January 2019 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<2||isempty(tauInv))\n tauInv=0;\nend\n\nif(nargin<3||isempty(tauAccelInv))\n tauAccelInv=0;\nend\n\n%Extract the heading and speed (polar velocity components).\ntheta=x(3);\nv=x(4);\nomega=x(5);%The turn rate\n\nxDim=size(x,1);\n\nsinTheta=sin(theta);\ncosTheta=cos(theta);\nswitch(xDim)\n case 5%There is no linear acceleration\n %From Equations 61 and 67 in Li's paper.\n aVal=[v*cosTheta;%Position dervative\n v*sinTheta;%Position derivative\n omega;%Heading derivative\n 0;%Speed derivative\n -tauInv*omega];%Turn rate derivative\n \n if(nargout>1)\n dXdTheta=-v*sinTheta;\n dYdTheta=v*cosTheta;\n dXdv=cosTheta;\n dYdv=sinTheta;\n \n aJacob=[0,0,dXdTheta,dXdv,0;\n 0,0,dYdTheta,dYdv,0;\n 0,0,0, 0,1;\n 0,0,0, 0,0;\n 0,0,0, 0,-tauInv];\n \n if(nargout>2)\n aHess=zeros(5,5,5);\n \n dXdThetadTheta=-v*cosTheta;\n dXdvdTheta=-sinTheta;\n \n dXdThetadv=dXdvdTheta;\n dXdvdv=0;\n \n %%%\n dYdThetadTheta=-v*sinTheta;\n dYdvdTheta=cosTheta;\n \n dYdThetadv=dYdvdTheta;\n dYdvdv=0;\n \n aHess(:,:,3)=[0,0,dXdThetadTheta,dXdvdTheta,0;\n 0,0,dYdThetadTheta,dYdvdTheta,0;\n zeros(3,5)];\n aHess(:,:,4)=[0,0,dXdThetadv,dXdvdv,0;\n 0,0,dYdThetadv,dYdvdv,0;\n zeros(3,5)];\n\n if(nargout>3)\n papt=zeros(5,1);\n end\n end\n end\n case 6%There is a linear acceleration component.\n al=x(6);%The linear acceleration (vDot)\n \n aVal=[v*cosTheta;%Position dervative\n v*sinTheta;%Position derivative\n omega;%Heading derivative\n al;%Speed derivative\n -tauInv*omega;%Turn rate derivative\n -tauAccelInv*al];%Linear acceleration derivative\n \n if(nargout>1)\n dXdTheta=-v*sinTheta;\n dYdTheta=v*cosTheta;\n dXdv=cosTheta;\n dYdv=sinTheta;\n\n aJacob=[0,0,dXdTheta,dXdv, 0,0;\n 0,0,dYdTheta,dYdv, 0,0;\n 0,0, 0, 0, 1,0;\n 0,0, 0, 0, 0,1;\n 0,0, 0, 0, -tauInv,0;\n 0,0, 0, 0, 0,-tauAccelInv];\n \n if(nargout>2)\n aHess=zeros(6,6,6);\n \n dXdThetadTheta=-v*cosTheta;\n dXdvdTheta=-sinTheta;\n \n dXdThetadv=dXdvdTheta;\n dXdvdv=0;\n \n %%%\n dYdThetadTheta=-v*sinTheta;\n dYdvdTheta=cosTheta;\n \n dYdThetadv=dYdvdTheta;\n dYdvdv=0;\n \n aHess(:,:,3)=[0,0,dXdThetadTheta,dXdvdTheta,0,0;\n 0,0,dYdThetadTheta,dYdvdTheta,0,0;\n zeros(4,6)];\n\n aHess(:,:,4)=[0,0,dXdThetadv,dXdvdv,0,0;\n 0,0,dYdThetadv,dYdvdv,0,0;\n zeros(4,6)];\n\n if(nargout>3)\n papt=zeros(6,1);\n end\n end\n end\n otherwise\n error('The dimensionality of the state is neither 5 nor 6.');\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/Dynamic_Models/Continuous_Time/aPolarCoordTurn2DOmega.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4848906814662769}} {"text": "function [ fea, out ] = ex_navierstokes12( varargin )\n%EX_NAVIERSTOKES12 3D Example flow over a backwards facing step\n%\n% [ FEA, OUT ] = EX_NAVIERSTOKES12( VARARGIN ) Sets up and solves stationary and\n% laminar 3D flow over a backwards facing step. Accepts the following property/value pairs.\n%\n% Input Value/{Default} Description\n% -----------------------------------------------------------------------------------\n% rho scalar {1} Density\n% miu scalar {2/3/389} Molecular/dynamic viscosity\n% uin scalar {1} Magnitude of inlet velocity\n% sf_u string {sflag1} Shape function for velocity\n% sf_p string {sflag1} Shape function for pressure\n% solver string 'openfoam'/{''} Use OpenFOAM or default solver\n% iplot scalar 0/{1} Plot solution and error (=1)\n% .\n% Output Value/(Size) Description\n% -----------------------------------------------------------------------------------\n% fea struct Problem definition struct\n% out struct Output struct\n%\n% See also EX_NAVIERSTOKES4\n\n% Copyright 2013-2022 Precise Simulation, Ltd.\n\n\ncOptDef = { ...\n 'rho', 1;\n 'miu', 2/3/389;\n 'uin', 1;\n 'igrid', 1;\n 'sf_u', 'sflag1';\n 'sf_p', 'sflag1';\n 'solver', '';\n 'iplot', 1;\n 'tol', 0.55;\n 'fid', 1 };\n[got,opt] = parseopt(cOptDef,varargin{:});\nfid = opt.fid;\n\n\n% Geometry.\nh_step = 0.0049/0.0101;\nl_inlet = 0.02/0.0101;\nl_channel = 0.08/0.0101;\nfea.sdim = { 'x', 'y', 'z' };\ngobj1 = gobj_block( -l_inlet, l_channel, -0.5, 0.5, -h_step, 1-h_step, 'B1' );\ngobj2 = gobj_block( -l_inlet, 0, -0.5, 0.5, -h_step, 0, 'B2' );\nfea.geom.objects = { gobj1, gobj2 };\nfea = geom_apply_formula( fea, 'B1-B2' );\n\n\n% Grid generation.\nif( opt.igrid>=1 )\n n = 4;\n fea.grid = rectgrid(10*n,n,[-l_inlet, l_channel; -0.5, 0.5]);\n fea.grid = delcells( fea.grid, selcells(fea.grid,'(y<=0).*(x<=0)') );\n ix = find( fea.grid.p(2,:) <= -0.5 + sqrt(eps) );\n fea.grid.p(2,ix) = -h_step;\n ix = find( fea.grid.p(2,:) >= 0.5 - sqrt(eps) );\n fea.grid.p(2,ix) = 1-h_step;\n\n fea.grid = gridextrude( fea.grid, n, 1, -2 );\n fea.grid.p(2,:) = fea.grid.p(2,:) + 0.5;\n fea.grid = assign_bdr( fea.grid, fea.geom );\n for i=1:opt.igrid\n fea.grid = gridrefine( fea.grid, fid );\n end\nelse\n fea.grid = gridgen( fea, 'hmax', 0.1, 'fid', fid );\n % fea.grid = gridsmooth( tet2hex( fea.grid ), 5 );\nend\n\n\n% Problem definition.\nfea = addphys( fea, @navierstokes );\nfea.phys.ns.eqn.coef{1,end} = { opt.rho };\nfea.phys.ns.eqn.coef{2,end} = { opt.miu };\nfea.phys.ns.sfun = { opt.sf_u opt.sf_u opt.sf_u opt.sf_p };\n% fea.phys.ns.prop.artstab.iupw = 4;\nif( any(strcmp(opt.solver,{'openfoam','su2'})) )\n [fea.phys.ns.sfun{:}] = deal('sflag1');\nend\n\n\n% Boundary conditions.\ni_inflow = findbdr( fea, ['x<',num2str(-l_inlet+1e-3)] ); % Inflow boundary number.\ni_outflow = findbdr( fea, ['x>',num2str( l_channel-1e-3)] ); % Outflow boundary number.\n% s_inflow = ['4*',num2str(umax),'*(y*(',num2str((1-y)*h),'-y))/',num2str((1-y)*h),'^2']; % Definition of inflow profile.\ns_inflow = ['4*',num2str(opt.uin),'*(z*(',num2str(1-h_step),'-z))/(1-',num2str(1-h_step),')^2'];\nu_init = [s_inflow,'*(z>0)'];\nfea.phys.ns.bdr.sel(i_inflow) = 2;\nfea.phys.ns.bdr.sel(i_outflow) = 4;\nfea.phys.ns.bdr.coef{2,end}{1,i_inflow} = s_inflow;\nif( ~strcmp(opt.solver,'openfoam') )\n fea.phys.ns.eqn.coef{6,end} = { u_init };\nend\n\n\n% Parse and solve problem.\nfea = parsephys( fea );\nfea = parseprob( fea );\nif( strcmp(opt.solver,'openfoam') )\n logfid = fid; if( ~got.fid ), fid = []; end\n fea.sol.u = openfoam( fea, 'fid', fid, 'logfid', logfid );\n fid = logfid;\nelseif( strcmp(opt.solver,'su2') )\n logfid = fid; if( ~got.fid ), fid = []; end\n fea.sol.u = su2( fea, 'fid', fid, 'logfid', logfid );\n fid = logfid;\nelse\n fea.sol.u = solvestat( fea, 'maxnit',50, 'nlrlx',1, 'tolchg',1e-3, 'fid', fid );\nend\n\n\n% Postprocessing.\nif( opt.iplot>0 )\n postplot( fea, 'sliceexpr', 'sqrt(u^2+v^2+w^2)' )\nend\n\n\n% Error checking.\n[~,slen] = minmaxsubd( ['(u<-eps)*x/',num2str(h_step),'*(z<0)*(y<0.01)*(y>-0.01)'], fea );\nif( ~isempty(fid) )\n fprintf(fid,'\\nRecirculation zone length: %3f (Ref: 7.93)\\n\\n',slen)\n fprintf(fid,'\\n\\n')\nend\n\nout.slen = [slen, 7.93];\nout.err = abs(diff(out.slen))/out.slen(end);\nout.pass = out.err 0;\n u(id) = fp1(x(id),y(id),z(id),t);\n end\n function u = f2(x,y,z,t)\n u = fm2(x,y,z,t);\n id = intf(x,y,z) > 0;\n u(id) = fp2(x(id),y(id),z(id),t);\n end\n function u = f3(x,y,z,t)\n u = fm3(x,y,z,t);\n id = intf(x,y,z) > 0;\n u(id) = fp3(x(id),y(id),z(id),t);\n end\n\n function u = fm1(x,y,z,t)\n u = zeros(size(x));\n end\n function u = fm2(x,y,z,t)\n u = zeros(size(x));\n end\n function u = fm3(x,y,z,t)\n u = zeros(size(x));\n end\n function u = fp1(x,y,z,t)\n u = zeros(size(x));\n end\n function u = fp2(x,y,z,t)\n u = zeros(size(x));\n end\n function u = fp3(x,y,z,t)\n u = zeros(size(x));\n end\n\n%%%%% intial condition\n function u = E1(x,y,z,t)\n u = exp(-b*(a*(x-intPt)-omega*t).^2);\n% id = pulregion(x,y,z) > 0;\n% u(id) = zeros(size(x(id)));\n end\n function u = E2(x,y,z,t)\n u = -exp(-b*(a*(x-intPt)-omega*t).^2);\n end\n function u = E3(x,y,z,t)\n u = zeros(size(x));\n end\n function u = Et1(x,y,z,t)\n u = exp(-b*(a*(x-intPt)-omega*t).^2)*2*omega*b.*(a*(x-intPt)-omega*t);\n end\n function u = Et2(x,y,z,t)\n u = -exp(-b*(a*(x-intPt)-omega*t).^2)*2*omega*b.*(a*(x-intPt)-omega*t);\n end\n function u = Et3(x,y,z,t)\n u = zeros(size(x));\n end\n% function u = pulregion(x,y,z)\n% u = (x-intPt).^2/(0.15)^2 - 1; \n% end\n%% Diffusion coefficient function\n function u = Mu(x,y,z)\n u = Mum(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = Mup(x(id),y(id),z(id));\n end\n function u = Mum(x,y,z)\n u = mum^(-1)*ones(size(x));\n end\n function u = Mup(x,y,z)\n u = mup^(-1)*ones(size(x));\n end\n\n%% Mass coefficient function\n function u = Epslon(x,y,z)\n u = Epslonm(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = Epslonp(x(id),y(id),z(id));\n end\n function u = Epslonm(x,y,z)\n u = epsm*ones(size(x));\n end\n function u = Epslonp(x,y,z)\n u = epsp*ones(size(x));\n end\n \n function u = Sig(x,y,z)\n u = Sigm(x,y,z);\n id = intf(x,y,z) > 0;\n u(id) = Sigp(x(id),y(id),z(id));\n end\n function u = Sigm(x,y,z)\n u = sigm*ones(size(x));\n end\n function u = Sigp(x,y,z)\n u = sigp*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/ExampleFun/TorusTimeInitial3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4845490902836164}} {"text": "% Function to derive short term power contour as is done in Ishi et al 2008\n%\n% Description\n% Function to derive short term power contour as is done in Ishi et al 2008\n%\n%\n% Inputs\n% x : [samples] [Nx1] Speech signal\n% fs : [Hz] [1x1] Sampling frequency\n%\n% Outputs\n% pow : [dB] [Mx1] Power contour\n% pow_std : [samples] [Px1] Standard deviation of power contour\n%\n% Example\n% Please see the HOWTO_glottalsource.m example file.\n%\n% References\n% [1] Ishi, C., Sakakibara, K-I, Ishiguro, H., (2008) `A method for \n% automatic detection of vocal fry', IEEE TASLP, 16(1), 47-56.\n% [2] Drugman, T., Kane, J., Gobl, C., `Automatic Analysis of Creaky\n% Excitation Patterns', Submitted to Computer Speech and\n% Language.\n% [3] Kane, J., Drugman, T., Gobl, C., (2013) `Improved automatic \n% detection of creak', Computer Speech and Language 27(4), pp.\n% 1028-1047.\n% [4] Drugman, T., Kane, J., Gobl, C., (2012) `Resonator-based creaky \n% voice detection', Interspeech 2012, Portland, Oregon, USA.\n%\n% Copyright (c) 2013 University of Mons, FNRS & 2013 Trinity College Dublin\n%\n% License\n% This code is a part of the GLOAT toolbox with the following\n% licence:\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% This function is part of the Covarep project: http://covarep.github.io/covarep\n% \n% Authors\n% Thomas Drugman & John Kane \n\nfunction [pow,pow_std,pow_std_inter] = get_short_pow(x,fs)\n\n% Get very short term power contour\nveryShort_len = 4*(fs/1000); % 4ms frame length for \"very short-term\" analysis\nveryShort_shift = 2*(fs/1000); % 2ms shift for \"very short-term\" analysis\nveryShort_powCont = zeros(1,ceil((length(x)-veryShort_len)/veryShort_shift));\nstart=1;\nfinish=start+veryShort_len-1;\n\nn=1;\nx2 = x.^2;\nwhile finish <= length(x)\n veryShort_powCont(n) = mean(x2(start:finish));\n start = start + veryShort_shift;\n finish=start+veryShort_len-1;\n n=n+1;\nend\nclear x2;\n\npow = 20*log10(veryShort_powCont);\ninf_idx=isinf(pow);\npow(inf_idx)=min(pow(~inf_idx));\n\npow_std=zeros(1,length(pow));\nstd_len=16;\n\nfor n=std_len+1:length(pow)-std_len\n \n pow_std(n) = std(pow(n-std_len:n+std_len));\nend\npow_std=medfilt1(pow_std,13);\n\n\npow_std_inter=interp1(linspace(1,length(x),length(pow)),pow_std,1:length(x));", "meta": {"author": "covarep", "repo": "covarep", "sha": "5a2be5d6b776f14a0b275c69fde90eb13849e60d", "save_path": "github-repos/MATLAB/covarep-covarep", "path": "github-repos/MATLAB/covarep-covarep/covarep-5a2be5d6b776f14a0b275c69fde90eb13849e60d/glottalsource/creaky_voice_detection/private/get_short_pow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.4845490902836163}} {"text": "function ds_dsm = cosmo_dissimilarity_matrix_measure(ds, varargin)\n% Compute a dissimilarity matrix measure\n%\n% ds_dsm = cosmo_dissimilarity_matrix_measure(ds[, varargin])\n%\n% Inputs:\n% dataset dataset struct with fields .samples (PxQ) and\n% .sa.targets (Px1) for P samples and Q features.\n% each target should occur exactly once\n% args optional struct:\n% .metric a string with the name of the distance\n% metric to be used by pdist (default: 'correlation')\n% .center_data If true, then data is centered before the pair-wise\n% distances are computed. The default is false; when\n% used with the 'correlation' metric, it is recommended\n% to use center_data, 'true'.\n%\n% Returns\n%\n% Output:\n% ds_sa Struct with fields:\n% .samples Nx1 flattened lower triangle of a dissimilarity\n% matrix as returned by [cosmo_]pdist, where\n% N=P*(P-1)/2 is the number of pairwise distances\n% between all samples in the dataset.\n% .a.sdim.labels Set to\n% .sa Struct with field:\n% .targets1 } Nx1 vectors indicating the pairs of indices in the\n% .targets2 } lower part of the square form of the dissimilarity\n% matrix. if .dsm_pairs(k,:)==[i,j] then .samples(k)\n% the dissimlarity between the i-th and j-th sample\n% target.\n%\n%\n% Example:\n% % ds is a dataset struct with ds.sa.targets=(11:16)';\n% ds=struct();\n% ds.samples=[1 2 3; 1 2 3; 1 0 1; 1 1 2; 1 1 2];\n% ds.sa.targets=(11:15)';\n% %\n% % compute dissimilarity with centered data\n% dsm_ds=cosmo_dissimilarity_matrix_measure(ds,'center_data',true);\n% cosmo_disp(dsm_ds);\n% %|| .sa\n% %|| .targets1\n% %|| [ 2\n% %|| 3\n% %|| 4\n% %|| :\n% %|| 4\n% %|| 5\n% %|| 5 ]@10x1\n% %|| .targets2\n% %|| [ 1\n% %|| 1\n% %|| 1\n% %|| :\n% %|| 3\n% %|| 3\n% %|| 4 ]@10x1\n% %|| .a\n% %|| .sdim\n% %|| .labels\n% %|| { 'targets1' 'targets2' }\n% %|| .values\n% %|| { [ 11 [ 11\n% %|| 12 12\n% %|| 13 13\n% %|| 14 14\n% %|| 15 ] 15 ] }\n% %|| .samples\n% %|| [ 0\n% %|| 2\n% %|| 2\n% %|| :\n% %|| 1.11e-16\n% %|| 1.11e-16\n% %|| -2.22e-16 ]@10x1\n% %\n% % map results to matrix. values of 0 mean perfect correlation\n% [samples, labels, values]=cosmo_unflatten(dsm_ds,1,...\n% 'set_missing_to',NaN);\n% cosmo_disp(samples)\n% %|| [ NaN NaN NaN NaN NaN\n% %|| 0 NaN NaN NaN NaN\n% %|| 2 2 NaN NaN NaN\n% %|| 2 2 1.11e-16 NaN NaN\n% %|| 2 2 1.11e-16 -2.22e-16 NaN ]\n% %\n% cosmo_disp(labels)\n% %|| { 'targets1' 'targets2' }\n% %\n% cosmo_disp(values)\n% %|| { [ 11 [ 11\n% %|| 12 12\n% %|| 13 13\n% %|| 14 14\n% %|| 15 ] 15 ] }\n%\n% % Searchlight using this measure\n% ds=cosmo_synthetic_dataset('ntargets',6,'nchunks',1);\n% % (in this toy example there are only 6 voxels, and the radius\n% % of the searchlight is 1 voxel. Real-life examples use larger\n% % datasets and a larger radius)\n% nbrhood=cosmo_spherical_neighborhood(ds,'radius',1,'progress',false);\n% opt=struct();\n% opt.progress=false; % do not show progress\n% opt.metric='euclidean'; % (instead of default 'correlation')\n% measure=@cosmo_dissimilarity_matrix_measure;\n% sl_ds=cosmo_searchlight(ds, nbrhood, measure, opt);\n% cosmo_disp(sl_ds);\n% %|| .a\n% %|| .fdim\n% %|| .labels\n% %|| { 'i' 'j' 'k' }\n% %|| .values\n% %|| { [ 1 2 3 ] [ 1 2 ] [ 1 ] }\n% %|| .vol\n% %|| .mat\n% %|| [ 2 0 0 -3\n% %|| 0 2 0 -3\n% %|| 0 0 2 -3\n% %|| 0 0 0 1 ]\n% %|| .dim\n% %|| [ 3 2 1 ]\n% %|| .xform\n% %|| 'scanner_anat'\n% %|| .sdim\n% %|| .labels\n% %|| { 'targets1' 'targets2' }\n% %|| .values\n% %|| { [ 1 [ 1\n% %|| 2 2\n% %|| 3 3\n% %|| 4 4\n% %|| 5 5\n% %|| 6 ] 6 ] }\n% %|| .fa\n% %|| .nvoxels\n% %|| [ 3 4 3 3 4 3 ]\n% %|| .radius\n% %|| [ 1 1 1 1 1 1 ]\n% %|| .center_ids\n% %|| [ 1 2 3 4 5 6 ]\n% %|| .i\n% %|| [ 1 2 3 1 2 3 ]\n% %|| .j\n% %|| [ 1 1 1 2 2 2 ]\n% %|| .k\n% %|| [ 1 1 1 1 1 1 ]\n% %|| .samples\n% %|| [ 3.1 3.68 3.56 1.47 2.96 2.27\n% %|| 6.06 6.39 3.29 6.54 4.43 4.1\n% %|| 5.85 4.2 2.11 6.47 6.18 3.47\n% %|| : : : : : :\n% %|| 4.62 3.18 0.829 5.53 5.53 3.14\n% %|| 3.7 3.08 1.75 4.71 4.95 3.39\n% %|| 1.23 0.83 1.48 1.03 1.75 1.31 ]@15x6\n% %|| .sa\n% %|| .targets1\n% %|| [ 2\n% %|| 3\n% %|| 4\n% %|| :\n% %|| 5\n% %|| 6\n% %|| 6 ]@15x1\n% %|| .targets2\n% %|| [ 1\n% %|| 1\n% %|| 1\n% %|| :\n% %|| 4\n% %|| 4\n% %|| 5 ]@15x1\n% %||\n%\n% % limitation: cannot have repeated targets\n% ds=cosmo_synthetic_dataset('nchunks',2,'ntargets',3);\n% cosmo_dissimilarity_matrix_measure(ds);\n% %|| error('...')\n%\n% % averaging the samples for each unique target resolves the issue of\n% % repeated targets\n% ds=cosmo_synthetic_dataset('nchunks',2,'ntargets',3);\n% ds_avg=cosmo_fx(ds,@(x)mean(x,1),'targets');\n% ds_dsm=cosmo_dissimilarity_matrix_measure(ds_avg);\n% cosmo_disp(ds_dsm);\n% ||.sa\n%|| .targets1\n%|| [ 2\n%|| 3\n%|| 3 ]\n%|| .targets2\n%|| [ 1\n%|| 1\n%|| 2 ]\n%||.a\n%|| .sdim\n%|| .labels\n%|| { 'targets1' 'targets2' }\n%|| .values\n%|| { [ 1 [ 1\n%|| 2 2\n%|| 3 ] 3 ] }\n%||.samples\n%|| [ 1.68\n%|| 1.71\n%|| 0.711 ]\n%\n% Notes:\n% - it is recommended to set the 'center_data' to true when using\n% the default 'correlation' metric, as this removes a main effect\n% common to all samples; but note that this option is disabled by\n% default due to historical reasons.\n% - [cosmo_]pdist defaults to 'euclidean' distance, but correlation\n% distance is preferable for neural dissimilarity matrices, hence it\n% is used as the default here\n% - Results from this function, when used with the default 'correlation'\n% metric, should *not* be Fisher transformed (using atanh) because\n% the output ranges from 0 to 2 (=one minus Pearson correlation)\n% and the Fisher transform of a value >1 is complex (non-real). This is\n% generally a Bad Thing.\n%\n% See also: cosmo_pdist, pdist\n%\n% # For CoSMoMVPA's copyright information and license terms, #\n% # see the COPYING file distributed with CoSMoMVPA. #\n\n % check input\n check_input(ds);\n args=get_args(varargin);\n\n % make new dataset\n ds_dsm=struct();\n\n % if center_data, then subtract the mean first\n samples=ds.samples;\n if args.center_data\n samples=bsxfun(@minus,samples,mean(samples,1));\n end\n\n % compute pair-wise distances between all samples using cosmo_pdist,\n % then store them as samples in ds_dsm\n % >@@>\n dsm = cosmo_pdist(samples, args.metric)';\n\n % store dsm\n ds_dsm=get_sample_attributes(ds.sa.targets);\n ds_dsm.samples=dsm;\n % <@@<\n\n\n\nfunction check_input(ds)\n if ~(isstruct(ds) && ...\n isfield(ds,'samples') && ...\n isfield(ds,'sa') && ...\n isfield(ds.sa,'targets'))\n error(['require dataset structure with fields '...\n '.samples and .sa.targets']);\n end\n\nfunction args=get_args(varargin)\n persistent cached_varargin;\n persistent cached_args;\n\n if ~isequal(varargin, cached_varargin)\n cached_args=cosmo_structjoin('metric','correlation',...\n 'center_data',false,...\n varargin);\n cached_varargin=varargin;\n end\n\n args=cached_args;\n\n\nfunction ds_skeleton=get_sample_attributes(targets)\n persistent cached_targets;\n persistent cached_ds_skeleton;\n\n if ~isequal(targets, cached_targets)\n ntargets=numel(targets);\n\n % unique targets\n classes=unique(targets);\n nclasses=numel(classes);\n\n % each should occur exactly once\n if nclasses~=ntargets\n error(['.sa.targets should be permutation of unique targets; '...\n 'to average samples with the same targets, consider '...\n 'ds_mean=cosmo_fx(ds,@(x)mean(x,1),''targets'')'],...\n nclasses);\n end\n\n % store single sample attribute: the pairs of sample attribute indices\n % used to compute the dsm.\n [i,j]=find(triu(repmat(1:nclasses,nclasses,1),1)');\n cached_ds_skeleton.sa=struct();\n cached_ds_skeleton.sa.targets1=i;\n cached_ds_skeleton.sa.targets2=j;\n\n % set sample dimensions\n add_labels={'targets1','targets2'};\n add_values={targets, targets};\n\n cached_ds_skeleton.a.sdim=struct();\n cached_ds_skeleton.a.sdim.labels=add_labels;\n cached_ds_skeleton.a.sdim.values=add_values;\n\n cached_targets=targets;\n end\n\n ds_skeleton=cached_ds_skeleton;", "meta": {"author": "CoSMoMVPA", "repo": "CoSMoMVPA", "sha": "5de75a1b4bef89b082d39d69e2b99d7f894ad717", "save_path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA", "path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA/CoSMoMVPA-5de75a1b4bef89b082d39d69e2b99d7f894ad717/mvpa/cosmo_dissimilarity_matrix_measure.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597971, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4844653804094942}} {"text": "function SRout = SR(VAR,SIGN,VARopt)\n% =======================================================================\n% Compute IRs, VDs, and HDs for a VAR model estimated with VARmodel and \n% identified with sign restrictions\n% =======================================================================\n% SRout = SR(VAR,R,VARopt)\n% -----------------------------------------------------------------------\n% INPUT\n% - VAR: structure, result of VARmodel function\n% - SIGN: matrix containing the sign restrictions (nvar,nshocks). 1\n% stands for positive, -1 for negative, 0 for unrestricted. For\n% example the following identifies only one shock with positive\n% impact on the VAR1, and negative imnpact on VAR2 and VAR3\n% \n% shock1 shock2 shock3\n% SIGN = [ 1 0 0 % VAR1\n% -1 0 0 % VAR2\n% -1 0 0]; % VAR3\n% \n% - VARopt: options of the VAR (see VARoption from VARmodel)\n% -----------------------------------------------------------------------\n% OUTPUT\n% - SRout\n% * IRall : 4-D matrix of IRs (nsteps,nvar,nshocks,ndraws)\n% * IRmed : median of IRall\n% * IRinf : lower bound of IRall\n% * IRsup : upper bound of IRall\n% * IR : IR based on true B matrix that is closest to median B\n% * (similar structure for VD, B, and HD)\n% -----------------------------------------------------------------------\n% EXAMPLE\n% - See VARToolbox_Code.m in \"../Primer/\"\n% =======================================================================\n% VAR Toolbox 3.0\n% Ambrogio Cesa-Bianchi\n% ambrogiocesabianchi@gmail.com\n% March 2012. Updated November 2020\n% -----------------------------------------------------------------------\n\n\n%% Check inputs\n%==========================================================================\nif ~exist('SIGN','var')\n error('You have not provided sign restrictions (SIGN)')\nend\n\nif ~exist('VARopt','var')\n error('You need to provide VAR options (VARopt from VARmodel)');\nend\n\n\n%% Retrieve parameters and preallocate variables\n%==========================================================================\nnvar = VAR.nvar;\nnvar_ex = VAR.nvar_ex;\nnsteps = VARopt.nsteps;\nndraws = VARopt.ndraws;\nnobs = VAR.nobs;\nnlag = VAR.nlag;\npctg = VARopt.pctg;\n\n% Initialize empty matrix for the IR draws\nIRall = nan(nsteps,nvar,nvar,ndraws); \nVDall = nan(nsteps,nvar,nvar,ndraws); \nHDall.shock = zeros(nobs+nlag,nvar,nvar,ndraws); \nHDall.init = zeros(nobs+nlag,nvar,ndraws); \nHDall.const = zeros(nobs+nlag,nvar,ndraws); \nHDall.trend = zeros(nobs+nlag,nvar,ndraws); \nHDall.trend2 = zeros(nobs+nlag,nvar,ndraws); \nHDall.endo = zeros(nobs+nlag,nvar,ndraws); \nHDall.exo = zeros(nobs+nlag,nvar,nvar_ex,ndraws);\nBall = nan(nvar,nvar,ndraws); \n\n\n%% Sign restriction routine\n%==========================================================================\njj = 0; % accepted draws\ntt = 0; % total draws\nww = 1; % index for printing on screen\nwhile jj < ndraws\n\n % Check total number of draws\n if tt>VARopt.sr_draw\n disp('------------------------------------------------------------')\n disp( 'Total number of draws for finding sign restrictions exceeed')\n disp( 'Change the restrictions or increase VARopt.sr_draw');\n disp('------------------------------------------------------------')\n error('See details above')\n end\n \n % Set up VAR_draw.(draw{j}) for rotations: Only identification uncertainty\n label = {['draw' num2str(jj)]};\n VAR_draw.(label{1}) = VAR;\n VARopt.ident = 'sign';\n % If selected, set up VAR_draw.(draw{j}) to consider identification + model uncertainty\n if VARopt.sr_mod==1 \n % Draw F and sigma from the posterior and \n [sigma_draw, Ft_draw, F_draw, Fcomp_draw] = VARdrawpost(VAR);\n VAR_draw.(label{1}).Ft = Ft_draw;\n VAR_draw.(label{1}).F = F_draw;\n VAR_draw.(label{1}).Fcomp = Fcomp_draw;\n VAR_draw.(label{1}).sigma = sigma_draw;\n end\n \n % Compute rotated B matrix\n B = SignRestrictions(SIGN,VAR_draw.(label{1}),VARopt); \n \n % Note: e = (inv(B)*VAR_draw.(draw{j}).resid')';\n % Check orthogonality:\n % round(corr((inv(B)*VAR_draw.(draw{j}).resid')'))\n \n if ~isempty(B)\n % Store B\n jj = jj+1; tt = tt+1;\n Ball(:,:,jj) = B;\n \n % Update VAR_draw.(draw{j}) with the rotated B matrix for IR, VD, and HD\n VAR_draw.(label{1}).B = B; \n\n % Compute and store IR, VD, HD\n [aux_irf, VAR_draw.(label{1})] = VARir(VAR_draw.(label{1}),VARopt); \n IRall(:,:,:,jj) = aux_irf;\n aux_fevd = VARvd(VAR_draw.(label{1}),VARopt);\n VDall(:,:,:,jj) = aux_fevd;\n aux_hd = VARhd(VAR_draw.(label{1}),VARopt);\n HDall.shock(:,:,:,jj) = aux_hd.shock;\n HDall.init(:,:,jj) = aux_hd.init;\n HDall.const(:,:,jj) = aux_hd.const;\n HDall.trend(:,:,jj) = aux_hd.trend;\n HDall.trend2(:,:,jj) = aux_hd.trend2;\n HDall.endo(:,:,jj) = aux_hd.endo;\n if nvar_ex>0; HDall.exo(:,:,:,jj) = aux_hd.exo; end\n\n % Display number of loops\n if jj==VARopt.mult*ww\n disp(['Rotation: ' num2str(jj) ' / ' num2str(ndraws)]);\n ww=ww+1;\n end\n else\n tt=tt+1;\n end\nend\ndisp('-- Done!');\ndisp(' ');\n\n\n%% Store results\n%==========================================================================\n% Store all accepted IRs and VDs\nSRout.IRall = IRall;\nSRout.VDall = VDall;\nSRout.Ball = Ball;\nSRout.HDall = HDall;\n\n% Compute and save median B matrix\nSRout.Bmed = median(Ball,3);\n\n% Compute and save true B matrix that is closer to median\naux = sum(sum((Ball-SRout.Bmed).^2,1),2);\nsel = find(aux==min(aux));\nsel = sel(1);\nSRout.B = Ball(:,:,sel);\n\n% Compute IR and VD based on all rotations\npctg_inf = (100-pctg)/2; \npctg_sup = 100 - (100-pctg)/2;\nSRout.IRmed = median(IRall,4);\naux = prctile(IRall,[pctg_inf pctg_sup],4);\nSRout.IRinf = aux(:,:,:,1);\nSRout.IRsup = aux(:,:,:,2);\nSRout.VDmed = median(VDall,4);\naux = prctile(VDall,[pctg_inf pctg_sup],4);\nSRout.VDinf = aux(:,:,:,1);\nSRout.VDsup = aux(:,:,:,2);\n\n% Compute IR, VD, and HD based on the VARdraw that is closest to the median\n% B matrix\nVARopt.ident = 'sign';\nlabel = {['draw' num2str(sel)]}; % Recover the position in VARdraw\nVAR = VAR_draw.(label{1}); % Set a VAR based on the selected VARdraw\nSRout.IR = VARir(VAR,VARopt); % Compute IR\nSRout.VD = VARvd(VAR,VARopt); % Compute VD \nSRout.HD = VARhd(VAR,VARopt); % Compute HD\n\n\n", "meta": {"author": "ambropo", "repo": "VAR-Toolbox", "sha": "9fe5d763da307cdded2827851325766b3a7c60e1", "save_path": "github-repos/MATLAB/ambropo-VAR-Toolbox", "path": "github-repos/MATLAB/ambropo-VAR-Toolbox/VAR-Toolbox-9fe5d763da307cdded2827851325766b3a7c60e1/v3dot0/VAR/SR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597974, "lm_q2_score": 0.6442250996557035, "lm_q1q2_score": 0.4844653752727475}} {"text": "function [f] = spm_cost_SHC_fxa(x,v,a,P)\n% equations of motion for a foraging problem\n% FORMAT [f] = spm_cost_SHC_fxa(x,v,a,P)\n%\n% x - hidden states\n% v - exogenous inputs\n% a - action\n% P - parameters for mountain car\n%\n% returns f = dx/dt (see spm_cost_SHC_fx)\n% These equations of motion model dissipative flow x.x and x.v on a flat \n% potential and increases in physiological states x.q as radial basis \n% functions of secrete locations. The agent has to discover these \n% locations % using an appropriate policy. This generative process would \n% also substitute for Morris water-maze simulations or unbounded saccades.\n%__________________________________________________________________________\n% Copyright (C) 2010 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: spm_cost_SHC_fxa.m 3757 2010-03-08 11:41:53Z guillaume $\n \n% location and radius of attractors A (only A.q attractors deliver reward)\n%--------------------------------------------------------------------------\nglobal A; X = A.x(:,A.q);\n \n% physical flow\n%--------------------------------------------------------------------------\nf = x;\nf.x = x.v;\nf.v = a - x.x*2 - x.v*4;\n \n% physiological flow\n%--------------------------------------------------------------------------\nfor i = 1:size(X,2)\n f.q(i) = (norm(x.x - X(:,i)) < A.d) - x.q(i)/2;\nend\n \n% flow\n%--------------------------------------------------------------------------\ndt = 1/8;\nf.x = f.x*dt;\nf.v = f.v*dt;\nf.q = f.q*dt;\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/DEM/spm_cost_SHC_fxa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.5660185351961013, "lm_q1q2_score": 0.48442760839013776}} {"text": "classdef LogisticRegression < handle\n %LOGISTICREGRESSION Logistic Regression classifier\n %\n % ## Logistic Regression\n %\n % ML implements logistic regression, which is a probabilistic\n % classification technique. Logistic Regression is a binary classification\n % algorithm which is closely related to Support Vector Machines (SVM).\n % Like SVM, Logistic Regression can be extended to work on multi-class\n % classification problems like digit recognition (i.e. recognizing digitis\n % like 0,1 2, 3,... from the given images). This version of Logistic\n % Regression supports both binary and multi-class classifications (for\n % multi-class it creates a multiple 2-class classifiers). In order to\n % train the logistic regression classifier, Batch Gradient Descent and\n % Mini-Batch Gradient Descent algorithms are used (see [BatchDesWiki]).\n % Logistic Regression is a discriminative classifier (see [LogRegTomMitch]\n % for more details). Logistic Regression is implemented as a C++ class in\n % cv.LogisticRegression.\n %\n % In Logistic Regression, we try to optimize the training parameter\n % `theta` such that the hypothesis `0 <= h_theta(x) <= 1` is achieved. We\n % have `h_theta(x) = g(h_theta(x))` and `g(z)=1/(1+e^(-z))` as the\n % logistic or sigmoid function. The term \"Logistic\" in Logistic Regression\n % refers to this function. For given data of a binary classification\n % problem of classes 0 and 1, one can determine that the given data\n % instance belongs to class 1 if `h_theta(x) >= 0.5` or class 0 if\n % `h_theta(x) < 0.5`.\n %\n % In Logistic Regression, choosing the right parameters is of utmost\n % importance for reducing the training error and ensuring high training\n % accuracy:\n %\n % * The learning rate can be set with `LearningRate` property. It\n % determines how fast we approach the solution. It is a positive real\n % number.\n % * Optimization algorithms like Batch Gradient Descent and Mini-Batch\n % Gradient Descent are supported in cv.LogisticRegression. It is\n % important that we mention the number of iterations these optimization\n % algorithms have to run. The number of iterations can be set with\n % `Iterations` property. This parameter can be thought as number of\n % steps taken and learning rate specifies if it is a long step or a\n % short step. This and previous parameter define how fast we arrive at a\n % possible solution.\n % * In order to compensate for overfitting regularization is performed,\n % which can be enabled with `Regularization` property. One can specify\n % what kind of regularization has to be performed by passing one of\n % regularization kinds to this property.\n % * Logistic regression implementation provides a choice of 2 training\n % methods with Batch Gradient Descent or the MiniBatch Gradient Descent.\n % To specify this, set `TrainMethod` property as either `Batch` or\n % `MiniBatch`. If training method is set to `MiniBatch`, the size of the\n % mini batch has to be to a positive integer set with `MiniBatchSize`\n % property.\n %\n % ## Example\n % A sample set of training parameters for the Logistic Regression\n % classifier can be initialized as follows:\n %\n % lr = cv.LogisticRegression();\n % lr.LearningRate = 0.05;\n % lr.Iterations = 1000;\n % lr.Regularization = 'L2';\n % lr.TrainMethod = 'MiniBatch';\n % lr.MiniBatchSize = 10;\n %\n % ## References\n % [LogRegWiki]:\n % > [Logistic regression](https://en.wikipedia.org/wiki/Logistic_regression)\n %\n % [BatchDesWiki]:\n % > [Gradient descent optimization](https://en.wikipedia.org/wiki/Gradient_descent_optimization)\n %\n % [LogRegTomMitch]:\n % > \"Generative and Discriminative Classifiers: Naive Bayes and Logistic\n % > Regression\" in Machine Learning, Tom Mitchell.\n % > [Machine Learning](http://www.cs.cmu.edu/~tom/NewChapters.html)\n %\n % [RenMalik2003]:\n % > \"Learning a Classification Model for Segmentation\". Proc. CVPR, Nice,\n % > France (2003).\n %\n % See also: cv.LogisticRegression.LogisticRegression, fitglm\n %\n\n properties (SetAccess = private)\n % Object ID\n id\n end\n\n properties (Dependent)\n % The learning rate of the optimization algorithm.\n %\n % The higher the value, faster the rate and vice versa. If the value\n % is too high, the learning algorithm may overshoot the optimal\n % parameters and result in lower training accuracy. If the value is\n % too low, the learning algorithm converges towards the optimal\n % parameters very slowly. The value must a be a positive real number.\n % You can experiment with different values with small increments as in\n % 0.0001, 0.0003, 0.001, 0.003, 0.01, 0.03, 0.1, 0.3, ... and select\n % the learning rate with less training error. Default 0.001\n LearningRate\n % Number of iterations.\n %\n % The number of iterations required for the learing algorithm\n % (Gradient Descent or Mini Batch Gradient Descent). It has to be a\n % positive integer. You can try different number of iterations like in\n % 100, 1000, 2000, 3000, 5000, 10000, .. so on. Default 1000\n Iterations\n % Kind of regularization to be applied.\n %\n % Default 'L2'. Possible values:\n %\n % * __Disable__ Regularization disabled.\n % * __L1__ L1 norm.\n % * __L2__ L2 norm.\n Regularization\n % Kind of training method used to train the classifier.\n %\n % Default 'Batch'. Possible values:\n %\n % * __Batch__ batch gradient descent.\n % * __MiniBatch__ Mini-Batch Gradient Descent. Set `MiniBatchSize` to\n % a positive integer when using this method.\n TrainMethod\n % Number of training samples taken in each step of Mini-Batch Gradient\n % Descent.\n %\n % Will only be used if using `MiniBatch` training algorithm. It has to\n % take values less than the total number of training samples.\n % Default 1\n MiniBatchSize\n % Termination criteria of the training algorithm.\n %\n % A struct with the following fields is accepted:\n %\n % * __type__ one of 'Count', 'EPS', 'Count+EPS'. default 'Count+EPS'\n % * __maxCount__ maximum number of iterations. default `Iterations`\n % * __epsilon__ tolerance value. default `LearningRate`\n TermCriteria\n end\n\n %% Constructor/destructor\n methods\n function this = LogisticRegression(varargin)\n %LOGISTICREGRESSION Creates/trains a logistic regression model\n %\n % model = cv.LogisticRegression()\n % model = cv.LogisticRegression(...)\n %\n % The first variant creates Logistic Regression model with default\n % parameters.\n %\n % The second variant accepts the same parameters as the train\n % method, in which case it forwards the call after construction.\n %\n % See also: cv.LogisticRegression, cv.LogisticRegression.train\n %\n this.id = LogisticRegression_(0, 'new');\n if nargin > 0\n this.train(varargin{:});\n end\n end\n\n function delete(this)\n %DELETE Destructor\n %\n % model.delete()\n %\n % See also: cv.LogisticRegression\n %\n if isempty(this.id), return; end\n LogisticRegression_(this.id, 'delete');\n end\n end\n\n %% Algorithm\n methods\n function clear(this)\n %CLEAR Clears the algorithm state\n %\n % model.clear()\n %\n % The method clear does the same job as the destructor: it\n % deallocates all the memory occupied by the class members. But\n % the object itself is not destructed and can be reused further.\n % This method is called from the destructor, from the `train` and\n % `load` methods, or even explicitly by the user.\n %\n % See also: cv.LogisticRegression.empty, cv.LogisticRegression.load\n %\n LogisticRegression_(this.id, 'clear');\n end\n\n function b = empty(this)\n %EMPTY Returns true if the algorithm is empty\n %\n % b = model.empty()\n %\n % ## Output\n % * __b__ Returns true if the algorithm is empty (e.g. in the very\n % beginning or after unsuccessful read).\n %\n % See also: cv.LogisticRegression.clear, cv.LogisticRegression.load\n %\n b = LogisticRegression_(this.id, 'empty');\n end\n\n function varargout = save(this, filename)\n %SAVE Saves the algorithm parameters to a file or a string\n %\n % model.save(filename)\n % str = model.save(filename)\n %\n % ## Input\n % * __filename__ Name of the file to save to. In case of string\n % output, only the filename extension is used to determine the\n % output format (XML or YAML).\n %\n % ## Output\n % * __str__ optional output. If requested, the model is persisted\n % to a string in memory instead of writing to disk.\n %\n % This method stores the complete model state to the specified\n % XML or YAML file (or to a string in memory, based on the number\n % of output arguments).\n %\n % See also: cv.LogisticRegression.load\n %\n [varargout{1:nargout}] = LogisticRegression_(this.id, 'save', filename);\n end\n\n function load(this, fname_or_str, varargin)\n %LOAD Loads algorithm from a file or a string\n %\n % model.load(filename)\n % model.load(str, 'FromString',true)\n % model.load(..., 'OptionName',optionValue, ...)\n %\n % ## Input\n % * __filename__ Name of the file to read.\n % * __str__ String containing the serialized model you want to\n % load.\n %\n % ## Options\n % * __ObjName__ The optional name of the node to read (if empty,\n % the first top-level node will be used). default empty\n % * __FromString__ Logical flag to indicate whether the input is a\n % filename or a string containing the serialized model (switches\n % between `Algorithm::load()` and\n % `Algorithm::loadFromString()` C++ methods). default false\n %\n % This method loads the complete model state from the specified\n % XML or YAML file (either from disk or serialized string). The\n % previous model state is cleared.\n %\n % See also: cv.LogisticRegression.save\n %\n LogisticRegression_(this.id, 'load', fname_or_str, varargin{:});\n end\n\n function name = getDefaultName(this)\n %GETDEFAULTNAME Returns the algorithm string identifier\n %\n % name = model.getDefaultName()\n %\n % ## Output\n % * __name__ This string is used as top level XML/YML node tag\n % when the object is saved to a file or string.\n %\n % See also: cv.LogisticRegression.save, cv.LogisticRegression.load\n %\n name = LogisticRegression_(this.id, 'getDefaultName');\n end\n end\n\n %% StatModel\n methods\n function count = getVarCount(this)\n %GETVARCOUNT Returns the number of variables in training samples\n %\n % count = model.getVarCount()\n %\n % ## Output\n % * __count__ number of variables in training samples (plus one to\n % account for the implicitly prepended bias/intercept term).\n %\n % See also: cv.LogisticRegression.train\n %\n count = LogisticRegression_(this.id, 'getVarCount');\n end\n\n function b = isTrained(this)\n %ISTRAINED Returns true if the model is trained\n %\n % b = model.isTrained()\n %\n % ## Output\n % * __b__ Returns true if the model is trained, false otherwise.\n %\n % See also: cv.LogisticRegression.empty, cv.LogisticRegression.train\n %\n b = LogisticRegression_(this.id, 'isTrained');\n end\n\n function b = isClassifier(this)\n %ISCLASSIFIER Returns true if the model is a classifier\n %\n % b = model.isClassifier()\n %\n % ## Output\n % * __b__ Returns true if the model is a classifier, false if the\n % model is a regressor.\n %\n % Always true for logistic regression.\n %\n % See also: cv.LogisticRegression.isTrained\n %\n b = LogisticRegression_(this.id, 'isClassifier');\n end\n\n function status = train(this, samples, responses, varargin)\n %TRAIN Trains the statistical model\n %\n % status = model.train(samples, responses)\n % status = model.train(csvFilename, [])\n % [...] = model.train(..., 'OptionName', optionValue, ...)\n %\n % ## Input\n % * __samples__ matrix of training samples. It should have\n % `single` type. By default, each row represents a sample (see\n % the `Layout` option).\n % * __responses__ matrix of associated responses. A vector of\n % categorical labels, stored in an array of type `single`.\n % * __csvFilename__ The input CSV file name from which to load\n % dataset. In this variant, you should set the second argument\n % to an empty array.\n %\n % ## Output\n % * __status__ Success flag.\n %\n % ## Options\n % * __Data__ Training data options, specified as a cell array of\n % key/value pairs of the form `{'key',val, ...}`. See below.\n % * __Flags__ The optional training flags, model-dependent.\n % Not used. default 0\n %\n % ### Options for `Data` (first variant with samples and reponses)\n % * __Layout__ Sample types. Default 'Row'. One of:\n % * __Row__ each training sample is a row of samples.\n % * __Col__ each training sample occupies a column of samples.\n % * __VarIdx__ vector specifying which variables to use for\n % training. It can be an integer vector (`int32`) containing\n % 0-based variable indices or logical vector (`uint8` or\n % `logical`) containing a mask of active variables. Not set by\n % default, which uses all variables in the input data.\n % * __SampleIdx__ vector specifying which samples to use for\n % training. It can be an integer vector (`int32`) containing\n % 0-based sample indices or logical vector (`uint8` or\n % `logical`) containing a mask of training samples of interest.\n % Not set by default, which uses all samples in the input data.\n % * __SampleWeights__ optional floating-point vector with weights\n % for each sample. Some samples may be more important than\n % others for training. You may want to raise the weight of\n % certain classes to find the right balance between hit-rate and\n % false-alarm rate, and so on. Not set by default, which\n % effectively assigns an equal weight of 1 for all samples.\n % * __VarType__ optional vector of type `uint8` and size\n % ` + `,\n % containing types of each input and output variable. By default\n % considers all variables as numerical (both input and output\n % variables). In case there is only one output variable of\n % integer type, it is considered categorical. You can also\n % specify a cell-array of strings (or as one string of single\n % characters, e.g 'NNNC'). Possible values:\n % * __Numerical__, __N__ same as 'Ordered'\n % * __Ordered__, __O__ ordered variables\n % * __Categorical__, __C__ categorical variables\n % * __MissingMask__ Indicator mask for missing observation (not\n % currently implemented). Not set by default\n % * __TrainTestSplitCount__ divides the dataset into train/test\n % sets, by specifying number of samples to use for the test set.\n % By default all samples are used for the training set.\n % * __TrainTestSplitRatio__ divides the dataset into train/test\n % sets, by specifying ratio of samples to use for the test set.\n % By default all samples are used for the training set.\n % * __TrainTestSplitShuffle__ when splitting dataset into\n % train/test sets, specify whether to shuffle the samples.\n % Otherwise samples are assigned sequentially (first train then\n % test). default true\n %\n % ### Options for `Data` (second variant for loading CSV file)\n % * __HeaderLineCount__ The number of lines in the beginning to\n % skip; besides the header, the function also skips empty lines\n % and lines staring with '#'. default 1\n % * __ResponseStartIdx__ Index of the first output variable. If\n % -1, the function considers the last variable as the response.\n % If the dataset only contains input variables and no responses,\n % use `ResponseStartIdx = -2` and `ResponseEndIdx = 0`, then the\n % output variables vector will just contain zeros. default -1\n % * __ResponseEndIdx__ Index of the last output variable + 1. If\n % -1, then there is single response variable at\n % `ResponseStartIdx`. default -1\n % * __VarTypeSpec__ The optional text string that specifies the\n % variables' types. It has the format\n % `ord[n1-n2,n3,n4-n5,...]cat[n6,n7-n8,...]`. That is, variables\n % from `n1` to `n2` (inclusive range), `n3`, `n4` to `n5` ...\n % are considered ordered and `n6`, `n7` to `n8` ... are\n % considered as categorical. The range\n % `[n1..n2] + [n3] + [n4..n5] + ... + [n6] + [n7..n8]` should\n % cover all the variables. If `VarTypeSpec` is not specified,\n % then algorithm uses the following rules:\n % * all input variables are considered ordered by default. If\n % some column contains has non- numerical values, e.g.\n % 'apple', 'pear', 'apple', 'apple', 'mango', the\n % corresponding variable is considered categorical.\n % * if there are several output variables, they are all\n % considered as ordered. Errors are reported when\n % non-numerical values are used.\n % * if there is a single output variable, then if its values are\n % non-numerical or are all integers, then it's considered\n % categorical. Otherwise, it's considered ordered.\n % * __Delimiter__ The character used to separate values in each\n % line. default ','\n % * __Missing__ The character used to specify missing\n % measurements. It should not be a digit. Although it's a\n % non-numerical value, it surely does not affect the decision of\n % of whether the variable ordered or categorical. default '?'\n % * __TrainTestSplitCount__ same as above.\n % * __TrainTestSplitRatio__ same as above.\n % * __TrainTestSplitShuffle__ same as above.\n %\n % The training algorithm uses one-vs-rest scheme for multiclass\n % case (i.e a binary problem is fit for each label).\n %\n % See also: cv.LogisticRegression.predict, cv.LogisticRegression.calcError\n %\n status = LogisticRegression_(this.id, 'train', samples, responses, varargin{:});\n end\n\n function [err,resp] = calcError(this, samples, responses, varargin)\n %CALCERROR Computes error on the training or test dataset\n %\n % err = model.calcError(samples, responses)\n % err = model.calcError(csvFilename, [])\n % [err,resp] = model.calcError(...)\n % [...] = model.calcError(..., 'OptionName', optionValue, ...)\n %\n % ## Input\n % * __samples__ See the train method.\n % * __responses__ See the train method.\n % * __csvFilename__ See the train method.\n %\n % ## Output\n % * __err__ computed error.\n % * __resp__ the optional output responses.\n %\n % ## Options\n % * __Data__ See the train method.\n % * __TestError__ if true, the error is computed over the test\n % subset of the data, otherwise it's computed over the training\n % subset of the data. Please note that if you loaded a\n % completely different dataset to evaluate an already trained\n % classifier, you will probably want not to set the test subset\n % at all with `TrainTestSplitRatio` and specify\n % `TestError=false`, so that the error is computed for the whole\n % new set. Yes, this sounds a bit confusing. default false\n %\n % The method uses the predict method to compute the error. For\n % regression models the error is computed as RMS, for classifiers\n % as a percent of missclassified samples (0%-100%).\n %\n % See also: cv.LogisticRegression.train, cv.LogisticRegression.predict\n %\n [err,resp] = LogisticRegression_(this.id, 'calcError', samples, responses, varargin{:});\n end\n\n function [results,f] = predict(this, samples, varargin)\n %PREDICT Predicts responses for input samples\n %\n % [results,f] = model.predict(samples)\n % [...] = model.predict(..., 'OptionName', optionValue, ...)\n %\n % ## Input\n % * __samples__ The input data for the prediction algorithm. `MxN`\n % matrix, where each row contains variables (features) of one\n % object being classified. Should have `single` data type.\n %\n % ## Output\n % * __results__ Predicted labels as a column vector of `int32`\n % type. In case `RawOutput` was set, it returns a `single`\n % matrix of size `size(samples,1)-by-size(thetas,1)` which\n % contains the raw output of the sigmoid function(s).\n % * __f__ The same as the response of the first sample, i.e\n % `results(1)`.\n %\n % ## Options\n % * __Flags__ The optional predict flags, model-dependent. For\n % convenience, you can set the individual flag options below,\n % instead of directly setting bits here. default 0\n % * __RawOutput__ makes the method return the raw results (the\n % value of the sigmoid function), not the class label.\n % default false\n %\n % See also: cv.LogisticRegression.train, cv.LogisticRegression.calcError\n %\n [results,f] = LogisticRegression_(this.id, 'predict', samples, varargin{:});\n end\n end\n\n %% LogisticRegression\n methods\n function thetas = getLearntThetas(this)\n %GETLEARNTTHETAS Returns the trained parameters\n %\n % thetas = model.getLearntThetas()\n %\n % ## Output\n % * __thetas__ It returns learnt parameters of the Logistic\n % Regression as a matrix of type `single` arranged across rows.\n % For a two-class classifcation problem, it returns a single row\n % matrix.\n %\n % `thetas` is a matrix of size `nclasses-by-model.getVarCount()`\n % if `nclasses>2`, otherwise `1-by-model.getVarCount()` if\n % `nclasses=2`.\n %\n % See also: cv.LogisticRegression.train\n %\n thetas = LogisticRegression_(this.id, 'get_learnt_thetas');\n end\n end\n\n %% Getters/Setters\n methods\n function value = get.Iterations(this)\n value = LogisticRegression_(this.id, 'get', 'Iterations');\n end\n function set.Iterations(this, value)\n LogisticRegression_(this.id, 'set', 'Iterations', value);\n end\n\n function value = get.LearningRate(this)\n value = LogisticRegression_(this.id, 'get', 'LearningRate');\n end\n function set.LearningRate(this, value)\n LogisticRegression_(this.id, 'set', 'LearningRate', value);\n end\n\n function value = get.MiniBatchSize(this)\n value = LogisticRegression_(this.id, 'get', 'MiniBatchSize');\n end\n function set.MiniBatchSize(this, value)\n LogisticRegression_(this.id, 'set', 'MiniBatchSize', value);\n end\n\n function value = get.Regularization(this)\n value = LogisticRegression_(this.id, 'get', 'Regularization');\n end\n function set.Regularization(this, value)\n LogisticRegression_(this.id, 'set', 'Regularization', value);\n end\n\n function value = get.TermCriteria(this)\n value = LogisticRegression_(this.id, 'get', 'TermCriteria');\n end\n function set.TermCriteria(this, value)\n LogisticRegression_(this.id, 'set', 'TermCriteria', value);\n end\n\n function value = get.TrainMethod(this)\n value = LogisticRegression_(this.id, 'get', 'TrainMethod');\n end\n function set.TrainMethod(this, value)\n LogisticRegression_(this.id, 'set', 'TrainMethod', value);\n end\n end\n\nend\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/+cv/LogisticRegression.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.6654105720171531, "lm_q1q2_score": 0.48440256772503787}} {"text": "function [nlogL,nlogLvar,exitflag,output] = ibslike(fun,params,respMat,designMat,options,varargin)\n%IBSLIKE Unbiased negative log-likelihood via inverse binomial sampling.\n% NLOGL = IBLLIKE(FUN,PARAMS,RESPMAT,DESIGNMAT) returns unbiased estimate \n% NLOGL of the negative of the log-likelihood for the simulated model \n% and data, calculated using inverse binomial sampling (IBS). \n% FUN is a function handle to a function that simulates the model's \n% responses (see below). \n% PARAMS is the parameter vector used to simulate the model's responses. \n% RESPMAT is a \"response\" data matrix, where each row correspond to one \n% observation or \"trial\" (e.g., a trial of a psychophysical experiment), \n% and each column represents a different response feature (e.g., the \n% subject's response and reported confidence level). Responses need to \n% belong to a finite set.\n% DESIGNMAT is an optional experimental design matrix, where each row \n% corresponds to one trial, and each column corresponds to a different \n% trial feature (such as condition, stimulus value, etc.).\n%\n% FUN takes as input a vector of parameters PARAMS and an experimental \n% design matrix DMAT (one row per trial), and generates a matrix of \n% simulated model responses (one row per trial, corresponding to rows of \n% DMAT). DMAT is built by the algorithm out of rows of DESIGNMAT.\n%\n% DESIGNMAT can be omitted or left empty, in which case FUN needs to \n% accept a parameter vector PARAMS and an array of trial numbers T, and \n% returns a matrix of simulated responses, where the i-th row contains \n% the simulated response for trial T(i) (the indices in T may repeat).\n%\n% NLOGL = IBSLIKE(FUN,PARAMS,RESPMAT,DESIGNMAT,OPTIONS) uses options in \n% structure OPTIONS to replace default values. (To be explained...)\n%\n% NLOGL = IBSLIKE(...,VARARGIN) additional arguments are passed to FUN.\n%\n% [NLOGL,NLOGLVAR] = IBSLIKE(...) also returns an estimate NLOGVAR of the\n% variance of the log likelihood.\n%\n% [NLOGL,NLOGLVAR,EXITFLAG] = IBSLIKE(...) returns an EXITFLAG that \n% describes the exit condition. Possible values of EXITFLAG and the \n% corresponding exit conditions are\n%\n% 2 IBS terminated after reaching the maximum runtime specified by the \n% user (the estimate can be arbitrarily biased).\n% 1 IBS terminated after reaching the negative log-likelihood\n% threshold specified by the user (the estimate is biased).\n% 0 Correct run of IBS; the estimate is unbiased.\n%\n% [NLOGL,NLOGLVAR,EXITFLAG,OUTPUT] = IBSLIKE(...) returns a structure \n% OUTPUT with additional information about the sampling.\n%\n% OPTIONS = IBSLIKE('defaults') returns a basic default OPTIONS structure.\n%\n% EXITFLAG = IBSLIKE('test') runs some tests. Here EXITFLAG is 0 if \n% everything works correctly.\n% \n% Test code on binomial sampling:\n% p = 0.7; Ntrials = 100; % Define binomial probability\n% fun = @(x,dmat) rand(size(dmat)) < x; % Simulating function\n% rmat = fun(p,NaN(Ntrials,1)); % Generate responses\n% [nlogL,nlogLvar,pc,output] = ibslike(fun,p,rmat);\n% nlogL_true = -log(p)*sum(rmat == 1) - log(1-p)*sum(rmat == 0);\n% fprintf('Ground truth: %.4g, Estimate: %.4g ± %.4g.\\n',nlogL_true,nlogL,sqrt(nlogLvar));\n%\n% Reference: \n% van Opheusden*, B., Acerbi*, L. & Ma, W. J. (2020), \"Unbiased and \n% efficient log-likelihood estimation with inverse binomial sampling\". \n% (* equal contribution), PLoS Computational Biology 16(12): e1008483.\n% Link: https://doi.org/10.1371/journal.pcbi.1008483\n%\n% See also @.\n\n%--------------------------------------------------------------------------\n% IBS: Inverse Binomial Sampling for unbiased log-likelihood estimation\n% To be used under the terms of the MIT License \n% (https://opensource.org/licenses/MIT).\n%\n% Authors (copyright): Luigi Acerbi and Bas van Opheusden, 2020-2022\n% e-mail: luigi.acerbi@helsinki.fi, svo@princeton.edu\n% URL: http://luigiacerbi.com\n% Version: 0.96\n% Release date: Jan 21, 2021\n% Code repository: https://github.com/acerbilab/ibs\n%--------------------------------------------------------------------------\n\nif nargin < 4; designMat = []; end\nif nargin < 5; options = []; end\n\nt0 = tic;\n\n% Default options\n% defopts.Display = 'off'; % Level of display on screen\ndefopts.Nreps = 10; % # independent log-likelihood estimates per trial\ndefopts.NegLogLikeThreshold = Inf; % Stop sampling if estimated nLL is above threshold (incompatible with vectorized sampling)\ndefopts.Vectorized = 'auto'; % Use vectorized sampling algorithm with acceleration\ndefopts.Acceleration = 1.5; % Acceleration factor for vectorized sampling\ndefopts.NsamplesPerCall = 0; % # starting samples per trial per function call (0 = choose automatically)\ndefopts.MaxIter = 1e5; % Maximum number of iterations (per trial and estimate)\ndefopts.ReturnPositive = false; % If true, the first returned output is the *positive* log-likelihood\ndefopts.ReturnStd = false; % If true, the second returned output is the standard deviation of the estimate\ndefopts.MaxTime = Inf; % Maximum time for a IBS call (in seconds)\ndefopts.TrialWeights = []; % Vector of per-trial weights to yield a weighted sum of log-likelihood\n\n%% If called with no arguments or with 'defaults', return default options\nif nargout <= 1 && (nargin == 0 || (nargin == 1 && ischar(fun) && strcmpi(fun,'defaults')))\n if nargin < 1\n fprintf('Basic default options returned (type \"help ibslike\" for help).\\n');\n end\n nlogL = defopts;\n return;\nend\n\n%% If called with the first argument as 'test', run test\nif ischar(fun) && strcmpi(fun,'test')\n if nargin < 2; options = []; else; options = params; end\n figure; \n subplot(1,3,1);\n exitflag(1) = runtest1(options);\n subplot(1,3,2);\n exitflag(2) = runtest2(options);\n subplot(1,3,3);\n exitflag(3) = runtest3(options);\n nlogL = any(exitflag);\n return;\nend\n\nfor f = fields(defopts)'\n if ~isfield(options,f{:}) || isempty(options.(f{:}))\n options.(f{:}) = defopts.(f{:});\n end\nend\n\nNtrials = size(respMat,1);\n\n% Add hard-coded options\noptions.MaxSamples = 1e4; % Maximum # of samples per function call\noptions.AccelerationThreshold = 0.1; % Keep accelerating until threshold is passed (in s)\noptions.VectorizedThreshold = 0.1; % Max threshold for using vectorized algorithm (in s)\noptions.MaxMem = 1e6; % Maximum number of samples for vectorized implementation\noptions.MaxMem = max(min(Ntrials,1e4),10)*100; % Maximum number of samples for vectorized implementation\n\n% NSAMPLESPERCALL should be a scalar integer\nif ~isnumeric(options.NsamplesPerCall) || ~isscalar(options.NsamplesPerCall)\n error('ibslike:NsamplesPerCall','OPTIONS.NsamplesPerCall should be a scalar integer.');\nend\n\n% ACCELERATION should be a scalar equal or greater than 1\nif ~isnumeric(options.Acceleration) || ~isscalar(options.Acceleration) || ...\n options.Acceleration < 1\n error('ibslike:Acceleration','OPTIONS.Acceleration should be a scalar equal or greater than one.');\nend\n\n% NEGLOGLIKETHRESHOLD should be a scalar greater than 0 (or Inf)\nif ~isnumeric(options.NegLogLikeThreshold) || ~isscalar(options.NegLogLikeThreshold) || ...\n options.NegLogLikeThreshold <= 0\n error('ibslike:NegLogLikeThreshold','OPTIONS.NegLogLikeThreshold should be a positive scalar (including Inf).');\nend\n\n% MAXTIME should be a positive scalar (including Inf)\nif ~isnumeric(options.MaxTime) || ~isscalar(options.MaxTime) || ...\n options.MaxTime <= 0\n error('ibslike:MaxTime','OPTIONS.MaxTime should be a positive scalar (or Inf).');\nend\n\n% WEIGHT vector should be a scalar or same as number of trials\nweights = options.TrialWeights(:);\nif isempty(weights); weights = 1; end\n\nif numel(weights) ~= 1 && numel(weights) ~= Ntrials\n error('ibslike:NumWeights','OPTIONS.TrialWeights should be empty, a scalar or an array of weights with as many elements as the number of trials.');\nend\n\nTrials = (1:Ntrials)';\nfuncCount = 0;\n\nsimdata = []; elapsed_time = [];\n\n% Use vectorized or loop version?\nif ischar(options.Vectorized) && options.Vectorized(1) == 'a'\n if options.Nreps == 1\n vectorized_flag = false;\n else\n % First full simulation to determine computation time\n fun_clock = tic;\n if isempty(designMat) % Pass only trial indices\n simdata = fun(params,Trials(:),varargin{:});\n else % Pass full design matrix per trial\n simdata = fun(params,designMat(Trials(:),:),varargin{:}); \n end\n elapsed_time = toc(fun_clock);\n vectorized_flag = elapsed_time < options.VectorizedThreshold;\n funcCount = 1;\n end\nelse\n vectorized_flag = logical(options.Vectorized);\n if options.Nreps == 1 && vectorized_flag\n vectorized_flag = false;\n warning('Vectorized IBS requires OPTIONS.Nreps > 1. Switching to non-vectorized algorithm.');\n end\nend\n\nif vectorized_flag\n [nlogL,K,Nreps,Ns,fc,exitflag] = ...\n vectorized_ibs_sampling(fun,params,respMat,designMat,simdata,elapsed_time,t0,options,varargin{:});\nelse\n [nlogL,K,Nreps,Ns,fc,exitflag] = ...\n loop_ibs_sampling(fun,params,respMat,designMat,simdata,elapsed_time,t0,options,varargin{:});\nend\nfuncCount = funcCount + fc;\n\n% Variance of estimate per trial\nif nargout > 1\n K_max = max(max(K(:),1));\n Ktab = -(psi(1,1:K_max)' - psi(1,1)); \n LLvar = Ktab(max(K,1)); \n nlogLvar = sum(LLvar,2)./Nreps.^2;\nend\n\n% OUTPUT structure with additional information\nif nargout > 2\n output.funcCount = funcCount;\n output.NsamplesPerTrial = Ns/Ntrials;\n output.nlogL_trials = nlogL;\n output.nlogLvar_trials = nlogLvar;\nend\n\n% Return negative log-likelihood and variance summed over trials\nnlogL = sum(nlogL.*weights);\nif options.ReturnPositive; nlogL = -nlogL; end\nif nargout > 1\n nlogLvar = sum(nlogLvar.*(weights.^2));\n if options.ReturnStd % Return standard deviation instead of variance\n nlogLvar = sqrt(nlogLvar);\n end\nend\n\nend\n\n%--------------------------------------------------------------------------\nfunction [nlogL,K,Nreps,Ns,fc,exitflag] = vectorized_ibs_sampling(fun,params,respMat,designMat,simdata0,elapsed_time0,t0,options,varargin)\n\nNtrials = size(respMat,1);\nTrials = (1:Ntrials)';\nNs = 0;\nfc = 0;\nexitflag = 0;\n\nPsi_tab = []; % Empty PSI table\n\n% Empty matrix of K values (samples-to-hit) for each repeat for each trial\nK_mat = zeros([max(options.Nreps),Ntrials]);\n\n% Matrix of rep counts\nK_place0 = repmat((1:size(K_mat,1))',[1,Ntrials]);\n\n% Current rep being sampled for each trial\nRidx = ones(1,Ntrials);\n\n% Current vector of \"open\" K values per trial (not reached a \"hit\" yet)\nK_open = zeros(1,Ntrials);\n\ntargetHits = options.Nreps(:)'.*ones(1,Ntrials);\nMaxIter = options.MaxIter*max(options.Nreps);\n\n% Starting samples\nif options.NsamplesPerCall == 0\n samples_level = options.Nreps;\nelse\n samples_level = options.NsamplesPerCall;\nend\n\nfor iter = 1:MaxIter\n % Pick trials that need more hits, sample multiple times\n T = Trials(Ridx <= targetHits);\n if isfinite(options.MaxTime) && toc(t0) > options.MaxTime\n T = []; \n exitflag = 2; \n end\n if isempty(T); break; end\n \n Ttrials = numel(T); % Number of trials under consideration\n \n % With accelerated sampling, might request multiple samples at once\n Nsamples = min(options.MaxSamples,max(1,round(samples_level)));\n MaxSamples = ceil(options.MaxMem / Ttrials);\n Nsamples = min(Nsamples, MaxSamples);\n Tmat = repmat(T,[1,Nsamples]);\n \n % Simulate trials\n if iter == 1 && Nsamples == 1 && ~isempty(simdata0)\n simdata = simdata0;\n elapsed_time = elapsed_time0;\n else\n fun_clock = tic;\n if isempty(designMat) % Pass only trial indices\n simdata = fun(params,Tmat(:),varargin{:});\n fc = fc + 1;\n else % Pass full design matrix per trial\n simdata = fun(params,designMat(Tmat(:),:),varargin{:}); \n fc = fc + 1;\n end\n elapsed_time = toc(fun_clock);\n end\n \n % Check that the returned simulated data have the right size\n if size(simdata,1) ~= numel(Tmat)\n error('ibslike:SizeMismatch', ...\n 'Number of rows of returned simulated data does not match the number of requested trials.');\n end\n \n Ns = Ns + Ttrials;\n \n % Accelerated sampling\n if options.Acceleration > 0 && elapsed_time < options.AccelerationThreshold\n samples_level = samples_level*options.Acceleration;\n end\n \n % Check new \"hits\"\n hits_temp = all(respMat(Tmat(:),:) == simdata,2);\n \n % Build matrix of new hits (sandwich with buffer of hits, then removed)\n hits_new = [ones(1,Ttrials);reshape(hits_temp,size(Tmat))';ones(1,Ttrials)];\n \n % Warning: from now on it's going to be incomprehensible \n % (all vectorized for speed)\n \n % Extract matrix of Ks from matrix of hits for this iteration\n h = size(hits_new,1);\n list = find(hits_new(:) == 1)-1;\n row = floor(list/h)+1;\n col = mod(list,h)+1;\n delta = diff([col;1]);\n remidx = delta <= 0;\n delta(remidx) = [];\n row(remidx) = [];\n indexcol = find(diff([0;row]));\n col = 1 + (1:numel(row))' - indexcol(row);\n K_iter = zeros(size(T,1),max(col));\n K_iter(row + (col-1)*size(K_iter,1)) = delta;\n\n % This is the comprehensible version that we want to get to:\n %\n % for iTrial = 1:Ntrials\n % index = find(hits_new(iTrial,:),targetHits(iTrial));\n % K = diff([0 index]);\n % logL(iTrial) = sum(Ktab(K))/numel(index);\n % end\n \n \n % Add still-open K to first column\n K_iter(:,1) = K_open(T)' + K_iter(:,1);\n \n % Find last K position for each trial\n [~,idx_last] = min([K_iter,zeros(Ttrials,1)],[],2);\n idx_last = idx_last - 1;\n ii = sub2ind(size(K_iter),(1:Ttrials)',idx_last);\n \n % Subtract one hit from last K (it was added)\n K_iter(ii) = K_iter(ii) - 1;\n K_open(T) = K_iter(ii)';\n \n % For each trial, ignore entries of K_iter past max # of reps\n idx_mat = bsxfun(@plus,Ridx(T)',repmat(0:size(K_iter,2)-1,[Ttrials,1]));\n K_iter(idx_mat > (options.Nreps)) = 0;\n \n % Find last K position for each trial again\n [~,idx_last2] = min([K_iter,zeros(Ttrials,1)],[],2);\n idx_last2 = idx_last2 - 1;\n \n % Add current K to full K matrix \n K_iter_place = bsxfun(@ge,K_place0(:,1:Ttrials),Ridx(T)) & bsxfun(@le,K_place0(:,1:Ttrials),Ridx(T) + idx_last2'- 1);\n K_place = false(size(K_place0));\n K_place(:,T) = K_iter_place;\n Kt = K_iter'; \n K_mat(K_place) = Kt(Kt > 0);\n Ridx(T) = Ridx(T) + idx_last' - 1;\n \n % Compute log-likelihood only if requested for thresholding\n if isfinite(options.NegLogLikeThreshold)\n Rmin = min(Ridx(T)); % Find repeat still ongoing\n if Rmin > size(K_mat,1); continue; end\n [LL_temp,Psi_tab] = get_LL_from_K(Psi_tab,K_mat(Rmin,:));\n nLL_temp = -sum(LL_temp,1);\n if nLL_temp > options.NegLogLikeThreshold\n idx_move = Ridx == Rmin;\n Ridx(idx_move) = Rmin+1;\n K_open(idx_move) = 0;\n exitflag = 1;\n end\n end\nend\n\nif ~isempty(T)\n error('ibslike:ConvergenceFail', ...\n 'Maximum number of iterations or time limit reached and algorithm did not converge. Check FUN and DATA.');\nend\n \n% Log likelihood estimate per trial and run lengths K for each repetition\nNreps = sum(K_mat > 0,1)';\n[LL_mat,Psi_tab] = get_LL_from_K(Psi_tab,K_mat);\nnlogL = sum(-LL_mat',2)./Nreps;\nK = K_mat';\n\nend\n\n\n\n%--------------------------------------------------------------------------\nfunction [nlogL,K,Nreps,Ns,fc,exitflag] = loop_ibs_sampling(fun,params,respMat,designMat,simdata0,elapsed_time0,t0,options,varargin)\n\nNtrials = size(respMat,1);\nTrials = (1:Ntrials)';\nMaxIter = options.MaxIter;\nexitflag = 0;\n\nK = zeros(Ntrials,options.Nreps);\nNs = 0;\nfc = 0;\nPsi_tab = [];\n\nfor iRep = 1:options.Nreps\n \n offset = 1;\n hits = zeros(Ntrials,1);\n if isfinite(options.MaxTime) && toc(t0) > options.MaxTime\n exitflag = 2;\n break;\n end\n \n for iter = 1:MaxIter\n % Pick trials that need more hits, sample multiple times\n T = Trials(hits < 1);\n if isempty(T); break; end \n\n % Simulate trials\n if iter == 1 && iRep == 1 && ~isempty(simdata0)\n simdata = simdata0;\n elseif isempty(designMat) % Pass only trial indices\n simdata = fun(params,T(:),varargin{:});\n fc = fc + 1;\n else % Pass full design matrix per trial\n simdata = fun(params,designMat(T(:),:),varargin{:}); \n fc = fc + 1;\n end\n \n % Check that the returned simulated data have the right size\n if size(simdata,1) ~= numel(T)\n error('ibslike:SizeMismatch', ...\n 'Number of rows of returned simulated data does not match the number of requested trials.');\n end\n \n Ns = Ns + numel(T); % Count samples\n hits_new = all(respMat(T(:),:) == simdata,2); \n hits(T) = hits(T) + hits_new;\n \n K(T(hits_new),iRep) = offset; \n offset = offset + 1;\n \n % Terminate if negative log likelihood is above a given threshold\n if isfinite(options.NegLogLikeThreshold)\n K(hits < 1,iRep) = offset;\n [LL_mat,Psi_tab] = get_LL_from_K(Psi_tab,K(:,iRep));\n nlogL_sum = -sum(LL_mat,1); \n if nlogL_sum > options.NegLogLikeThreshold\n T = [];\n exitflag = 1;\n break;\n end\n end\n \n % Terminate if above maximum allowed runtime\n if isfinite(options.MaxTime) && toc(t0) > options.MaxTime\n T = [];\n exitflag = 2;\n break;\n end\n\n end\n \n if ~isempty(T)\n error('ibslike:ConvergenceFail', ...\n 'Maximum number of iterations reached and algorithm did not converge. Check FUN and DATA.');\n end \nend\n \nNreps = sum(K > 0,2);\n[LL_mat,Psi_tab] = get_LL_from_K(Psi_tab,K);\nnlogL = sum(-LL_mat,2)./Nreps;\n\nend\n\n\n%--------------------------------------------------------------------------\nfunction [LL_mat,Psi_tab] = get_LL_from_K(Psi_tab,K_mat)\n%GET_LL_FROM_K Convert matrix of K values into log-likelihoods.\n\nK_max = max(1,max(K_mat(:)));\nif K_max > numel(Psi_tab) % Fill digamma function table\n Psi_tab = [Psi_tab; (psi(1) - psi(numel(Psi_tab)+1:K_max)')];\nend\nLL_mat = Psi_tab(max(1,K_mat));\n\nend\n\n%--------------------------------------------------------------------------\nfunction exitflag = runtest1(options)\n\nNreps = 1e3;\nRMSE_tol = 2/sqrt(Nreps);\n\n% Binomial probability model\np_model = exp(linspace(log(1e-3),log(1),10));\nfun = @(x,dmat) rand(size(dmat)) < x; % Simulating function\nrmat = fun(1,NaN);\n\nfprintf('\\n');\nfprintf('TEST 1: Using IBS to compute log(p) of Bernoulli distributions with %d repeats.\\n',Nreps);\nfprintf('We consider p = %s.\\n',mat2str(p_model,3));\n\noptions.Nreps = Nreps;\noptions.NegLogLikeThreshold = Inf;\n\nnlogL = zeros(1,numel(p_model));\nnlogLvar = zeros(1,numel(p_model));\nfor iter = 1:numel(p_model)\n [nlogL(iter),nlogLvar(iter)] = ibslike(fun,p_model(iter),rmat,[],options);\nend\n\n% We expect the true value to be almost certainly (> 99.99%) in this range\nLL_min = (-nlogL - 4*sqrt(nlogLvar));\nLL_max = (-nlogL + 4*sqrt(nlogLvar));\n\nexitflag = any(log(p_model) < LL_min) | any(log(p_model) > LL_max);\n\nrmse = sqrt(mean((-nlogL - log(p_model)).^2));\nfprintf('Average RMSE of log(p) estimates across p: %.4f.\\n',rmse);\n\nexitflag = exitflag | (rmse > RMSE_tol);\n\nif exitflag\n fprintf('Test FAILED. Something might be wrong.\\n'); \nelse\n fprintf('Test PASSED. IBS estimates are calibrated and close to ground truth.\\n'); \nend\n\n% Plot figure\nxx = log(p_model);\nh(1) = plot(xx,xx,'k-','LineWidth',2); hold on;\n\nyy = -nlogL;\nxxerr = [xx, fliplr(xx)];\nyyerr_down = yy - 1.96*sqrt(nlogLvar);\nyyerr_up = yy + 1.96*sqrt(nlogLvar);\nyyerr = [yyerr_down, fliplr(yyerr_up)];\nfill(xxerr, yyerr,'b','FaceAlpha',0.5,'LineStyle','none'); hold on;\nh(2) = plot(xx,yy,'b-','LineWidth',2); hold on;\n\nbox off;\nset(gca,'TickDir','out');\nset(gcf,'Color','w');\nxlabel('True log(p)');\nylabel('Estimated log(p)')\n%xlim([-5 5]);\nhl = legend(h,'True log(p)','IBS estimate (95% CI)');\nset(hl,'Location','NorthWest','Box','off');\ntitle('IBS estimation test');\n\nend\n\n\n%--------------------------------------------------------------------------\nfunction exitflag = runtest2(options)\n\n% Binomial probability model\nNtrials = 100; \np_true = 0.9*rand() + 0.05; % True probability\np_model = 0.9*rand() + 0.05; % Model probability\nfun = @(x,dmat) rand(size(dmat)) < x; % Simulating function\nNexps = 2e3;\n\noptions.NegLogLikeThreshold = Inf;\n\nfprintf('\\n');\nfprintf('TEST 2: Using IBS to compute the log-likelihood of a binomial distribution.\\n');\nfprintf('Parameters: p_true=%.2g, p_model=%.2g, %d trials per experiment.\\n',p_true,p_model,Ntrials);\nfprintf('The distribution of z-scores should approximate a standard normal distribution (mean 0, SD 1).\\n');\n\nzscores = zeros(1,Nexps);\nfor iter = 1:Nexps\n rmat = fun(p_true,NaN(Ntrials,1)); % Generate data\n [nlogL,nlogLvar] = ibslike(fun,p_model,rmat,[],options);\n nlogL_exact = -log(p_model)*sum(rmat == 1) - log(1-p_model)*sum(rmat == 0);\n zscores(iter) = (nlogL_exact - nlogL)/sqrt(nlogLvar);\nend\n\nedges = -4.75:0.5:4.75;\nnz = histc(zscores,edges);\nh(1) = bar(edges,nz,'histc');\nhold on;\nxx = linspace(-5,5,1e4);\nh(2) = plot(xx,Nexps*exp(-xx.^2/2)/sqrt(2*pi)/2,'k-','LineWidth',2);\n\nbox off;\nset(gca,'TickDir','out');\nset(gcf,'Color','w');\nxlabel('z-score');\nylabel('pdf')\nxlim([-5 5]);\nhl = legend(h,'z-scores histogram','expected pdf');\nset(hl,'Location','NorthEast','Box','off');\ntitle('Calibration test');\n\nexitflag = abs(mean(zscores)) > 0.15 || abs(std(zscores) - 1) > 0.1;\n\nfprintf('Distribution of z-scores (%d experiments). Mean: %.4g. Standard deviation: %.4g.\\n',Nexps,mean(zscores),std(zscores));\nif exitflag\n fprintf('Test FAILED. Something might be wrong.\\n'); \nelse\n fprintf('Test PASSED. We verified that IBS is unbiased (~zero mean) and calibrated (SD ~1).\\n');\nend\n\nend\n\n%--------------------------------------------------------------------------\nfunction exitflag = runtest3(options)\n\nNreps = 100;\nRMSE_tol = 4/sqrt(Nreps);\n\n% Binomial probability model\np_model = exp(linspace(log(1e-3),log(0.1),10));\nfun = @(x,dmat) rand(size(dmat)) < x; % Simulating function\nrmat = fun(1,NaN);\nthresh = -log(0.01);\np_target = max(p_model,exp(-thresh));\n\nfprintf('\\n');\nfprintf('TEST 3: Log-likelihood thresholding at log(p) = %.3f.\\n',-thresh);\nfprintf('Using IBS to compute thresholded log(p) of Bernoulli distributions with %d repeats.\\n',Nreps);\nfprintf('We consider p = %s.\\n',mat2str(p_model,3));\n\noptions.Nreps = Nreps;\noptions.NegLogLikeThreshold = thresh;\noptions.Acceleration = 1;\n\nnlogL = zeros(1,numel(p_model));\nnlogLvar = zeros(1,numel(p_model));\nfor iter = 1:numel(p_model)\n [nlogL(iter),nlogLvar(iter)] = ibslike(fun,p_model(iter),rmat,[],options);\nend\n\n% We expect the true value to be almost certainly (> 99.99%) in this range\nLL_min = (-nlogL - 4*sqrt(nlogLvar));\nLL_max = (-nlogL + 4*sqrt(nlogLvar));\n\n% We expect the estimates to be (almost) correct away from the threshold\nidx = log(p_model) > -thresh*0.75;\nexitflag = any(log(p_model(idx)) < LL_min(idx)) | any(log(p_model(idx)) > LL_max(idx));\n\n% We expect the estimates to be above the true value below the threshold\nLL_thresh = (-nlogL - sqrt(nlogLvar));\nidx_below = log(p_model) < -thresh;\nexitflag = exitflag | any(log(p_model(idx_below)) > LL_thresh(idx_below));\n% exitflag = any(log(p_target) < LL_min) | any(log(p_target) > LL_max);\n\nrmse = sqrt(mean((-nlogL(idx) - log(p_target(idx))).^2));\nfprintf('Average RMSE of log(p) estimates across p: %.4f.\\n',rmse);\n\nexitflag = exitflag | (rmse > RMSE_tol);\n\nif exitflag\n fprintf('Test FAILED. Something might be wrong.\\n'); \nelse\n fprintf('Test PASSED. IBS estimates are calibrated and close to (thresholded) ground truth.\\n'); \nend\n\n% Plot figure\nxx = log(p_model);\nh(1) = plot(xx,xx,'k-','LineWidth',2); hold on;\n\nyy = -nlogL;\nxxerr = [xx, fliplr(xx)];\nyyerr_down = yy - 1.96*sqrt(nlogLvar);\nyyerr_up = yy + 1.96*sqrt(nlogLvar);\nyyerr = [yyerr_down, fliplr(yyerr_up)];\nfill(xxerr, yyerr,'b','FaceAlpha',0.5,'LineStyle','none'); hold on;\n\nh(2) = plot(xx,yy,'b-','LineWidth',2); hold on;\nh(3) = plot([xx(1),xx(end)],-thresh*[1 1],'k:','LineWidth',2);\n\nbox off;\nset(gca,'TickDir','out');\nset(gcf,'Color','w');\nxlabel('True log(p)');\nylabel('Estimated log(p) with thresholding')\n%xlim([-5 5]);\nhl = legend(h,'True log(p)','IBS estimate (95% CI)','Threshold');\nset(hl,'Location','NorthWest','Box','off');\ntitle('Thresholded IBS test');\n\nend\n\n\n% TODO:\n% - Fix help and documentation\n% - Optimal allocation of estimates?\n", "meta": {"author": "acerbilab", "repo": "vbmc", "sha": "54ba2cdd6c11d2595b9613557da14573abbb7b92", "save_path": "github-repos/MATLAB/acerbilab-vbmc", "path": "github-repos/MATLAB/acerbilab-vbmc/vbmc-54ba2cdd6c11d2595b9613557da14573abbb7b92/utils/ibslike.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.484402540550008}} {"text": "function path = imGeodesicPath(img, source, target, varargin)\n%IMGEODESICPATH Compute a geodesic path between two markers in an image\n%\n% PATH = imGeodesicPath(MASK, SOURCE, TARGET)\n% Computea minimal geodesic-distance path between the two markers SOURCE\n% and TARGET. Both SOURCE and TARGET can be either a binary image the\n% same size as MASK, or a N-by-2 array containing a list of coordinates\n% (x first, y second).\n% The result PATH is a P-by-2 array containing coordinates of a polyline\n% with minimal geodesic length starting from one of the points specified\n% by SOURCE, and terminating at one of the points specified by TARGET.\n% Note that the result is not uniquely defined, and the returned solution\n% is one of the possible solutions. \n%\n% PATH = imGeodesicPath(..., WEIGHTS)\n% Specify the weights to use for propagating chamfer distance. Default is\n% [3 4], as suggested by Borgefors.\n%\n% PATH = imGeodesicPath(..., 'verbose', V)\n% Specify the verbosity. V can be either TRUE or FALSE.\n%\n% \n% Example\n% % read circle image, and create 2 markers \n% img = imread('circles.png');\n% imshow(img); hold on;\n% p1 = [130 130]; % (x1,y1)\n% p2 = [170 170]; % (x2,y2)\n% plot(p1(1), p1(2), 'bo');\n% plot(p2(1), p2(2), 'ro');\n% % Compute and display the path as a polyline\n% path = imGeodesicPath(img, p1, p2);\n% plot(path(:,1), path(:,2), 'color', 'm', 'linewidth', 2);\n%\n% See also\n% imGeodesics, imGeodesicDistanceMap, imMaxGeodesicPath\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2011-04-04, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011 INRA - Cepia Software Platform.\n\n\n%% Default values \n\n% weights for computing geodesic lengths\nws = [3 4];\n\n% no verbosity by default\nverbose = 0;\n\n\n%% process input arguments\n\n% extract weights if present\nif ~isempty(varargin)\n if isnumeric(varargin{1})\n ws = varargin{1};\n varargin(1) = [];\n end\nend\n\n% Extract options\nwhile ~isempty(varargin)\n paramName = varargin{1};\n if strcmpi(paramName, 'verbose')\n verbose = varargin{2};\n else\n error(['Unkown option in imGeodesicLength: ' paramName]);\n end\n varargin(1:2) = [];\nend\n\n% forces input image to binary\nimg = img > 0;\n\n\n%% Propagate distance from destination markers\n\n% initialize marker image\nif sum(size(target) == size(img)) == 2\n % initialize from binary mask\n markers = target > 0;\n \nelse\n % initialize from set of points\n markers = false(size(img));\n for i = 1:size(target, 1)\n markers(target(i,2), target(i,1)) = true;\n end\nend\n\n% compute distance map from marker\ndist = imGeodesicDistanceMap(img, markers, ws, 'verbose', verbose);\n\n\n%% Find position of first source point \n\n% find position of closest point belonging to the source\nif sum(size(source) == size(img)) == 2\n % compute in a binary mask\n [minDist, ind] = min(dist(source));\n [ys, xs] = ind2sub(size(source), ind);\n \nelse\n % initialize from set of points\n minDist = inf;\n for i = 1:size(source, 1)\n value = dist(source(i,2), source(i,1));\n if value < minDist\n xs = source(i,1);\n ys = source(i,2);\n minDist = value;\n end\n end\nend\n\n% check existence of path\nif isempty(minDist)\n warning([mfilename ':NoPathFound'], ...\n 'No path could be found between the two markers');\n path = [];\n return;\nend\n\n\n%% Create the path by returning to destination marker\n\n% add a 1-pixel wide border around image, initialized with very high value\ntmp = dist;\ndist = zeros(size(dist)+2, class(dist));\ndist(:) = max(tmp(:)) + 2;\ndist(2:end-1, 2:end-1) = tmp;\n\n% keep coordinates of geodesic extremity\nx = xs + 1;\ny = ys + 1;\n\n% initialize path\npath = [x y];\n\nwhile true\n % check around current point\n neigh = dist(y-1:y+1, x-1:x+1);\n \n % look for the minimum\n [mini, ind] = min(neigh(:));\n \n % if minimum is the same as current value, minima is found\n if mini == dist(y, x)\n break;\n end\n \n % convert index to sub\n [iy, ix] = ind2sub([3 3], ind(1));\n \n % update coord\n x = x + ix - 2;\n y = y + iy - 2;\n \n % stores result\n path = [path; x y]; %#ok\nend\n\n% subtract 1, because of border\npath = path - 1;\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/imGeodesicPath.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.4843579901833688}} {"text": "function y = erfc(x)\n%ERFC Implements erfc(x) for real intervals\n%\n% y = erfc(x)\n%\n%interval standard function implementation\n%\n\n% written 05/30/13 S.M. Rump\n%\n\n if x.complex\n error('Error function only for real arguments')\n end\n \n if issparse(x)\n index = ( x==0 );\n if any(index(:)) % treat zero indices\n y = intval(ones(size(x)));\n index = ~index;\n %VVVV y(index) = erfc(full(x(index)));\n s.type = '()'; s.subs = {index}; y = subsasgn(y,s,erfc(full(subsref(x,s))));\n %AAAA Matlab bug fix\n else\n y = erfc(full(x));\n end\n return\n end\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 y = x;\n \n if all( x.inf(:)==x.sup(:) ); % thin input\n \n [y.inf,y.sup] = erfc_rnd(x.inf(:),[]);\n \n else % thick input\n \n y.inf = erfc_rnd(x.sup(:),-1);\n y.sup = erfc_rnd(x.inf(:),1);\n \n end\n \n y.inf = reshape(y.inf,size(x.inf));\n y.sup = reshape(y.sup,size(x.sup));\n \n setround(rndold) \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/intval/@intval/erfc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.484347193675547}} {"text": "% OP_GRADSYMU_GRADSYMV_MP: assemble the stiffness matrix A = [a(i,j)], a(i,j) = (epsilon gradsym u_j, gradsym v_i), in a multipatch domain.\n%\n% mat = op_gradsymu_gradsymv_mp (spu, spv, msh, [epsilon], [patches]);\n%\n% INPUT:\n%\n% spu: object representing the space of trial functions (see sp_multipatch)\n% spv: object representing the space of test functions (see sp_multipatch)\n% msh: object defining the domain partition and the quadrature rule (see msh_multipatch)\n% epsilon: function handle to compute the diffusion coefficient. Equal to one if left empty.\n% patches: list of patches where the integrals have to be computed. By default, all patches are selected.\n%\n% OUTPUT:\n%\n% mat: assembled stiffness matrix\n% \n% Copyright (C) 2015, 2016, 2020 Rafael Vazquez\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\nfunction A = op_gradsymu_gradsymv_mp (spu, spv, msh, coeff, patch_list)\n\n if (nargin < 5)\n patch_list = 1:msh.npatch;\n end\n\n if ((spu.npatch ~= spv.npatch) || (spu.npatch ~= msh.npatch))\n error ('op_gradsymu_gradsymv_mp: the number of patches does not coincide')\n end\n \n ncounter = 0;\n for iptc = patch_list\n if (nargin < 4 || isempty (coeff))\n [rs, cs, vs] = op_gradsymu_gradsymv_tp (spu.sp_patch{iptc}, spv.sp_patch{iptc}, msh.msh_patch{iptc});\n else\n [rs, cs, vs] = op_gradsymu_gradsymv_tp (spu.sp_patch{iptc}, spv.sp_patch{iptc}, msh.msh_patch{iptc}, coeff);\n end\n rows(ncounter+(1:numel (rs))) = spv.gnum{iptc}(rs);\n cols(ncounter+(1:numel (rs))) = spu.gnum{iptc}(cs);\n\n if (~isempty (spv.dofs_ornt))\n vs = spv.dofs_ornt{iptc}(rs)' .* vs;\n end\n if (~isempty (spu.dofs_ornt))\n vs = vs .* spu.dofs_ornt{iptc}(cs)';\n end\n \n vals(ncounter+(1:numel (rs))) = vs;\n ncounter = ncounter + numel (rs);\n end\n\n A = sparse (rows, cols, vals, spv.ndof, spu.ndof);\n clear rows cols vals rs cs vs\n \nend\n", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/multipatch/@sp_multipatch/op_gradsymu_gradsymv_mp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.4842579055552275}} {"text": "function n = kpu_order ( l )\n\n%*****************************************************************************80\n%\n%% KPU_ORDER computes the order of a KPU rule from the level.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 May 2012\n%\n% Author:\n%\n% John Burkardt.\n%\n% Parameters:\n%\n% Input, integer L, the level of the rule.\n% 1 <= L <= 25\n%\n% Output, integer N, the order of the rule.\n%\n if ( l < 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'KPU_ORDER - Fatal error!\\n' );\n fprintf ( 1, ' 1 <= L <= 25 required.\\n' );\n fprintf ( 1, ' Input L = %d\\n', l );\n error ( 'KPU_ORDER - Fatal error!' );\n elseif ( l == 1 )\n n = 1;\n elseif ( l <= 3 )\n n = 3;\n elseif ( l <= 6 )\n n = 7;\n elseif ( l <= 12 )\n n = 15;\n elseif ( l <= 24 )\n n = 31;\n elseif ( l <= 25 )\n n = 63;\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'KPU_ORDER - Fatal error!\\n' );\n fprintf ( 1, ' 1 <= L <= 25 required.\\n' );\n fprintf ( 1, ' Input L = %d\\n', l );\n error ( 'KPU_ORDER - 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/sparse_grid_hw/kpu_order.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.4841328591565634}} {"text": "% LORENZ system\n% Train ensemble of models (e.g. for varying training data length, noise\n% level, etc.)\n% System identification: SINDYc\n\nclear all, close all, clc\n\nSystemModel = 'LORENZ';\nDERIV_NOISE = 0;\nTRACK_MODEL_BEST = 0;\n%% Set Paths\nfigpath = '../FIGURES/EX_LORENZ_Dependencies/SINDYc/'; mkdir(figpath)\ndatapath = '../DATA/EX_LORENZ_Dependencies/SINDYc/'; mkdir(datapath)\n\n% Overwrite if necessary\nif exist('DERIV_NOISE')\n if DERIV_NOISE == 1\n figpath = '../FIGURES/EX_LORENZ_Dependencies/SINDYc/TVRegDiff/'; mkdir(figpath)\n datapath = '../DATA/EX_LORENZ_Dependencies/SINDYc/TVRegDiff/'; mkdir(datapath)\n end\nend\naddpath('../utils');\n\n%% Parameters\nModelName = 'SINDYc';\npolyorder = 2;\nusesine = 0;\nlambda0 = 0.1; % lambda is our sparsification knob.\ndep_trainlength = 1;\ndep_noise = 0;\n\nMOD_VAL = 10;\n\n%% Select case 1 or 2\n% 1) Dependency on training length\nNtrain_vec = [5:15,20:5:95,100:100:1000];%,1250,1500,2000,3000];%,1500:500:3000];\neta_vec = 0;%0.05;\nNr = 1;%50;\n\n% 2) Noise dependency\n% Ntrain_vec = 3000;\n% eta_vec = [0.01 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5];\n% Nr = 50;\n\nN_LENGTHS = length(Ntrain_vec);\nN_ETA = length(eta_vec);\n\n%% Parameters\nSAVE_MODEL = 0;\nSHOW_RESULTS = 0;\nSHOW_STATS = 1;\nONLY_TRAINING_LENGTH = 1; % if 0 : 3000 time unit, otherwise 1000\n\nif ONLY_TRAINING_LENGTH == 1\n PostName = ['_TrainLength'];\nelse\n PostName = [];\nend\n%% Generate Data %{'sine2', 'chirp','prbs', 'sphs'}\nInputSignalType = 'sphs'; %prbs; chirp; noise; sine2; sphs; mixed\ngetTrainingData\n\nDataTrain.x = x;\nDataTrain.t = t;\nDataTrain.tspan = tspan;\nDataTrain.u = u;\n\nxstd = std(xv(:,3));\n\nclose all\nrng(0,'twister')\n\nerrBest = inf*ones(N_LENGTHS,N_ETA);\n% BestModels(1:N_LENGTHS,1:N_ETA) = struct('name', [], 'polyorder', [], 'usesine', [], 'Xi', [], ...\n% 'dt', [], 'N', [], 'Ttraining', [], 'Err', [], 'ErrM', []);\nBestModelsList = zeros(N_LENGTHS,N_ETA);\nLambda = zeros(N_LENGTHS,N_ETA);\nNvar = 3;\n%% SINDYc\nif ONLY_TRAINING_LENGTH == 0\n for iN = 1:N_LENGTHS\n for iNoise = 1:N_ETA\n disp(['Running for noise case ', num2str(iNoise), ' of ', num2str(N_ETA)])\n \n Results = struct('err', zeros(Nr,1), 'errM', zeros(Nr,1), 'xA', zeros(length(tv),Nvar), 'xB', zeros(length(tv),Nvar,Nr),'Ttraining',zeros(Nr,1));\n \n for iR = 1:Nr\n \n % Setup data\n x = DataTrain.x(1:Ntrain_vec(iN),:);\n u = DataTrain.u(1:Ntrain_vec(iN));\n t = DataTrain.t(1:Ntrain_vec(iN));\n tspan = DataTrain.tspan(1:Ntrain_vec(iN));\n \n % Add noise\n eps = eta_vec(iNoise)*xstd;\n x = x + eps*randn(size(x));\n \n % Train model\n lambda = lambda0;\n tic\n trainSINDYc\n telapsed = toc\n \n % Prediction over training phase\n p.ahat = Xi(:,1:3);\n p.polyorder = polyorder;\n p.usesine = usesine;\n p.dt = dt;\n [N,Ns] = size(DataTrain.x);\n xSINDYc = zeros(Ns,N); xSINDYc(:,1) = x0';\n for ct=1:N-1\n xSINDYc(:,ct+1) = rk4u(@sparseGalerkinControl_Discrete,xSINDYc(:,ct),DataTrain.u(ct),dt,1,[],p);\n end\n xSINDYc = xSINDYc';\n \n % Show validation\n SHOW_PREDICTION_FOR_TRAINING_PHASE\n \n %% Prediction\n % Reference\n xA = [xv];\n tA = tv;\n \n % Model\n [N,Ns] = size(xA);\n xB = zeros(Ns,N); xB(:,1) = DataTrain.x(end,:)';\n for ct=1:N\n xB(:,ct+1) = rk4u(@sparseGalerkinControl_Discrete,xB(:,ct),uv(ct),dt,1,[],p);\n end\n xB = xB(:,1:N+1)';\n tB = [tv(1)-dt;tv];\n \n % Show training and prediction\n SHOW_PREDICTION_FOR_VALIDATION_PHASE\n \n %% Error\n err = mean(sum((xB(2:end,:)-xA).^2,2));\n errM = mean(sum((xB(2:250+1,:)-xA(1:250,:)).^2,2));\n \n \n %% Save Data\n Model.name = 'SINDYc';\n Model.polyorder = polyorder;\n Model.usesine = usesine;\n Model.Xi = Xi;\n Model.dt = dt;\n Model.N = Ntrain_vec(iN);\n Model.Ttraining = telapsed;\n Model.Err = err;\n Model.ErrM = errM;\n \n \n if SAVE_MODEL == 1\n if mod(iR,MOD_VAL) == 0 || iR == 1\n \n save(fullfile(datapath,['EX_',SystemModel,'_SI_',ModelName,'_',InputSignalType,'_N',sprintf('%04g',Ntrain_vec(iN)),'_Eta',sprintf('%03g',100*eta_vec(iNoise)),'_iR',num2str(iR),'.mat']),'Model')\n end\n end\n \n Results.err(iR) = err;\n Results.errM(iR) = errM;\n Results.xA = xA;\n Results.xB(:,1:3,iR) = xB(2:end,:);\n Results.Ttraining(iR) = telapsed;\n \n %% Track best model\n % errBest = 10^12*ones(N_LENGTHS,N_ETA)\n if TRACK_MODEL_BEST == 1\n if Results.err(iR)0.1;\n idx = [];\n for iVar = 1:Nvar\n idx = [idx ; find(TF(:,iVar)==1,1,'first')];\n end\n Results.PredLength(iL,1) = max(idx);\n \n tmp2 = sqrt(sum(abs(DataTrain.x - xSINDYc).^2,2));\n idx = find(tmp2>3,1,'first');\n Results.PredHor_Ball(iL,1) = idx-1;\n %% Prediction\n % Reference\n xA = [xv];\n tA = tv;\n \n % Model\n [N,Ns] = size(xA);\n xB = zeros(Ns,N); xB(:,1) = DataTrain.x(end,:)';\n for ct=1:N\n xB(:,ct+1) = rk4u(@sparseGalerkinControl_Discrete,xB(:,ct),uv(ct),dt,1,[],p);\n end\n xB = xB(:,1:N+1)';\n tB = [tv(1)-dt;tv];\n \n %% Error over prediction phase\n xB = xB(2:end,:);\n Results.err(iL,2) = mean(sum((xB-xA).^2,2));\n Results.RelErr(iL,2) = mean( sum( abs( (xA - xB)./xA ),2) );\n Results.RelErrMax(iL,2) = mean( max( abs( (xA - xB)./xA ),[],2) );\n Results.Ttraining(iL) = telapsed;\n \n tmp = abs( (xA - xB)./xA );\n TF = tmp>0.1;\n idx = [];\n for iVar = 1:Nvar\n idx = [idx ; find(TF(:,iVar)==1,1,'first')];\n end\n Results.PredLength(iL,2) = max(idx);\n \n tmp2 = sqrt(sum(abs(xA - xB).^2,2));\n idx = find(tmp2>3,1,'first');\n Results.PredHor_Ball(iL,2) = idx-1;\n end\n \n Results.DataTrain = DataTrain;\n Results.DataValid.x = xv;\n Results.DataValid.u = uv;\n Results.DataValid.t = tv;\n Results.DataValid.tspan = tspanv;\n save(fullfile(datapath,['EX_',SystemModel,'_SI_',ModelName,'_',InputSignalType,'_Eta',sprintf('%03g',100*eta_vec),'_Nevol','_STATS.mat']),'Results')\nend", "meta": {"author": "eurika-kaiser", "repo": "SINDY-MPC", "sha": "e1dfd9908b2b56af303ee9fb30a133aced4fd757", "save_path": "github-repos/MATLAB/eurika-kaiser-SINDY-MPC", "path": "github-repos/MATLAB/eurika-kaiser-SINDY-MPC/SINDY-MPC-e1dfd9908b2b56af303ee9fb30a133aced4fd757/EX_LORENZ/EX_LORENZ_SI_SINDYc_Dependency.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.48383755815253415}} {"text": "function jed = transition_to_jed_english ( )\n\n%*****************************************************************************80\n%\n%% TRANSITION_TO_JED_ENGLISH returns the English calendar transition as a JED.\n%\n% Discussion:\n%\n% In the English calendar, the last moment of the Julian calendar was\n% 11:59 pm, 2 September 1752 Julian/English,\n% 11:59 pm, 13 September 1752 Gregorian/CE.\n% The first minute of the Gregorian calendar ended at\n% 12:01 am, 3 September 1752 Julian,\n% 12:01 am, 15 September 1752 Gregorian/CE/English.\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 = 2361221.5;\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/calpak/transition_to_jed_english.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.48373292744923424}} {"text": "function f = non_domination_sort_mod(x, M, V)\n\n%% function f = non_domination_sort_mod(x, M, V)\n% This function sort the current popultion based on non-domination. All the\n% individuals in the first front are given a rank of 1, the second front\n% individuals are assigned rank 2 and so on. After assigning the rank the\n% crowding in each front is calculated.\n\n% Copyright (c) 2009, Aravind Seshadri\n% All rights reserved.\n\n% [N, m] = size(x);\n% clear m;\nN = size(x,1); % modified by zzb\nx_temp = zeros(N,M + V + 1); % modified by zzb\nx_temp(:,1:M + V) = x(:,1:M + V); % modified by zzb\n% Initialize the front number to 1.\nfront = 1;\n% There is nothing to this assignment, used only to manipulate easily in\n% MATLAB.\n% F(front).f = [];\n% individual = [];\nF = struct('f',cell(1,N)); % modified by zzb\nindividual = struct('n',cell(1,N),'p',cell(1,N)); % modified by zzb\n\n%% Non-Dominated sort. \n% The initialized population is sorted based on non-domination. The fast\n% sort algorithm [1] is described as below for each\n\n% ?for each individual p in main population P do the following\n% ?Initialize Sp = []. This set would contain all the individuals that is\n% being dominated by p.\n% ?Initialize np = 0. This would be the number of individuals that domi-\n% nate p.\n% ?for each individual q in P\n% * if p dominated q then\n% ?add q to the set Sp i.e. Sp = Sp ? {q}\n% * else if q dominates p then\n% ?increment the domination counter for p i.e. np = np + 1\n% ?if np = 0 i.e. no individuals dominate p then p belongs to the first\n% front; Set rank of individual p to one i.e prank = 1. Update the first\n% front set by adding p to front one i.e F1 = F1 ? {p}\n% ?This is carried out for all the individuals in main population P.\n% ?Initialize the front counter to one. i = 1\n% ?following is carried out while the ith front is nonempty i.e. Fi != []\n% ?Q = []. The set for storing the individuals for (i + 1)th front.\n% ?for each individual p in front Fi\n% * for each individual q in Sp (Sp is the set of individuals\n% dominated by p)\n% ?nq = nq-1, decrement the domination count for individual q.\n% ?if nq = 0 then none of the individuals in the subsequent\n% fronts would dominate q. Hence set qrank = i + 1. Update\n% the set Q with individual q i.e. Q = Q ? q.\n% ?Increment the front counter by one.\n% ?Now the set Q is the next front and hence Fi = Q.\n%\n% This algorithm is better than the original NSGA ([2]) since it utilize\n% the informatoion about the set that an individual dominate (Sp) and\n% number of individuals that dominate the individual (np).\n\nfor i = 1 : N\n % Number of individuals that dominate this individual\n individual(i).n = 0;\n % Individuals which this individual dominate\n individual(i).p = [];\n for j = 1 : N\n dom_less = 0;\n dom_equal = 0;\n dom_more = 0;\n for k = 1 : M\n if (x_temp(i,V + k) < x_temp(j,V + k))\n dom_less = dom_less + 1;\n elseif (x_temp(i,V + k) == x_temp(j,V + k))\n dom_equal = dom_equal + 1;\n else\n dom_more = dom_more + 1;\n end\n end\n if dom_less == 0 && dom_equal ~= M\n individual(i).n = individual(i).n + 1;\n elseif dom_more == 0 && dom_equal ~= M\n individual(i).p = [individual(i).p j];\n end\n end \n if individual(i).n == 0\n x_temp(i,M + V + 1) = 1;\n F(front).f = [F(front).f i];\n end\nend\n% Find the subsequent fronts\nwhile ~isempty(F(front).f)\n Q.temp = []; % modified by zzb\n for i = 1 : length(F(front).f)\n if ~isempty(individual(F(front).f(i)).p)\n for j = 1 : length(individual(F(front).f(i)).p)\n \tindividual(individual(F(front).f(i)).p(j)).n = ...\n \tindividual(individual(F(front).f(i)).p(j)).n - 1;\n if individual(individual(F(front).f(i)).p(j)).n == 0\n x_temp(individual(F(front).f(i)).p(j),M + V + 1) = front + 1;\n Q.temp = [Q.temp individual(F(front).f(i)).p(j)]; % modified by zzb\n end\n end\n end\n end\n front = front + 1;\n F(front).f = Q.temp; % modified by zzb\nend\n\n%% Crowding distance\n%The crowing distance is calculated as below\n% ?For each front Fi, n is the number of individuals.\n% ?initialize the distance to be zero for all the individuals i.e. Fi(dj ) = 0,\n% where j corresponds to the jth individual in front Fi.\n% ?for each objective function m\n% * Sort the individuals in front Fi based on objective m i.e. I =\n% sort(Fi,m).\n% * Assign infinite distance to boundary values for each individual\n% in Fi i.e. I(d1) = ? and I(dn) = ?\n% * for k = 2 to (n-1)\n% ?I(dk) = I(dk) + (I(k + 1).m ? I(k ? 1).m)/fmax(m) - fmin(m)\n% ?I(k).m is the value of the mth objective function of the kth\n% individual in I\n\n% Find the crowding distance for each individual in each front\n[~,index_of_fronts] = sort(x_temp(:,M + V + 1));\nsorted_based_on_front = x_temp; % Initialize by x % modified by zzb \nfor i = 1 : length(index_of_fronts)\n sorted_based_on_front(i,:) = x_temp(index_of_fronts(i),:);\nend\ncurrent_index = 0;\n\n% for front = 1 : (length(F) - 1) % The last front of F is []\nfor front_count = 1 : (front - 1) % modified by zzb\n % objective = [];\n % distance = 0;\n % y = [];\n y = zeros(length(F(front_count).f),2*M + V + 1); % modified by zzb\n previous_index = current_index + 1;\n for i = 1 : length(F(front_count).f) % modified by zzb\n %y(i,:) = sorted_based_on_front(current_index + i,:);\n y(i,1:M + V + 1) = sorted_based_on_front(current_index + i,:); % modified by zzb\n end\n current_index = current_index + i;\n % Sort each individual based on the objective\n % sorted_based_on_objective = []; % modified by zzb\n for i = 1 : M\n [~, index_of_objectives] = sort(y(:,V + i)); % modified by zzb\n % sorted_based_on_objective = [];\n sorted_based_on_objective = y; % Initialize by y % modified by zzb\n for j = 1 : length(index_of_objectives)\n sorted_based_on_objective(j,:) = y(index_of_objectives(j),:);\n end\n f_max = sorted_based_on_objective(length(index_of_objectives), V + i);\n f_min = sorted_based_on_objective(1, V + i);\n y(index_of_objectives(length(index_of_objectives)),M + V + 1 + i) = Inf;\n y(index_of_objectives(1),M + V + 1 + i) = Inf;\n for j = 2 : length(index_of_objectives) - 1\n next_obj = sorted_based_on_objective(j + 1,V + i);\n previous_obj = sorted_based_on_objective(j - 1,V + i);\n if (f_max - f_min == 0)\n y(index_of_objectives(j),M + V + 1 + i) = Inf;\n else\n y(index_of_objectives(j),M + V + 1 + i) = ...\n (next_obj - previous_obj)/(f_max - f_min);\n end\n end\n end\n % distance = [];\n % distance(:,1) = zeros(length(F(front_count).f),1); % modified by zzb\n distance = zeros(length(F(front_count).f),1); % modified by zzb\n for i = 1 : M\n % distance(:,1) = distance(:,1) + y(:,M + V + 1 + i);% modified by zzb\n distance = distance + y(:,M + V + 1 + i);% modified by zzb\n end\n y(:,M + V + 2) = distance;\n % y = y(:,1 : M + V + 2);\n % z(previous_index:current_index,:) = y;\n z(previous_index:current_index,:) = y(:,1 : M + V + 2);\nend\n% f = z();\nf = z;\n%% References\n% [1] *Kalyanmoy Deb, Amrit Pratap, Sameer Agarwal, and T. Meyarivan*, |A Fast\n% Elitist Multiobjective Genetic Algorithm: NSGA-II|, IEEE Transactions on \n% Evolutionary Computation 6 (2002), no. 2, 182 ~ 197.\n%\n% [2] *N. Srinivas and Kalyanmoy Deb*, |Multiobjective Optimization Using \n% Nondominated Sorting in Genetic Algorithms|, Evolutionary Computation 2 \n% (1994), no. 3, 221 ~ 248.\n", "meta": {"author": "sfvsfv", "repo": "Mathematical-modeling", "sha": "cef1a3688246851f067777b3599b1b3831d3d948", "save_path": "github-repos/MATLAB/sfvsfv-Mathematical-modeling", "path": "github-repos/MATLAB/sfvsfv-Mathematical-modeling/Mathematical-modeling-cef1a3688246851f067777b3599b1b3831d3d948/ē¾Žčµ›A题常见代码/å¤šē›®ę ‡åæ«é€Ÿéžę”Æé…ęŽ’åŗé—ä¼ ē®—ę³•ä¼˜åŒ–ä»£ē /non_domination_sort_mod.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.48373292425369097}} {"text": "function [Fm,Vm]=cap_patchcylinder(F1,V1,F2,V2,nr,nz)\n\n% function [Fm,Vm]=cap_patchcylinder(F1,V1,F2,V2,nr,nz)\n% ------------------------------------------------------------------------\n% This function assumes the inputs F1, V1 and F2, V2 define the faces and\n% vertices of two concentrid cylinders and closes to top and bottom faces\n% by connecting the cylinders together. The input nr defines the number of\n% radial points to add for the connection. The input nz defines the number\n% of steps used in the z-direction for the cylinders. \n%\n% Kevin Mattheus Moerman\n% gibbon.toolbox@gmail.com\n% \n% Change log: \n% 2014/09/25\n% 2019/03/29 Updated help documentation\n% \n%------------------------------------------------------------------------\n\n%%\n\nFm=[F1; (F2+size(V1,1))]; \nVm=[V1; V2];\n\n%Coordinates created from nr*nz matrix \n\n%Top edge indices\nIt=ones(nr-1,1); Jt=(1:1:nr-1)';\nINDt=sub2ind([nz,nr-1],It,Jt);\n% Vt1=V1(INDt,:); Vt2=V2(INDt,:); Vt=[Vt1; Vt2];\n\n%Bottom edge indices\nIb=nz.*ones(nr-1,1); Jb=(1:1:nr-1)';\nINDb=sub2ind([nz,nr-1],Ib,Jb);\n% Vb1=V1(INDb,:); Vb2=V2(INDb,:); Vb=[Vb1; Vb2];\n\nFp=(ones(nr-1,1)*[1 2 2 1])+(((1:1:nr-1*ones)'-1)*ones(1,4)); Fp(Fp==nr)=1; %Quad order\n\nFq=[INDt(Fp(:,1:2)) INDt(Fp(:,3:4))+size(V1,1)];\nFtt=[Fq(:,[1 3 2]); Fq(:,[1 4 3])]; %Tri order\n\nFq=[INDb(Fp(:,1:2)) INDb(Fp(:,3:4))+size(V1,1)];\nFtb=[Fq(:,[1 3 2]); Fq(:,[1 4 3])]; %Tri order\n\nFm=[Fm; Ftt; Ftb];\n\nend\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/cap_patchcylinder.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.48373292377717997}} {"text": "function [ hyps ] = generateHypsB( lines, vp, tol, omap, gc )\n%GENERATEHYPS generate hypothesis, screen out inconsistent ones according\n%to OM, GC, and merged map\n% lines: line segment\n% vp: vanishing point, in z,y,x order\n% tol: tolerance when assigning lines to vp\n% omap & gc: evidence\n% hyps: all hyps with >0.5 consistency with OM will be returned;\n\n%% >> ASSIGN LINE SEGMENTS WITH TYPE\n\n%% get line segments align with vanishing point\nlines1 = getVanishingLine(lines, vp(1,:), tol);\nlines2 = getVanishingLine(lines, vp(2,:), tol);\nlines3 = getVanishingLine(lines, vp(3,:), tol);\n\n%% extend line representation with line type\n% line: [1x3 n] [planeID] [1x2 uv1] [u/d f/b r/l] (1/-1, 0 not sure, 2 not available)\nlines1_attr = zeros(size(lines1,1),9);\nlines2_attr = zeros(size(lines2,1),9);\nlines3_attr = zeros(size(lines3,1),9);\nlines1_attr(:,1:6) = lines1(:,1:6);\nlines2_attr(:,1:6) = lines2(:,1:6);\nlines3_attr(:,1:6) = lines3(:,1:6);\n\n%% horizontal line, line connecting vp2 and vp3, u=1, d=-1\nhorizontal = cross(vp(2,:),vp(3,:));\nhorizontal = horizontal./norm(horizontal);\nif horizontal(:,3)<0\n horizontal = -horizontal;\nend\n% line belong to vp2 and vp3 should have this attribute\n% lines1 not available\nlines1_attr(:,7) = 2;\n% lines2\nfor i = 1:size(lines2_attr,1)\n l = lines2(i,:);\n u = l(5:6)*2*pi-pi;\n v = computeUVN( l(1:3), u, l(4));\n xyz = uv2xyzN([u' v'], l(4));\n b1 = dot(xyz(1,:), horizontal)>0;\n b2 = dot(xyz(2,:), horizontal)>0;\n if b1&&b2\n lines2_attr(i,7) = 1;\n elseif ~b1&&~b2\n lines2_attr(i,7) = -1;\n else\n lines2_attr(i,7) = 0;\n end \nend\n% lines3\nfor i = 1:size(lines3_attr,1)\n l = lines3(i,:);\n u = l(5:6)*2*pi-pi;\n v = computeUVN( l(1:3), u, l(4));\n xyz = uv2xyzN([u' v'], l(4));\n b1 = dot(xyz(1,:), horizontal)>0;\n b2 = dot(xyz(2,:), horizontal)>0;\n if b1&&b2\n lines3_attr(i,7) = 1;\n elseif ~b1&&~b2\n lines3_attr(i,7) = -1;\n else\n lines3_attr(i,7) = 0;\n end \nend\n\n%% front and back, line connecting vp1 and vp3, f=1, b=-1\nfrontNback = cross(vp(1,:),vp(3,:));\nfrontNback = frontNback./norm(frontNback);\nif frontNback(:,2)<0\n frontNback = -frontNback;\nend\n% line belong to vp1 and vp3 should have this attribute\n% lines2 not available\nlines2_attr(:,8) = 2;\n% lines1\nfor i = 1:size(lines1_attr,1)\n l = lines1(i,:);\n u = l(5:6)*2*pi-pi;\n v = computeUVN( l(1:3), u, l(4));\n xyz = uv2xyzN( [u' v'], l(4));\n b1 = dot(xyz(1,:), frontNback)>0;\n b2 = dot(xyz(2,:), frontNback)>0;\n if b1&&b2\n lines1_attr(i,8) = 1;\n elseif ~b1&&~b2\n lines1_attr(i,8) = -1;\n else\n lines1_attr(i,8) = 0;\n end \nend\n% lines3\nfor i = 1:size(lines3_attr,1)\n l = lines3(i,:);\n u = l(5:6)*2*pi-pi;\n v = computeUVN( l(1:3), u, l(4));\n xyz = uv2xyzN( [u' v'], l(4));\n b1 = dot(xyz(1,:), frontNback)>0;\n b2 = dot(xyz(2,:), frontNback)>0;\n if b1&&b2\n lines3_attr(i,8) = 1;\n elseif ~b1&&~b2\n lines3_attr(i,8) = -1;\n else\n lines3_attr(i,8) = 0;\n end \nend\n\n%% left and right, line connecting vp1 and vp2, r=1, l=-1\nleftNright = cross(vp(1,:),vp(2,:));\nleftNright = leftNright./norm(leftNright);\nif leftNright(:,1)<0\n leftNright = -leftNright;\nend\n% line belong to vp1 and vp2 should have this attribute\n% lines3 not available\nlines3_attr(:,9) = 2;\n% lines1\nfor i = 1:size(lines1_attr,1)\n l = lines1(i,:);\n u = l(5:6)*2*pi-pi;\n v = computeUVN( l(1:3), u, l(4));\n xyz = uv2xyzN( [u' v'], l(4));\n b1 = dot(xyz(1,:), leftNright)>0;\n b2 = dot(xyz(2,:), leftNright)>0;\n if b1&&b2\n lines1_attr(i,9) = 1;\n elseif ~b1&&~b2\n lines1_attr(i,9) = -1;\n else\n lines1_attr(i,9) = 0;\n end \nend\n% lines2\nfor i = 1:size(lines2_attr,1)\n l = lines2(i,:);\n u = l(5:6)*2*pi-pi;\n v = computeUVN( l(1:3), u, l(4));\n xyz = uv2xyzN( [u' v'], l(4));\n b1 = dot(xyz(1,:), leftNright)>0;\n b2 = dot(xyz(2,:), leftNright)>0;\n if b1&&b2\n lines2_attr(i,9) = 1;\n elseif ~b1&&~b2\n lines2_attr(i,9) = -1;\n else\n lines2_attr(i,9) = 0;\n end \nend\n\n%% save line segments according to type\ntyp = [1 1 2; 1 2 -1; 1 -1 2; 1 2 1; ...\n -1 1 2; -1 2 -1; -1 -1 2; -1 2 1; ...\n 2 1 -1; 2 1 1; 2 -1 1; 2 -1 -1];\nallLines = [lines1_attr; lines2_attr; lines3_attr];\ntypLine = repmat(struct('lines', [], 'lsLength', [], 'lspool', [], ...\n 'poolLength', []), [size(typ,1) 1]);\nfor i = 1:size(typ,1)\n valid = (allLines(:,7)==typ(i,1)) & (allLines(:,8)==typ(i,2)) & (allLines(:,9)==typ(i,3));\n typLine(i).lines = allLines(valid,:); \n lsLength = typLine(i).lines(:,6)-typLine(i).lines(:,5);\n lsLength(lsLength<0) = lsLength(lsLength<0) + 1;\n sumLength = sum(lsLength);\n lspool = zeros( ceil(sumLength*100), 1);\n accumuLen = 0;\n poolLength = length(lspool);\n for j = 1:length(lsLength)\n startid = round(accumuLen/sumLength*poolLength) + 1;\n accumuLen = accumuLen + lsLength(j);\n endid = round(accumuLen/sumLength*poolLength);\n lspool(startid:endid) = j;\n end\n \n typLine(i).lsLength = lsLength;\n typLine(i).lspool = lspool;\n typLine(i).poolLength = poolLength;\nend\n\n%% >> BUILD UP RECIPE FROM LINE TYPE TO BOX\n% +1: max coords; -1: min coords;\n% uf [ 0 +1 +1] df [ 0 +1 -1] lf [-1 +1 0];\n% ul [-1 0 +1] dl [-1 0 -1] rf [+1 +1 0];\n% ub [ 0 -1 +1] db [ 0 -1 -1] rb [+1 -1 0];\n% ur [+1 0 +1] dr [+1 0 -1] lb [-1 -1 0];\n\n%% generate recipe: from line type to box by check rank of matrix\nallFunc = [ 0 0 0 1 0 -1; ...\n 1 0 0 0 0 -1; ...\n 0 0 1 0 0 -1; ...\n 0 1 0 0 0 -1; ...\n 0 0 0 1 -1 0; ...\n 1 0 0 0 -1 0; ...\n 0 0 1 0 -1 0; ...\n 0 1 0 0 -1 0; ...\n 1 0 0 -1 0 0; ...\n 0 1 0 -1 0 0; ...\n 0 1 -1 0 0 0; ...\n 1 0 -1 0 0 0];\n% combos = combntns(1:size(allFunc,1), 5);\ncombos = nchoosek(1:size(allFunc,1), 5);\ndegen = false(size(combos,1),1);\nfor i = 1:size(combos,1)\n equset = allFunc(combos(i,:), :);\n if rank(equset)<5\n degen(i) = true;\n end\nend\ncube_recipe = combos(~degen,:);\n\n%% define geometry of cuboid: correlation among corner, edge, and face\n% 8 corners, each is the intersection of 3 edges from 3 vps respectively\nedgeToPoint = [ 9 2 1; ...\n 12 2 3; ...\n 11 4 3; ...\n 10 4 1; ...\n 9 6 5; ...\n 12 6 7; ...\n 11 8 7; ...\n 10 8 5];\n% 8 corners, each is assigned with type [u(+1)/d(-1) f(+1)/b(-1) r(+1)/l(-1)]\npointDirect = [ 1 1 -1; ...\n 1 -1 -1; ...\n 1 -1 1; ...\n 1 1 1; ...\n -1 1 -1; ...\n -1 -1 -1; ...\n -1 -1 1; ...\n -1 1 1];\n% 12 edges, each connects two corners\nPointToEdge = [ 1 4; ...\n 2 1; ...\n 2 3; ...\n 3 4; ...\n 5 8; ...\n 6 5; ...\n 6 7; ...\n 7 8; ...\n 5 1; ...\n 8 4; ...\n 7 3; ...\n 6 2];\n% 6 faces, each face has 4 corners\n% ranked as u d f b r l; start from left bottom, clockwise\nPointToSurface = [1 2 3 4; ...\n 6 5 8 7; ...\n 5 1 4 8; ...\n 7 3 2 6; ...\n 8 4 3 7; ...\n 6 2 1 5];\nSurfaceNm = [1;1;2;2;3;3];\n\n%% >> START TO GENERATE CUBOID HYPOTHESIS, VALIDATE WITH OMAP\nmaxSample = 200000;\nvalidHyps = repmat(struct('extLine', [], 'hCorner', [], 'srcLine', [], ...\n 'omapScr', 0, 'vpLength', [], 'recipe', [], 'gcScr', -1, 'mgScr', -1, 'opScr', -1 ), maxSample, 1);\n\n%% sample line segments, long line segments are more likely to be selected.\nrcpNum = size(cube_recipe,1);\nfor samid = 1:maxSample\n if rem(samid,1000)==0\n% fprintf('%d/%d hypothesis validated, score: %f/%f\\n', samid, maxSample, maxScore, numPoint);\n fprintf('%d/%d hypothesis sampled\\r', samid, maxSample);\n end\n rcpid = cube_recipe(randsample(rcpNum, 1),:);\n \n if any([typLine(rcpid).poolLength]==0)\n validHyps(samid).srcLine = [];\n validHyps(samid).recipe = rcpid; \n continue;\n end\n \n lineID1 = typLine(rcpid(1)).lspool(randsample(typLine(rcpid(1)).poolLength, 1));\n lineID2 = typLine(rcpid(2)).lspool(randsample(typLine(rcpid(2)).poolLength, 1));\n lineID3 = typLine(rcpid(3)).lspool(randsample(typLine(rcpid(3)).poolLength, 1));\n lineID4 = typLine(rcpid(4)).lspool(randsample(typLine(rcpid(4)).poolLength, 1));\n lineID5 = typLine(rcpid(5)).lspool(randsample(typLine(rcpid(5)).poolLength, 1));\n \n hlines = zeros(12,9);\n hlines(rcpid(1),:) = typLine(rcpid(1)).lines(lineID1,:);\n hlines(rcpid(2),:) = typLine(rcpid(2)).lines(lineID2,:);\n hlines(rcpid(3),:) = typLine(rcpid(3)).lines(lineID3,:);\n hlines(rcpid(4),:) = typLine(rcpid(4)).lines(lineID4,:);\n hlines(rcpid(5),:) = typLine(rcpid(5)).lines(lineID5,:);\n \n validHyps(samid).srcLine = hlines;\n validHyps(samid).recipe = rcpid;\nend\nfprintf('\\n');\n\n%% finish up unknown edges, compute corner, check if ls locates in line\nfor samid = 1:maxSample\n if rem(samid,1000)==0\n% fprintf('%d/%d hypothesis validated, score: %f/%f\\n', samid, maxSample, maxScore, numPoint);\n fprintf('%d/%d hypothesis validated\\r', samid, maxSample);\n end\n if isempty(validHyps(samid).srcLine)\n validHyps(samid).omapScr = -1;\n continue;\n end\n hlines = validHyps(samid).srcLine;\n hCorner = zeros(8,3);\n lineExist = false(12,1);\n lineExist(validHyps(samid).recipe) = true;\n rcpid = validHyps(samid).recipe;\n % >> compute all the other edges, corner\n bDegenerate = false;\n while any(~lineExist)\n hits = lineExist(edgeToPoint);\n actLine = sum(hits,2)==2;\n i = find(actLine,1)';\n srcLineID = edgeToPoint(i,hits(i,:));\n dstLineID = edgeToPoint(i,~hits(i,:));\n dstVpID = find(~hits(i,:));\n dstCor = cross( hlines(srcLineID(1),1:3), hlines(srcLineID(2),1:3), 2);\n if norm(dstCor)<0.1\n bDegenerate = true;\n break;\n end\n\n hCorner(i,:) = dstCor./norm(dstCor);\n % check if intersection locates at right position\n v = dot([dstCor;dstCor;dstCor],[horizontal;frontNback;leftNright],2);\n if sign(v(1))~=pointDirect(i,1) ...\n ||sign(v(2))~=pointDirect(i,2) ...\n ||sign(v(3))~=pointDirect(i,3)\n hCorner(i,:) = -hCorner(i,:);\n end\n\n dstNM = cross(hCorner(i,:), vp(dstVpID,:), 2);\n hlines(dstLineID,1:3) = dstNM./norm(dstNM); \n lineExist(dstLineID) = true;\n end\n \n if bDegenerate\n validHyps(samid).omapScr = -1;\n continue;\n end\n \n I = find(actLine); i = I(end);\n srcLineID = edgeToPoint(i,hits(i,:));\n dstCor = cross( hlines(srcLineID(1),1:3), hlines(srcLineID(2),1:3), 2);\n hCorner(i,:) = dstCor./norm(dstCor);\n % check if intersection locates at right position\n v = dot([dstCor;dstCor;dstCor],[horizontal;frontNback;leftNright],2);\n if sign(v(1))~=pointDirect(i,1) ...\n ||sign(v(2))~=pointDirect(i,2) ...\n ||sign(v(3))~=pointDirect(i,3)\n hCorner(i,:) = -hCorner(i,:);\n end\n \n % >> compute extended line representation\n rcpidR = setdiff(1:12, rcpid);\n areaXY = abs(sum(hlines(rcpidR,1:3).*repmat([0 0 1], [length(rcpidR) 1]),2));\n areaYZ = abs(sum(hlines(rcpidR,1:3).*repmat([1 0 0], [length(rcpidR) 1]),2));\n areaZX = abs(sum(hlines(rcpidR,1:3).*repmat([0 1 0], [length(rcpidR) 1]),2));\n [~, planeIDs] = max([areaXY areaYZ areaZX], [], 2); % 1:XY 2:YZ 3:ZX\n hlines(rcpidR,4) = planeIDs;\n\n extLine = hlines(:,1:6);\n for i = 1:12\n endPoint = hCorner(PointToEdge(i,:),:);\n uv = xyz2uvN(endPoint,extLine(i,4));\n umin = (min(uv(:,1))+pi)/2/pi; umax = (max(uv(:,1))+pi)/2/pi;\n if umax-umin>0.5\n extLine(i,5) = umax;\n extLine(i,6) = umin;\n else\n extLine(i,5) = umin;\n extLine(i,6) = umax;\n end\n end\n \n % check if line segments locates in line\n validated = true;\n for i = rcpid\n lineRange = extLine(i,5:6);\n lsegRange = hlines(i,5:6);\n b = insideRange(lsegRange, lineRange);\n if ~b(1) || ~b(2)\n validated = false;\n break;\n end\n end\n if ~validated\n validHyps(samid).omapScr = -1;\n continue;\n end\n validHyps(samid).srcLine = hlines(rcpid,1:6);\n validHyps(samid).extLine = extLine;\n validHyps(samid).hCorner = hCorner;\nend\nfprintf('\\n');\n\n%% compute the checking direction on omap \n[candiSetXYZ, ~] = icosahedron2sphere(6);\n[ohei, owid, ~] = size(omap); \ncandiSetUV = uv2coords(xyz2uvN(candiSetXYZ), owid, ohei);\ncandiInd = sub2ind([ohei owid], candiSetUV(:,2), candiSetUV(:,1));\n% convert gc to omap\ngndGC = zeros(ohei, owid, 3);\ngndGC(:,:,1) = max(gc(:,:,5),gc(:,:,6));\ngndGC(:,:,2) = max(gc(:,:,1),gc(:,:,3));\ngndGC(:,:,3) = max(gc(:,:,2),gc(:,:,4));\nnormGndGC = sum(gndGC(candiInd))+sum(gndGC(candiInd+1*ohei*owid))+sum(gndGC(candiInd+2*ohei*owid));\n% omap\ngndOmap = omap;\ngndOmap(gndOmap>0) = 1;\nnormGndOmap = sum(gndOmap, 3);\ngndOmap = gndOmap./(repmat(normGndOmap+0.0001, [1 1 3])); \nnormGndOmap = sum(gndOmap(candiInd))+sum(gndOmap(candiInd+1*ohei*owid))+sum(gndOmap(candiInd+2*ohei*owid));\nnumPoint = size(candiSetXYZ,1);\n\n% merge\ngndMerge = zeros(ohei, owid, 3);\ngndMerge(1:ohei/2,:,:) = gndOmap(1:ohei/2,:,:);\ngndMerge(ohei/2+1:ohei, :, :) = gndGC(ohei/2+1:ohei, :, :);\n% normMegMap = sum(gndOmap, 3);\n% gndOmap = gndOmap./(repmat(normMegMap+0.0001, [1 1 3])); \nnormMegMap = sum(gndMerge(candiInd))+sum(gndMerge(candiInd+1*ohei*owid))+sum(gndMerge(candiInd+2*ohei*owid));\n\n% optimal merge\ngndOptim = zeros(ohei, owid, 3);\ngndOptim(1:685,:,:) = gndOmap(1:685,:,:);\ngndOptim(686:ohei, :, :) = gndGC(686:ohei, :, :);\n% normMegMap = sum(gndOmap, 3);\n% gndOmap = gndOmap./(repmat(normMegMap+0.0001, [1 1 3])); \nnormOptMap = sum(gndOptim(candiInd))+sum(gndOptim(candiInd+1*ohei*owid))+sum(gndOptim(candiInd+2*ohei*owid));\n\n%% check consistency of orientation on uniformly sampled point on sphere \nfor samid = 1:maxSample\n hypVp = false(numPoint,3);\n if validHyps(samid).omapScr>-0.5\n hCorner = validHyps(samid).hCorner;\n for i = 1:6\n% suf1 = cross(hCorner(PointToSurface(i,2),:), hCorner(PointToSurface(i,1),:), 2);\n% suf2 = cross(hCorner(PointToSurface(i,3),:), hCorner(PointToSurface(i,2),:), 2);\n% suf3 = cross(hCorner(PointToSurface(i,4),:), hCorner(PointToSurface(i,3),:), 2);\n% suf4 = cross(hCorner(PointToSurface(i,1),:), hCorner(PointToSurface(i,4),:), 2);\n% vad1 = dot(candiSetXYZ, repmat(suf1, [numPoint 1]), 2);\n% vad2 = dot(candiSetXYZ, repmat(suf2, [numPoint 1]), 2);\n% vad3 = dot(candiSetXYZ, repmat(suf3, [numPoint 1]), 2);\n% vad4 = dot(candiSetXYZ, repmat(suf4, [numPoint 1]), 2);\n% vadIN = vad1<0 & vad2<0 & vad3<0 & vad4<0;\n vadIN = insideCone( hCorner(PointToSurface(i,[4 3 2 1]),:), candiSetXYZ, 0);\n hypVp( vadIN, SurfaceNm(i)) = true;\n end\n% response = selVp & hypVp;\n% validHyps(samid).omapScr = sum( sum(response,2)>0 )/size(response,1);\n response = sum(gndOmap(candiInd(hypVp(:,1))+0*ohei*owid)) ...\n + sum(gndOmap(candiInd(hypVp(:,2))+1*ohei*owid)) ...\n + sum(gndOmap(candiInd(hypVp(:,3))+2*ohei*owid));\n validHyps(samid).omapScr = response/normGndOmap;\n response = sum(gndGC(candiInd(hypVp(:,1))+0*ohei*owid)) ...\n + sum(gndGC(candiInd(hypVp(:,2))+1*ohei*owid)) ...\n + sum(gndGC(candiInd(hypVp(:,3))+2*ohei*owid));\n validHyps(samid).gcScr = response/normGndGC;\n response = sum(gndMerge(candiInd(hypVp(:,1))+0*ohei*owid)) ...\n + sum(gndMerge(candiInd(hypVp(:,2))+1*ohei*owid)) ...\n + sum(gndMerge(candiInd(hypVp(:,3))+2*ohei*owid));\n validHyps(samid).mgScr = response/normMegMap;\n response = sum(gndOptim(candiInd(hypVp(:,1))+0*ohei*owid)) ...\n + sum(gndOptim(candiInd(hypVp(:,2))+1*ohei*owid)) ...\n + sum(gndOptim(candiInd(hypVp(:,3))+2*ohei*owid));\n validHyps(samid).opScr = response/normOptMap;\n end\nend\n\n%% save only validate hypothesis, with high score\nomapScr = [validHyps.omapScr];\n% [B, IX] = sort(omapScr, 'descend');\n% selIX = IX(B>-0.5);\n% hyps = validHyps(selIX);\n\nhyps = validHyps(omapScr>-0.5);\nend\n\nfunction b = insideRange(pt, range)\nrange = range + [-0.02 +0.02];\nif range(2)>range(1)\n b = pt>=range(1) & pt<=range(2);\nelse\n b1 = pt>=range(1) & pt<=1;\n b2 = pt>=0 & pt<=range(2);\n b = b1 | b2;\nend\n\nend\n", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/panoContext_code/RoomHypothesisSampling/generateHypsB.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4837216466120841}} {"text": "function [ug] = amu2ug(amu)\n% Convert mass from atomic mass units to micrograms. \n% Chad Greene 2012\nug = amu*1.6605402e-18;", "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/amu2ug.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6334102705979902, "lm_q1q2_score": 0.48359845727009626}} {"text": "function [varargout] = solver_RPCA_Lagrangian(Y,lambda_L,lambda_S,varargin)\n% [L,S,errHist] = solver_RPCA_Lagrangian(Y,lambda_L,lambda_S, A_cell, opts)\n% Solves the problem\n% minimize_{L,S} .5|| L + S - Y ||_F^2 + lambda_L ||L||_* + lambda_S ||S||_1\n%\n% or if A_cell is provided, where A_cell = {A, At}\n% (A is a function handle, At is a function handle to the transpose of A)\n% then\n%\n% minimize_{L,S} .5|| A(L + S) - Y ||_F^2 + lambda_L ||L||_* + lambda_S ||S||_1\n% (here, Y usually represents A(Y) )\n%\n% errHist(:,1) is a record of the residual\n% errHist(:,2) is a record of the full objective (.f*resid^2 + lambda_L,\n% etc.)\n% errHist(:,3) is the output of opts.errFcn if provided\n%\n% opts is a structure with options:\n% opts.sum, opts.max (as described above)\n% opts.L0 initial guess for L (default is 0)\n% opts.S0 initial guess for S (default is 0)\n% opts.tol sets stopping tolerance\n% opts.maxIts sets maximum number of iterations\n% opts.printEvery will print information this many iterations\n% opts.displayTime will print out timing information (default is true for large problems)\n% opts.errFcn a function of (L,S) that records information\n% opts.trueObj if provided, this will be subtracted from errHist(2,:)\n% opts.Lip Lipschitz constant, i.e., 2*spectralNorm(A)^2\n% by default, assume 2 (e.g., good if A = P_Omega)\n% opts.FISTA whether to use FISTA or not. By default, false\n% opts.restart how often to restart FISTA; set to -Inf to make it automatic\n% opts.BB whether to use the Barzilai-Borwein spectral steplength\n% opts.BB_type which BB stepsize to take. Default is 1, the larger step\n% opts.BB_split whether to calculate stepslengths for S and L independently.\n% Default is false, which is recommended.\n% opts.quasiNewton uses quasi-Newton-like Gauss-Seidel scheme. By\n% default, true\n% opts.quasiNewton_stepsize stepsize length. Default is .8*(2/Lip)\n% opts.quasinewton_SLS whether to take S-L-S sequence (default is true)\n% otherwise, takes a L-S Gauss-Seidel sequence\n% opts.SVDstyle controls what type of SVD is performed.\n% 1 = full svd using matlab's \"svd\". Best for small problems\n% 2 = partial svd using matlab's \"svds\". Not recommended.\n% 3 = partial svd using PROPACK, if installed. Better than option 2, worse than 4\n% 4 = partial svd using randomized linear algebra, following\n% the Halko/Tropp/Martinnson \"Structure in Randomness\" paper\n% in option 4, there are additional options:\n% opts.SVDwarmstart whether to \"warm-start\" the algorithm\n% opts.SVDnPower number of power iterations (default is 2 unless warm start)\n% opts.SVDoffset oversampling, e.g., \"rho\" in Tropp's paper. Default is 5\n%\n% opts.L1L2 instead of using l1 penalty, e.g., norm(S(:),1), we can\n% also use block norm penalties, such as (if opts.L1L2 = 'rows')\n% the sum of the l2-norm of rows (i.e., l1-norm of rows),\n% or if opts.L1L2='cols', the sum of the l2-norms of colimns.\n% By default, or if opts.L1L2 = [] or false, then uses usual l1 norm.\n% [Feature added April 17 2015]\n%\n% Stephen Becker, March 6 2014\n% See also solver_RPCA_constrained.m\n\n\n[varargout{1:nargout}] = solver_RPCA_constrained(Y,lambda_S/lambda_L, -lambda_L, varargin{:});", "meta": {"author": "stephenbeckr", "repo": "fastRPCA", "sha": "44dfee56f142ebffe5a7003578868e84bd4330b7", "save_path": "github-repos/MATLAB/stephenbeckr-fastRPCA", "path": "github-repos/MATLAB/stephenbeckr-fastRPCA/fastRPCA-44dfee56f142ebffe5a7003578868e84bd4330b7/solvers/solver_RPCA_Lagrangian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.4835984557360052}} {"text": "function [ x, y ] = dswap ( n, x, incx, y, incy )\n\n%*****************************************************************************80\n%\n%% DSWAP interchanges two vectors.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 June 2005\n%\n% Author:\n%\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Jack Dongarra, Cleve Moler, Jim Bunch and Pete Stewart,\n% LINPACK User's Guide,\n% SIAM, 1979.\n%\n% Charles Lawson, Richard Hanson, David Kincaid, Fred Krogh,\n% Basic Linear Algebra Subprograms for Fortran Usage,\n% Algorithm 539, \n% ACM Transactions on Mathematical Software, \n% Volume 5, Number 3, September 1979, pages 308-323.\n%\n% Parameters:\n%\n% Input, integer N, the number of entries in the vectors.\n%\n% Input, real X(*), one of the vectors to swap.\n%\n% Input, integer INCX, the increment between successive entries of X.\n%\n% Input, real Y(*), one of the vectors to swap.\n%\n% Input, integer INCY, the increment between successive elements of Y.\n%\n% Output, real X(*), the swapped vector.\n%\n% Output, real Y(*), the swapped vector.\n%\n if ( n <= 0 )\n\n elseif ( incx == 1 & incy == 1 )\n\n m = mod ( n, 3 );\n\n for i = 1 : m\n temp = x(i);\n x(i) = y(i);\n y(i) = temp;\n end\n\n for i = m+1 : 3 : n\n\n temp = x(i);\n x(i) = y(i);\n y(i) = temp;\n\n temp = x(i+1);\n x(i+1) = y(i+1);\n y(i+1) = temp;\n\n temp = x(i+2);\n x(i+2) = y(i+2);\n y(i+2) = temp;\n\n end\n\n else\n\n if ( 0 <= incx )\n ix = 1;\n else\n ix = ( - n + 1 ) * incx + 1;\n end\n\n if ( 0 <= incy )\n iy = 1;\n else\n iy = ( - n + 1 ) * incy + 1;\n end\n\n for i = 1 : n\n temp = x(ix);\n x(ix) = y(iy);\n y(iy) = temp;\n ix = ix + incx;\n iy = iy + incy;\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/dswap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.4835984451691612}} {"text": " function xs = eml_inc_em(x, Gb, yi, ci, ri, varargin)\n%|function xs = eml_inc_em(x, Gb, yi, ci, ri, varargin)\n%| E-ML-INC-EM algorithm for image reconstruction from Poisson emission data\n%| (incremental EM algorithm)\n%| model: Y_i ~ Poisson(c_i [G x]_i + r_i)\n%| in\n%|\tx\t[np,1]\t\tinitial estimate\n%|\tGb\t[nd,np]\t\tGblock object (see eml_osem_test.m)\n%|\tyi,ci,ri [nb,na]\tsee em_fbp.m (for model too)\n%|\n%| options\n%|\t'niter'\t(#)\t\t# of iterations\n%|\t'isave'\t[]\t\tlist of iterations to archive\n%|\t\t\t\t(default: [] 'last)\n%|\tchat\t(0 | 1)\t\tverbosity\n%|\tpixmax\t(value)\t\tupper constraint for pixel values\n%|\thds\t(value)\t\t'1' or '3' hidden data space\n%|\tos\t(#)\t\thow many \"warmup\" osem iterations\n%|\n%| out\n%|\txs [np nsave]\t\testimates each (saved) iteration\n%|\n%| Copyright 2004-3-20, Jeff Fessler, University of Michigan\n\nif nargin < 3, ir_usage, end\n\n% options\narg.chat = 0;\narg.pixmax = inf;\narg.hds = 1;\narg.niter = 1;\narg.isave = 'last';\narg.os = 0;\narg.userfun = [];\n\narg = vararg_pair(arg, varargin);\narg.isave = iter_saver(arg.isave, arg.niter);\n\nif ~isvar('ci') || isempty(ci)\n\tci = ones(size(yi));\nend\nif ~isvar('ri') || isempty(ri)\n\tri = zeros(size(yi));\nend\n\nGb = block_ob(Gb, 'ensure'); % make it a block object (if not already)\nnblock = block_ob(Gb, 'n');\nstarts = subset_start(nblock);\n\neml_check(yi, ci, ri, 'os', nblock);\n[nb na] = size(yi);\n\nticker(mfilename, 1, arg.niter)\n\n% precompute hidden data space factor\ngam = eml_hds(Gb, ci, ri, arg.hds);\nif arg.chat, printf('hds = %g', gam), end\n\n% system (block) sensitivities\nnp = length(x);\nasum = zeros(np, 1);\nprecon = zeros(np, nblock); % classic OSEM preconditioner\nfor iset=1:nblock\n\tticker([mfilename ' : precon'], iset, nblock)\n\tistart = starts(iset);\n\tia = istart:nblock:na;\n\tasum_m = Gb{istart}' * col(ci(:,ia));\n\tasum = asum + asum_m;\n\tasum_m(asum_m == 0) = Inf; % avoid divide by 0\n\tprecon(:, iset) = 1 ./ asum_m;\nend, clear asum_m\n% asum = Gb' * ci(:);\n\nx = max(x,0);\nx = min(x,arg.pixmax);\nxs = zeros(numel(x), length(arg.isave));\nif any(arg.isave == 0)\n\txs(:,find(arg.isave == 0)) = x;\nend\n\n\n%\n% precompute sufficient statistics,\n% possibly using osem warmup iterations\n%\nff = zeros(np,nblock);\nif arg.os == 0\n\tfor iblock=1:nblock\n\t\tff(:,iblock) = compute_fm(x, Gb, yi, ci, ri, gam, iblock);\n\tend\n\nelse\n\tfor iter = 1:arg.os\n\t\tfor iset = 1:nblock\n\t\t\tticker([mfilename ': osem'], [iter iset], [arg.os nblock])\n\t\t\tiblock = starts(iset);\n\t\t\tia = iblock:nblock:na;\n\n\t\t\ttmp = compute_fm(x, Gb, yi, ci, ri, gam, iblock);\n\n\t\t\tpre = precon(:,min(iset,ncol(precon)));\t% 1 or iset\n\t\t\tx = max(pre .* tmp - gam, 0);\n\n\t\t\tif iter == arg.os\n\t\t\t\tff(:,iblock) = tmp;\n\t\t\tend\n\t\tend\n\n\t\tif any(arg.isave == iter)\n\t\t\txs(:, arg.isave == iter) = x;\n\t\tend\n\tend\nend\nfsum = sum(ff, 2);\n\n\n%\n% loop over incremental EM iterations\n%\n\nfor iter = (2+arg.os):arg.niter\n\n\t%\n\t% loop over subsets\n\t%\n\tfor iset=1:nblock\n\t\tticker(mfilename, [iter iset], [arg.niter nblock])\n\t\tiblock = starts(iset);\n\n\t\tx = fsum ./ asum - gam;\n\t\tx = max(x,0);\n\t\tx = min(x,arg.pixmax);\n\n\t\tfsum = fsum - ff(:,iblock);\n\t\tff(:,iblock) = compute_fm(x, Gb, yi, ci, ri, gam, iblock);\n\t\tfsum = fsum + ff(:,iblock);\n\tend\n\n\tif arg.chat, printf('Range %g %g', min(x), max(x)), end\n\tif any(arg.isave == iter)\n\t\txs(:, arg.isave == iter) = x;\n\tend\nend\n\n\n%\n% compute_fm()\n% compute sufficient statistics\n%\nfunction fm = compute_fm(x, Gb, yi, ci, ri, gam, iblock)\neterm = eml_eterm(x, Gb, yi, ci, ri, iblock);\nfm = (x + gam) .* eterm;\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/emission/eml_inc_em.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.48356338907551855}} {"text": "%EIMM_SMOOTH EKF based fixed-interval IMM smoother using two IMM-EKF filters.\n%\n% Syntax:\n% [X_S,P_S,X_IS,P_IS,MU_S] = EIMM_SMOOTH(MM,PP,MM_i,PP_i,MU,p_ij,mu_0j,ind,dims,A,a,a_param,Q,R,H,h,h_param,Y)\n%\n% In:\n% MM - Means of forward-time IMM-filter on each time step\n% PP - Covariances of forward-time IMM-filter on each time step\n% MM_i - Model-conditional means of forward-time IMM-filter on each time step \n% PP_i - Model-conditional covariances of forward-time IMM-filter on each time step\n% MU - Model probabilities of forward-time IMM-filter on each time step \n% p_ij - Model transition probability matrix\n% ind - Indices of state components for each model as a cell array\n% dims - Total number of different state components in the combined system\n% A - Dynamic model matrices for each linear model and Jacobians of each\n% non-linear model's measurement model function as a cell array\n% a - Cell array containing function handles for dynamic functions\n% for each model having non-linear dynamics\n% a_param - Parameters of a as a cell array.\n% Q - Process noise matrices for each model as a cell array.\n% R - Measurement noise matrices for each model as a cell array.\n% H - Measurement matrices for each linear model and Jacobians of each\n% non-linear model's measurement model function as a cell array\n% h - Cell array containing function handles for measurement functions\n% for each model having non-linear measurements\n% h_param - Parameters of h as a cell array.\n% Y - Measurement sequence\n%\n% Out:\n% X_S - Smoothed state means for each time step\n% P_S - Smoothed state covariances for each time step\n% X_IS - Model-conditioned smoothed state means for each time step\n% P_IS - Model-conditioned smoothed state covariances for each time step\n% MU_S - Smoothed model probabilities for each time step\n% \n% Description:\n% EKF based two-filter fixed-interval IMM smoother.\n%\n% See also:\n% EIMM_UPDATE, EIMM_PREDICT\n\n% History:\n% 09.01.2008 JH The first official version.\n%\n% Copyright (C) 2007,2008 Jouni Hartikainen\n%\n% $Id: imm_update.m 111 2007-11-01 12:09:23Z jmjharti $\n%\n% This software is distributed under the GNU General Public \n% Licence (version 2 or later); please refer to the file \n% Licence.txt, included with the software, for details.\n \nfunction [x_sk,P_sk,x_sik,P_sik,mu_sk] = eimm_smooth(MM,PP,MM_i,PP_i,MU,p_ij,mu_0j,ind,dims,A,a,a_param,Q,R,H,h,h_param,Y)\n % Default values for mean and covariance\n MM_def = zeros(dims,1);\n PP_def = diag(ones(dims,1));\n\n % Number of models\n m = length(A);\n \n % Number of measurements\n n = size(Y,2);\n \n % The prior model probabilities for each step\n p_jk = zeros(m,n);\n p_jk(:,1) = mu_0j;\n for i1 = 2:n\n for i2 = 1:m\n p_jk(i2,i1) = sum(p_ij(:,i2).*p_jk(:,i1-1));\n end\n end\n \n % Backward-time transition probabilities\n p_ijb = cell(1,n);\n for k = 1:n\n for i1 = 1:m\n % Normalizing constant\n b_i = sum(p_ij(:,i1).*p_jk(:,k));\n for j = 1:m\n p_ijb{k}(i1,j) = 1/b_i.*p_ij(j,i1).*p_jk(j,k);\n end\n end\n end\n \n % Space for overall smoothed estimates\n x_sk = zeros(dims,n);\n P_sk = zeros(dims,dims,n);\n mu_sk = zeros(m,n);\n \n % Values of smoothed estimates at the last time step.\n x_sk(:,end) = MM(:,end);\n P_sk(:,:,end) = PP(:,:,end);\n mu_sk(:,end) = MU(:,end);\n \n % Space for model-conditioned smoothed estimates\n x_sik = cell(m,n);\n P_sik = cell(m,n);\n \n % Values for last time step\n x_sik(:,end) = MM_i(:,end);\n P_sik(:,end) = PP_i(:,end);\n \n % Backward-time estimated model probabilities\n mu_bp = MU(:,end);\n \n % Space for model-conditioned backward-time updated means and covariances\n x_bki = cell(1,m);\n P_bki = cell(1,m);\n \n % Initialize with default values\n for i1 = 1:m\n x_bki{i1} = MM_def;\n x_bki{i1}(ind{i1}) = MM_i{i1,end};\n P_bki{i1} = PP_def;\n P_bki{i1}(ind{i1},ind{i1}) = PP_i{i1,end};\n end\n \n % Space for model-conditioned backward-time predicted means and covariances\n x_kp = cell(1,m);\n P_kp = cell(1,m);\n \n % Initialize with default values\n for i1 = 1:m\n x_kp{i1} = MM_def;\n P_kp{i1} = PP_def;\n end\n\n for k = n-1:-1:1\n % Space for normalizing constants and conditional model probabilities\n a_j = zeros(1,m);\n mu_bijp = zeros(m,m);\n \n for i2 = 1:m\n % Normalizing constant\n a_j(i2) = sum(p_ijb{k}(:,i2).*mu_bp(:));\n % Conditional model probability\n mu_bijp(:,i2) = 1/a_j(i2).*p_ijb{k}(:,i2).*mu_bp(:); \n \n % Retrieve the transition matrix or the Jacobian of the dynamic model\n if isnumeric(A{i2})\n A2 = A{i2};\n elseif isstr(A{i2}) | strcmp(class(A{i2}),'function_handle')\n A2 = feval(A{i2},x_bki{i2}(ind{i2}),a_param{i2});\n else\n A2 = A{i2}(x_bki{i2}(ind{i2}),a_param{i2});\n end\n \n % Backward-time EKF prediction step\n [x_kp{i2}(ind{i2}), P_kp{i2}(ind{i2},ind{i2})] = ekf_predict1(x_bki{i2}(ind{i2}),...\n P_bki{i2}(ind{i2},ind{i2}),...\n inv(A2),Q{i2},a{i2},[],a_param{i2});\n \n end \n \n % Space for mixed predicted mean and covariance\n x_kp0 = cell(1,m);\n P_kp0 = cell(1,m);\n \n % Space for measurement likelihoods\n lhood_j = zeros(1,m);\n \n for i2 = 1:m\n % Initialize with default values\n x_kp0{i2} = MM_def;\n P_kp0{i2} = PP_def; \n P_kp0{i2}(ind{i2},ind{i2}) = zeros(length(ind{i2}),length(ind{i2}));\n \n % Mix the mean\n for i1 = 1:m\n x_kp0{i2}(ind{i2}) = x_kp0{i2}(ind{i2}) + mu_bijp(i1,i2)*x_kp{i1}(ind{i2});\n end\n \n % Mix the covariance \n for i1 = 1:m\n P_kp0{i2}(ind{i2},ind{i2}) = P_kp0{i2}(ind{i2},ind{i2}) + mu_bijp(i1,i2)*(P_kp{i1}(ind{i2},ind{i2})+(x_kp{i1}(ind{i2})-x_kp0{i2}(ind{i2}))*(x_kp{i1}(ind{i2})-x_kp0{i2}(ind{i2}))'); \n end\n\n % Backward-time EKF update \n %\n % If the measurement model is linear don't pass h and h_param to ekf_update1\n if isempty(h) | isempty(h{i2})\n [x_bki{i2}(ind{i2}), P_bki{i2}(ind{i2},ind{i2}),K,MUP,S,lhood_j(i2)] = ekf_update1(x_kp0{i2}(ind{i2}),P_kp0{i2}(ind{i2},ind{i2}),Y(:,k),H{i2},R{i2},[],[],[]);\n else\n [x_bki{i2}(ind{i2}), P_bki{i2}(ind{i2},ind{i2}),K,MUP,S,lhood_j(i2)] = ekf_update1(x_kp0{i2}(ind{i2}),P_kp0{i2}(ind{i2},ind{i2}),Y(:,k),H{i2},R{i2},h{i2},[],h_param{i2});\n end\n end\n \n % Normalizing constant\n a_s = sum(lhood_j.*a_j);\n % Updated model probabilities\n mu_bp = 1/a_s.*a_j.*lhood_j; \n \n % Space for conditional measurement likelihoods\n lhood_ji = zeros(m,m);\n for i1 = 1:m\n for i2 = 1:m\n d_ijk = MM_def;\n D_ijk = PP_def;\n d_ijk = d_ijk + x_kp{i1};\n d_ijk(ind{i2}) = d_ijk(ind{i2}) - MM_i{i2,k};\n PP2 = zeros(dims,dims);\n PP2(ind{i2},ind{i2}) = PP_i{i2,k};\n D_ijk = P_kp{i1} + PP2;\n\n % Calculate the (approximate) conditional measurement likelihoods\n lhood_ji(i2,i1) = gauss_pdf(d_ijk,0,D_ijk); \n end\n end\n \n d_j = zeros(m,1);\n for i2 = 1:m\n d_j(i2) = sum(p_ij(i2,:).*lhood_ji(i2,:)); \n end\n d = sum(d_j.*MU(:,k));\n \n mu_ijsp = zeros(m,m);\n for i1 = 1:m\n for i2 = 1:m\n mu_ijsp(i1,i2) = 1./d_j(i2)*p_ij(i2,i1)*lhood_ji(i2,i1);\n end\n end\n \n mu_sk(:,k) = 1/d.*d_j.*MU(:,k);\n \n % Space for two-step conditional smoothing distributions p(x_k^j|m_{k+1}^i,y_{1:N}),\n % which are a products of two Gaussians\n x_jis = cell(m,m);\n P_jis = cell(m,m);\n for i2 = 1:m\n for i1 = 1:m\n MM1 = MM_def;\n MM1(ind{i2}) = MM_i{i2,k};\n \n PP1 = PP_def;\n PP1(ind{i2},ind{i2}) = PP_i{i2,k};\n\n iPP1 = inv(PP1);\n iPP2 = inv(P_kp{i1});\n \n % Covariance of the Gaussian product\n P_jis{i2,i1} = inv(iPP1+iPP2);\n % Mean of the Gaussian product\n x_jis{i2,i1} = P_jis{i2,i1}*(iPP1*MM1 + iPP2*x_kp{i1});\n end\n end\n \n % Mix the two-step conditional distributions to yield model-conditioned\n % smoothing distributions.\n for i2 = 1:m\n % Initialize with default values\n x_sik{i2,k} = MM_def;\n P_sik{i2,k} = PP_def;\n P_sik{i2,k}(ind{i2},ind{i2}) = zeros(length(ind{i2}),length(ind{i2}));\n \n % Mixed mean\n for i1 = 1:m\n x_sik{i2,k} = x_sik{i2,k} + mu_ijsp(i1,i2)*x_jis{i2,i1};\n end\n \n % Mixed covariance\n for i1 = 1:m\n P_sik{i2,k} = P_sik{i2,k} + mu_ijsp(i1,i2)*(P_jis{i2,i1} + (x_jis{i2,i1}-x_sik{i2,k})*(x_jis{i2,i1}-x_sik{i2,k})'); \n end\n end\n \n % Mix the overall smoothed mean\n for i1 = 1:m\n x_sk(:,k) = x_sk(:,k) + mu_sk(i1,k)*x_sik{i1,k};\n end\n \n % Mix the overall smoothed covariance\n for i1 = 1:m\n P_sk(:,:,k) = P_sk(:,:,k) + mu_sk(i1,k)*(P_sik{i1,k} + (x_sik{i1,k}-x_sk(:,k))*(x_sik{i1,k}-x_sk(:,k))');\n end\n \n end\n \n", "meta": {"author": "EEA-sensors", "repo": "ekfukf", "sha": "d08550a5b14caac525e51ed4ef5ec0ef1ea3e8f8", "save_path": "github-repos/MATLAB/EEA-sensors-ekfukf", "path": "github-repos/MATLAB/EEA-sensors-ekfukf/ekfukf-d08550a5b14caac525e51ed4ef5ec0ef1ea3e8f8/eimm_smooth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6001883592602049, "lm_q1q2_score": 0.48353106727368267}} {"text": "function c = rdivide(a,b)\n%RDIVIDE Interval elementwise right division a ./ b\n%\n\n% written 10/16/98 S.M. Rump\n% modified 11/30/98 S.M. Rump modified for infinity\n% modified 06/06/98 S.M. Rump modified for NaN+Nan*i\n% modified 09/02/00 S.M. Rump rounding unchanged after use\n% modified 04/04/04 S.M. Rump set round to nearest for safety\n% remove check for 'double'\n% take care of Matlab sparse Inf/NaN bug\n% modified 04/06/05 S.M. Rump rounding unchanged\n% modified 11/03/05 S.M. Rump sparse flag corrected\n% modified 11/20/05 S.M. Rump fast check for rounding to nearest\n% modified 02/11/06 S.M. Rump SparseInfNanFlag removed\n% improved performance\n% modified 05/23/06 S.M. Rump sparse Inf/NaN bug corrected in Version 7.2+\n% modified 12/03/06 S.M. Rump Sparse Bug global flag (thanks to Arnold)\n% modified 10/23/07 S.M. Rump complex numbers\n% modified 02/18/09 S.M. Rump NaN performance improved\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 end\n \n % no need to take care about huge matrices: result would be almost full anyway\n % also no care necessary about previous Matlab sparse NaN bug (would be helpful, in fact)\n % make sure a full except b is scalar, b full anyway\n if isa(b,'intval')\n bcomplex = b.complex;\n if bcomplex\n b.mid = full(b.mid);\n b.rad = full(b.rad);\n makefull = ( prod(size(b.mid))~=1 );\n nanindex = isnan(b.mid) | isnan(b.rad);\n else\n b.inf = full(b.inf);\n b.sup = full(b.sup);\n makefull = ( prod(size(b.inf))~=1 );\n nanindex = isnan(b.inf) | isnan(b.sup);\n end\n else\n bcomplex = ~isreal(b);\n b = full(b);\n makefull = ( prod(size(b))~=1 );\n nanindex = isnan(b);\n end\n nanindex = sparse(nanindex); % careful: full(True) | sparse = full\n if isa(a,'intval')\n acomplex = a.complex;\n if acomplex\n if makefull\n a.mid = full(a.mid);\n a.rad = full(a.rad);\n end\n nanindex = nanindex | isnan(a.mid) | isnan(a.rad);\n else\n if makefull\n a.inf = full(a.inf);\n a.sup = full(a.sup);\n end\n nanindex = nanindex | isnan(a.inf) | isnan(a.sup);\n end\n else\n acomplex = ~isreal(a);\n if makefull\n a = full(a);\n end\n nanindex = nanindex | isnan(a);\n end\n anynanindex = any(nanindex);\n anynanindex = any(anynanindex(:));\n\n ws = warning;\n warning off\n\n if acomplex | bcomplex % numerator complex\n b = intval(b); % make sure b is interval\n if ~bcomplex % denominator is real\n c = a.*(1./b);\n return\n end\n x = real(b.mid); % denominator is complex\n y = imag(b.mid);\n setround(-1)\n Ninf = x.*x + y.*y + (-b.rad).*b.rad;\n index = ( Ninf<=0 );\n setround(1)\n Nsup = x.*x + y.*y + (-b.rad).*b.rad;\n x2 = max( x./Ninf , x./Nsup );\n y2 = max( y./Ninf , y./Nsup );\n setround(-1)\n x1 = max( x./Ninf , x./Nsup );\n y1 = max( y./Ninf , y./Nsup );\n c1 = x1 - j*y2;\n setround(1)\n c2 = x2 - j*y1;\n binv.complex = 1;\n binv.inf = [];\n binv.sup = [];\n binv.mid = c1 + 0.5*(c2-c1);\n binv.rad = abs( binv.mid - c1 ) + b.rad./Ninf;\n index = index | ( binv.rad<0 );\n if any(index(:)) % division by zero\n binv.mid(index) = complex(NaN,NaN);\n binv.rad(index) = NaN;\n end\n binv = class(binv,'intval');\n c = a.*binv;\n if anynanindex\n c.mid(nanindex) = NaN;\n c.rad(nanindex) = NaN; % radius for sparse cannot be 0\n end\n else % both a and b real\n c.complex = 0;\n if ~isa(a,'intval') % R ./ IR\n % be sure min/max works correct for zero upper bounds in b\n b.sup(b.sup==0) = -0;\n setround(-1)\n c.inf = min( a./b.inf , a./b.sup );\n setround(1)\n c.sup = max( a./b.inf , a./b.sup );\n index = ( b.inf<=0 ) & ( b.sup>=0 ); % 0 in b\n if ~isempty(find(index))\n c.inf(index) = -inf;\n c.sup(index) = inf;\n index = index & ( a==0 ); % 0/0\n if any(index(:))\n c.inf(index) = NaN;\n c.sup(index) = NaN;\n end\n if anynanindex\n c.inf(nanindex) = NaN;\n c.sup(nanindex) = NaN;\n end\n end\n elseif ~isa(b,'intval') % IR ./ R\n setround(-1)\n c.inf = min( a.inf./b , a.sup./b );\n setround(1)\n c.sup = max( a.inf./b , a.sup./b );\n index = ( b==0 ); % numerator/0\n if ~isempty(find(index))\n c.inf(index) = -inf;\n c.sup(index) = inf;\n index = index & ( a.inf<=0 ) & ( 0<=a.sup );\n if any(index(:))\n c.inf(index) = NaN;\n c.sup(index) = NaN;\n end\n if anynanindex\n c.inf(nanindex) = NaN;\n c.sup(nanindex) = NaN;\n end\n end\n else % IR ./ IR\n % be sure min/max works correct for zero upper bounds in b\n b.sup(b.sup==0) = -0;\n setround(-1)\n c.inf = min( a.inf./b.inf , a.inf./b.sup );\n c.inf = min( c.inf , a.sup./b.inf );\n c.inf = min( c.inf , a.sup./b.sup );\n setround(1)\n c.sup = max( a.inf./b.inf , a.inf./b.sup );\n c.sup = max( c.sup , a.sup./b.inf );\n c.sup = max( c.sup , a.sup./b.sup );\n index = ( b.inf<=0 ) & ( b.sup>=0 ); % 0 in b\n if ~isempty(find(index))\n if prod(size(b.inf))==1\n c.inf = -inf*ones(size(c.inf));\n c.sup = -c.inf;\n else\n c.inf(index) = -inf;\n c.sup(index) = inf;\n end\n index = index & ( a.inf<=0 ) & ( a.sup>=0 ); % 0./0\n if any(index(:))\n c.inf(index) = NaN;\n c.sup(index) = NaN;\n end\n end\n if anynanindex\n c.inf(nanindex) = NaN;\n c.sup(nanindex) = NaN;\n end\n end\n c.mid = [];\n c.rad = [];\n c = class(c,'intval');\n end\n \n if issparse(b) & ( prod(size(c))~=1 )\n c = sparse(c);\n end\n\n warning(ws)\n setround(rndold)\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/intval/@intval/rdivide.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.483531061671867}} {"text": "% [INPUT]\n% pods = A vector of floats [0,1] of length n representing the probabilities of default.\n% g = A boolean n^2-by-n matrix representing the posterior density orthants.\n% p = A vector of floats [0,1] of length n^2 representing the posterior density probabilities.\n%\n% [OUTPUT]\n% jpod = A float [0,1] representing the Joint Probability of Default.\n% fsi = A float [1,n] representing the Financial Stability Index.\n% pce = A float [0,1] representing the Probability of Cascade Effects.\n% dide = A float n-by-n matrix [0,1] representing the Distress Dependency.\n% si = A row vector of floats [0,1] of length n representing the Systemic Importance.\n% sv = A row vector of floats [0,1] of length n representing the Systemic Vulnerability.\n% cojpods = A row vector of floats [0,1] of length n representing the Conditional Joint Probabilities of Default.\n\nfunction [jpod,fsi,pce,dide,si,sv,cojpods] = cross_entropy_metrics(varargin)\n\n persistent ip;\n\n if (isempty(ip))\n ip = inputParser();\n ip.addRequired('pods',@(x)validateattributes(x,{'double'},{'real' 'finite' '>=' 0 '<=' 1 'vector' 'nonempty'}));\n ip.addRequired('g',@(x)validateattributes(x,{'double'},{'real' 'finite' 'binary' '2d' 'nonempty'}));\n ip.addRequired('p',@(x)validateattributes(x,{'double'},{'real' 'finite' '>=' 0 '<=' 1 'vector' 'nonempty'}));\n end\n\n ip.parse(varargin{:});\n\n ipr = ip.Results;\n [pods,g,p] = validate_input(ipr.pods,ipr.g,ipr.p);\n\n nargoutchk(7,7);\n\n [jpod,fsi,pce,dide,si,sv,cojpods] = cross_entropy_metrics_internal(pods,g,p);\n\nend\n\nfunction [jpod,fsi,pce,dide,si,sv,cojpods] = cross_entropy_metrics_internal(pods,g,p)\n\n n = numel(pods);\n g_refs = sum(g,2);\n\n jpod = p(g_refs == n,:);\n fsi = min(max(sum(pods,'omitnan') / (1 - p(g_refs == 0,:)),1),n);\n pce = sum(p(g_refs >= 2,:)) / sum(p(g_refs >= 1,:));\n\n dide = eye(n);\n\n for i = 1:n\n for j = 1:n\n if (isnan(pods(j)))\n dide(i,j) = NaN;\n elseif (i ~= j)\n dide(i,j) = p((g_refs == 2) & (g(:,i) == 1) & (g(:,j) == 1),:) / pods(j);\n end\n end\n end\n\n dide_pods = ((dide - eye(n)) .* repmat(pods,1,n));\n si = sum(dide_pods,2);\n sv = sum(dide_pods,1).';\n\n jpods = ones(n,1) .* jpod;\n cojpods = (jpods ./ pods).';\n\nend\n\nfunction [pods,g,p] = validate_input(pods,g,p)\n\n pods = pods(:);\n n = numel(pods);\n\n if (n < 2)\n error('The value of ''pods'' is invalid. Expected input to be a vector containing at least 2 elements.');\n end\n\n k = n^2;\n\n [kg,ng] = size(g);\n\n if ((kg ~= k) || (ng ~= n))\n error(['The value of ''g'' is invalid. Expected input to be a matrix of size ' num2str(k) 'x' num2str(n) '.']);\n end\n\n kp = numel(p);\n\n if (kp ~= k)\n error(['The value of ''p'' is invalid. Expected input to be a vector containing ' num2str(k) ' elements.']);\n end\n\n p = p(:);\n\nend\n", "meta": {"author": "TommasoBelluzzo", "repo": "SystemicRisk", "sha": "f5e9b4823eabab2130974e535d13762c0cb3e4bf", "save_path": "github-repos/MATLAB/TommasoBelluzzo-SystemicRisk", "path": "github-repos/MATLAB/TommasoBelluzzo-SystemicRisk/SystemicRisk-f5e9b4823eabab2130974e535d13762c0cb3e4bf/ScriptsModels/cross_entropy_metrics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4833964854793604}} {"text": "function value = r4_besi0e ( x )\n\n%*****************************************************************************80\n%\n%% R4_BESI0E evaluates the exponentially scaled Bessel function I0(X).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 September 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Wayne Fullerton.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Wayne Fullerton,\n% Portable Special Function Routines,\n% in Portability of Numerical Software,\n% edited by Wayne Cowell,\n% Lecture Notes in Computer Science, Volume 57,\n% Springer 1977,\n% ISBN: 978-3-540-08446-4,\n% LC: QA297.W65.\n%\n% Parameters:\n%\n% Input, real X, the argument.\n%\n% Output, real VALUE, the exponentially scaled Bessel function I0(X).\n%\n persistent ai02cs\n persistent ai0cs\n persistent bi0cs\n persistent ntai0\n persistent ntai02\n persistent nti0\n persistent xsml\n\n if ( isempty ( nti0 ) )\n ai02cs = [ ...\n 0.05449041101410882E+00, ...\n 0.00336911647825569E+00, ...\n 0.00006889758346918E+00, ...\n 0.00000289137052082E+00, ...\n 0.00000020489185893E+00, ...\n 0.00000002266668991E+00, ...\n 0.00000000339623203E+00, ...\n 0.00000000049406022E+00, ...\n 0.00000000001188914E+00, ...\n -0.00000000003149915E+00, ...\n -0.00000000001321580E+00, ...\n -0.00000000000179419E+00, ...\n 0.00000000000071801E+00, ...\n 0.00000000000038529E+00, ...\n 0.00000000000001539E+00, ...\n -0.00000000000004151E+00, ...\n -0.00000000000000954E+00, ...\n 0.00000000000000382E+00, ...\n 0.00000000000000176E+00, ...\n -0.00000000000000034E+00, ...\n -0.00000000000000027E+00, ...\n 0.00000000000000003E+00 ]';\n ai0cs = [ ...\n 0.07575994494023796E+00, ...\n 0.00759138081082334E+00, ...\n 0.00041531313389237E+00, ...\n 0.00001070076463439E+00, ...\n -0.00000790117997921E+00, ...\n -0.00000078261435014E+00, ...\n 0.00000027838499429E+00, ...\n 0.00000000825247260E+00, ...\n -0.00000001204463945E+00, ...\n 0.00000000155964859E+00, ...\n 0.00000000022925563E+00, ...\n -0.00000000011916228E+00, ...\n 0.00000000001757854E+00, ...\n 0.00000000000112822E+00, ...\n -0.00000000000114684E+00, ...\n 0.00000000000027155E+00, ...\n -0.00000000000002415E+00, ...\n -0.00000000000000608E+00, ...\n 0.00000000000000314E+00, ...\n -0.00000000000000071E+00, ...\n 0.00000000000000007E+00 ]';\n bi0cs = [ ...\n -0.07660547252839144951E+00, ...\n 1.927337953993808270E+00, ...\n 0.2282644586920301339E+00, ...\n 0.01304891466707290428E+00, ...\n 0.00043442709008164874E+00, ...\n 0.00000942265768600193E+00, ...\n 0.00000014340062895106E+00, ...\n 0.00000000161384906966E+00, ...\n 0.00000000001396650044E+00, ...\n 0.00000000000009579451E+00, ...\n 0.00000000000000053339E+00, ...\n 0.00000000000000000245E+00 ]';\n nti0 = r4_inits ( bi0cs, 12, 0.1 * r4_mach ( 3 ) );\n ntai0 = r4_inits ( ai0cs, 21, 0.1 * r4_mach ( 3 ) );\n ntai02 = r4_inits ( ai02cs, 22, 0.1 * r4_mach ( 3 ) );\n xsml = sqrt ( 4.0 * r4_mach ( 3 ) );\n end\n\n y = abs ( x );\n\n if ( y <= xsml )\n value = 1.0;\n elseif ( y <= 3.0 )\n value = exp ( - y ) * ( 2.75 + ...\n r4_csevl ( y * y / 4.5 - 1.0, bi0cs, nti0 ) );\n elseif ( y <= 8.0 )\n value = ( 0.375 + r4_csevl ...\n ( ( 48.0 / y - 11.0 ) / 5.0, ai0cs, ntai0 ) ) / sqrt ( y );\n else\n value = ( 0.375 + r4_csevl ...\n ( 16.0 / y - 1.0, ai02cs, ntai02 ) ) / sqrt ( y );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fn/r4_besi0e.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594354, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.48339647455814044}} {"text": " function ob = Jop(varargin)\n%function ob = Jop(varargin)\n%J = Jop({'J', 4, 'L', 4, 'kspace', kspace, 'fov', fov, ...\n% 'kn.ktype', 'kaiser', 'kn.kb_alf', kb_alf, 'kn.kb_m', kb_m});\n%\n% Creates fatrix J for use in operations of the form y = J * x. Designed\n% for use in iterative algorithms for estimating density compensation\n% weights for conjugate phase MRI reconstruction.\n%\n% J is an MxM symmetric banded matrix, with entries corresponding to a\n% gridding kernel, C, convolved with itself, evaluated at values\n% corresponding to the difference between kspace sample locations, i.e.\n% J(i,l) = C(*)C(v_i - v_l)\n% where C is the gridding kernel (usually a Kaiser-Bessel), (*) represents \n% the convolution operator, and kspace sample locations are {v_m}, \n% m = 1,..., M.\n%\n% in: \n% kspace kspace sample locations\n% fov Field of View\n%\n% optional inputs:\n% J neighborhood for interpolation kernel\n% L samples per integer\n% kn.* various information to define kernel\n% e.g. kn.ktype = 'kaiser', kn.kb_alf = 10, kn.kb_m = 0\n% out:\n% J [nd nd] Fatrix operator\n%\n% K. Khalsa, Mar. 2006\n\n\n% default assignments:\n\narg.J = 4; \narg.L = 4;\narg.kspace = [];\narg.fov = []; \narg.del = []; \n\narg.kn.ktype = 'kaiser';\narg.kn.kernel = {}; %*** find out what to do with this, see Gn.arg.st\narg.kn.kb_alf = []; %\narg.kn.kb_m = []; %\n\n% pair input arguments\nif iscell(varargin)\n varargs = varargin{1};\n arg = vararg_pair(arg, varargs);\nelse\n printf('input needs to be in a cell array.');\n help Jop;\n return;\nend\n\n\n\nif isempty(arg.kspace)\n error('kspace sample locations are a required input argument');\nelse\n arg.M = size(arg.kspace, 1);\n arg.dim = [arg.M arg.M];\nend\n\narg.del = 1 ./ (arg.fov * arg.L);\n\nkappa = linspace(-arg.J/2, arg.J/2, arg.J * arg.L + 1)';\n%kappa = [-arg.J/2 : 1/arg.L : arg.J/2]'; %equivalently\n\n\nif (arg.kn.ktype == 'kaiser')\n\n if xor(isempty(arg.kn.kb_alf), isempty(arg.kn.kb_m))\n printf('For Kaiser-Bessel kernel, both m and alpha are required, or neither');\n return;\n elseif (isempty(arg.kn.kb_alf) && isempty(arg.kn.kb_m))\n % use parameters from Jackson's 1991 gridding paper\n arg.kn.kb_m = 0;\n ww = [1.5 2.0 2.5 3.0 3.5 4.0];\n jack_alf = [6.6875 9.1375 11.5250 13.9086 16.2734 18.5547];\n arg.kn.kb_alf = interp1(ww, jack_alf, arg.J, 'linear', 'extrap');\n \n end\n % keyboard\n arg.kn.C = kaiser_bessel(kappa, arg.J, arg.kn.kb_alf, ...\n arg.kn.kb_m);\n if size(arg.kspace, 2) == 2\n arg.kn.C = arg.kn.C * arg.kn.C'; % 2D kernel\n end\n arg.kn.c0 = kaiser_bessel_ft(0, arg.J, arg.kn.kb_alf, arg.kn.kb_m);\n\nelseif (arg.kn.ktype == 'function_handle')\n % figure out what to do here\n % see Gn.arg.st.kernel = {[1x1] function_handle}... ??\nelse\n error('kn.ktype must be kaiser or function_handle');\nend\n\n\n% Build Fatrix object\nob = Fatrix(arg.dim, arg, 'forw', @J_forw, 'back', @J_forw, ...\n 'caller', mfilename);\n% transpose multiplication = same as fwd multiplication b/c we\n% stipulate that all kernels must be real and symmetric\n\n%-------------------------- \n% multiplication\nfunction y = J_forw(arg, x)\n\nif (size(x,1) ~= arg.dim(2))\n error('dimension mismatch in matrix vector multiplication');\nend\n\n% 1D case\nif size(arg.kspace, 2) == 1\n k0 = abs(min(arg.kspace / arg.del) - arg.J);\n k = round(arg.kspace / arg.del + k0);\n N = max(k) + arg.J;\n xtmp = full(sum(sparse(1:arg.M, k, x, arg.M, N), 1))';\n\n CC = conv(arg.kn.C, arg.kn.C);\n Jxtmp = conv(xtmp, CC);\n Jxtmp = arg.del * Jxtmp;\n Jxtmp = Jxtmp / max(CC); % adjust scaling?\n y = Jxtmp(k + arg.J * arg.L);\n\n\n % 2D case\nelseif size(arg.kspace, 2) == 2\n\n k01 = abs(min(arg.kspace(:,1) / arg.del(1)) - arg.J);\n k02 = abs(min(arg.kspace(:,2) / arg.del(2)) - arg.J);\n k0 = [k01, k02];\n\n k1 = round(arg.kspace(:,1) / arg.del(1) + k0(1));\n k2 = round(arg.kspace(:,2) / arg.del(2) + k0(2));\n N1 = max(k1); N2 = max(k2);\n\n xtmp = full(sparse(k1, k2, x, N1, N2));\n\n CC = conv2(arg.kn.C, arg.kn.C);\n Jxtmp = conv2(xtmp, CC, 'same');\n ind = sub2ind(size(Jxtmp), k1,k2);\n\n y = Jxtmp(ind);\n % y = y / max(CC(:)); % adjust scaling?\nelse\n error('only 1D and 2D currently supported')\nend\ny = y / ((arg.kn.c0)^2); % adjust scaling??\n% keyboard\n\n\n% %plot to see if it's working right 2D\n% figure(11), clf\n% subplot(211)\n% plot3(arg.kspace(:,1), arg.kspace(:,2), x, 'x');\n% title('ks locs before regridding'), xlabel('kx'), ylabel('ky')\n% subplot(212)\n% plot3(k1, k2, x, 'x'), title('ks locs after regridding'), xlabel('kapx')\n% \n% \n% figure(12), clf\n% subplot(211), imagesc(xtmp), axis square, colorbar, title('xtmp')\n% subplot(212), imagesc(Jx), axis square, colorbar, title('Jx')\n% keyboard\n\n%%plot to see if it's working right 1D\n% figure(11), clf\n% subplot(211)\n% stem(arg.kspace, x), title('wi before regridding'), xlabel('kx')\n% subplot(212)\n% stem(1:N, xtmp), title('wi after regridding'), xlabel('kap')\n\n% figure(12), clf\n% subplot(211), stem(1:length(Jxkap), Jxkap), title('Jxkap')\n% subplot(212), stem(arg.kspace, y), title('y = J * x'), xlabel('kx')\n% keyboard\n\n\n\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/contrib/khalsa/Jop.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.48326986307665803}} {"text": "% PAC_CONT - compute phase-amplitude coupling (power of first input\n% correlation with phase of second). There is no graphical output\n% to this function.\n%\n% Usage:\n% >> pac_cont(x,y,srate);\n% >> [pac timesout pvals] = pac_cont(x,y,srate,'key1', 'val1', 'key2', val2' ...);\n%\n% Inputs:\n% x = [float array] 1-D data vector of size (1xtimes)\n% y = [float array] 1-D data vector of size (1xtimes)\n% srate = data sampling rate (Hz)\n%\n% Optional time information inputs:\n% 'winsize' = If cycles==0: data subwindow length (fastest, 2^n0: *longest* window length to use. This\n% determines the lowest output frequency. Note that this\n% parameter is overwritten if the minimum frequency has been set\n% manually and requires a longer time window {~frames/8}\n% 'ntimesout' = Number of output times (int 1, X = X'; end\nif size(Y,1) > 1, Y = Y'; end\nif size(X,1) ~= 1 || size(Y,1) ~= 1, error('Cannot only process vector input'); end\nframe = size(X,2);\npvals = [];\n\ng = finputcheck(varargin, ...\n { ...\n 'alpha' 'real' [0 0.2] [];\n 'baseline' 'float' [] [];\n 'freqphase' 'real' [0 Inf] [0 srate/2];\n 'freqamp' 'real' [0 Inf] [];\n 'mcorrect' 'string' { 'none' 'fdr' } 'none';\n 'method' 'string' { 'plv' 'modulation' 'glm' 'corr' } 'modulation';\n 'naccu' 'integer' [1 Inf] 250;\n 'instantstat' 'string' {'on','off'} 'off';\n 'newfig' 'string' {'on','off'} 'on';\n 'nofig' 'string' {'on','off'} 'off';\n 'statlim' 'string' {'surrogate','parametric'} 'parametric';\n 'timesout' 'real' [] []; ...\n 'filterfunc' 'string' { 'eegfilt' 'iirfilt' 'eegfiltfft' } 'eegfiltfft'; ...\n 'filterphase' '' {} [];\n 'filteramp' '' {} [];\n 'ntimesout' 'integer' [] 200; ...\n 'tlimits' 'real' [] [0 frame/srate];\n 'title' 'string' [] '';\n 'vert' 'real' [] [];\n 'winsize' 'integer' [0 Inf] max(pow2(nextpow2(frame)-3),4) }, 'pac');\n\nif ischar(g), error(g); end\n\nif ~isempty(g.filterphase)\n x_freqphase = feval(g.filterphase, X(:)');\nelse x_freqphase = feval(g.filterfunc, X(:)', srate, g.freqphase(1), g.freqphase(end));\nend\nif ~isempty(g.filteramp)\n x_freqamp = feval(g.filteramp, Y(:)');\nelse x_freqamp = feval(g.filterfunc, Y(:)', srate, g.freqamp( 1), g.freqamp( end));\nend\nz_phasedata = hilbert(x_freqphase);\nz_ampdata = hilbert(x_freqamp);\nphase = angle(z_phasedata);\namplitude = abs( z_ampdata);\nz = amplitude.*exp(i*phase); % this is the pac measure\n\n% get time windows\n% ----------------\ng.verbose = 'on';\ng.causal = 'off';\n[ timesout1 indexout ] = gettimes(frame, g.tlimits, g.timesout, g.winsize, g.ntimesout, g.causal, g.verbose);\n\n% scan time windows\n% -----------------\nif ~isempty(g.alpha)\n m_raw = zeros(1,length(indexout));\n pvals = zeros(1,length(indexout));\nend\nfprintf('Computing PAC:\\n');\nfor iWin = 1:length(indexout)\n x_phaseEpoch = x_freqphase(indexout(iWin)+[-g.winsize/2+1:g.winsize/2]);\n x_ampEpoch = x_freqamp( indexout(iWin)+[-g.winsize/2+1:g.winsize/2]);\n z_phaseEpoch = z_phasedata(indexout(iWin)+[-g.winsize/2+1:g.winsize/2]);\n z_ampEpoch = z_ampdata( indexout(iWin)+[-g.winsize/2+1:g.winsize/2]);\n z_epoch = z( indexout(iWin)+[-g.winsize/2+1:g.winsize/2]);\n \n numpoints=length(x_phaseEpoch);\n if rem(iWin,10) == 0, verboseprintf(g.verbose, ' %d',iWin); end\n if rem(iWin,120) == 0, verboseprintf(g.verbose, '\\n'); end\n \n % Choose method\n % -------------\n if strcmpi(g.method, 'modulation')\n \n % Modulation index\n m_raw(iWin) = abs(sum(z_epoch))/numpoints;\n \n elseif strcmpi(g.method, 'plv')\n \n if iWin == 145\n %dsfsd; \n end\n \n %amplitude_filt = sgolayfilt(amplitude, 3, 101);\n if ~isempty(g.filterphase)\n amplitude_filt = feval(g.filterphase, z_ampEpoch);\n else amplitude_filt = feval(g.filterfunc , z_ampEpoch, srate, g.freqphase(1), g.freqphase(end));\n end\n z_amplitude_filt = hilbert(amplitude_filt);\n \n phase_amp_modulation = angle(z_amplitude_filt);\n m_raw(iWin) = abs(sum(exp(i*(x_phaseEpoch - phase_amp_modulation)))/numpoints);\n \n elseif strcmpi(g.method, 'corr')\n \n if iWin == inf %145\n figure; plot(abs(z_ampdata))\n hold on; plot(x_phasedata/10000000000, 'r')\n x = X(indexout(iWin)+[-g.winsize/2+1:g.winsize/2]);\n hold on; plot(x, 'g');\n dsfsd;\n end\n [r_ESC pval_corr] = corrcoef(x_phaseEpoch, abs(z_ampEpoch));\n m_raw(iWin) = r_ESC(1,2);\n pvals(iWin) = pval_corr(1,2);\n \n elseif strcmpi(g.method, 'glm')\n \n [b dev stats] = glmfit(x_phaseEpoch', abs(z_ampEpoch)', 'normal');\n GLM_beta = stats.beta(2,1);\n pvals(iWin) = stats.p(2,1);\n m_raw(iWin) = b(1);\n \n end\n \n %% compute statistics (instantaneous)\n % -----------------------------------\n if ~isempty(g.alpha) && strcmpi(g.instantstat, 'on') && ~strcmpi(g.method, 'corr') && ~strcmpi(g.method, 'glm')\n \n % compute surrogate values\n numsurrogate=g.naccu;\n minskip=srate;\n maxskip=numpoints-srate; % max variation half a second\n if maxskip < 1\n error('Window size shorter than 1 second; too short for computing surrogate data');\n end\n skip=ceil(numpoints.*rand(numsurrogate*4,1));\n skip(skip>maxskip)=[];\n skip(skip= g.baseline(1) & timesout1 <= g.baseline(end));\n \n m_raw_base = abs(m_raw(baselineInd));\n \n if strcmpi(g.statlim, 'surrogate')\n for index = 1:length(m_raw)\n pvals(index) = stat_surrogate_pvals(m_raw_base, m_raw(index), 'upper');\n end\n else\n [surrogate_mean,surrogate_std]=normfit(m_raw_base);\n m_norm_length=(abs(m_raw)-surrogate_mean)/surrogate_std;\n pvals = normcdf(0, m_norm_length, 1);\n end\n if strcmpi(g.mcorrect, 'fdr')\n pvals = fdr(pvals);\n end\nend\n\n%% plot results\n% -------------\nif strcmpi(g.nofig, 'on')\n return\nend\nif strcmpi(g.newfig, 'on')\n figure;\nend\nif ~isempty(g.alpha)\n plotcurve(timesout1, m_raw, 'maskarray', pvals < g.alpha);\nelse plotcurve(timesout1, m_raw);\nend\nxlabel('Time (ms)');\nylabel('PAC (0 to 1)');\ntitle(g.title);\n\n% plot vertical lines\n% -------------------\nif ~isempty(g.vert)\n hold on;\n yl = ylim;\n for index = 1:length(g.vert)\n plot([g.vert(index) g.vert(index)], yl, 'g');\n end\nend\n\n% -------------\n% gettime function identical to timefreq function\n% DO NOT MODIFY\n% -------------\nfunction [ timevals, timeindices ] = gettimes(frames, tlimits, timevar, winsize, ntimevar, causal, verbose);\ntimevect = linspace(tlimits(1), tlimits(2), frames);\nsrate = 1000*(frames-1)/(tlimits(2)-tlimits(1));\n\nif isempty(timevar) % no pre-defined time points\n if ntimevar(1) > 0\n % generate linearly space vector\n % ------------------------------\n if (ntimevar > frames-winsize)\n ntimevar = frames-winsize;\n if ntimevar < 0\n error('Not enough data points, reduce the window size or lowest frequency');\n end\n verboseprintf(verbose, ['Value of ''timesout'' must be <= frame-winsize, ''timesout'' adjusted to ' int2str(ntimevar) '\\n']);\n end\n npoints = ntimevar(1);\n wintime = 500*winsize/srate;\n if strcmpi(causal, 'on')\n timevals = linspace(tlimits(1)+2*wintime, tlimits(2), npoints);\n else timevals = linspace(tlimits(1)+wintime, tlimits(2)-wintime, npoints);\n end\n verboseprintf(verbose, 'Generating %d time points (%1.1f to %1.1f ms)\\n', npoints, min(timevals), max(timevals));\n else\n % subsample data\n % --------------\n nsub = -ntimevar(1);\n if strcmpi(causal, 'on')\n timeindices = [ceil(winsize+nsub):nsub:length(timevect)];\n else timeindices = [ceil(winsize/2+nsub/2):nsub:length(timevect)-ceil(winsize/2)-1];\n end\n timevals = timevect( timeindices ); % the conversion at line 741 leaves timeindices unchanged\n verboseprintf(verbose, 'Subsampling by %d (%1.1f to %1.1f ms)\\n', nsub, min(timevals), max(timevals));\n end\nelse\n timevals = timevar;\n % check boundaries\n % ----------------\n wintime = 500*winsize/srate;\n if strcmpi(causal, 'on')\n tmpind = find( (timevals >= tlimits(1)+2*wintime-0.0001) & (timevals <= tlimits(2)) );\n else tmpind = find( (timevals >= tlimits(1)+wintime-0.0001) & (timevals <= tlimits(2)-wintime+0.0001) );\n end\n % 0.0001 account for numerical innacuracies on opteron computers\n if isempty(tmpind)\n error('No time points. Reduce time window or minimum frequency.');\n end\n if length(timevals) ~= length(tmpind)\n verboseprintf(verbose, 'Warning: %d out of %d time values were removed (now %3.2f to %3.2f ms) so the lowest\\n', ...\n length(timevals)-length(tmpind), length(timevals), timevals(tmpind(1)), timevals(tmpind(end)));\n verboseprintf(verbose, ' frequency could be computed with the requested accuracy\\n');\n end\n timevals = timevals(tmpind);\nend\n\n% find closet points in data\n% --------------------------\ntimeindices = round(eeg_lat2point(timevals, 1, srate, tlimits, 1E-3));\nif length(timeindices) < length(unique(timeindices))\n timeindices = unique_bc(timeindices)\n verboseprintf(verbose, 'Warning: duplicate times, reduce the number of output times\\n');\nend\nif length(unique(timeindices(2:end)-timeindices(1:end-1))) > 1\n verboseprintf(verbose, 'Finding closest points for time variable\\n');\n verboseprintf(verbose, 'Time values for time/freq decomposition is not perfectly uniformly distributed\\n');\nelse\n verboseprintf(verbose, 'Distribution of data point for time/freq decomposition is perfectly uniform\\n');\nend\ntimevals = timevect(timeindices);\n\nfunction verboseprintf(verbose, varargin)\nif strcmpi(verbose, 'on')\n fprintf(varargin{:});\nend\n\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/timefreqfunc/pac_cont.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.483146022487574}} {"text": "function yout = poolDataLIST_CONTROL(yin,ahat,nVars,polyorder,usesine)\n% Copyright 2015, All Rights Reserved\n% Code by Steven L. Brunton\n% For Paper, \"Discovering Governing Equations from Data: \n% Sparse Identification of Nonlinear Dynamical Systems\"\n% by S. L. Brunton, J. L. Proctor, and J. N. Kutz\n\nn = size(yin,1);\n\nind = 1;\n% poly order 0\nyout{ind,1} = ['1'];\nind = ind+1;\n\n% poly order 1\nfor i=1:nVars\n yout(ind,1) = yin(i);\n ind = ind+1;\nend\n\nif(polyorder>=2)\n % poly order 2\n for i=1:nVars\n for j=i:nVars\n yout{ind,1} = [yin{i},yin{j}];\n ind = ind+1;\n end\n end\nend\n\nif(polyorder>=3)\n % poly order 3\n for i=1:nVars\n for j=i:nVars\n for k=j:nVars\n yout{ind,1} = [yin{i},yin{j},yin{k}];\n ind = ind+1;\n end\n end\n end\nend\n\nif(polyorder>=4)\n % poly order 4\n for i=1:nVars\n for j=i:nVars\n for k=j:nVars\n for l=k:nVars\n yout{ind,1} = [yin{i},yin{j},yin{k},yin{l}];\n ind = ind+1;\n end\n end\n end\n end\nend\n\nif(polyorder>=5)\n % poly order 5\n for i=1:nVars\n for j=i:nVars\n for k=j:nVars\n for l=k:nVars\n for m=l:nVars\n yout{ind,1} = [yin{i},yin{j},yin{k},yin{l},yin{m}];\n ind = ind+1;\n end\n end\n end\n end\n end\nend\n\nif(usesine)\n for k=1:10;\n yout{ind,1} = ['sin(',num2str(k),'*yin)'];\n ind = ind + 1;\n yout{ind,1} = ['cos(',num2str(k),'*yin)'];\n ind = ind + 1;\n end\nend\n\n\noutput = yout;\nnewout(1) = {''};\nnewout{1,2} = 'u';\n% for k=1:length(yin)\n% newout{1,1+k} = [yin{k},'dot'];\n% end\n% newout = {'','xdot','ydot','udot'};\nfor k=1:size(ahat,1)\n newout(k+1,1) = output(k);\n for j=1:size(ahat,2)\n newout{k+1,1+j} = ahat(k,j);\n end\nend\nnewout", "meta": {"author": "eurika-kaiser", "repo": "SINDY-MPC", "sha": "e1dfd9908b2b56af303ee9fb30a133aced4fd757", "save_path": "github-repos/MATLAB/eurika-kaiser-SINDY-MPC", "path": "github-repos/MATLAB/eurika-kaiser-SINDY-MPC/SINDY-MPC-e1dfd9908b2b56af303ee9fb30a133aced4fd757/utils/poolDataLIST_CONTROL.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.4831337930296917}} {"text": "% Locate place fields in a firing map.\n%\n% Identifies the place fields in 2D firing map. First map is converted to binary image\n% by applying a global threshold. During the second step connected regions are labeled\n% by function bwlabel. Final step includes filtering of identified regions and verification\n% that they are valid place fields.\n%\n% USAGE\n% [fieldsMap, fields] = analyses.palcefield(map, )\n% map Firing rate map either structure obtained using analyses.map\n% or a matrix that represents firing map.\n% optional list of property-value pairs (see table below)\n%\n% =========================================================================\n% Properties Values\n% -------------------------------------------------------------------------\n% 'threshold' value above threshold*peak belong to a field (default = 0.2).\n% 'minBins' Minimum number of bins in a place field, i.e. total number\n% of bins of place field or an area of place field. Fields with\n% fewer bins are not considered as place fields. Remember to\n% adjust this value when you change the bin width.\n% (default = 9).\n% 'minPeak' peaks smaller than this value are considered spurious\n% and ignored (default = 1). Peak is normally a rate, however\n% it's units not necessary are Hz.\n% 'binWidth' Width of the bins in cm. It is used to calculate field size.\n% (default = 1).\n% 'pos' Position samples. Used to calculate posInd. If not provided,\n% then posInd will be an empty matrix.\n% 'minMeanRate' Fields with mean rate smaller that this value are ignored (default = 0).\n% =========================================================================\n%\n% OUTPUT\n%\n% fieldsMap Matrix of the same size as firing map. The elements of fieldsMap\n% are integer values greater or equal to 0. The elements labeled 0\n% are the background (not a place field). The pixels labeled 1 make up\n% first field; the pixels labeled 2 make up a second object; and so on.\n%\n% fields Structure with information about each field. Structure fields are:\n% row vector of rows that constitute this field;\n% col vector of columns that constitute this field;\n% area area of field measured by regionprops function, i.e. number of bins in the field;\n% bbox bounding box of the field;\n% peak field peak value;\n% size field size in cm; Calculated with help of binWidth argument.\n% x, y field centre of mass point;\n% meanRate mean firing rate;\n% PixelIdxList linear list of indices that constitute the field.\n% peakX X-coordinate of field's peak\n% peakY Y-coordinate of field's peak\n% map Binary map of the field. It has the same size as firing map. The elements of 'map'\n% equal to one if they belong to the field and are zeros otherwise.\n% posInd Indices of position samples that correspond to this field. In case position sample\n% matrix is of size Nx5 ([t x y x1 y1]), posInd corresponds to the left most position\n% columns ([x y]). If pos argument is not provided, then posInd will be an empty matrix.\n%\n% EXAMPLES\n%\n% 1. To obtain positions of the first field run:\n% [~, fields] = analyses.placefield(map, 'threshold', 0.3, 'minBins', 5, 'minPeak', 0.1, 'pos', pos);\n% fieldPos = pos(fields(1).posInd, :);\n%\n\n% Note to developers:\n% In order to improve speed and capture all fields the map is processed in two passes. First\n% we extract fields based solely on global peak value. This should be enough for most of the cases.\n% Secondly we check if extracted fields maxima is the same as results of imregionalmax. If they are\n% different, then we perform another extraction, which is slower.\n%\nfunction [fieldsMap, fields] = placefield(map, varargin)\n inp = inputParser;\n defaultMinPeak = 1.;\n defaultThreshold = 0.2;\n defaultMinBins = 9;\n defaultBinWidth = 1;\n defaultPos = [];\n defaultMinMeanRate = 0;\n\n % input argument check functions\n checkThreshold = @(x) helpers.isdscalar(x, '>=0', '<=1');\n checkScalarZero = @(x) helpers.isiscalar(x, '>=0');\n checkDScalar = @(x) helpers.isdscalar(x, '>0');\n checkDScalarZero = @(x) helpers.isdscalar(x, '>=0');\n\n % fill input parser object\n addRequired(inp, 'map');\n addParameter(inp, 'threshold', defaultThreshold, checkThreshold);\n addParameter(inp, 'minBins', defaultMinBins, checkScalarZero);\n addParameter(inp, 'minPeak', defaultMinPeak, checkDScalarZero);\n addParameter(inp, 'binWidth', defaultBinWidth, checkDScalar);\n addParameter(inp, 'minMeanRate', defaultMinMeanRate, checkScalarZero);\n addParameter(inp, 'pos', defaultPos, @(x) ismatrix(x) && size(x, 2) >= 3);\n\n parse(inp, map, varargin{:});\n\n % get parsed arguments\n minPeak = inp.Results.minPeak;\n threshold = inp.Results.threshold;\n minBins = inp.Results.minBins;\n binWidth = inp.Results.binWidth;\n pos = inp.Results.pos;\n minMeanRate = inp.Results.minMeanRate;\n\n originalMap = [];\n if isstruct(map)\n originalMap = map;\n map = map.z;\n end\n\n fieldsMap = zeros(size(map));\n fields = struct('row', {}, 'col', {}, ...\n 'size', {}, 'peak', {}, 'peakX', {}, 'peakY', {}, ...\n 'area', {}, 'bbox', {}, ...\n 'x', {}, 'y', {}, ...\n 'meanRate', {}, 'PixelIdxList', {}, ...\n 'map', {}, 'posInd', {} ...\n );\n\n if isempty(map)\n return\n end\n\n globalPeak = nanmax(nanmax(map));\n if isnan(globalPeak) || globalPeak == 0\n return;\n end\n\n mapNans = isnan(map);\n map(mapNans) = 0;\n regionalMaxMap = imregionalmax(map, 4); % obtain all local maxima\n testRegionalMx = zeros(size(map)); % map that will contain located fields maxima\n\n [ir, ic] = find(regionalMaxMap > 0); % get peak locations\n foundPeaks = map(sub2ind(size(map), ir ,ic)); % obtain peaks value\n\n % remove peaks that have smaller rate than minPeak\n selected = foundPeaks < minPeak;\n regionalMaxMap(ir(selected), ic(selected)) = 0;\n\n % Counter for the number of fields\n nFields = 0;\n\n binMap = ones(size(map));\n\n binMap(map < globalPeak*threshold) = 0;\n binMap(mapNans) = 0;\n\n cc = bwconncomp(binMap, 4);\n stats = regionprops(cc, 'Area', 'BoundingBox', 'Centroid');\n\n for i = 1:cc.NumObjects\n linInd = cc.PixelIdxList{i};\n [fieldPeak, peakLinearInd] = max(map(linInd));\n [r, c] = ind2sub(size(map), linInd);\n meanRate = nanmean(map(linInd));\n\n [pr, pc] = ind2sub(size(map), linInd(peakLinearInd));\n % mark this field as visited even if we reject if further down\n testRegionalMx(pr, pc) = 1;\n\n if fieldPeak < minPeak\n continue;\n end\n if meanRate < minMeanRate\n continue;\n end\n\n if length(r) >= minBins\n nFields = nFields + 1;\n\n fields(nFields).row = r;\n fields(nFields).col = c;\n fields(nFields).size = length(r) * binWidth^2;\n fields(nFields).peak = fieldPeak;\n fields(nFields).peakX = pc;\n fields(nFields).peakY = pr;\n fields(nFields).area = stats(i).Area;\n fields(nFields).bbox = stats(i).BoundingBox;\n fields(nFields).PixelIdxList = linInd;\n\n fields(nFields).x = stats(i).Centroid(1);\n fields(nFields).y = stats(i).Centroid(2);\n\n fields(nFields).meanRate = meanRate;\n fields(nFields).map = zeros(size(map));\n fields(nFields).map(linInd) = 1;\n fields(nFields).map(mapNans) = nan;\n\n % fields(nFields).Extent = stats(i).Extent;\n % fields(nFields).Orientation = stats(i).Orientation;\n % fields(nFields).Eccentricity = stats(i).Eccentricity;\n % fields(nFields).MinorAxisLength = stats(i).MinorAxisLength;\n % fields(nFields).MajorAxisLength = stats(i).MajorAxisLength;\n % fields(nFields).Perimeter = stats(i).Perimeter;\n\n if ~isempty(pos)\n intRect = ceil(fields(nFields).bbox); % bounding box with integers\n if isempty(originalMap)\n % we do not have position distribution from the map, so assume that it's based\n % on data min/max values\n nBins = size(map);\n limitsX = [nanmin(pos(:, bntConstants.PosX)) nanmax(pos(:, bntConstants.PosX))];\n limitsY = [nanmin(pos(:, bntConstants.PosY)) nanmax(pos(:, bntConstants.PosY))];\n xSpace = linspace(limitsX(1), limitsX(2), nBins(2));\n ySpace = linspace(limitsY(1), limitsY(2), nBins(1));\n else\n xSpace = originalMap.x;\n ySpace = originalMap.y;\n end\n\n xMin = xSpace(intRect(1));\n xMax = xSpace(intRect(1) + intRect(3) - 1);\n\n yMin = ySpace(intRect(2));\n yMax = ySpace(intRect(2) + intRect(4) - 1);\n\n posIndX = pos(:, bntConstants.PosX) >= xMin & pos(:, bntConstants.PosX) <= xMax;\n posIndY = pos(:, bntConstants.PosY) >= yMin & pos(:, bntConstants.PosY) <= yMax;\n fields(nFields).posInd = find(posIndX & posIndY);\n else\n fields(nFields).posInd = [];\n end\n\n fieldsMap(linInd) = nFields;\n end\n end\n\n if ~isequaln(testRegionalMx, regionalMaxMap)\n map(fieldsMap > 0) = 0; % turn off map values for known fields, prevent field duplicates\n\n % we have some uncounted fields\n leftPeaksMap = regionalMaxMap - testRegionalMx;\n [ir, ic] = find(leftPeaksMap > 0); % get peak locations\n foundPeaks = map(sub2ind(size(leftPeaksMap), ir ,ic)); % obtain peaks value\n mapThresholds = foundPeaks * threshold;\n if sum(foundPeaks) == 0\n return;\n end\n\n finalMap = zeros(size(map));\n for i = 1:length(foundPeaks)\n binMap = zeros(size(map));\n binMap( (map > mapThresholds(i)) & (map <= foundPeaks(i)) ) = 1;\n binMap(mapNans) = 0;\n\n [binMap, linInd] = bwselect(binMap, ic(i), ir(i), 4); % leave only region that relates to current field\n if isempty(linInd)\n continue;\n end\n\n % check for minimum number of bins\n [r, ~] = ind2sub(size(map), linInd);\n if length(r) < minBins\n continue;\n end\n\n stats = regionprops(binMap, 'Centroid', 'EulerNumber'); % find statistics on field candidates\n distToPeak = sqrt((stats.Centroid(1) - ic(i))^2 + (stats.Centroid(2) - ir(i))^2);\n % distToPeak = pdist2(stats.Centroid, [ic(i) ir(i)]);\n if distToPeak > 4 || stats.EulerNumber < 1 % we want object without holes (euler number)\n continue;\n end\n finalMap(linInd) = 1;\n end\n\n cc = bwconncomp(finalMap, 4); % somehow regionprops is not working if finalMap is passed directly\n stats = regionprops(cc, 'Area', 'BoundingBox', 'Centroid');\n\n for fieldInd = 1:length(stats)\n linInd = cc.PixelIdxList{fieldInd};\n [r, c] = ind2sub(size(map), linInd);\n meanRate = nanmean(map(linInd));\n [peakRate, peakInd] = nanmax(map(linInd));\n [pr, pc] = ind2sub(size(map), linInd(peakInd));\n\n if peakRate < minPeak\n continue;\n end\n if meanRate < minMeanRate\n continue;\n end\n\n nFields = nFields + 1;\n\n fields(nFields).row = r;\n fields(nFields).col = c;\n fields(nFields).size = length(r) * binWidth^2;\n fields(nFields).peak = peakRate;\n fields(nFields).peakX = pc;\n fields(nFields).peakY = pr;\n fields(nFields).area = stats(fieldInd).Area;\n fields(nFields).bbox = stats(fieldInd).BoundingBox;\n fields(nFields).PixelIdxList = linInd;\n\n fields(nFields).x = stats(fieldInd).Centroid(1);\n fields(nFields).y = stats(fieldInd).Centroid(2);\n\n fields(nFields).meanRate = meanRate;\n fields(nFields).map = zeros(size(map));\n fields(nFields).map(linInd) = 1;\n fields(nFields).map(mapNans) = nan;\n\n if ~isempty(pos)\n intRect = ceil(fields(nFields).bbox); % bounding box with integers\n if isempty(originalMap)\n % we do not have position distribution from the map, so assume that it's based\n % on data min/max values\n nBins = size(map);\n limitsX = [nanmin(pos(:, bntConstants.PosX)) nanmax(pos(:, bntConstants.PosX))];\n limitsY = [nanmin(pos(:, bntConstants.PosY)) nanmax(pos(:, bntConstants.PosY))];\n xSpace = linspace(limitsX(1), limitsX(2), nBins(2));\n ySpace = linspace(limitsY(1), limitsY(2), nBins(1));\n else\n xSpace = originalMap.x;\n ySpace = originalMap.y;\n end\n\n xMin = xSpace(intRect(1));\n xMax = xSpace(intRect(1) + intRect(3) - 1);\n\n yMin = ySpace(intRect(2));\n yMax = ySpace(intRect(2) + intRect(4) - 1);\n\n posIndX = pos(:, bntConstants.PosX) >= xMin & pos(:, bntConstants.PosX) <= xMax;\n posIndY = pos(:, bntConstants.PosY) >= yMin & pos(:, bntConstants.PosY) <= yMax;\n fields(nFields).posInd = find(posIndX & posIndY);\n else\n fields(nFields).posInd = [];\n end\n\n fieldsMap(linInd) = nFields;\n end\n end\nend\n", "meta": {"author": "kavli-ntnu", "repo": "MINI2P_toolbox", "sha": "83311a49baea69ecf027e19390e608fd4eaeae8d", "save_path": "github-repos/MATLAB/kavli-ntnu-MINI2P_toolbox", "path": "github-repos/MATLAB/kavli-ntnu-MINI2P_toolbox/MINI2P_toolbox-83311a49baea69ecf027e19390e608fd4eaeae8d/Analysis/+SpatialTuning_BNT/placefield.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.48303377711780915}} {"text": "% DESCRIPTION:\n% subscript to create the absorption variables\n%\n% ABOUT:\n% author - Bradley Treeby\n% date - 26th November 2010\n% last update - 11th February 2014\n% \n% This function is part of the k-Wave Toolbox (http://www.k-wave.org)\n% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox\n\n% This file is part of k-Wave. k-Wave is free software: you can\n% redistribute it and/or modify it under the terms of the GNU Lesser\n% General Public License as published by the Free Software Foundation,\n% either version 3 of the License, or (at your option) any later version.\n% \n% k-Wave is distributed in the hope that it will be useful, but WITHOUT ANY\n% WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n% FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for\n% more details. \n% \n% You should have received a copy of the GNU Lesser General Public License\n% along with k-Wave. If not, see .\n\n% define the lossy derivative operators and proportionality coefficients\nif strcmp(equation_of_state, 'absorbing')\n \n % make sure the operators are positive and real\n medium.alpha_coeff = abs(real(medium.alpha_coeff));\n medium.alpha_power = abs(real(medium.alpha_power));\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 % compute the absorbing fractional Laplacian operator and coefficient\n if ~(isfield(medium, 'alpha_mode') && strcmp(medium.alpha_mode, 'no_absorption'))\n absorb_nabla1 = (kgrid.k).^(medium.alpha_power-2); \n absorb_nabla1(isinf(absorb_nabla1)) = 0;\n absorb_nabla1 = ifftshift(absorb_nabla1);\n absorb_tau = -2*medium.alpha_coeff.*medium.sound_speed.^(medium.alpha_power - 1);\n else\n absorb_nabla1 = 0;\n absorb_tau = 0;\n end\n \n % compute the dispersive fractional Laplacian operator and coefficient\n if ~(isfield(medium, 'alpha_mode') && strcmp(medium.alpha_mode, 'no_dispersion'))\n absorb_nabla2 = (kgrid.k).^(medium.alpha_power-1); \n absorb_nabla2(isinf(absorb_nabla2)) = 0;\n absorb_nabla2 = ifftshift(absorb_nabla2); \n absorb_eta = 2*medium.alpha_coeff.*medium.sound_speed.^(medium.alpha_power)*tan(pi*medium.alpha_power/2);\n else\n absorb_nabla2 = 0;\n absorb_eta = 0;\n end\n \n % pre-filter the absorption parameters if alpha_filter is defined (this\n % is used for time-reversal photoacoustic image reconstruction\n % with absorption compensation)\n if isfield(medium, 'alpha_filter');\n \n % update command line status\n disp(' filtering absorption variables...'); \n \n % frequency shift the absorption parameters\n absorb_nabla1 = fftshift(absorb_nabla1);\n absorb_nabla2 = fftshift(absorb_nabla2);\n \n % apply the filter\n absorb_nabla1 = absorb_nabla1.*medium.alpha_filter;\n absorb_nabla2 = absorb_nabla2.*medium.alpha_filter;\n\n % shift the parameters back\n absorb_nabla1 = ifftshift(absorb_nabla1);\n absorb_nabla2 = ifftshift(absorb_nabla2); \n \n end \n\n % modify the sign of the absorption operators if alpha_sign is defined\n % (this is used for time-reversal photoacoustic image reconstruction\n % with absorption compensation)\n if isfield(medium, 'alpha_sign')\n if numel(medium.alpha_sign) == 2\n % if two parameters are given, apply the first to the absorption\n % parameter and the second to the disperion parameters\n absorb_tau = sign(medium.alpha_sign(1))*absorb_tau;\n absorb_eta = sign(medium.alpha_sign(2))*absorb_eta;\n else\n error('medium.alpha_sign must be given as a 2 element array controlling absorption and dispersion, respectively.');\n end\n end\nend", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/K-wave/k-Wave/private/kspaceFirstOrder_createAbsorptionVariables.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152498, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4828262790916939}} {"text": "function [s, d, S_rf, S_sf, S_k, S_l] = projHmgLinIntoPinHoleOnRob(Rf, Sf, Sk, l)\n\n% PROJHMGLININTOPINHOLEONROB Project Hmg line into pinhole on robot.\n% [s, d] = PROJHMGLININTOPINHOLEONROB(Rf, Sf, Sk, l) projects the\n% inverse-depth line l into a pin/hole camera with intrinsic parameters\n% Sk mounted on a robot. The robot frame is Rf and the sensor frame in\n% the robot is Sf.\n%\n% The results are a 2D segment S and a depths vector D.\n%\n% [s, d, S_rf, S_sf, S_k, S_l] = (...) returns the Jacobians wrt all\n% input parameters.\n\n% Copyright 2009 Teresa Vidal.\n\n\nif nargout <= 2\n \n sw = hmgLin2seg(l);\n s = projSegLinIntoPinHoleOnRob(Rf, Sf, Sk, sw);\n d = 1./l([6 9]);\n\nelse\n \n [sw, SW_l] = hmgLin2seg(l);\n [s, d, S_rf, S_sf, S_k, S_sw] = projSegLinIntoPinHoleOnRob(Rf, Sf, Sk, sw);\n S_l = S_sw*SW_l;\n \nend\n\n\n\n% ========== End of function - Start GPL license ==========\n\n\n% # START GPL LICENSE\n\n%---------------------------------------------------------------------\n%\n% This file is part of SLAMTB, a SLAM toolbox for Matlab.\n%\n% SLAMTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% SLAMTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with SLAMTB. If not, see .\n%\n%---------------------------------------------------------------------\n\n% SLAMTB is Copyright:\n% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,\n% Copyright (c) 2010-2013, Joan Sola,\n% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,\n% SLAMTB is Copyright 2009 \n% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol\n% @ LAAS-CNRS.\n% See on top of this file for its particular copyright.\n\n% # END GPL LICENSE\n\n", "meta": {"author": "joansola", "repo": "slamtb", "sha": "b4767f6bf38bceed205abb85f1aed12422c9a972", "save_path": "github-repos/MATLAB/joansola-slamtb", "path": "github-repos/MATLAB/joansola-slamtb/slamtb-b4767f6bf38bceed205abb85f1aed12422c9a972/Observations/projHmgLinIntoPinHoleOnRob.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.48275976621470135}} {"text": "function [hIm, ww] = L1SR(lIm, zooming, patch_size, overlap, Dh, Dl, lambda, regres)\n% Use sparse representation as the prior for image super-resolution\n% Usage\n% [hIm] = L1SR(lIm, zooming, patch_size, overlap, Dh, Dl, lambda)\n% \n% Inputs\n% -lIm: low resolution input image, single channel, e.g.\n% illuminance\n% -zooming: zooming factor, e.g. 3\n% -patch_size: patch size for the low resolution image\n% -overlap: overlap among patches, e.g. 1\n% -Dh: dictionary for the high resolution patches\n% -Dl: dictionary for the low resolution patches\n% -regres: 'L1' use the sparse representation directly to high\n% resolution dictionary;\n% 'L2' use the supports found by sparse representation\n% and apply least square regression coefficients to high\n% resolution dictionary.\n% Ouputs\n% -hIm: the recovered image, single channel\n%\n% Written by Jianchao Yang @ IFP UIUC\n% April, 2009\n% Webpage: http://www.ifp.illinois.edu/~jyang29/\n% For any questions, please email me by jyang29@uiuc.edu\n%\n% Reference\n% Jianchao Yang, John Wright, Thomas Huang and Yi Ma. Image superresolution\n% as sparse representation of raw image patches. IEEE Computer Society\n% Conference on Computer Vision and Pattern Recognition (CVPR), 2008. \n%\n\n[lhg, lwd] = size(lIm);\nhhg = lhg*zooming;\nhwd = lwd*zooming;\n\nmIm = imresize(lIm, 2,'bicubic');\n[mhg, mwd] = size(mIm);\nhpatch_size = patch_size*zooming;\nmpatch_size = patch_size*2;\n\n% extract gradient feature from lIm\nhf1 = [-1,0,1];\nvf1 = [-1,0,1]';\nhf2 = [1,0,-2,0,1];\nvf2 = [1,0,-2,0,1]';\n\nlImG11 = conv2(mIm,hf1,'same');\nlImG12 = conv2(mIm,vf1,'same');\nlImG21 = conv2(mIm,hf2,'same');\nlImG22 = conv2(mIm,vf2,'same');\n\nlImfea(:,:,1) = lImG11;\nlImfea(:,:,2) = lImG12;\nlImfea(:,:,3) = lImG21;\nlImfea(:,:,4) = lImG22;\n\nlgridx = 2:patch_size-overlap:lwd-patch_size;\nlgridx = [lgridx, lwd-patch_size];\nlgridy = 2:patch_size-overlap:lhg-patch_size;\nlgridy = [lgridy, lhg-patch_size];\n\nmgridx = (lgridx - 1)*2 + 1;\nmgridy = (lgridy - 1)*2 + 1;\n\n% using linear programming to find sparse solution\nbhIm = imresize(lIm, zooming, 'bicubic');\nhIm = zeros([hhg, hwd]);\nnrml_mat = zeros([hhg, hwd]);\n\nhgridx = (lgridx-1)*zooming + 1;\nhgridy = (lgridy-1)*zooming + 1;\n\ndisp('Processing the patches sequentially...');\ncount = 0;\n\n%ProjM = inv(Dl'*Dl+0.001*eye(size(Dl,2)))*Dl';\n\n% loop to recover each patch\nfor xx = 1:length(mgridx),\n for yy = 1:length(mgridy),\n \n mcolx = mgridx(xx);\n mrowy = mgridy(yy);\n \n count = count + 1;\n% if ~mod(count, 10000),\n% fprintf('.\\n');\n% else\n% fprintf('.');\n% end;\n if ~mod(count, 1000),\n fprintf('%g/%g\\n',count,length(mgridx)*length(mgridy));\n end\n mpatch = mIm(mrowy:mrowy+mpatch_size-1, mcolx:mcolx+mpatch_size-1);\n mmean = mean(mpatch(:));\n \n mpatchfea = lImfea(mrowy:mrowy+mpatch_size-1, mcolx:mcolx+mpatch_size-1, :);\n mpatchfea = mpatchfea(:);\n \n mnorm = sqrt(sum(mpatchfea.^2));\n \n if mnorm > 1,\n y = mpatchfea./mnorm;\n else\n y = mpatchfea;\n end;\n %w = ProjM*y;\n w = SolveLasso(Dl, y, size(Dl, 2), 'nnlasso', [], lambda);\n %w = feature_sign(Dl, y, lambda*2);\n \n if isempty(w),\n w = zeros(size(Dl, 2), 1);\n end;\n switch regres,\n case 'L1'\n if mnorm > 1,\n hpatch = Dh*w*mnorm;\n else\n hpatch = Dh*w;\n end;\n case 'L2'\n idx = find(w);\n lsups = Dl(:, idx);\n hsups = Dh(:, idx);\n w = inv(lsups'*lsups)*lsups'*mpatchfea;\n hpatch = hsups*w;\n otherwise\n error('Unknown fitting!');\n end;\n \n hpatch = reshape(hpatch, [hpatch_size, hpatch_size]);\n hpatch = hpatch + mmean;\n \n hcolx = hgridx(xx);\n hrowy = hgridy(yy);\n \n hIm(hrowy:hrowy+hpatch_size-1, hcolx:hcolx+hpatch_size-1)...\n = hIm(hrowy:hrowy+hpatch_size-1, hcolx:hcolx+hpatch_size-1) + hpatch;\n nrml_mat(hrowy:hrowy+hpatch_size-1, hcolx:hcolx+hpatch_size-1)...\n = nrml_mat(hrowy:hrowy+hpatch_size-1, hcolx:hcolx+hpatch_size-1) + 1;\n end;\nend;\n\nfprintf('done!\\n');\n\n% fill the empty\nhIm(1:3, :) = bhIm(1:3, :);\nhIm(:, 1:3) = bhIm(:, 1:3);\n\nhIm(end-2:end, :) = bhIm(end-2:end, :);\nhIm(:, end-2:end) = bhIm(:, end-2:end);\n\nnrml_mat(nrml_mat < 1) = 1;\nhIm = hIm./nrml_mat;\n% hIm = uint8(hIm);\n\n", "meta": {"author": "thomas-koehler", "repo": "SupER", "sha": "d8c6f2e4b26db002ff55bc2beba18639f1d0bb49", "save_path": "github-repos/MATLAB/thomas-koehler-SupER", "path": "github-repos/MATLAB/thomas-koehler-SupER/SupER-d8c6f2e4b26db002ff55bc2beba18639f1d0bb49/matlab/algorithms/SRAlgorithms/Aplus/CVPR08-SR/L1SR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4826443451363598}} {"text": "function c = tapas_ehgf_ar1_binary_config\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Contains the configuration for the enhanced Hierarchical Gaussian Filter (eHGF)\n% for binary inputs in the absence of perceptual uncertainty.\n%\n% The HGF is the model introduced in \n%\n% Mathys C, Daunizeau J, Friston, KJ, and Stephan KE. (2011). A Bayesian foundation\n% for individual learning under uncertainty. Frontiers in Human Neuroscience, 5:39.\n%\n% The binary HGF model has since been augmented with a positive factor kappa1 which\n% scales the second level with respect to the first, i.e., the relation between the\n% first and second level is\n%\n% p(x1=1|x2) = s(kappa1*x2), where s(.) is the logistic sigmoid.\n%\n% By default, kappa1 is fixed to 1, leading exactly to the model introduced in\n% Mathys et al. (2011).\n%\n% This file refers to BINARY inputs (Eqs 1-3 in Mathys et al., (2011));\n% for continuous inputs, refer to tapas_ehgf_config.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% The HGF configuration consists of the priors of parameters and initial values. All priors are\n% Gaussian in the space where the quantity they refer to is estimated. They are specified by their\n% sufficient statistics: mean and variance (NOT standard deviation).\n% \n% Quantities are estimated in their native space if they are unbounded (e.g., the omegas). They are\n% estimated in log-space if they have a natural lower bound at zero (e.g., the sigmas).\n% \n% Parameters can be fixed (i.e., set to a fixed value) by setting the variance of their prior to\n% zero. Aside from being useful for model comparison, the need for this arises whenever the scale\n% and origin at the j-th level are arbitrary. This is the case if the observation model does not\n% contain the representations mu_j and sigma_j. A choice of scale and origin is then implied by\n% fixing the initial value mu_j_0 of mu_j and either kappa_j-1 or omega_j-1.\n%\n% Fitted trajectories can be plotted by using the command\n%\n% >> tapas_ehgf_binary_plotTraj(est)\n% \n% where est is the stucture returned by tapas_fitModel. This structure contains the estimated\n% perceptual parameters in est.p_prc and the estimated trajectories of the agent's\n% representations (cf. Mathys et al., 2011). Their meanings are:\n% \n% est.p_prc.mu_0 row vector of initial values of mu (in ascending order of levels)\n% est.p_prc.sa_0 row vector of initial values of sigma (in ascending order of levels)\n% est.p_prc.rho row vector of rhos (representing drift; in ascending order of levels)\n% est.p_prc.ka row vector of kappas (in ascending order of levels)\n% est.p_prc.om row vector of omegas (in ascending order of levels)\n%\n% Note that the first entry in all of the row vectors will be NaN because, at the first level,\n% these parameters are either determined by the second level (mu_0 and sa_0) or undefined (rho,\n% kappa, and omega).\n%\n% est.traj.mu mu (rows: trials, columns: levels)\n% est.traj.sa sigma (rows: trials, columns: levels)\n% est.traj.muhat prediction of mu (rows: trials, columns: levels)\n% est.traj.sahat precisions of predictions (rows: trials, columns: levels)\n% est.traj.v inferred variance of random walk (rows: trials, columns: levels)\n% est.traj.w weighting factors (rows: trials, columns: levels)\n% est.traj.da volatility prediction errors (rows: trials, columns: levels)\n% est.traj.ud updates with respect to prediction (rows: trials, columns: levels)\n% est.traj.psi precision weights on prediction errors (rows: trials, columns: levels)\n% est.traj.epsi precision-weighted prediction errors (rows: trials, columns: levels)\n% est.traj.wt full weights on prediction errors (at the first level,\n% this is the learning rate) (rows: trials, columns: levels)\n%\n% Note that in the absence of sensory uncertainty (which is the assumption here), the first\n% column of mu, corresponding to the first level, will be equal to the inputs. Likewise, the\n% first column of sa will be 0 always.\n%\n% Tips:\n% - When analyzing a new dataset, take your inputs u and use\n%\n% >> est = tapas_fitModel([], u, 'tapas_ehgf_binary_config', 'tapas_bayes_optimal_binary_config');\n%\n% to determine the Bayes optimal perceptual parameters (given your current priors as defined in\n% this file here, so choose them wide and loose to let the inputs influence the result). You can\n% then use the optimal parameters as your new prior means for the perceptual parameters.\n%\n% - If you get an error saying that the prior means are in a region where model assumptions are\n% violated, lower the prior means of the omegas, starting with the highest level and proceeding\n% downwards.\n%\n% - Alternatives are lowering the prior means of the kappas, if they are not fixed, or adjusting\n% the values of the kappas or omegas, if any of them are fixed.\n%\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2012-2020 Christoph Mathys, TNU, UZH & ETHZ\n%\n% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or .\n\n\n% Config structure\nc = struct;\n\n% Model name\nc.model = 'ehgf_ar1_binary';\n\n% Number of levels (minimum: 3)\nc.n_levels = 3;\n\n% Input intervals\n% If input intervals are irregular, the last column of the input\n% matrix u has to contain the interval between inputs k-1 and k\n% in the k-th row, and this flag has to be set to true\nc.irregular_intervals = false;\n\n% Sufficient statistics of Gaussian parameter priors\n\n% Initial mus and sigmas\n% Format: row vectors of length n_levels\n% For all but the first two levels, this is usually best\n% kept fixed to 1 (determines origin on x_i-scale). The \n% first level is NaN because it is determined by the second,\n% and the second implies neutrality between outcomes when it\n% is centered at 0.\nc.mu_0mu = [NaN, 0, 1];\nc.mu_0sa = [NaN, 0, 0];\n\nc.logsa_0mu = [NaN, log(0.1), log(1)];\nc.logsa_0sa = [NaN, 0, 0];\n\n% Phis\n% Format: row vector of length n_levels.\n% Undefined (therefore NaN) at the first level.\n% Fix this to zero (-Inf in logit space) to set to zero.\nc.logitphimu = [NaN, -Inf, tapas_logit(0.5,1)]; %tapas_logit(0.1,1)\nc.logitphisa = [NaN, 0, 2];\n\n% ms\n% Format: row vector of length n_levels.\n% This should be fixed for all levels where the omega of\n% the next lowest level is not fixed because that offers\n% an alternative parametrization of the same model.\nc.mmu = [NaN, c.mu_0mu(2), c.mu_0mu(3)];\nc.msa = [NaN, 0, 1];\n\n% Rhos\n% Format: row vector of length n_levels.\n% Undefined (therefore NaN) at the first level.\n% Fix this to zero to turn off drift.\nc.rhomu = [NaN, 0, 0];\nc.rhosa = [NaN, 0, 0];\n\n% Kappas\n% Format: row vector of length n_levels-1.\n% Fixing log(kappa1) to log(1) leads to the original HGF model.\n% Higher log(kappas) should be fixed (preferably to log(1)) if the\n% observation model does not use mu_i+1 (kappa then determines the\n% scaling of x_i+1).\nc.logkamu = [log(1), log(1)];\nc.logkasa = [ 0, 0];\n\n% Omegas\n% Format: row vector of length n_levels.\n% Undefined (therefore NaN) at the first level.\nc.ommu = [NaN, -3, 2];\nc.omsa = [NaN, 4, 4];\n\n% Gather prior settings in vectors\nc.priormus = [\n c.mu_0mu,...\n c.logsa_0mu,...\n c.logitphimu,...\n c.mmu,...\n c.rhomu,...\n c.logkamu,...\n c.ommu,...\n ];\n\nc.priorsas = [\n c.mu_0sa,...\n c.logsa_0sa,...\n c.logitphisa,...\n c.msa,...\n c.rhosa,...\n c.logkasa,...\n c.omsa,...\n ];\n\n% Check whether we have the right number of priors\nexpectedLength = 5*c.n_levels+2*(c.n_levels-1)+1;\nif length([c.priormus, c.priorsas]) ~= 2*expectedLength\n error('tapas:hgf:PriorDefNotMatchingLevels', 'Prior definition does not match number of levels.')\nend\n\n% Model function handle\nc.prc_fun = @tapas_ehgf_ar1_binary;\n\n% Handle to function that transforms perceptual parameters to their native space\n% from the space they are estimated in\nc.transp_prc_fun = @tapas_ehgf_ar1_binary_transp;\n\nend\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/HGF/tapas_ehgf_ar1_binary_config.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.629774621301746, "lm_q1q2_score": 0.48259228888039557}} {"text": "function niederreiter2_test04 ( )\n\n%*****************************************************************************80\n%\n%% NIEDERREITER2_TEST04 tests NIEDERREITER2.\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 dim_max = 4;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'NIEDERREITER2_TEST04\\n' );\n fprintf ( 1, ' NIEDERREITER2 computes the next element of\\n' );\n fprintf ( 1, ' a Niederreiter quasirandom sequence using base 2.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' In this test, we call NIEDERREITER2 repeatedly.\\n' );\n\n for dim_num = 2 : dim_max\n\n seed = 0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Using dimension DIM_NUM = %d\\n', dim_num );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Seed Seed Niederreiter2\\n' );\n fprintf ( 1, ' In Out\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 0 : 110\n seed_in = seed;\n [ r, seed ] = niederreiter2 ( dim_num, seed );\n seed_out = seed;\n if ( i <= 11 | 95 <= i )\n fprintf ( 1, '%3d %3d ', seed_in, seed_out );\n for j = 1 : dim_num\n fprintf ( 1, '%10f', r(j) );\n end\n fprintf ( 1, '\\n' );\n elseif ( i == 12 )\n fprintf ( 1, '......................\\n' );\n end\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/niederreiter2/niederreiter2_test04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.48258079324504805}} {"text": "function frac = i4vec_frac ( n, a, k )\n\n%*****************************************************************************80\n%\n%% I4VEC_FRAC searches for the K-th smallest entry in an I4VEC.\n%\n% Discussion:\n%\n% Hoare's algorithm is used.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 05 November 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of elements of A.\n%\n% Input, integer A(N), the array to search.\n%\n% Input, integer K, the fractile to be sought. If K = 1, the minimum\n% entry is sought. If K = N, the maximum is sought. Other values\n% of K search for the entry which is K-th in size. K must be at\n% least 1, and no greater than N.\n%\n% Output, integer FRAC, the value of the K-th fractile of A.\n%\n if ( n <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4VEC_FRAC - Fatal error!\\n' );\n fprintf ( 1, ' Illegal nonpositive value of N = %d\\n', n );\n error ( 'I4VEC_FRAC - Fatal error!' );\n end\n\n if ( k <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4VEC_FRAC - Fatal error!\\n' );\n fprintf ( 1, ' Illegal nonpositive value of K = %d\\n', k );\n error ( 'I4VEC_FRAC - Fatal error!' );\n end\n\n if ( n < k )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4VEC_FRAC - Fatal error!\\n' );\n fprintf ( 1, ' Illegal N < K, K = %d\\n', k );\n error ( 'I4VEC_FRAC - Fatal error!' );\n end\n\n left = 1;\n iryt = n;\n\n while ( 1 )\n\n if ( iryt <= left )\n frac = a(k);\n break;\n end\n\n x = a(k);\n i = left;\n j = iryt;\n\n while ( 1 )\n\n if ( j < i )\n if ( j < k )\n left = i;\n end\n if ( k < i )\n iryt = j;\n end\n break;\n end\n%\n% Find I so that X <= A(I)\n%\n while ( a(i) < x )\n i = i + 1;\n end\n%\n% Find J so that A(J) <= X\n%\n while ( x < a(j) )\n j = j - 1;\n end\n\n if ( i <= j )\n\n temp = a(i);\n a(i) = a(j);\n a(j) = temp;\n\n i = i + 1;\n j = j - 1;\n\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/i4lib/i4vec_frac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.4821466520283357}} {"text": "function r8sp_print_some ( m, n, nz_num, isym, row, col, a, ilo, jlo, ihi, ...\n jhi, title )\n\n%*****************************************************************************80\n%\n%% R8SP_PRINT_SOME prints some of a R8SP matrix.\n%\n% Discussion:\n%\n% This version of R8SP_PRINT_SOME has been specifically modified to allow,\n% and correctly handle, the case in which a single matrix location\n% A(I,J) is referenced more than once by the sparse matrix structure.\n% In such cases, the routine prints out the sum of all the values.\n%\n% The R8SP storage format stores the row, column and value of each nonzero\n% entry of a sparse matrix.\n%\n% It is possible that a pair of indices (I,J) may occur more than\n% once. Presumably, in this case, the intent is that the actual value\n% of A(I,J) is the sum of all such entries. This is not a good thing\n% to do, but I seem to have come across this in MATLAB.\n%\n% The R8SP format is used by CSPARSE (\"sparse triplet\"), DLAP/SLAP \n% (\"nonsymmetric SLAP triad\"), by MATLAB, and by SPARSEKIT (\"COO\" format).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 31 January 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns of the matrix.\n%\n% Input, integer NZ_NUM, the number of nonzero elements in the matrix.\n%\n% Input, integer ISYM, is 0 if the matrix is not symmetric, \n% and 1 if the matrix is symmetric. The symmetric case only makes sense\n% if the matrix is also square, that is, M = N. In this case, only\n% the nonzeroes on the diagonal and in the lower triangle are stored.\n%\n% Input, integer ROW(NZ_NUM), COL(NZ_NUM), the row and column indices\n% of the nonzero elements.\n%\n% Input, real A(NZ_NUM), the nonzero elements of the matrix.\n%\n% Input, integer ILO, JLO, IHI, JHI, the first row and\n% column, and the last row and column to be printed.\n%\n% Input, string TITLE, a title.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, '%s\\n', title );\n\n incx = 5;\n%\n% Print the columns of the matrix, in strips of 5.\n%\n for j2lo = jlo: incx: jhi\n\n j2hi = j2lo + incx - 1;\n j2hi = min ( j2hi, n );\n j2hi = min ( j2hi, jhi );\n\n inc = j2hi + 1 - j2lo;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Col: ' );\n\n for j = j2lo : j2hi\n fprintf ( 1, '%7d ', j );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Row\\n' );\n fprintf ( 1, ' ---\\n' );\n%\n% Determine the range of the rows in this strip.\n%\n i2lo = max ( ilo, 1 );\n i2hi = min ( ihi, m );\n\n for i = i2lo : i2hi\n%\n% Print out (up to) 5 entries in row I, that lie in the current strip.\n%\n nonzero = 0;\n\n aij(1:inc) = 0.0;\n\n for k = 1 : nz_num\n\n if ( i == row(k) && j2lo <= col(k) && col(k) <= j2hi )\n\n j2 = col(k) - j2lo + 1;\n\n if ( a(k) ~= 0.0 )\n nonzero = 1;\n aij(j2) = aij(j2) + a(k);\n end\n\n elseif ( isym == 1 && m == n && ...\n i == col(k) && j2lo <= row(k) && row(k) <= j2hi )\n\n j2 = row(k) - j2lo + 1;\n\n if ( a(k) ~= 0.0 )\n nonzero = 1;\n aij(j2) = aij(j2) + a(k);\n end\n\n end\n\n end\n\n if ( nonzero )\n fprintf ( 1, '%4d', i );\n for j = 1 : inc\n fprintf ( 1, ' %12g', aij(j) );\n end\n fprintf ( 1, '\\n' );\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/dlap_io/r8sp_print_some.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.48211616768198456}} {"text": "%**************************************************************************\n% SARSA Learning applied to Cart-Pole balancing problem.\n% The environment of the learning system is a black box, from which it has\n% several lines and a reinforcement line. Its task is to learn to give\n% responses which maximize the scalar signals on its reinforcement line.\n% The Q-value update is the following, if the system takes action a from \n% state s at time t, and arrives at state ss with feedback r at time t+1: \n% \n% Q(t+1, s, a) = Q(t, s, a) \n% + alpha (r + gamma *Q(t,ss, b) - Q(t, s, a)) \n\n\n% get_box: Given the current state, returns a number from 1 to 162\n% designating the region of the state space encompassing the current \n% state.\n% Returns a value of -1 if a failure state is encountered.\n\n% cart_pole2: The cart and pole dynamics; given the Force and\n% current state, estimates next state\n\n%Code written by: Savinay Nagendra\n%email id: nagsavi17@gmail.com \n%**************************************************************************\nclc;\nclear all;\nclose all;\n% Initialization\n\nNUM_BOXES = 163;\nALPHA = 0.5; % Learning rate parameter\nGAMMA = 0.999; % Discount factor for future reinf\nQ = zeros(NUM_BOXES,2); % State-Action Values\naction = [10 -10];\nMAX_FAILURES = 2000;\nMAX_STEPS = 150000;\nepsilon = 0;\nsteps = 0;\nfailures = 0;\nthetaPlot = 0;\nxPlot = 0;\n%Pendulum state initialization\ntheta = 0;\nthetaDot = 0;\nx = 0;\nxDot = 0;\nbox = getBox4(theta,thetaDot,x,xDot);\nif(rand>epsilon) % exploit\n [~,actionMax] = max(Q(box,:));\n currentAction = action(actionMax);\nelse % explore\n currentAction = datasample(action,1);\nend\nactionIndex1 = find(action == currentAction);\n\nwhile(steps<=MAX_STEPS && failures<+MAX_FAILURES)\n steps = steps + 1;\n [thetaNext,thetaDotNext,thetaacc,xNext,xDotNext] = cart_pole2(currentAction,theta,thetaDot,x,xDot);\n thetaPlot(end + 1) = thetaNext;\n xPlot(end + 1) = xNext;\n newBox = getBox4(thetaNext,thetaDotNext,xNext,xDotNext);\n theta = thetaNext;\n thetaDot = thetaDotNext;\n x = xNext;\n xDot = xDotNext;\n if(newBox == 163)\n r = -1;\n Q(newBox,:) = 0;\n figure(2);\n plot((1:length(thetaPlot)),thetaPlot,'-ob');\n figure(3);\n plot((1:length(xPlot)),xPlot,'-og');\n thetaPlot = 0;\n xPlot = 0;\n %Swing Up. Find the box.\n theta = 0;\n thetaDot = 0;\n x = 0;\n xDot = 0;\n \n newBox = getBox4(theta,thetaDot,x,xDot);\n failures = failures + 1;\n fprintf('Trial %d was %d steps. \\n',failures,steps);\n figure(1);\n plot(failures,steps,'-or');\n hold on;\n steps = 0;\n else\n r = 0;\n end\n if(rand > epsilon) %exploit\n [~,newActionMax] = max(Q(newBox,:));\n newAction = action(newActionMax);\n else %explore\n newAction = datasample(action,1);\n end\n actionIndex2 = find(action == newAction);\n Q(box,actionIndex1) = Q(box,actionIndex1) + ALPHA*(r + GAMMA*Q(newBox,actionIndex2) - Q(box,actionIndex1));\n box = newBox;\n currentAction = newAction;\n actionIndex1 = actionIndex2;\nend\n\nif(failures == MAX_FAILURES)\n fprintf('Pole not balanced. Stopping after %d failures.',failures);\nelse\n fprintf('Pole balanced successfully for at least %d steps\\n', steps);\n figure(1);\n plot(failures+1,steps,'-or');\n hold on;\n figure(2);\n plot((1:length(thetaPlot)),thetaPlot,'-ob');\n figure(3);\n plot((1:length(xPlot)),xPlot,'-og');\n figure(4);\n plot((1:301),thetaPlot(1:301),'-ob');\n hold on;\n figure(5);\n plot((1:301),xPlot(1:301),'-og');\n hold on;\nend", "meta": {"author": "savinay95n", "repo": "Reinforcement-learning-Algorithms-and-Dynamic-Programming", "sha": "ab531f4c5856e20800c64932a06d246c91c7f62c", "save_path": "github-repos/MATLAB/savinay95n-Reinforcement-learning-Algorithms-and-Dynamic-Programming", "path": "github-repos/MATLAB/savinay95n-Reinforcement-learning-Algorithms-and-Dynamic-Programming/Reinforcement-learning-Algorithms-and-Dynamic-Programming-ab531f4c5856e20800c64932a06d246c91c7f62c/SarsaLearningCartPole.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738010682209, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4820555658639178}} {"text": "function [cohsig,sptsig,c] = crbs7(y,rlx_int,eukenf,c_int,c_tr,xi)\n% Written by John Smith\n% October 21st, 2010\n% University of Colorado at Boulder, CIRES\n% John.A.Smith@Colorado.EDU\n% MATLAB version 7.10.0.59 (R2010a) 64-bit\n% Adapted from \"Coherent Rayleigh-Brillouin Scattering\"\n% by Xingguo Pan\n\n% Computes the coherent and spontaneous\n% RBS spectrum given the parameters\n% in crbs_molecular using the s7 model\n% by X. Pan, 2002\n\n% Called by: crbs_molecular.m\n\nn_xi=numel(xi);\n\nn=7;\na=zeros(n,n);\nb=zeros(n,2);\n\ncohsig=zeros(1,n_xi);\nsptsig=zeros(1,n_xi);\n\ncpxunit=sqrt(-1);\n\ny7=1.5*y;\ngamma_int=c_int/(c_tr+c_int);\nj020=-y;\nj030=1.5*j020;\nj100=-gamma_int*y/rlx_int;\nj001=j100*c_tr/c_int;\nj100001=j100*sqrt(c_tr/c_int);\nj110=j100*5/6+j020*2/3;\nj011110=j100*sqrt(5/(8*c_int));\nj_nu=0.4*(1.5+c_int)+(3+c_int)/(2*rlx_int)+9*eukenf/(16*rlx_int^2);\nj_de=-1+(4/15)*eukenf*(1.5+c_int)+(c_int/3)*eukenf/rlx_int;\nj_co=-y*(2*gamma_int/3);\nj011=j_co*j_nu/j_de;\n\nfor i=1:n_xi\n z=xi(i)+y7*cpxunit;\n\tw0=w0_func(z);\n\tw1=-sqrt(pi)+z*w0;\n\tw2=z*w1;\n\tw3=-0.5*sqrt(pi)+z*w2;\n\tw4=z*w3;\n\tw5=-3*sqrt(pi)/4+z*w4;\n\tw6=z*w5;\n \n i0000=w0/(sqrt(pi));\n\ti0100=w1*sqrt(2/pi);\n\ti0001=i0100;\n\ti0010=(2*w2-w0)/(sqrt(6*pi));\n\ti1000=i0010;\n\ti0011=(2*w3-3*w1)/(sqrt(5*pi));\n\ti1100=i0011;\n\ti0101=2*w2/sqrt(pi);\n\ti0110=(-w1+2*w3)/sqrt(3*pi);\n\ti1001=i0110;\n\ti0111=(-3*w2+2*w4)*sqrt(2/(5*pi));\n\ti1101=i0111;\n\ti1111=(13*w2-12*w4+4*w6)/(5*sqrt(pi));\n\ti0002=(-w0+2*w2)/sqrt(3*pi);\n\ti0200=i0002;\n\ti0211=(-w1+8*w3-4*w5)/sqrt(15*pi);\n\ti1102=i0211;\n\ti0202=2*(w0-2*w2+2*w4)/(3*sqrt(pi));\n\ti0210=(w0+4*w2-4*w4)/(3*sqrt(2*pi));\n\ti1002=i0210;\n\ti0102=(-w1+2*w3)*sqrt(2/(3*pi));\n\ti0201=i0102;\n\ti1010=(5*w0-4*w2+4*w4)/(6*sqrt(pi));\n\ti1110=(7*w1-8*w3+4*w5)/sqrt(30*pi);\n\ti1011=i1110;\n \n a(:,1)=-j030*[i0000 i0001 i0011 i0002 i0010 0 0]+[cpxunit 0 0 0 0 0 0];\n a(:,2)=-j030*[i0100 i0101 i0111 i0102 i0110 0 0]+[0 cpxunit 0 0 0 0 0];\n a(:,3)=(j030-j110)*[i1100 i1101 i1111 i1102 i1110 0 0]+j011110*[0 0 0 0 0 -i0100 -i0101]+[0 0 -cpxunit 0 0 0 0];\n a(:,4)=(j020-j030)*[i0200 i0201 i0211 i0202 i0210 0 0]+[0 0 0 3/2*cpxunit 0 0 0];\n a(:,5)=(j030-j100)*[i1000 i1001 i1011 i1002 i1010 0 0]+j100001*[0 0 0 0 0 -i0000 -i0001]+[0 0 0 0 -cpxunit 0 0];\n a(:,6)=j100001*[i1000 i1001 i1011 i1002 i1010 0 0]+(j001-j030)*[0 0 0 0 0 i0000 i0001]+[0 0 0 0 0 cpxunit 0];\n a(:,7)=j011110*[i1100 i1101 i1111 i1102 i1110 0 0]+(j011-j030)*[0 0 0 0 0 i0100 i0101]+[0 0 0 0 0 0 cpxunit];\n \n b(:,1)=-[i0100 i0101 i0111 i0102 i0110 0 0];\n b(:,2)=-[i0000 i0001 i0011 i0002 i0010 0 0];\n \n c=linsolve(a,b);\n \n cohsig(i)=c(1,1)*conj(c(1,1));\n sptsig(i)=2*real(c(1,2));\nend\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/29108-coherent+spontaneous-rayleigh-brillouin-scattering-spectra/s6s7_RBS/crbs7.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4820555630362387}} {"text": "function [dist,binned,stats] = CircularDistribution(angles,varargin)\n\n%CircularDistribution - Compute circular distribution and statistics.\n%\n% USAGE\n%\n% [dist,binned,stats] = CircularDistribution(angles,)\n%\n% angles angles in radians\n% optional list of property-value pairs (see table below)\n%\n% =========================================================================\n% Properties Values\n% -------------------------------------------------------------------------\n% 'nBins' number of bins (default = 100)\n% 'smooth' standard deviation of Gaussian kernel (default = 0)\n% 'groups' groups for multiple circular distributions (see below)\n% =========================================================================\n%\n% OUTPUT\n%\n% dist circular distribution (one column per group)\n% binned centers of the angular bins\n% stats.m mean angle (one per group)\n% stats.mode distribution mode (one per group)\n% stats.r mean resultant length (one per group)\n% stats.k concentration (one per group)\n% stats.p p-value for Rayleigh test (one per group)\n%\n% NOTE\n%\n% For multiple circular distributions, groups can be indicated in two different\n% manners:\n%\n% - a vector of group IDs (one per angle)\n% - a logical matrix (one line per angle, one column per group), where\n% the element (i,j) is 1 iff angle i belongs to group j\n%\n% The vector form is convenient when each angle can only belong to one group.\n% The matrix form is useful when a single angle can belong to multiple groups.\n%\n% SEE\n%\n% See also PlotCircularDistribution.\n\n% Copyright (C) 2011-2012 by MichaĆ«l Zugaro\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 3 of the License, or\n% (at your option) any later version.\n\n% Default values\nnBins = 100;\nsmooth = 0;\n\n% Check number of parameters\nif nargin < 1 | mod(length(varargin),2) ~= 0,\n error('Incorrect number of parameters (type ''help CircularDistribution'' for details).');\nend\n\n% Check parameter size\nif ~isdvector(angles),\n\terror('Incorrect angles (type ''help CircularDistribution'' for details).');\nend\nangles = angles(:);\ngroups = ones(size(angles));\n\n% Parse parameter list\nfor i = 1:2:length(varargin),\n if ~ischar(varargin{i}),\n error(['Parameter ' num2str(i+2) ' is not a property (type ''help CircularDistribution'' for details).']);\n end\n switch(lower(varargin{i})),\n case 'nbins',\n nBins = varargin{i+1};\n if ~isiscalar(nBins,'>0'),\n error('Incorrect value for property ''nBins'' (type ''help CircularDistribution'' for details).');\n end\n case 'smooth',\n smooth = varargin{i+1};\n if ~isdscalar(smooth,'>=0'),\n error('Incorrect value for property ''smooth'' (type ''help CircularDistribution'' for details).');\n end\n case 'groups',\n groups = varargin{i+1};\n if ~isdvector(groups,'>0') && ~islmatrix(groups),\n error('Incorrect value for property ''groups'' (type ''help CircularDistribution'' for details).');\n end\n if isdvector(groups), groups = groups(:); end\n if length(angles) ~= size(groups,1),\n error('Phases and groups have different numbers of lines (type ''help CircularDistribution'' for details).');\n end\n otherwise,\n error(['Unknown property ''' num2str(varargin{i}) ''' (type ''help CircularDistribution'' for details).']);\n end\nend\n\n% Angle bins\nbinned = linspace(0,2*pi,nBins+1)';binned(end) = [];\nbinSize = binned(2)-binned(1);\nbinned = binned + binSize/2;\n\n% Groups: transform vector form into matrix form\nif isdvector(groups),\n\tgroupIDs = unique(groups);\n\tnGroups = max(groupIDs);\n\tg = groups;\n\tgroups = logical(zeros(length(g),nGroups));\n\tfor i = 1:nGroups,\n\t\tgroups(g==i,i) = 1;\n\tend\nend\n\n% Loop through groups\nnGroups = size(groups,2);\nfor i = 1:nGroups,\n\t% Distribution\n\tp = angles(groups(:,i));\n\th = Smooth(hist(p,binned),smooth);h = h/sum(h);\n\tdist(:,i) = h;\n\t% Stats\n\tif ~isempty(p)\n [stats.m(i)] = circ_mean(p);\n [stats.r(i)] = circ_r(p);\n\t stats.k(i) = Concentration(p);\n\t n = sum(groups(:,i));\n\t R = stats.r(i)*n;\n\t stats.p(i) = exp(sqrt(1+4*n+4*(n^2-R^2))-(1+2*n)); % Zar, Biostatistical Analysis, p. 617\n\t x = find(h==max(h));x = x(1);\n\t stats.mode(i) = binned(x);\n\telse\n\t stats.m(i)=NaN;\n\t stats.r(i)=NaN;\n\t stats.k(i)=NaN;\n\t stats.p(i)=NaN;\n\t stats.mode(i)=NaN;\n\tend\nend\n\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/FMAToolbox/General/CircularDistribution.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.48204996326143823}} {"text": "function datapt = lvd_KinematicStateTasks(stateLogEntry, subTask, inFrame)\n%lvd_KinematicStateTasks Summary of this function goes here\n% Detailed explanation goes here\n \n cartElem = stateLogEntry.getCartesianElementSetRepresentation();\n cartElem = cartElem.convertToFrame(inFrame);\n \n datapt = -1;\n switch subTask\n % Cartesian Elements\n case 'rVectX'\n rVect = cartElem.rVect;\n datapt = rVect(1);\n case 'rVectY'\n rVect = cartElem.rVect;\n datapt = rVect(2);\n case 'rVectZ'\n rVect = cartElem.rVect;\n datapt = rVect(3);\n case 'vVectX'\n vVect = cartElem.vVect;\n datapt = vVect(1);\n case 'vVectY'\n vVect = cartElem.vVect;\n datapt = vVect(2);\n case 'vVectZ'\n vVect = cartElem.vVect;\n datapt = vVect(3);\n \n % Keplerian Elements\n case 'sma'\n kepElemSet = cartElem.convertToKeplerianElementSet();\n datapt = kepElemSet.sma;\n case 'ecc'\n kepElemSet = cartElem.convertToKeplerianElementSet();\n datapt = kepElemSet.ecc;\n case 'inc'\n kepElemSet = cartElem.convertToKeplerianElementSet();\n datapt = rad2deg(kepElemSet.inc);\n case 'raan'\n kepElemSet = cartElem.convertToKeplerianElementSet();\n datapt = rad2deg(kepElemSet.raan);\n case 'arg'\n kepElemSet = cartElem.convertToKeplerianElementSet();\n datapt = rad2deg(kepElemSet.arg);\n case 'tru'\n kepElemSet = cartElem.convertToKeplerianElementSet();\n datapt = rad2deg(kepElemSet.tru);\n case 'mean'\n kepElemSet = cartElem.convertToKeplerianElementSet();\n datapt = rad2deg(kepElemSet.getMeanAnomaly());\n \n % Geographic Elements\n case 'lat'\n geoElemSet = cartElem.convertToGeographicElementSet();\n datapt = rad2deg(geoElemSet.lat);\n case 'long'\n geoElemSet = cartElem.convertToGeographicElementSet();\n datapt = rad2deg(geoElemSet.long);\n case 'alt'\n geoElemSet = cartElem.convertToGeographicElementSet();\n datapt = geoElemSet.alt;\n case 'velAz'\n geoElemSet = cartElem.convertToGeographicElementSet();\n datapt = rad2deg(geoElemSet.velAz);\n case 'velEl'\n geoElemSet = cartElem.convertToGeographicElementSet();\n datapt = rad2deg(geoElemSet.velEl);\n case 'velMag'\n geoElemSet = cartElem.convertToGeographicElementSet();\n datapt = geoElemSet.velMag;\n \n % Universal Elements - don't need to do Kep repeated elements\n case 'c3'\n univElemSet = cartElem.convertToUniversalElementSet();\n datapt = univElemSet.c3;\n case 'tau'\n univElemSet = cartElem.convertToUniversalElementSet();\n datapt = univElemSet.tau;\n \n % Misc.\n case 'period'\n kepElemSet = cartElem.convertToKeplerianElementSet();\n datapt = kepElemSet.getPeriod();\n case 'rPe'\n kepElemSet = cartElem.convertToKeplerianElementSet();\n datapt = kepElemSet.getRadiusPeriapsis();\n case 'rApo'\n kepElemSet = cartElem.convertToKeplerianElementSet();\n datapt = kepElemSet.getRadiusApoapsis();\n case 'altPeri'\n kepElemSet = cartElem.convertToKeplerianElementSet();\n datapt = kepElemSet.getAltitudePeriapsis();\n case 'altApo'\n kepElemSet = cartElem.convertToKeplerianElementSet();\n datapt = kepElemSet.getAltitudeApoapsis();\n case 'H1'\n kepElemSet = cartElem.convertToKeplerianElementSet();\n [datapt, ~, ~, ~] = kepElemSet.getEquinoctialElements();\n case 'K1'\n kepElemSet = cartElem.convertToKeplerianElementSet();\n [~, datapt, ~, ~] = kepElemSet.getEquinoctialElements();\n case 'H2'\n kepElemSet = cartElem.convertToKeplerianElementSet();\n [~, ~, datapt, ~] = kepElemSet.getEquinoctialElements();\n case 'K2'\n kepElemSet = cartElem.convertToKeplerianElementSet();\n [~, ~, ~, datapt] = kepElemSet.getEquinoctialElements();\n case 'FPA'\n kepElemSet = cartElem.convertToKeplerianElementSet();\n datapt = rad2deg(kepElemSet.getFlightPathAngle());\n case 'hyperVelUnitVectX'\n kepElemSet = cartElem.convertToKeplerianElementSet();\n [datapt, ~, ~, ~, ~, ~] = kepElemSet.getOutboundHyperbolicVelocityElements();\n case 'hyperVelUnitVectY'\n kepElemSet = cartElem.convertToKeplerianElementSet();\n [~, datapt, ~, ~, ~, ~] = kepElemSet.getOutboundHyperbolicVelocityElements();\n case 'hyperVelUnitVectZ'\n kepElemSet = cartElem.convertToKeplerianElementSet();\n [~, ~, datapt, ~, ~, ~] = kepElemSet.getOutboundHyperbolicVelocityElements();\n case 'hyperVelUnitVectRA'\n kepElemSet = cartElem.convertToKeplerianElementSet();\n [~, ~, ~, datapt, ~, ~] = kepElemSet.getOutboundHyperbolicVelocityElements();\n case 'hyperVelUnitVectDec'\n kepElemSet = cartElem.convertToKeplerianElementSet();\n [~, ~, ~, ~, datapt, ~] = kepElemSet.getOutboundHyperbolicVelocityElements();\n case 'hyperVelMag'\n kepElemSet = cartElem.convertToKeplerianElementSet();\n [~, ~, ~, ~, ~, datapt] = kepElemSet.getOutboundHyperbolicVelocityElements();\n \n\n case 'radius'\n datapt = cartElem.getRadiusMagnitude();\n case 'velocity'\n datapt = cartElem.getVelocityMagnitude();\n case 'horzVel'\n [datapt, ~] = cartElem.getHorzVertVelocities();\n case 'vertVel'\n [~, datapt] = cartElem.getHorzVertVelocities();\n \n case 'longDriftRate'\n kepElemSet = cartElem.convertToKeplerianElementSet();\n datapt = kepElemSet.getLongDriftRate() * (3600*180/pi); %convert rad/sec to deg/hr\n \n case 'centralBodyId'\n datapt = stateLogEntry.centralBody.id;\n end\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_lvd/process_data/GraphicalAnalysis/tasks/lvd_KinematicStateTasks.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4819412822530937}} {"text": "% Copyright (C) 2004 Josep Mones i Teixidor \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 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\n% FITNESS 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% -*- texinfo -*-\n% @deftypefn {Function File} {@var{BW} = } octave_poly2mask (@var{x},@var{y},@var{m},@var{n})\n% Convert a polygon to a region mask.\n%\n% BW=octave_poly2mask(x,y,m,n) converts a polygon, specified by a list of\n% vertices in @var{x} and @var{y} and returns in a @var{m}-by-@var{n}\n% logical mask @var{BW} the filled polygon. Region inside the polygon\n% is set to 1, values outside the shape are set to 0.\n%\n% @var{x} and @var{y} should always represent a closed polygon, first\n% and last points should be coincident. If they are not octave_poly2mask will\n% close it for you. If @var{x} or @var{y} are fractional they are\n% nearest integer.\n%\n% If all the polygon or part of it falls outside the masking area\n% (1:m,1:n), it is discarded or clipped.\n%\n% This function uses scan-line polygon filling algorithm as described\n% in http://www.cs.rit.edu/~icss571/filling/ with some minor\n% modifications: capability of clipping and scan order, which can\n% affect the results of the algorithm (algorithm is described not to\n% reach ymax, xmax border when filling to avoid enlarging shapes). In\n% this function we scan the image backwards (we begin at ymax and end\n% at ymin), and we don't reach ymin, xmin, which we believe should be\n% compatible with MATLAB.\n% @end deftypefn\n\n% TODO: check how to create a logical BW without any conversion\n\nfunction BW = octave_poly2mask (x, y, m, n)\n if (nargin ~= 4)\n print_usage ();\n end\n\n % check x and y\n x = round (x (:).');\n y = round (y (:).');\n if (length (x) < 3)\n error ('octave_poly2mask: polygon must have at least 3 vertices.');\n end\n if (length (x) ~= length (y))\n error ('octave_poly2mask: length of x doesn''t match length of y.');\n end\n\n % create output matrix\n BW = false (m, n);\n\n % close polygon if needed\n if ((x (1) ~= x (length (x))) || (y (1) ~= y (length (y))))\n x = horzcat (x, x (1));\n y = horzcat (y, y (1));\n end\n\n % build global edge table\n ex = [x(1:length (x) - 1); x(1, 2:length (x))]; % x values for each edge\n ey = [y(1:length (y) - 1); y(1, 2:length (y))]; % y values for each edge\n idx = (ey(1, :) ~= ey(2, :)); % eliminate horizontal edges\n ex = ex (:, idx);\n ey = ey (:, idx);\n eminy = min (ey); % minimum y for each edge\n emaxy = max (ey); % maximum y for each edge\n t = (ey == [eminy; eminy]); % values associated to miny\n exvec = ex(:);\n exminy = exvec(t); % x values associated to min y\n exmaxy = exvec(~t); % x values associated to max y\n emaxy = emaxy.'; % we want them vertical now...\n eminy = eminy.';\n m_inv = (exmaxy - exminy)./(emaxy - eminy); % calculate inverse slope\n ge = [emaxy, eminy, exmaxy, m_inv]; % build global edge table\n ge = sortrows (ge, [1, 3]); % sort on eminy and exminy\n\n % we add an extra dummy edge at the end just to avoid checking\n % while indexing it\n ge = [-Inf, -Inf, -Inf, -Inf; ge];\n\n % initial parity is even (0)\n parity = 0;\n\n % init scan line set to bottom line\n sl = ge (size (ge, 1), 1);\n\n % init active edge table\n % we use a loop because the table is sorted and edge list could be\n % huge\n ae = [];\n gei = size (ge, 1);\n while (sl == ge (gei, 1))\n ae = [ge(gei, 2:4); ae];\n gei = gei - 1;\n end\n\n % calc minimum y to draw\n miny = min (y);\n if (miny < 1)\n miny = 1;\n end\n\n while (sl >= miny)\n % check vert clipping\n if (sl <= m)\n % draw current scan line\n % we have to round because 1/m is fractional\n ie = round (reshape (ae (:, 2), 2, size (ae, 1)/2));\n\n % this discards left border of image (this differs from version at\n % http://www.cs.rit.edu/~icss571/filling/ which discards right\n % border) but keeps an exception when the point is a vertex.\n ie (1, :) = ie (1, :) + (ie (1, :) ~= ie (2, :));\n\n % we'll clip too, just in case m,n is not big enough\n ie (1, (ie (1, :) < 1)) = 1;\n ie (2, (ie (2, :) > n)) = n;\n\n % we eliminate segments outside window\n ie = ie (:, (ie (1, :) <= n));\n ie = ie (:, (ie (2, :) >= 1));\n for i = 1:size(ie,2)\n BW (sl, ie (1, i):ie (2, i)) = true;\n end\n end\n\n % decrement scan line\n sl = sl - 1;\n\n % eliminate edges that eymax==sl\n % this discards ymin border of image (this differs from version at\n % http://www.cs.rit.edu/~icss571/filling/ which discards ymax).\n ae = ae ((ae (:, 1) ~= sl), :);\n\n % update x (x1=x0-1/m)\n ae(:, 2) = ae(:, 2) - ae(:, 3);\n\n % update ae with new values\n while (sl == ge (gei, 1))\n ae = vertcat (ae, ge (gei, 2:4));\n gei = gei - 1;\n end\n\n % order the edges in ae by x value\n if (size(ae,1) > 0)\n ae = sortrows (ae, 2);\n end\n end\nend\n\n% This should create a filled octagon\n%!demo\n%! s = [0:pi/4:2*pi];\n%! x = cos (s) * 90 + 101;\n%! y = sin (s) * 90 + 101;\n%! bw = octave_poly2mask(x, y, 200, 200);\n%! imshow (bw);\n\n% This should create a 5-vertex star\n%!demo\n%! s = [0:2*pi/5:pi*4];\n%! s = s ([1, 3, 5, 2, 4, 6]);\n%! x = cos (s) * 90 + 101;\n%! y = sin (s) * 90 + 101;\n%! bw = octave_poly2mask (x, y, 200, 200);\n%! imshow (bw);\n\n%!# Convex polygons\n\n%!shared xs, ys, Rs, xt, yt, Rt\n%! xs=[3,3,10,10];\n%! ys=[4,12,12,4];\n%! Rs=zeros(16,14);\n%! Rs(5:12,4:10)=1;\n%! Rs=logical(Rs);\n%! xt=[1,4,7];\n%! yt=[1,4,1];\n%! Rt=[0,0,0,0,0,0,0;\n%! 0,0,1,1,1,1,0;\n%! 0,0,0,1,1,0,0;\n%! 0,0,0,1,0,0,0;\n%! 0,0,0,0,0,0,0];\n%! Rt=logical(Rt);\n\n%!assert(octave_poly2mask(xs,ys,16,14),Rs); # rectangle\n%!assert(octave_poly2mask(xs,ys,8,7),Rs(1:8,1:7)); # clipped\n%!assert(octave_poly2mask(xs-7,ys-8,8,7),Rs(9:16,8:14)); # more clipping\n\n%!assert(octave_poly2mask(xt,yt,5,7),Rt); # triangle\n%!assert(octave_poly2mask(xt,yt,3,3),Rt(1:3,1:3)); # clipped\n\n\n%!# Concave polygons\n\n%!test\n%! x=[3,3,5,5,8,8,10,10];\n%! y=[4,12,12,8,8,11,11,4];\n%! R=zeros(16,14);\n%! R(5:12,4:5)=1;\n%! R(5:8,6:8)=1;\n%! R(5:11,9:10)=1;\n%! R=logical(R);\n%! assert(octave_poly2mask(x,y,16,14), R);\n\n%!# Complex polygons\n%!test\n%! x=[1,5,1,5];\n%! y=[1,1,4,4];\n%! R=[0,0,0,0,0,0;\n%! 0,0,1,1,0,0;\n%! 0,0,1,1,0,0;\n%! 0,1,1,1,1,0;\n%! 0,0,0,0,0,0];\n%! R=logical(R);\n%! assert(octave_poly2mask(x,y,5,6), R);\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/mulaclab/octave_poly2mask.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.685949467848392, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.4819001190177414}} {"text": "% SP_INTEGRAL_PRESERVING_TRANSFORM: apply the integral-preserving transform to the functions in the parametric domain\n%\n% sp = sp_integral_preserving_transform (space, msh)\n%\n% INPUTS:\n% \n% space: structure with the information in the parametric domain (see sp_scalar/sp_evaluate_col)\n% msh: msh structure containing the information of the parametrization\n% in the points where basis functions have to be computed (see msh_cartesian/msh_evaluate_col)\n% \n% Name | Default value | Meaning\n% ------------+-----------------+----------------------------------\n% value | true | compute shape_functions\n%\n% OUTPUT:\n%\n% sp: struct representing the discrete function space, with the following fields:\n% (see the article for a detailed description)\n%\n% FIELD_NAME (SIZE) DESCRIPTION\n% ncomp (scalar) number of components of the functions of the space (actually, 1)\n% ndof (scalar) total number of degrees of freedom\n% ndof_dir (ncomp x ndim matrix) for each component, number of degrees of freedom along each direction\n% nsh_max (scalar) maximum number of shape functions per element\n% nsh (1 x msh_col.nel vector) actual number of shape functions per each element\n% connectivity (nsh_max x msh_col.nel vector) indices of basis functions that do not vanish in each element\n% shape_functions (msh_col.nqn x nsh_max x msh_col.nel) basis functions evaluated at each quadrature node in each element\n%\n% Copyright (C) 2015 Rafael Vazquez\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\nfunction sp = sp_integral_preserving_transform (sp, msh, value)\n\n if (nargin < 3 && isfield (sp, 'shape_functions'))\n value = true;\n end\n\n if (value)\n jacdet = reshape (geopdes_det__ (msh.geo_map_jac), msh.nqn, 1, msh.nel);\n sp.shape_functions = bsxfun (@rdivide, sp.shape_functions, jacdet);\n sp.shape_functions = sp.shape_functions;\n if (isfield (msh, 'side_number'))\n sp.shape_functions = sp.shape_functions * (-1)^msh.side_number;\n end\n end\n \n if (isfield (sp, 'shape_function_gradients'))\n sp = rmfield (sp, 'shape_function_gradients');\n end\n if (isfield (sp, 'shape_function_hessians'))\n sp = rmfield (sp, 'shape_function_hessians');\n end\n\nend", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/space/sp_integral_preserving_transform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.48175031758563763}} {"text": "function varargout=bss_decomp_tvfilt(varargin)\n\n% decompose an estimated source into target/interference/noise/artefacts components, assuming the admissible distortion is a time-varying filter.\n%\n% Usage:\n%\n% [s_target,e_interf[,e_noise],e_artif]=bss_decomp_tvfilt(se,index,S[,N],tvshape,tvstep,L)\n%\n% Input:\n% - se: row vector of length T containing the estimated source,\n% - index: points which component of S se has to be compared to,\n% - S: n x T matrix containing the original sources,\n% - N: m x T matrix containing the noise on the obseravtions (if any).\n% - tvshape : row vector of length V at most T containing the shape of the elementary \n% allowed time variations of the filter coefficients\n% - tvstep : hop size (in number of samples) between two consecutive\n% variations of the filter coefficients\n% - L: the number of lags\n%\n% Output:\n% - s_target: row vector of length T containing the target source(s)\n% contribution,\n% - e_interf: row vector of length T containing the interferences\n% contribution,\n% - e_noise: row vector of length T containing the noise contribution (if\n% any),\n% - e_artif: row vector of length T containing the artifacts\n% contribution.\n%\n% Developers: - Cedric Fevotte (cf269@cam.ac.uk) - Emmanuel Vincent\n% (vincent@ircam.fr) - Remi Gribonval (remi.gribonval@irisa.fr)\n\nse=varargin{1}; index=varargin{2}; S=varargin{3};\n \nswitch nargin\n case 5\n N=[]; tvshape = varargin{4}; tvstep = varargin{5}; L = varargin{6};\n case 6\n N=varargin{4}; tvshape = varargin{5}; tvstep = varargin{6}; L = varargin{7};\n otherwise\n disp('Wrong number of arguments.')\nend\n\n[ne,Te]=size(se);\n[n,T]=size(S);\n\n%%%%%%%%%% WARNINGS %%%%%%%%%%%%%\nswitch isempty(N)\n case 1\n if n>T | ne>Te, disp('Watch out: signals must be in rows.'), return; end \n if ne~=1, disp('Watch out: se must contain only one row.'), return; end\n if T~=Te, disp('Watch out: se and S have different lengths.'), return; end \n case 0\n [m,Tm]=size(N); \n if n>T | ne>Te | m>Tm, disp('Watch out: signals must be in rows.'), return; end \n if ne~=1, disp('Watch out: se must contain only one row.'), return; end\n if T~=Te, disp('Watch out: S and Se have different lengths.'), return; end \n if T~=Tm, disp('Watch out: N, S and Se have different lengths.'), return; end \nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Create the space of target source(s)\ntarget_space = bss_make_lags(S(index,:),L); \n% Create the space of sources\nsources_space= bss_make_lags(S,L);\n% Create the noise space\nnoise_space = bss_make_lags(N,L);\n\ns_target=zeros(1,T);\ne_interf=zeros(1,T);\ne_artif=zeros(1,T);\nif isempty(noise_space)==0, e_noise=zeros(1,T); end\n\n%%% Target source(s) contribution %%%\ns_target = bss_tvproj(se,target_space,tvshape,tvstep);\n\n%%% Interferences contribution %%%\nP_S_se = bss_tvproj(se,[sources_space],tvshape,tvstep);\ne_interf = P_S_se - s_target;\n\nswitch isempty(noise_space)\n case 1 % No noise\n %%% Artifacts contribution %%% \n e_artif= se - P_S_se;\n \n %%% Output %%%\n varargout{1}=s_target;\n varargout{2}=e_interf;\n varargout{3}=e_artif;\n \n case 0 % Noise\n %%% Noise contribution %%%\n P_SN_se= bss_tvproj(se,[sources_space;noise_space],tvshape,tvstep);\n e_noise=P_SN_se-P_S_se;\n \n %%% Artifacts contribution %%% \n e_artif=se-P_SN_se;\n \n %%% Output %%%\n varargout{1}=s_target;\n varargout{2}=e_interf;\n varargout{3}=e_noise;\n varargout{4}=e_artif; \nend ", "meta": {"author": "posenhuang", "repo": "deeplearningsourceseparation", "sha": "6a6e54d9234756e9624507f66d9e8fcd0b868dc7", "save_path": "github-repos/MATLAB/posenhuang-deeplearningsourceseparation", "path": "github-repos/MATLAB/posenhuang-deeplearningsourceseparation/deeplearningsourceseparation-6a6e54d9234756e9624507f66d9e8fcd0b868dc7/tools/bss_eval/bss_decomp_tvfilt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4817387903573459}} {"text": "function [z,uTx,uTarRx,uTarTx]=Cart2RuvStdRefrac(zC,useHalfRange,zTx,zRx,M,Ns,includeW,ce,rE,spherCent)\n%%CART2RUVSTDREFRAC Convert points in Cartesian coordinates (either the\n% global system or a local system at the receiver) into local\n% bistatic r-u-v coordinates of the receiver, accounting for how a\n% standard exponential atmospheric model warps the measurements.\n% r-u-v coordinates consist of a bistatic range and direction\n% cosines at the receiver. The \"direction cosines\" u and v are just\n% the x and y coordinates of a unit vector from the receiver to\n% the target in the coordinate system at the receiver (Here, to the\n% refraction-corrupted apparent direction). This basically assumes\n% that the boresight direction of the receiver is the z axis.\n% Assuming the target is in front of the receiver, the third unit\n% vector coordinate is not needed. However, with the includeW\n% option, it can be provided, resulting in r-u-v-w coordinates. This\n% function is not suitable for computing refraction between\n% satellites, grazing the Earth's atmosphere. The algorithm might\n% have an error if the ray path goes too far underground.\n%\n%INPUT: zC A 3XN matrix of Cartesian points (target locations) in global\n% [x;y;z] Cartesian coordinates.\n% useHalfRange A boolean value specifying whether the bistatic range value\n% should be divided by two. This normally comes up when operating\n% in monostatic mode, so that the range reported is a one-way\n% range. The default if this parameter is not provided (or an\n% empty matrix is provided) is false.\n% zTx The 3X1 [x;y;z] location vector of the transmitter in global\n% Cartesian coordinates. If this parameter is omitted or an\n% empty matrix is passed, then the receiver is placed at the origin.\n% zRx The 3X1 [x;y;z] location vector of the receiver in global\n% Cartesian coordinates. If this parameter is omitted or an empty\n% matrix is passed, then the receiver is placed at the origin.\n% M A 3X3 rotation matrix to go from the alignment of the global\n% coordinate system to the local alignment of the receiver. The z\n% vector of the local coordinate system of the receiver is the\n% pointing direction of the receiver. If this matrix is omitted,\n% then the identity matrix is used.\n% Ns The atmospheric refractivity reduced to the reference sphere.\n% Note that the refractivity is (n-1)*1e6, where n is the index\n% of refraction. The function reduceStdRefrac2Spher can be used\n% to reduce a refractivity to the surface of a reference\n% ellipsoid. This function does not allow different\n% refractivities to be used as the transmitter and receiver. If\n% this parameter is omitted or an empty matrix is passed, a\n% default value of 313 is used.\n% includeW An optional boolean value indicating whether a third direction\n% cosine component should be included. The u and v direction\n% cosines are two parts of a 3D unit vector. Generally, one might\n% assume that the target is in front of the sensor, so the third\n% component would be positive and is not needed. However, the\n% third component can be included if ambiguity exists. The\n% default if this parameter is omitted or an empty matrix is\n% passed is false.\n% ce The optional decay constant of the exponential model. The\n% refractivity N at height h is N=Ns*exp(-ce*(h-h0)) where h0 is\n% the reference height (in this function, the height of the\n% reference ellipsoid surface is used). ce is related to the\n% change in refractivity at an elevation of 1km based on the\n% refractivity at sea level as\n% ce=log(Ns/(Ns+DeltaN))/1000;%Units of inverse meters.\n% where the change in refractivity for a change in elevation of\n% 1km is DeltaN=-multConst*exp(expConst*Ns); In [1], standard\n% values for the two constants are expConst=0.005577; and\n% multConst=7.32; If ce is omitted or an empty matrix is passed,\n% the value based on the standard model is used.\n% rE,spherCent The radius of the Earth to use for the spherical Earth\n% approximation used in the model and also the offset between the\n% global model and the local spherical model. It is assumed that\n% zC,zTx,and zRx are all given in the global model and will need\n% to be transformed to the local model to the used. If rE is\n% omitted or an empty matrix is passed, then the default of\n% [rE,spherCent]=osculatingSpher4LatLon(Cart2Ellipse(zRx)) is\n% used. The defaults here mean that a WGS-84 reference ellipsoid\n% is approximated by the local osculating sphere.\n%\n%OUTPUTS: z The 3XN (or 4XN if includeW is true) matrix of location vectors\n% of the points in bistatic [r;u;v] coordinates. If\n% useHalfRange=true, then the r component is half the bistatic\n% range (half the round-trip range for a monostatic scenario).\n% uTx A 3XN set of unit vectors pointing from the transmitter to the\n% refraction-corrupted position (of the target as seen by the\n% transmitter. This is in the global coordinate system.\n% uTarRx A 3XN set of unit vectors pointing from the target to the\n% refraction-corrupted position of the receiver as seen by the\n% target. This is in the global coordinate system.\n% uTarTx A 3XN set of unit vectors pointing from the target to the\n% refraction-corrupted position of the transmitter as seen by the\n% target. This is in the global coordinate system.\n%\n%This function implements the refraction algorithm for the basic\n%exponential atmosphere as described in [1] for the bistatic case. If the\n%target is collocated with the transmitter or the receiver, then NaNs will\n%be returned for some values. The basic exponential refraction model is in\n%[2].\n%\n%The model is parameterized in terms of a height above a sphere. The Earth\n%is more of an ellipsoid than a sphere. Thus, we use local spherical\n%approximations about the transmitter and the receiver. That is, for\n%computing the refraction from the transmitter to the target, we use the\n%distance from the center of the Earth to the surface of the reference\n%ellipsoid at the transmitter as the radius of an approximately spherical\n%Earth. Similarly, the distance from the center of the Earth to the\n%receiver is used in the approximation for the path from the target to the\n%receiver.\n%\n%The algorithm in [1] performs ray tracing by solving a boundary value\n%problem. here, the bvp5c function in Matlab is used to solve the problem.\n%\n%For paths that are nearly vertical, it is approximated that there is no\n%bending in angle and an explicit solution to the integral over the index\n%of refraction in the vertical direction is used to obtain the range.\n%\n%EXAMPLE:\n%Here, we have two radars and one target near Hawaii.\n% latLonRx=deg2rad([20.269202;-155.852051]);\n% AltRx=0;\n% latLonTx=deg2rad([20.724568;-155.978394]);\n% AltTx=0;\n% latLonTar=deg2rad([20.835390;-155.313721]);\n% AltTar=8e3;%8km target altitude.\n% %Convert locations to Cartesian.\n% zRx=ellips2Cart([latLonRx;AltRx]);\n% zTx=ellips2Cart([latLonTx;AltTx]);\n% zTar=ellips2Cart([latLonTar;AltTar]);\n% \n% %The receiver faces 45 degrees East of North and 15 degrees up from the\n% %local ellipsoidal level.\n% M=findRFTransParam([latLonRx;AltRx],deg2rad(45),deg2rad(15));\n% Ns=350;%Assumed refractivity at the sea surface.\n% useHalfRange=false;\n% includeW=true;%Include third dimension of unit vector.\n% [z,uTx,uTarRx,uTarTx]=Cart2RuvStdRefrac(zTar,useHalfRange,zTx,zRx,M,Ns,includeW);\n% zNoRefrac=Cart2Ruv(zTar,useHalfRange,zTx,zRx,M,includeW);\n% z(1)-zNoRefrac(1)%Bistatic range difference of 31.0813 meters\n% %Direction difference of 0.0927 degrees\n% rad2deg(angBetweenVecs(z(2:end),zNoRefrac(2:end)))\n%\n%REFERENCES:\n%[1] D. F. Crouse, \"Basic tracking using 3D monostatic and bistatic\n% measurements in refractive environments,\" IEEE Aerospace and\n% Electronic Systems Magazine, vol. 29, no. 8, Part II, pp. 54-75, Aug.\n% 2014.\n%[2] B. R. Bean and G. D. Thayer, CRPL Exponential Reference Atmosphere.\n% Washington, D.C.: U. S. Department of Commerce, National Bureau of\n% Standards, Oct. 1959. [Online]. Available:\n% http://digicoll.manoa.hawaii.edu/techreports/PDF/NBS4.pdf\n%\n%June 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumMeas=size(zC,2);\n\n%The assumes refractivity at sea level to use if none is provided.\nif(nargin<7||isempty(includeW))\n includeW=false; \nend\n\nif(nargin<6||isempty(Ns))\n Ns=313;\nend\n\nif(nargin<5||isempty(M))\n M=eye(3); \nend\n\nif(nargin<4||isempty(zRx))\n zRx=zeros(3,1); \nend\n\nif(nargin<3||isempty(zTx))\n zTx=zeros(3,1);\nend\n\nif(nargin<2||isempty(useHalfRange))\n useHalfRange=false;\nend\n\nif(nargin<8||isempty(ce))\n expConst=0.005577;\n multConst=7.32;\n\n %The change in refractivity at an elevation of 1km based on the\n %refractivity on the surface of the Earth.\n DeltaN=-multConst*exp(expConst*Ns);\n ce=log(Ns/(Ns+DeltaN))/1000;%Units of inverse meters.\nend\n\nif(nargin<9||isempty(rE))\n %Use the radius of the Earth that is the radius of the osculating\n %sphere at the location of the observed. This will be the radius used\n %in the local spherical Earth approximation for computing atmospheric\n %refraction. This uses the WGS-84 reference ellipsoid.\n [rE,spherCent]=osculatingSpher4LatLon(Cart2Ellipse(zRx));\nend\n\n%Adjust all the Cartesian values based on the osculating sphere.\nzC=zC-spherCent;\nzTx=zTx-spherCent;\nzRx=zRx-spherCent;\n\n%Allocate space\nif(includeW)\n z=zeros(4,numMeas);\nelse\n z=zeros(3,numMeas);\nend\nuTx=zeros(3,numMeas);\nuTarTx=zeros(3,numMeas);\nuTarRx=zeros(3,numMeas);\n\nif(any(zRx~=zTx))%If the scenario is bistatic\n for curMeas=1:numMeas\n [r2,uArrive,uTarRx(:,curMeas)]=atmosRefracMeas(zRx,zC(:,curMeas),Ns,ce,rE);\n [r1,uTx(:,curMeas),uTarTx(:,curMeas)]=atmosRefracMeas(zTx,zC(:,curMeas),Ns,ce,rE);\n\n r=(r1+r2);\n u=M*uArrive;\n \n if(useHalfRange)\n r=r/2; \n end\n \n zCur=[r;u];\n \n if(includeW)\n z(:,curMeas)=zCur;\n else\n z(:,curMeas)=zCur(1:3);\n end\n end\nelse%The scenario is monostatic.\n for curMeas=1:numMeas\n [range,uArrive,uTarRx(:,curMeas)]=atmosRefracMeas(zTx,zC(:,curMeas),Ns,ce,rE);\n uTx=uArrive;\n r=2*range;%Round-trip range.\n u=M*uArrive;\n\n if(useHalfRange)\n r=r/2; \n end\n\n zCur=[r;u];\n\n if(includeW)\n z(:,curMeas)=zCur;\n else\n z(:,curMeas)=zCur(1:3);\n end\n\n uTx(:,curMeas)=uArrive;\n uTarTx(:,curMeas)=uTarRx(:,curMeas);\n end\nend\nend\n\nfunction [range,uArrive,uDepart]=atmosRefracMeas(xObs,xObj,Ns,ce,rE)\n%%ATMOSREFRACMEAS Given the location of an observer and an object in the\n% atmosphere of the Earth, find the delay and angle of\n% arrival of a signal from the object to the observer,\n% accounting for basic,standard refraction. A\n% low-fidelity exponential atmospheric model is used. This\n% function is not suitable for computing refraction\n% between satellites, grazing the Earth's atmosphere. The\n% algorithm might have an error if the raypath\n% goes too far underground.\n%\n%INPUTS: xObs The Cartesian location of the observer in ECEF coordinates in\n% meters as [x;y;z].\n% xObj The Cartesian location of the object being observed in\n% ECEF coordinates in meters as [x;y;z].\n% Ns The refractivity as reduced to at sea level.\n% expConst,multConst The parameters of the refractivity model such that\n% increasing the height by 1km, the model is that the\n% refractivity changes by deltaN=-multConst*exp(expConst*N).\n% deltaN cannot be negative.\n% rE The radius of the Earth to use in the spherical Earth\n% approximation. An osculating sphere near a sensor is\n% suggested.\n%\n%OUTPUTS: range The apparent one-way range (in meters) of the signal from\n% the transmitter to the target and back to the receiver.\n% uArrive A unit vector in ECEF coordinates pointing in the apparent\n% direction of the signal the observer received (as seen by\n% the observer).\n% uDepart The direction of the signal departing the object that\n% arrives at the observer. Put another way, if the observer\n% were to transmit a signal to the object, this is the\n% apparent direction of the observer as seen by the object.\n%\n%This function implements the refraction algorithm for the basic\n%exponential atmosphere as described in [1] for the monostatic case. If the\n%points are collocated, then NaNs are returned for uArrive and uDepart.\n%\n%The function will fail for paths that go too deep into the Earth.\n%\n%REFERENCES:\n%[1] D. F. Crouse, \"Basic tracking using 3D monostatic and bistatic\n% measurements in refractive environments,\" IEEE Aerospace and\n% Electronic Systems Magazine, vol. 29, no. 8, Part II, pp. 54-75, Aug.\n% 2014.\n%\n%May 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n%We need the conversion from the 3D coordinate system of the observer and\n%object into the 2D coordinate system used for raytracing. The 2D\n%coordinate system has the center of the Earth as its origin and the x-y\n%axes are in the plane of the vector from the observer to the target. One\n%vector common to both coordinate systems in the local up vector, which\n%will be the local y axis. The second vector common to both will be the\n%local x vector, which will be the projection of xObj-xObs onto the local\n%tangent plane. Here, the vertical is the spherical model vertical. Since\n%the precision of the model is low enough that the difference between the\n%spherical and gravitational verticals shouldn't matter.\nuENU=getENUAxes(Cart2Ellipse(xObs,[],rE,0));\nuVertGlobal=uENU(:,3);\nuVertLocal=[0;1;0];\n\nvec2TarGlobal=xObj-xObs;\n\n%The projection of the xObj-xObs vector into the local tangent plane can be\n%obtained by subtracting the component of the vector that is orthogonal to\n%the plane.\nuHorizGlobalOrig=vec2TarGlobal-dot(vec2TarGlobal,uENU(:,3))*uENU(:,3);\n\nuHorizGlobal=uHorizGlobalOrig/norm(uHorizGlobalOrig);\nuHorizLocal=[1;0;0];\n\n%Find the rotation matrix from the global coordinate system into the local\n%coordinate system.\nECEF2LocalRot=findTransParam([uVertLocal,uHorizLocal],[uVertGlobal,uHorizGlobal]);\n\n%The third (z) coordinate in the local system should be zero after this\n%transformation.\nvec2TarLocal=ECEF2LocalRot*vec2TarGlobal;\n\n%The location of the receiver in the local 2D coordinate system.\nx0Init=0;\ny0Init=norm(xObs);\n\n%The location of the target in the local 2D coordinate system.\nx1Init=vec2TarLocal(1);\ny1Init=vec2TarLocal(2)+y0Init;\n\n%If the two points are nearly vertical, then the ray tracing algorithm will\n%fail. For nearly vertical points, the bending due to refraction in the\n%model should be negligible, so we can perform an integral in the y\n%direction to solve for the excess range instead of having to solve the\n%more complicated general bistatic problem. To deal with x1Init not being\n%exactly zero, we actually go to a full range of norm([x1Init;y1Init])\nif(norm(uHorizGlobalOrig)<1e-3)\n %Integrating the index of refraction from y0Init to\n %norm([x1Init;y1Init]) at a constant x yields the following measured\n %range. It is not just the geometric range, because the index of\n %refraction is not a constant 1.\n yMax=norm([x1Init;y1Init]);\n \n range=((exp(ce*(rE-y0Init))-exp(ce*(rE-yMax)))*Ns)/(1e6*ce)+yMax-y0Init;\n\n uArrive=vec2TarGlobal/norm(vec2TarGlobal);\n uDepart=-uArrive;\n return;\nend\n\n%Now, set up the boundary-value problem to determine the path taken by\n%light between the target and the receiver.\n\n%The initial guess is just the linear solution. The solver requires a fixed\n%number of steps. 20 is probably sufficient for things near the Earth. that\n%is, up to distances of, say 400km. We can scale the number of steps as 20\n%for every 400 kilometers with a minimum of, say 10.\n%Things outside of the atmosphere should use the astronomical refraction\n%routines.\nnumSteps=max(20,ceil(20*norm(vec2TarLocal)/400e3));\nx=linspace(x0Init,x1Init,numSteps);\nslope=(y1Init-y0Init)/(x1Init-x0Init);\nb=y1Init-slope*x1Init;%The y-intercept.\n%The initial estimate of the solution.\nsolInit=bvpinit(x,@(x)[x*slope+b;slope]);\n\n%Now, solve the differential equation.\noldOpts=bvpset();\nnewOpts=bvpset(oldOpts,'RelTol',1e-8,'AbsTol',1e-8,'FJacobian',@(x,y)odefunJacob(x,y,Ns,rE,ce),'BCJacobian',@bcfunJacob);%Increase the accuracy.\nsol=bvp5c(@(x,y)expDiffEq(x,y,Ns,rE,ce),@(y0,y1)bcfun(y0,y1,y0Init,y1Init),solInit,newOpts);\n\n%Get the refraction-corrupted range measurement for a signal traveling from\n%the object to the observer. \nrange=integral(@(x)pathFun2D(x,sol,Ns,rE,ce),x0Init,x1Init,'AbsTol',eps(1),'RelTol',1e-15);\n\nif(nargout>1)\n %Get the angle of arrival for a signal traveling from the object to the\n %observer. The angle is determined by the slope at the initial point.\n thetaOrig=atan(sol.y(2,1));\n uLocal=[cos(thetaOrig);sin(thetaOrig);0];\n\n %The inverse rotation is given the transpose of the rotation\n %matrix. This is the apparent direction of the object as seen by the\n %observer.\n uArrive=ECEF2LocalRot'*uLocal;\n\n thetaEnd=atan(sol.y(2,end));\n uLocal=[cos(thetaEnd);sin(thetaEnd);0];\n %This is the apparent direction of the observer as seen by the object.\n uDepart=-ECEF2LocalRot'*uLocal;\nend\nend\n\nfunction val=pathFun2D(x,sol,Ns,rE,ce)\n %This function is used to integrate the time taken\n y=deval(x,sol);\n val=(1+NRefracExp(x,y(1,:),Ns,rE,ce)).*sqrt(1+y(2,:).^2);\nend\n\nfunction res=bcfun(y0,y1,y0Init,y1Init)\n %The residue to define the boundary condition for the numeric\n %differential equation solver as applied to the 2D exponential\n %atmospheric model.\n\n res=[y0(1)-y0Init;\n y1(1)-y1Init];\nend\n\nfunction [dbcy0,dbcy1]=bcfunJacob(~,~)\n %The Jacobians of the boundary conditions for raytracing the 2D\n %exponential atmospheric refraction model.\n dbcy0=[1 0\n 0 0];\n dbcy1=[0 0\n 1 0];\nend\n\nfunction J=odefunJacob(x,y,Ns,rE,ce)\n %The Jacobian of the differential equation for raytracing the 2D\n %exponential atmospheric model.\n expVal=NRefracExp(x,y(1),Ns,rE,ce);\n\n J=zeros(2,2);\n J(1,2)=1;\n J(2,1)=ce*(1+y(2)^2)*(-expVal)*(ce*y(1)*(x*y(2)-y(1))*sqrt(x^2+y(1)^2)+x*(x+y(1)*y(2))*(expVal+1))/((x^2+y(1)^2)^(3/2)*(expVal+1)^2);\n J(2,2)=ce*(x-2*y(1)*y(2)+3*x*y(2)^2)*expVal/((expVal+1)*sqrt(x^2+y(1)^2));\nend\n\nfunction dxdy=expDiffEq(x,y,Ns,rE,ce)\n %Find the refractivity at location (x,y).\n expVal=NRefracExp(x,y(1),Ns,rE,ce);\n\n dxdy=[y(2)\n ce*(1+y(2)^2)*(x*y(2)-y(1))*expVal/((expVal+1)*sqrt(x^2+y(1)^2))];\nend\n\nfunction nRefrac=NRefracExp(x,y,Ns,rE,ce)\n %The refractivity. This is 10^6*(index of refraction-1)\n nRefrac=1e-6*Ns*exp(-ce*(sqrt(x.^2+y.^2)-rE));\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/Atmosphere_and_Refraction/Standard_Exponential_Model/Cart2RuvStdRefrac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733983715524, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4817372544616735}} {"text": "classdef MaOEAIT < ALGORITHM\n% \n% Many-objective evolutionary algorithms based on an independent two-stage\n% approach\n% Evaluation1 --- 20000 --- Number of evaluations for NDWA\n% Evaluation1 --- 6000 --- Number of evaluations for reference lines mapping\n% epsilon --- 0.999 --- Threshold in PCA\n\n%------------------------------- Reference --------------------------------\n% Y. Sun, B. Xue, M. Zhang, G. G. Yen, A new two-stage evolutionary\n% algorithm for many-objective optimization, IEEE Transactions on\n% Evolutionary Computation, 2019, 23(5): 748-761.\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 methods\n function main(Algorithm,Problem)\n %% Parameter setting\n [Evaluation1,Evaluation2,epsilon] = Algorithm.ParameterSet(20000,6000,0.999);\n\n %% Generate random population\n Population = Problem.Initialization();\n Archive = [];\n\n %% Generate the weight vectors\n [W,W_num] = UniformPoint(Problem.N,Problem.M);\n UW = [W;W(end:-1:1,:)];\n num_W = size(UW,1);\n\n %% The objective value of each solution on single-objective in different stage\n SF = zeros(Problem.N+floor(Problem.N/2)*2,1);\n\n %% The objective value of each solution on single-objective in phase 1\n SF(1:Problem.N) = sum(Population.objs.*UW(1,:),2);\n\n %% Non-dominated dynamic weight aggregation (NDWA)\n while Algorithm.NotTerminated(Population) && Problem.FE < Evaluation1\n W_index = mod(ceil(Problem.FE/Problem.N)+1,num_W);\n if W_index == 0\n W_index = num_W;\n end\n MatingPool = TournamentSelection(2,Problem.N,SF(1:Problem.N));\n Offspring = OperatorGA(Problem,Population(MatingPool),{0.9,20,1,20});\n SF(Problem.N+1:end) = sum(Offspring.objs.*UW(W_index,:),2);\n [Population,SF] = NDWA_EnvironmentalSelection([Population,Offspring],SF,Problem.N);\n Archive = [Archive,Population];\n Archive = Archive(NDSort(Archive.objs,1)==1);\n end\n\n %% Pareto-optimal subspace learning\n learned_data = FindSubspace(Archive.decs,epsilon);\n mean_val = mean(learned_data,1);\n u_limit = ones(size(Problem.upper));\n l_limit = zeros(size(Problem.lower));\n for i = 1:numel(mean_val)\n if abs(learned_data(1,i)-mean_val(i)) < 0.1\n l_limit(i) = round(mean_val(i),1);\n u_limit(i) = round(mean_val(i),1);\n else\n l_limit(i) = Problem.lower(i);\n u_limit(i) = Problem.upper(i);\n end\n end\n\n %% Reference lines mapping\n % Optimize Problem.M single-objective optimization problems\n rf_list = diag(ones(1,Problem.M));\n SO_maxeval = floor(Evaluation2/Problem.M);\n Extreme_point = repmat(Population(1),1,Problem.M);\n for i = 1 : Problem.M\n Curr_evl = Problem.FE;\n PopDec = rand(Problem.N, Problem.D).*repmat(u_limit-l_limit,Problem.N,1) + repmat(l_limit,Problem.N,1);\n Population = Problem.Evaluation(PopDec);\n SF(1:Problem.N) = cos_v_func(Population.objs,rf_list(i,:));\n while Algorithm.NotTerminated(Population) && Problem.FE < (Curr_evl+SO_maxeval)\n MatingPool = TournamentSelection(2,Problem.N,SF(1:Problem.N));\n Offspring = Operator(Problem,Population(MatingPool).decs,l_limit,u_limit); \n SF(Problem.N+1:end) = cos_v_func(Offspring.objs,rf_list(i,:));\n [~,Rank] = sort(SF,1);\n Population = [Population,Offspring];\n Population = Population(Rank(1:Problem.N));\n SF(1:Problem.N) = SF(Rank(1:Problem.N));\n end\n Extreme_point(i) = Population(1);\n end\n Ideal_point = min(Extreme_point.objs,[],1);\n Nadir_point = max(Extreme_point.objs,[],1);\n RefPoint = W.*repmat(Nadir_point-Ideal_point,size(W,1),1) + repmat(Ideal_point,size(W,1),1);\n\n %% Diversity maintaining\n % Optimize W_num single-objective optimization problems\n SO_maxeval = floor((Problem.maxFE-Evaluation1-Evaluation2)/W_num);\n Result = repmat(Population(1),1,size(RefPoint,1));\n for i = 1 : W_num\n Curr_evl = Problem.FE;\n PopDec = rand(Problem.N,Problem.D).*repmat(u_limit-l_limit,Problem.N, 1) + repmat(l_limit,Problem.N,1);\n Population = Problem.Evaluation(PopDec);\n SF(1:Problem.N) = cos_v_func(Population.objs,RefPoint(i,:));\n while Algorithm.NotTerminated(Population) && Problem.FE < (Curr_evl+SO_maxeval)\n MatingPool = TournamentSelection(2,Problem.N,SF(1:Problem.N));\n Offspring = Operator(Problem,Population(MatingPool).decs,l_limit,u_limit);\n SF(Problem.N+1:end) = cos_v_func(Offspring.objs,RefPoint(i,:));\n [~,Rank] = sort(SF,1);\n Population = [Population,Offspring];\n Population = Population(Rank(1:Problem.N));\n SF(1:Problem.N) = SF(Rank(1:Problem.N));\n if i == W_num && Problem.FE == (Curr_evl+SO_maxeval) \n Result(W_num) = Population(1);\n Population = Result;\n end \n end\n Result(i) = Population(1);\n end\n end\n end\nend\n\nfunction [Population,SF] = NDWA_EnvironmentalSelection(Population,SF,N)\n% Environmental selection\n\n [FrontNo,MaxFNo] = NDSort(Population.objs,Population.cons,N);\n Next = FrontNo < MaxFNo;\n Last = find(FrontNo==MaxFNo);\n Next(Last(1:N-sum(Next))) = true;\n Population = Population(Next);\n SF(1:N) = SF(Next);\nend\n\nfunction SF = cos_v_func(PopObj,v)\n% Calculate the objective value of each solution on each single-objective\n% optimization problem\n\n r1 = sum(PopObj.*v,2);\n r2 = sqrt(sum(PopObj.^2,2));\n SF = -r1./r2;\nend\n\nfunction Offspring = Operator(Problem,ParentDec,lower,upper)\n% Simulated binary crossover and polynomial mutation\n\n [proC,disC,proM,disM] = deal(1,20,1,20);\n Parent1 = ParentDec(1:floor(end/2),:);\n Parent2 = ParentDec(floor(end/2)+1:floor(end/2)*2,:);\n [N,D] = size(Parent1);\n\n beta = zeros(N,D);\n mu = rand(N,D);\n beta(mu<=0.5) = (2*mu(mu<=0.5)).^(1/(disC+1));\n beta(mu>0.5) = (2-2*mu(mu>0.5)).^(-1/(disC+1));\n beta = beta.*(-1).^randi([0,1],N,D);\n beta(rand(N,D)<0.5) = 1;\n beta(repmat(rand(N,1)>proC,1,D)) = 1;\n Offspring = [(Parent1+Parent2)/2+beta.*(Parent1-Parent2)/2\n (Parent1+Parent2)/2-beta.*(Parent1-Parent2)/2];\n\n Lower = repmat(lower,2*N,1);\n Upper = repmat(upper,2*N,1);\n Site = rand(2*N,D) < proM/D;\n mu = rand(2*N,D);\n temp = Site & mu<=0.5;\n Offspring = min(max(Offspring,Lower),Upper);\n Offspring(temp) = Offspring(temp)+(Upper(temp)-Lower(temp)).*((2.*mu(temp)+(1-2.*mu(temp)).*...\n (1-(Offspring(temp)-Lower(temp))./(Upper(temp)-Lower(temp))).^(disM+1)).^(1/(disM+1))-1);\n temp = Site & mu>0.5; \n Offspring(temp) = Offspring(temp)+(Upper(temp)-Lower(temp)).*(1-(2.*(1-mu(temp))+2.*(mu(temp)-0.5).*...\n (1-(Upper(temp)-Offspring(temp))./(Upper(temp)-Lower(temp))).^(disM+1)).^(1/(disM+1)));\n\n Offspring = Problem.Evaluation(Offspring);\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Algorithms/Multi-objective optimization/MaOEA-IT/MaOEAIT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339556397749, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4817372383552225}} {"text": "function SCKS = spm_SCK(SCKS)\n% FORMAT SCKS = spm_SCK(SCKS)\n%__________________________________________________________________________\n% Square-root Cubature Kalman Filters [2] & Square-root Rauch-Tang-Striebel\n% Smoother (SCKF-SCKS [1]).\n%==========================================================================\n% This function performs joint estimation of the states, input and parameters\n% of a model that is described as a stochastic continuous-discrete \n% state-space in terms of nonlinear blind deconvolution. The state equations\n% must have the form of ordinary differential equations, where the \n% discretization is performed through local-linearization scheme [3]. \n% Additionally, the parameter noise covariance is estimated online via \n% stochastic Robbins-Monro approximation method [4], and the measurement noise \n% covariance is estimated using a combined variational Bayesian (VB) \n% approach with a nonlinear filter/smoother [5].\n%__________________________________________________________________________\n%\n% SCKS.M - model structure (based on DEM [6] in SPM8 toolbox)\n% SCKS.Y - response variable, output or data\n%__________________________________________________________________________\n%\n% generative model:\n%--------------------------------------------------------------------------\n% M(1).f = dx/dt = f(x,v,P) {inline function, string or m-file}\n% M(1).g = y(t) = g(x,v,P) {inline function, string or m-file}\n% \n% M(1).xP = state error covariance matrix\n% M(1).uP = input error variance\n% M(1).wP = parameter error covariance matrix\n%\n% M(1).pE = prior expectation of p model-parameters\n% M(1).pC = prior covariances of p model-parameters\n% M(1).ip = parameter indices\n% M(1).cb = constrain on parameters [lower, upper];\n%\n% M(1).Q = precision components on observation noise\n% M(1).V = fixed precision (input noise)\n% M(1).W = precision on state noise (approximated by annealing)\n%\n% M(i).m = number of inputs v(i + 1);\n% M(1).n = number of states x(i);\n% M(1).l = number of output v(i);\n%\n% M(1).Qf = form of measurement noise cov estimate:\n% 'auto'[default],'min','mean'\n% M(1).E.nN = number of SCKF-SCKS algorithm iterations\n% M(1).E.Itol = tolerance value for SCKF-SCKS convergence \n% M(1).E.nD = number of integration step between observations\n% M(1).VB.N = number of VB algorithm iterations\n% M(1).VB.Itol = tolerance value for VB convergence \n% M(1).VB.l = VB scaling factor;\n%\n% conditional moments of model-states - q(u)\n%--------------------------------------------------------------------------\n% qU.x = Conditional expectation of hidden states (backward estimate)\n% qU.v = Conditional expectation of input (backward estimate)\n% qU.z = Conditional prediction error \n% qU.S = Conditional covariance: cov(x) (states - backward estimate)\n% qU.C = Conditional covariance: cov(u) (input - backward estimate)\n%\n% conditional moments of model-parameters - q(p)\n%--------------------------------------------------------------------------\n% qP.P = Conditional expectation\n% qP.C = Conditional covariance\n%\n% F = negative log-likelihood\n%__________________________________________________________________________\n% Copyright (c) Brno University of Technology (2010)...\n% Martin Havlicek 05-12-2010\n% \n% References:\n% [1] Havlicek M et al (2011)\n% [2] Arasaratnam, I., Haykin, S. (2009) Cubature Kalman Filters. IEEE\n% Transactions on Automatic Control 54, 1254-1269.\n% [3] Jimenez, J.C. (2002) A simple algebraic expression to evaluate the\n% local linearization schemes for stochastic differential equations* \n% 1. Applied Mathematics Letters 15, 775-780.\n% [4] Van der Merwe, R., 2004. Sigma-point Kalman filters for probabilistic\n% inference in dynamic state-space models. Ph.D.thesis, Oregon Graduate \n% Institute of Science and Technology.\n% [5] Sarkka, S., Hartikainen, J. (2011?) Extension of VB-AKF to Estimation\n% of Full Covariance and Non-Linear Systems. In Press.\n% [6] Friston, K.J., et al. (2008) DEM: a variational treatment of dynamic\n% systems. Neuroimage 41, 849-885.\n%__________________________________________________________________________\n% Copyright (C) - Martin Havlicek\n \n% Martin Havlicek\n% $Id: spm_SCK.m 4628 2012-01-27 20:51:41Z karl $\n% check model specification\n%--------------------------------------------------------------------------\nM = SCKS.M;\nM = spm_DEM_M_set(M);\n \n% get integration step dt:\n%--------------------------------------------------------------------------\nnD = M(1).E.nD; \ndt = 1/nD; \n\n% INITIALISATION:\n% =========================================================================\n\n% interpolate observation according to integration step\n%--------------------------------------------------------------------------\ny = SCKS.Y; % observations\nif size(y,1) > size(y,2) % check the dimensions\n y = y';\nend\n\n% interpolate if dt < 1:\n%--------------------------------------------------------------------------\ny = spm_interp(y',1/dt)';\nif size(y,1) > size(y,2) % check dimensions again\n y = y';\nend\nT = size(y,2); % number of time points \n \n% initial condition:\n%--------------------------------------------------------------------------\nx = M(1).x; % states\nu = M(2).v; % input\npE = spm_vec(M(1).pE); % all model parameter\nip = M(1).ip; % parameter indices to be estimated\ntheta = pE(ip); % selected parameters\n \ntry cb = M(1).cb; catch, cb = []; end; % parameter constraints \ntry tE = spm_vec(SCKS.pP.P{1}); catch, tE = []; end; % true parameters for display (if available)\n \n% covariances (square-roots)\n%--------------------------------------------------------------------------\nsR = cell(1,T);\n[sR{:}] = deal(sparse(real(chol(inv(M(1).V)))*dt)); % observation noise variance\nsQ = sparse(real(chol(inv(M(1).W)))*dt); % hidden state noise variance\nif ~isempty(M(2).v)\n sV = sparse(real(chol(inv(M(2).V)))*dt); % input noise variance\nelse\n sV = [];\nend\n \n% process error covariances (square-roots)\n%--------------------------------------------------------------------------\nSx = sparse(real(chol(M(1).xP))*dt);\nif ~isempty(M(2).v)\n Su = sparse(real(chol(M(1).uP))*dt);\nelse\n Su = [];\nend\nif ~isempty(ip)\n Sw = sparse(real(chol(M(1).wP(ip,ip)))*dt);\n sW = sparse(real(chol(M(1).pC(ip,ip)))*dt); % parameter noise variance\n dv = diag(sW); \nelse\n Sw = [];\n sW = [];\nend\n \n% number of states, inputs and parameters:\n%--------------------------------------------------------------------------\nnx = size(Sx,1); % number of states\nnu = size(sV,1); % number of states\nnw = size(sW,1); % number of parameters\nno = size(sR{1},1); % number of observations\nnoises = nx + nu + nw + no; % number of noise components\n \n% concatenate state vector and square-root error covariance:\n%--------------------------------------------------------------------------\nxc = [x(:); u(:); theta(:)];\nxx = zeros(nx+nu+nw,T);\nxx(:,1) = xc;\nSc = cell(1,T);\n[Sc{:}] = deal(sparse(nx+nu+nw,nx+nu+nw));\nSc{1} = blkdiag(Sx,Su,Sw);\n \n% get vector indices for components of concatenated state vector\n%--------------------------------------------------------------------------\nxmask = [ones(1,nx),ones(1,nu)*2,ones(1,nw)*3,ones(1,no)*4];\nxind = find(xmask==1);\nuind = find(xmask==2);\nwind = find(xmask==3);\nclear xmask;\n \n% setting for VB: observation noise estimation:\n%--------------------------------------------------------------------------\nif ~isempty(M(1).Q)\n try, iter0 = M(1).VB.N; catch, iter0 = 3; end\n try, lambda = M(1).VB.l; catch, lambda = 1-exp(-2); end\n NU = 6;\n V = diag(repmat(1e-4,1,no));\n [sR{:}] = deal(sqrt(1./(NU-no-1).*V));\n B = sqrt(lambda)*eye(no);\n k = size(sR{1},1);\n iter = iter0;\n MSE0 = zeros(no,1);\n RR0 = zeros(no,T);\n VBrun = [];\nelse\n iter0 = 1;\n iter = iter0;\n RR = [];\n VBrun = [];\nend\n \n% Pre-calculate cubature points: \n%--------------------------------------------------------------------------\nn = nx + nu + nw + noises; % total state vector dimension\nnPts = 2*n; % number of cubature points\nCubPtArray = sqrt(n)*[eye(n) -eye(n)]; % cubature points array\n \n% augment paramter matrix by number of cubature points:\n%--------------------------------------------------------------------------\npE = pE(:,ones(1,nPts));\n \n% prepare matrix template for integration by Local linearization scheme:\n%--------------------------------------------------------------------------\nEXPm = repmat({[ones(nx),2*ones(nx,1);zeros(1,nx+1)]},1,nPts);\nEXPm = sparse(blkdiag(EXPm{:}));\nxt = repmat([zeros(1,nx) 1],1,nPts)';\n \n \n% =========================================================================\n% Iteration scheme:\n% =========================================================================\n% get maximum number of iterations and tolerance:\n%--------------------------------------------------------------------------\ntry, ItolVB = M(1).VB.Itol; catch, ItolVB = 1e-4; end\ntry, Itol = M(1).E.Itol; catch, Itol = 1e-3; end\ntry, RUN = M(1).E.nN; catch, RUN = 32; end\ntry, ap = M(1).E.RM; catch, ap = [1e3 1e6]; end % Robins-Monro approximation parameters\n \nMLdiff0 = 1e-1;\nmloglik0 = 0;\nML = [];\nVBrun = RUN;\nt0 = tic;\n% =========================================================================\n% Iteration loop (until convergence)\n% =========================================================================\n \nfor run = 1:RUN\n t1 = tic;\n mloglik = -log(2.*pi).*(T/dt);\n % =====================================================================\n % Forward pass:\n % =====================================================================\n for t = 2:T\n \n sQ = diag(diag((1/sqrt(0.9995)-1)*Sc{t-1}(xind,xind)));\n Sa = blkdiag(Sc{t-1},sQ,sV,sW,sR{t-1});\n xa = [xc;zeros(noises,1)];\n Xi = xa(:,ones(1,nPts)) + Sa*CubPtArray;\n \n %------------------------------------------------------------------\n % PREDICTION STEP:\n %------------------------------------------------------------------\n xPred(uind,:) = Xi(uind,:) + Xi(uind+nx+nu+nw,:); % add input noise\n xPred(wind,:) = Xi(wind,:) + Xi(wind+nx+nu+nw,:); % add parameter noise\n \n % parameter constraint:\n %------------------------------------------------------------------\n if ~isempty(cb) && ~isempty(ip)\n xPred(wind,:) = min(cb(:,2*ones(1,nPts)),xPred(wind,:)); % upper constrain\n xPred(wind,:) = max(cb(:,1*ones(1,nPts)),xPred(wind,:)); % lower constrain\n end\n pE(ip,:) = xPred(wind,:);\n \n % propagation of cubature points through nonlinear function:\n %------------------------------------------------------------------\n f = M(1).f(Xi(xind,:),xPred(uind,:),pE);\n \n % integration by local-linearization scheme:\n %------------------------------------------------------------------\n dfdx = spm_diff_all(M(1).f,Xi(xind,:),xPred(uind,:),pE,1);\n dx = expmall(dfdx,f,dt,EXPm)*xt;\n xPred(xind,:) = Xi(xind,:) + reshape(dx(~xt),nx,nPts) + Xi(xind+nx+nu+nw,:);\n \n % mean prediction:\n %------------------------------------------------------------------\n x1 = sum(xPred,2)/nPts;\n X = (xPred-x1(:,ones(1,nPts)))/sqrt(nPts);\n [foo,S] = qr([X]',0);\n S = S';\n \n % in the case of VB observation noise estimation:\n %------------------------------------------------------------------\n if ~isempty(M(1).Q) && iter~=1\n NU = lambda.*(NU-k-1)+k+1;\n V = B*V*B';\n NU = NU + 1;\n V0 = V;\n end\n x10 = x1;\n S0 = S;\n yPred0 = M(1).g(xPred(xind,:),xPred(uind,:),pE);\n \n %------------------------------------------------------------------\n % UPDATE STEP:\n %------------------------------------------------------------------\n \n % VB estimation of sR (iteratively)\n %------------------------------------------------------------------\n for it = 1:iter\n \n % VB part - update of square-root measurement noise cov\n %---------------------------------------------------------------\n if ~isempty(M(1).Q) && iter ~= 1\n sR{t} = real(chol(1/(NU - no - 1)*V)); \n end\n \n % propagate cubature points through observation function:\n %--------------------------------------------------------------\n yPred = yPred0 + sR{t}*CubPtArray(end-no+1:end,:);\n y1 = sum(yPred,2)/nPts;\n \n Y = (yPred-y1(:,ones(1,nPts)))/sqrt(nPts);\n [foo,Sy] = qr([Y]',0);\n Sy = Sy';\n \n Pxy = X*Y'; % cross covariance\n K = (Pxy/Sy')/Sy; % Kalman gain\n resid = y(:,t) - y1; % innovations\n \n % state (input,parameter) estimates:\n %--------------------------------------------------------------\n xc = x10 + K*(resid);\n \n % check parameter constraints: \n %--------------------------------------------------------------\n if ~isempty(cb) && ~isempty(ip)\n xc(wind) = min(cb(:,2),xc(wind)); % upper constrain\n xc(wind) = max(cb(:,1),xc(wind)); % lower constrain\n end\n % estimate of process error covarinace:\n %--------------------------------------------------------------\n [foo,S] = qr([(X - K*Y)]',0);\n S = S';\n \n % VB part\n %--------------------------------------------------------------\n if ~isempty(M(1).Q) && iter~=1\n Sa = blkdiag(S,sQ,sV,sW,sR{t});\n Xi = repmat([xc;zeros(noises,1)],1,nPts) + Sa*CubPtArray;\n yPreds = M(1).g(Xi(xind,:),Xi(uind,:),pE); % no additive noise!\n D = repmat(y(:,t),1,nPts)-yPreds;\n D = D*D'/nPts;\n V = V0 + D;\n end\n \n end\n Sc{t} = S;\n xx(:,t) = xc;\n \n % Maximum log-Likelihood\n %------------------------------------------------------------------\n mloglik = mloglik - log(det(Sy*Sy')) - resid'/(Sy*Sy')*resid;\n \n % Robins-Monro stochastic approximation for of parameters noise cov\n %------------------------------------------------------------------\n if ~isempty(ip)\n subKG = K(wind,:);\n dv = sqrt((1-1/ap(1))*(dv.^2) + 1/ap(1)*diag(subKG*(subKG*resid*resid')'));\n sW = diag(dv);\n ap(1) = min(ap(1)+1,ap(2));\n end\n if ~isempty(M(1).Q) && iter~=1\n RR(:,t) = diag(sR{t});\n end\n end\n xxf = xx;\n Sf = Sc;\n %----------------------------------------------------------------------\n % END of forward pass\n % ---------------------------------------------------------------------\n \n % =====================================================================\n % Backward pass:\n % =====================================================================\n for t = T-1:-1:1\n % VB part:\n %------------------------------------------------------------------\n if ~isempty(M(1).Q) && iter~=1\n NU = lambda.*(NU-k-1)+k+1;\n V = B*V*B';\n NU = NU + 1;\n V0 = V;\n sR{t} = real(chol(1/(NU-no-1)*V)); \n end\n \n % Square-root Cubature Rauch-Tung-Striebel smoother\n %------------------------------------------------------------------\n \n % evaluate cubature points:\n %------------------------------------------------------------------\n Sa = blkdiag(Sc{t},sQ,sV,sW,sR{t});\n xa = [xx(:,t);zeros(noises,1)];\n Xi = xa(:,ones(1,nPts)) + Sa*CubPtArray;\n \n xPred(uind,:) = Xi(uind,:) + Xi(uind+nx+nu+nw,:);\n xPred(wind,:) = Xi(wind,:) + Xi(wind+nx+nu+nw,:);\n \n % check parameter constraints:\n %------------------------------------------------------------------\n if ~isempty(cb) && ~isempty(ip)\n xPred(wind,:) = min(cb(:,2*ones(1,nPts)),xPred(wind,:)); % upper constrain\n xPred(wind,:) = max(cb(:,1*ones(1,nPts)),xPred(wind,:)); % lower constrain\n end\n \n pE(ip,:) = xPred(wind,:);\n % propagate cubature points through nonlinear function:\n %------------------------------------------------------------------\n f = M(1).f(Xi(xind,:),xPred(uind,:),pE);\n dfdx = spm_diff_all(M(1).f,Xi(xind,:),xPred(uind,:),pE,1);\n dx = expmall(dfdx,f,dt,EXPm)*xt;\n xPred(xind,:) = Xi(xind,:) + reshape(dx(~xt),nx,nPts) + Xi(xind+nx+nu+nw,:) ;\n \n x1 = sum(xPred,2)/nPts;\n X = (xPred-x1(:,ones(1,nPts)))/sqrt(nPts) + eps;\n x01 = xx(:,t);\n X01 = (Xi([xind,uind,wind],:) - repmat(x01,1,nPts))/sqrt(nPts);\n [foo,S] = qr([X]',0);\n S = S';\n \n Pxy = X01*X'; % cross covariance\n K = (Pxy/S')/S; % Kalman gain\n \n % smoothed estimate of the states (input, parameters)\n % and process error covariance:\n %------------------------------------------------------------------\n xx(:,t) = xx(:,t) + K*(xx(:,t+1) - x1);\n [foo,S] = qr([X01 - K*X, K*Sc{t+1}]',0);\n S = S';\n Sc{t} = S;\n \n % check parameter constraint:\n %------------------------------------------------------------------\n if ~isempty(cb) && ~isempty(ip)\n xx(wind,t) = min(cb(:,2),xx(wind,t)); % upper constrain\n xx(wind,t) = max(cb(:,1),xx(wind,t));\n end\n \n % VB part (smoothing):\n %------------------------------------------------------------------\n if ~isempty(M(1).Q) && iter~=1\n Sa = blkdiag(S,sQ,sV,sW,sR{t});\n Xi = repmat([xx(:,t);zeros(noises,1)],1,nPts) + Sa*CubPtArray;\n yPreds = M(1).g(Xi(xind,:),Xi(uind,:),pE); % no additive noise!\n D = repmat(y(:,t),1,nPts)-yPreds;\n D = D*D'/nPts;\n V = V0 + D;\n end\n \n if ~isempty(M(1).Q) && iter~=1\n RR(:,t) = diag(sR{t});\n end\n \n end\n xxb = xx;\n Sb = Sc;\n %----------------------------------------------------------------------\n % END of backward pass\n %----------------------------------------------------------------------\n \n str{1} = sprintf('SCKS: %i (1:%i)',run,iter);\n \n % iteration condition for measurement noise estimate:\n % iterate until stabilization of sR estimate\n %----------------------------------------------------------------------\n if ~isempty(M(1).Q) && iter0 ~= 1\n \n MSE = mean((RR -(RR0)).^2,2);\n RR0 = RR;\n MSEdiff = abs(MSE - MSE0);\n MSE0 = MSE;\n \n if MSEdiff < ItolVB % (till it gets stable)\n switch(lower(M(1).Qf))\n case('all')\n % take all\n case('mean')\n sR = cell(1,T);\n [sR{:}] = deal(diag(mean(RR,2)));\n case('min')\n RRs = sort(RR,2,'descend');\n sR = cell(1,T);\n [sR{:}] = deal(diag(mean(RRs(:,round(T*0.90):end),2)));\n case('auto')\n dlim = min(RR,[],2);\n ulim = max(RR,[],2);\n if all(ulim./dlim<4)\n % take all\n else\n RRs = sort(RR,2,'descend');\n sR = cell(1,T);\n [sR{:}] = deal(diag(mean(RRs(:,round(T*0.90):end),2)));\n end\n end\n iter0 = 1;\n iter = iter0;\n mloglik0 = 0;\n VBrun = run;\n end\n end\n \n \n % log-likelihood difference:\n %----------------------------------------------------------------------\n MLdiff(run) = abs(mloglik-mloglik0);\n ML(run) = mloglik;\n if mloglik > 0\n mloglik = mloglik - 5000;\n MLdiff(run) = abs(mloglik-mloglik0);\n ML(run) = mloglik;\n end\n \n timed = toc(t1);\n str{2} = sprintf('F:%.4e',ML(end));\n str{3} = sprintf('dF:%.4e',MLdiff(end));\n str{4} = sprintf('(%.2e sec)',timed);\n fprintf('%-16s%-16s%-16s%-16s\\n',str{:})\n \n % plot estimates:\n %----------------------------------------------------------------------\n doplotting(M,xxf,xxb,Sf,Sb,ML,T,wind,ip,run,RR,VBrun);\n \n \n % stopping condition:\n %----------------------------------------------------------------------\n if RUN > 1 && (~isempty(ip) || ~isempty(M(1).Q))\n if run == 2\n MLdiff0 = MLdiff(run);\n elseif run > 2\n if MLdiff0 < MLdiff(run),\n MLdiff0 = MLdiff(run);\n end\n end\n if (((MLdiff(run)/MLdiff0)