{"text": "% this script tests GLCM features between CERR and pyradiomics on a wavelet filtered image.\n%\n% RKP, 03/22/2018\n\n%% Load image\nglcmParamFileName = fullfile(fileparts(fileparts(getCERRPath)),...\n 'Unit_Testing','tests_for_cerr','test_glcm_radiomics_extraction_settings.json');\ncerrFileName = fullfile(fileparts(fileparts(getCERRPath)),...\n 'Unit_Testing','data_for_cerr_tests','CERR_plans','head_neck_ex1_20may03.mat.bz2');\n\nplanC = loadPlanC(cerrFileName,tempdir);\nindexS = planC{end};\n\nparamS = getRadiomicsParamTemplate(glcmParamFileName);\nstrNum = getMatchingIndex(paramS.structuresC{1},{planC{indexS.structures}.structureName});\nscanNum = getStructureAssociatedScan(strNum,planC);\n\n\nscanType = 'wavelet';\ndirString = 'HHH';\n\n%% Calculate features using CERR\nharFeat3DdirS = calcGlobalRadiomicsFeatures...\n (scanNum, strNum, paramS, planC);\nharlCombS = harFeat3DdirS.Wavelets_Coif1__HHH.glcmFeatS.AvgS;\ncerrGlcmV = [harlCombS.autoCorr, harlCombS.jointAvg, harlCombS.clustPromin, harlCombS.clustShade, harlCombS.clustTendency, ...\nharlCombS.contrast, harlCombS.corr, harlCombS.diffAvg, harlCombS.diffEntropy, harlCombS.diffVar, harlCombS.dissimilarity, ...\nharlCombS.energy, harlCombS.jointEntropy, harlCombS.invDiff, harlCombS.invDiffMom, harlCombS.firstInfCorr, ...\nharlCombS.secondInfCorr, harlCombS.invDiffMomNorm, harlCombS.invDiffNorm, harlCombS.invVar, ...\nharlCombS.sumAvg, harlCombS.sumEntropy, harlCombS.sumVar];\n\n% %% Calculate features using pyradiomics\n% % image and mask for a structure\n% testM = single(planC{indexS.scan}(scanNum).scanArray) - ...\n% single(planC{indexS.scan}(scanNum).scanInfo(1).CTOffset);\n% mask3M = zeros(size(testM),'logical');\n% [rasterSegments, planC, isError] = getRasterSegments(strNum,planC);\n% [maskBoundBox3M, uniqueSlices] = rasterToMask(rasterSegments, scanNum, planC);\n% mask3M(:,:,uniqueSlices) = maskBoundBox3M;\n% \n% dx = planC{indexS.scan}(scanNum).scanInfo(1).grid1Units;\n% dy = planC{indexS.scan}(scanNum).scanInfo(1).grid1Units;\n% dz = mode(diff([planC{indexS.scan}(scanNum).scanInfo(:).zValue]));\n% pixelSize = [dx dy dz]*10;\n% \n% teststruct = PyradWrapper(testM, mask3M, pixelSize, scanType, dirString);\n% \n% %teststruct = PyradWrapper(testM, mask3M, scanType, dirString);\n% pyradGlcmNamC = {'Autocorrelation', 'JointAverage', 'ClusterProminence', 'ClusterShade', 'ClusterTendency', ...\n% 'Contrast', 'Correlation', 'DifferenceAverage', 'DifferenceEntropy', 'DifferenceVariance', 'Dissimilarity', ...\n% 'JointEnergy', 'JointEntropy','Id','Idm', 'Imc1' , ...\n% 'Imc2', 'Idmn','Idn','InverseVariance', 'sumAverage', 'SumEntropy', 'sumVariance'};\n% \n% pyradGlcmNamC = strcat(['wavelet','_', dirString,'_glcm_'],pyradGlcmNamC);\n% pyRadGlcmV = [];\n% for i = 1:length(pyradGlcmNamC)\n% if isfield(teststruct,pyradGlcmNamC{i})\n% pyRadGlcmV(i) = teststruct.(pyradGlcmNamC{i});\n% else\n% pyRadGlcmV(i) = NaN;\n% end\n% end\n% \n% %% Compare\n% glcmDiffV = (cerrGlcmV - pyRadGlcmV) ./ cerrGlcmV * 100\n\n%% Compare using previously calculated values of pyradiomics glcm\nsaved_pyRadGlcmV = [929.516284841440,30.4950632056943,5316.83199378276,-0.303806680516285,20.9971321089971,22.7275310589439,-0.0380659828547803,2.78099962843313,3.04970358686672,14.7880425011987,NaN,0.0446949242970363,6.28336538646016,0.479852104826365,0.424210035556516,-0.0921069324860780,0.664903434331990,0.993049866792659,0.955511453133062,0.367836063144979,NaN,3.75942560575858,NaN];\nglcmDiffV = (cerrGlcmV - saved_pyRadGlcmV) ./ cerrGlcmV * 100\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/Unit_Testing/tests_for_cerr/testGLCMWithPyrad_Wavelet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.4999988597340606}} {"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": "%% Calculating optical flow of a sequence of images or from Video file\n%% Author Gurkirt Singh\n%% Date 09 June 2011 at Vision Lab IIT DELHI\n%% Reading a Video file\nclear all\nclc\nObject=mmreader('1.avi');\nlastframe=read(Object, inf);\nNumFrames = Object.NumberOfFrames;\n%% Initialization of paramEters\n% Alpha\nalpha=10;\n% Number of iterations.\niterations=3;\n% Do you Want to reduce size of Image for less computation? If yes DoYou=1;\nDoYou=1;\n% Width and Height\nU=cell(NumFrames/2-1,1);\nV=cell(NumFrames/2-1,1);\nn=0;\n% Normal Intensity flow\n\nNormal=cell(NumFrames-1,1);\n\nWindow=[1/12 1/6 1/12;1/6 0 1/6;1/12 1/6 1/12];\n\n%% Main program Starts here\nhsize=[5 5];\nsigma=1;\nI=rgb2gray(read(Object,1));\nh = fspecial('gaussian',hsize,sigma);\n% I = imfilter(I,h,'replicate');\nPreviousFrame= imfilter(I,h,'replicate');\nif DoYou==1\nPreviousFrame=impyramid(PreviousFrame,'reduce');\nPreviousFrame=impyramid(PreviousFrame,'reduce');\nend\n[height width]=size(PreviousFrame);\n%%\nfor k = 2:1:NumFrames\n \n I=rgb2gray(read(Object,k));\n% I=imfilter(I,h,'replicate');\n CurrentFrame=imfilter(I,h,'replicate');\n if DoYou==1;\n CurrentFrame=impyramid(CurrentFrame,'reduce');\n CurrentFrame=impyramid(CurrentFrame,'reduce');\n end\n \n [TempU TempV TempNormal]=Opticalflow(CurrentFrame,PreviousFrame,alpha,iterations,height,width);\n n=n+1;\n U{n,1}=single(TempU);\n V{n,1}=single(TempV);\n% Normal{n,1}=single(TempNormal);\n PreviousFrame=CurrentFrame;\n \nend\n%% Last Part\n% myObj = VideoWriter('Ite3.wmv');\n% myObj.FrameRate = 10;\n% open(myObj);\n\n% for i=1:49-1\n% % u=U{i,1};\n% % v=V{i,1};\n% % temp=mat2gray(sqrt(v.^2+u.^2));\n% temp=mat2gray(abs(Normal{i,1}));\n% imshow(temp);\n% % BW =im2bw(I,0.12);\n% currFrame = getframe;\n% writeVideo(myObj,currFrame);\n% end\n% close(myObj)\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/31854-horn-and-schunck-optical-flow-method-for-a-video-file/Horn-Schunck Optical Flow Method/Flow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709795, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4999848265014477}} {"text": "classdef SymmetricTensorInverter < Inverter\n \n \n properties (Access = private)\n voigtTensor\n invVoigtTensor\n end\n \n methods (Access = public)\n \n function obj = SymmetricTensorInverter(tensor)\n obj.compute(tensor);\n end\n end\n \n methods (Access = protected)\n \n function computeInverse(obj)\n obj.transformTensor2Voigt()\n obj.makeInverseOfVoigtTensor()\n obj.transformVoigt2Tensor()\n end\n end\n \n methods (Access = private)\n \n \n function transformTensor2Voigt(obj)\n obj.voigtTensor = Tensor2VoigtConverter.convert(obj.tensor);\n end\n \n function makeInverseOfVoigtTensor(obj)\n obj.invVoigtTensor = Inverter.invert(obj.voigtTensor);\n end\n \n function transformVoigt2Tensor(obj)\n invT = obj.invVoigtTensor;\n obj.invertedTensor = Voigt2TensorConverter.convert(invT);\n end\n \n \n end\n \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/Topology Optimization/Homogenization/Sources/Inverter/SymmetricTensorInverter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4999848153478098}} {"text": "function [fhat,xhat,fcount,retcode] = sims_csminit(fcn,x0,f0,g0,badg,H0,varargin)\n% [fhat,xhat,fcount,retcode] = csminit(fcn,x0,f0,g0,badg,H0,...\n% P1,P2,P3,P4,P5,P6,P7,P8)\n% retcodes: 0, normal step. 5, largest step still improves too fast.\n% 4,2 back and forth adjustment of stepsize didn't finish. 3, smallest\n% stepsize still improves too slow. 6, no improvement found. 1, zero\n% gradient.\n%---------------------\n% Modified 7/22/96 to omit variable-length P list, for efficiency and compilation.\n% Places where the number of P's need to be altered or the code could be returned to\n% its old form are marked with ARGLIST comments.\n%\n% Fixed 7/17/93 to use inverse-hessian instead of hessian itself in bfgs\n% update.\n%\n% Fixed 7/19/93 to flip eigenvalues of H to get better performance when\n% it's not psd.\n%\n%tailstr = ')';\n%for i=nargin-6:-1:1\n% tailstr=[ ',P' num2str(i) tailstr];\n%end\n%ANGLE = .03;\nANGLE = .005;\n%THETA = .03;\nTHETA = .3; %(0 1e12\n % disp('Bad, small gradient problem.')\n % dx = dx*FCHANGE/dxnorm;\n % end\n %else\n % Gauss-Newton step;\n %---------- Start of 7/19/93 mod ---------------\n %[v d] = eig(H0);\n %toc\n %d=max(1e-10,abs(diag(d)));\n %d=abs(diag(d));\n %dx = -(v.*(ones(size(v,1),1)*d'))*(v'*g);\n% toc\n dx = -H0*g;\n% toc\n dxnorm = norm(dx);\n if dxnorm > 1e12\n dx = dx*FCHANGE/dxnorm;\n end\n dfhat = dx'*g0;\n %end\n %\n %\n if ~badg\n % test for alignment of dx with gradient and fix if necessary\n a = -dfhat/(gnorm*dxnorm);\n if a1\n dxtest=x0+dx'*lambda;\n else\n dxtest=x0+dx*lambda;\n end\n % home\n f = feval(fcn,dxtest,varargin{:});\n if f 0) & (f0-f > -(1-THETA)*dfhat*lambda) );\n if shrinkSignal & ( (lambda>lambdaPeak) | (lambda<0) )\n if (lambda>0) & ((~shrink) | (lambda/factor <= lambdaPeak))\n shrink=1;\n factor=factor^.6;\n while lambda/factor <= lambdaPeak\n factor=factor^.6;\n end\n %if (abs(lambda)*(factor-1)*dxnorm < MINDX) | (abs(lambda)*(factor-1) < MINLAMB)\n if abs(factor-1)lambdaPeak)\n lambdaMax=lambda;\n end\n lambda=lambda/factor;\n if abs(lambda) < MINLAMB\n if (lambda > 0) & (f0 <= fhat)\n % try going against gradient, which may be inaccurate\n lambda = -lambda*factor^6;\n else\n if lambda < 0\n retcode = 6;\n else\n retcode = 3;\n end\n done = 1;\n end\n end\n elseif (growSignal & lambda>0) | (shrinkSignal & ((lambda <= lambdaPeak) & (lambda>0)))\n if shrink\n shrink=0;\n factor = factor^.6;\n %if ( abs(lambda)*(factor-1)*dxnorm< MINDX ) | ( abs(lambda)*(factor-1)< MINLAMB)\n if abs(factor-1)0)\n fPeak=f;\n lambdaPeak=lambda;\n if lambdaMax<=lambdaPeak\n lambdaMax=lambdaPeak*factor*factor;\n end\n end\n lambda=lambda*factor;\n if abs(lambda) > 1e20;\n retcode = 5;\n done =1;\n end\n else\n done=1;\n if factor < 1.2\n retcode=7;\n else\n retcode=0;\n end\n end\n end\nend\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/sims_csminit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4999848153478098}} {"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 parent = connectedComponents(A)\n% label connected componentes in an graph (adjacency matrix)\n\n%elimination tree\nparent = etree(A);\n\nisleaf = parent ~= 0;\nparent(~isleaf) = 1:nnz(~isleaf);\ni = find(isleaf);\nfor i = i(end:-1:1)\n parent(i) = parent(parent(i));\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/tools/graph_tools/connectedComponents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.49994302435922755}} {"text": "function vars(vh)\n\nnum_masses = vh.userdata.num_masses;\n\nlbx = horzcat(-4*ones(1,num_masses), -inf*ones(1,num_masses)).';\nubx = horzcat(4*ones(1,num_masses), inf*ones(1,num_masses)).';\n\nvh.addState('x', [2*num_masses 1], 'lb', lbx, 'ub', ubx);\nvh.addControl('u', [num_masses-1 1], 'lb', -0.5, 'ub', 0.5);", "meta": {"author": "OpenOCL", "repo": "OpenOCL", "sha": "348fc31929791ddc8ed15a15733cf060a2e4674c", "save_path": "github-repos/MATLAB/OpenOCL-OpenOCL", "path": "github-repos/MATLAB/OpenOCL-OpenOCL/OpenOCL-348fc31929791ddc8ed15a15733cf060a2e4674c/+ocl/+examples/+mass_spring/vars.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.4999430241191714}} {"text": "function mse = EvalMSE(NN,tNN,sqi,HRVparams,windows_all)\n\n% mse = EvalMSE(NN,tNN,sqi,HRVparams,windows_all)\n%\n% OVERVIEW: This function returns MultiScale Entropy calculated on\n% input NN intervals for each window.\n%\n% INPUT: MANDATORY:\n% NN : a single row of NN (normal normal) interval \n% data in seconds\n% tNN : the time indices of the NN interval data \n% (seconds)\n% sqi : (Optional )Signal Quality Index; Requires \n% a matrix with at least two columns. Column \n% 1 should be timestamps of each sqi measure, \n% and Column 2 should be SQI on a scale from 0 to 1.\n% HRVparams : struct of settings for hrv_toolbox analysis\n% windows_all : vector containing the starting time of each\n% windows (in seconds) \n% \n% OUTPUT: \n% mse : vector of [max_tau, 1] doubles for each\n% window\n%\tREPO: \n% https://github.com/cliffordlab/PhysioNet-Cardiovascular-Signal-Toolbox\n% ORIGINAL SOURCE AND AUTHORS: \n% Written by Giulia Da Poian \n%\tCOPYRIGHT (C) 2016 \n% LICENSE: \n% This software is offered freely and without warranty under \n% the GNU (v3 or later) public license. See license file for\n% more information\n%\n\n% Verify input arguments\nif nargin < 4\n error('Wrong number of input parameters');\nend\nif nargin < 5 || isempty(windows_all)\n windows_all = 0; \nend\nif isempty(sqi) \n sqi(:,1) = tNN;\n sqi(:,2) = ones(length(tNN),1);\nend\n% Set Defaults\n\n\nif isempty(HRVparams.MSE.windowlength)\n windowlength = length(NN);\nelse\n windowlength = HRVparams.MSE.windowlength*3600;\nend\n\nthreshold1 = HRVparams.sqi.LowQualityThreshold;\nthreshold2 = HRVparams.RejectionThreshold;\n\nm = HRVparams.MSE.patternLength;\nr = HRVparams.MSE.RadiusOfSimilarity;\nmaxTau = HRVparams.MSE.maxCoarseGrainings;\n\ncg_moment = HRVparams.MSE.moment;\ncg_method = HRVparams.MSE.method;\nconstant_r = HRVparams.MSE.constant_r;\n\n% Preallocate arrays (all NaN) before entering the loop\nmse = nan(maxTau,length(windows_all));\n\n\n%Analyze by Window\n\n% Loop through each window of RR data\nfor i_win = 1:length(windows_all)\n % Check window for sufficient data\n if ~isnan(windows_all(i_win))\n % Isolate data in this window\n idx_NN_in_win = find(tNN >= windows_all(i_win) & tNN < windows_all(i_win) + windowlength);\n idx_sqi_win = find(sqi(:,1) >= windows_all(i_win) & sqi(:,1) < windows_all(i_win) + windowlength);\n \n sqi_win = sqi(idx_sqi_win,:);\n nn_win = NN(idx_NN_in_win);\n\n % Analysis of SQI for the window\n lowqual_idx = find(sqi_win(:,2) < threshold1);\n\n % If enough data has an adequate SQI, perform the calculations\n if numel(lowqual_idx)/length(sqi_win(:,2)) < threshold2\n mse(:,i_win) = ComputeMultiscaleEntropy(nn_win, m, r, maxTau, [], cg_moment,cg_method,constant_r);\n end\n \n\n end % end check for sufficient data\n \nend % end of loop through window\n\nend % end of function\n\n\n", "meta": {"author": "cliffordlab", "repo": "PhysioNet-Cardiovascular-Signal-Toolbox", "sha": "eec46e75e0b95c379ecb68cb0ebee0c4c9f54605", "save_path": "github-repos/MATLAB/cliffordlab-PhysioNet-Cardiovascular-Signal-Toolbox", "path": "github-repos/MATLAB/cliffordlab-PhysioNet-Cardiovascular-Signal-Toolbox/PhysioNet-Cardiovascular-Signal-Toolbox-eec46e75e0b95c379ecb68cb0ebee0c4c9f54605/Tools/Entropy_Tools/EvalMSE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.49994301825396187}} {"text": "function f_x = ParFor5(in1)\n%PARFOR5\n% F_X = PARFOR5(IN1)\n\n% This function was generated by the Symbolic Math Toolbox version 8.2.\n% 20-Sep-2019 09:35:35\n\nu = in1(:,1);\nux = in1(:,4);\nuxx = in1(:,5);\nuxxx = in1(:,6);\nf_x = ((u.*7.604652919865344e15+ux.*1.439296854415953e19+uxx.*4.056295991410688e16-uxxx.*3.942428646215516e17-u.*ux.*1.138844935991067e19-u.*uxxx.*1.804892689519346e18+2.199453572808704e15).*-1.0)./(u.*4.656689920376832e15-1.151078656075366e17);\n", "meta": {"author": "dynamicslab", "repo": "SINDy-PI", "sha": "42799b8e5a7585e400aa4bc3c83cfd659046cbb4", "save_path": "github-repos/MATLAB/dynamicslab-SINDy-PI", "path": "github-repos/MATLAB/dynamicslab-SINDy-PI/SINDy-PI-42799b8e5a7585e400aa4bc3c83cfd659046cbb4/Comparison/PDE_Comparison/Implicit_SINDy/TempFunctions/ParFor5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4999430182539618}} {"text": "function [aps, recall, precision] = calcAP(track_confs, tp_cell, fp_cell, num_vids, num_track_per_class, num_track_thr, defaultTrackThr)\n\nfprintf('computing AP\\n');\nrecall = cell(1,num_track_thr);\nprecision = cell(1,num_track_thr);\naps = cell(1,num_track_thr);\nconfs = [track_confs{:}];\n[~, ind] = sort(confs,'descend');\nfor o = 1:num_track_thr\n tp_all = [];\n fp_all = [];\n for v = 1:num_vids\n tp_all = [tp_all(:); tp_cell{v}{o}'];\n fp_all = [fp_all(:); fp_cell{v}{o}'];\n end\n \n tp_all = tp_all(ind)';\n fp_all = fp_all(ind)';\n \n % compute precision/recall\n tp = cumsum(tp_all);\n fp = cumsum(fp_all);\n recall{o} = (tp/num_track_per_class)';\n precision{o} = (tp./(fp+tp))';\n aps{o} = VOCap(recall{o},precision{o})*100;\nend\n\nfprintf('-------------\\n');\nap = aps{1};\nfor t = 2:length(aps)\n ap = ap + aps{t};\nend\nap = ap ./ length(aps);\nfprintf('Mean AP:\\t\\t %0.2f%%\\n',mean(ap));\nfprintf(' = = = = = = = = \\n');\nfor t = 1:length(aps)\n ap = aps{t};\n fprintf('Mean AP@%0.2f:\\t %0.2f%%\\n',defaultTrackThr(t),mean(ap));\nend\nfprintf(' = = = = = = = = \\n');", "meta": {"author": "VisDrone", "repo": "DroneCrowd", "sha": "3d25637f93f9476b4c949b6b9362287635b1a8c3", "save_path": "github-repos/MATLAB/VisDrone-DroneCrowd", "path": "github-repos/MATLAB/VisDrone-DroneCrowd/DroneCrowd-3d25637f93f9476b4c949b6b9362287635b1a8c3/STNNet/DroneCrowd-MOT-toolkit/eval/calcAP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.49985030744035436}} {"text": "%%% Nowcasting %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This script produces a nowcast of US real GDP growth for 2016:Q4 \n% using the estimated parameters from a dynamic factor model.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%% Clear workspace and set paths.\nclose all; clear; clc;\naddpath('functions');\n\n\n%% User inputs.\nseries = 'GDPC1' ; % Nowcasting real GDP (GDPC1) \nperiod = '2016q4'; % Forecasting target quarter\n\n\n%% Load model specification and first vintage of data.\n% Load model specification structure `Spec`\nSpec = load_spec('Spec_US_example.xls');\n\n\n%% Load DFM estimation results structure `Res`.\nRes = load('ResDFM'); % example_DFM.m used the first vintage of data for estimation\n\n\n%% Update nowcast and decompose nowcast changes into news.\n\n%%% Nowcast update from week of December 7 to week of December 16, 2016 %%%\nvintage_old = '2016-12-16'; datafile_old = fullfile('data','US',[vintage_old '.xls']);\nvintage_new = '2016-12-23'; datafile_new = fullfile('data','US',[vintage_new '.xls']);\n% Load datasets for each vintage\n[X_old,~ ] = load_data(datafile_old,Spec);\n[X_new,Time] = load_data(datafile_new,Spec);\n\n% check if spec used in estimation is consistent with the current spec\nif isequal(Res.Spec,Spec)\n Res = Res.Res;\nelse\n threshold = 1e-4; % Set to 1e-5 for robust estimates\n Res = dfm(X_new,Spec,threshold);\n save('ResDFM','Res','Spec');\nend \n\nupdate_nowcast(X_old,X_new,Time,Spec,Res,series,period,vintage_old,vintage_new);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n ", "meta": {"author": "FRBNY-TimeSeriesAnalysis", "repo": "Nowcasting", "sha": "19f365cab8269e3aac3faa11ad091d6e913c5c43", "save_path": "github-repos/MATLAB/FRBNY-TimeSeriesAnalysis-Nowcasting", "path": "github-repos/MATLAB/FRBNY-TimeSeriesAnalysis-Nowcasting/Nowcasting-19f365cab8269e3aac3faa11ad091d6e913c5c43/example_Nowcast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.49985030200527825}} {"text": "function [R,C] = syncRot(T)\n\n[~,L,Q] = proj_deformable_approx(T');\ns = sign(L(find(abs(L)==max(abs(L)),1)));\nC = s*L';\nR = s*Q';\nR(3,:) = cross(R(1,:),R(2,:));\n\n% [R,C] = projectNonrigid(T);\n% R(3,:) = cross(R(1,:),R(2,:));\n", "meta": {"author": "geopavlakos", "repo": "object3d", "sha": "44033b2b4fe15d41a411cba0bbff906c23e8a802", "save_path": "github-repos/MATLAB/geopavlakos-object3d", "path": "github-repos/MATLAB/geopavlakos-object3d/object3d-44033b2b4fe15d41a411cba0bbff906c23e8a802/code/utils/syncRot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.49976404461217583}} {"text": "function neg_tmpl = sample_neg(frame, p, out_size, margin)\n %% Sample 16 negative image samples arround the estimated bounding box with 2 different scales each\n % the parameter margin specifices the distance scale between the original bounding box and the sampled negative boxes\n count = 1;\n p_ori = p;\n len = (p(3) + p(4)) / 2;\n for context_scale = [0.5, 1] \n for i = -1 : 1\n for j = -1 : 1\n if i == 0 && j == 0\n continue;\n end\n tx = i * (p_ori(3) / 2 + len * (context_scale + min(margin / len, 0.1)));\n ty = j * (p_ori(4) / 2 + len * (context_scale + min(margin / len, 0.1)));\n p = p_ori;\n p(1) = p(1) + tx;\n p(2) = p(2) + ty;\n p(3) = 2 * len * context_scale;\n p(4) = 2 * len * context_scale;\n crop_img = im_crop(frame, round(p), out_size);\n neg_tmpl(:, count) = crop_img(:);\n count = count + 1;\n \n if i == 0\n p(1) = p(1) - len * context_scale;\n crop_img = im_crop(frame, round(p), out_size);\n neg_tmpl(:, count) = crop_img(:);\n count = count + 1;\n \n p(1) = p(1) + 2 * len * context_scale;\n crop_img = im_crop(frame, round(p), out_size);\n neg_tmpl(:, count) = crop_img(:);\n count = count + 1;\n end\n \n if j == 0\n p(2) = p(2) - len * context_scale;\n crop_img = im_crop(frame, round(p), out_size);\n neg_tmpl(:, count) = crop_img(:);\n count = count + 1;\n \n p(2) = p(2) + 2 * len * context_scale;\n crop_img = im_crop(frame, round(p), out_size);\n neg_tmpl(:, count) = crop_img(:);\n count = count + 1;\n end\n end\n end\n end\n \n\nend", "meta": {"author": "flyers", "repo": "drone-tracking", "sha": "c42e1833acfb858ac8f4ec69fa04ab02ac4c19ad", "save_path": "github-repos/MATLAB/flyers-drone-tracking", "path": "github-repos/MATLAB/flyers-drone-tracking/drone-tracking-c42e1833acfb858ac8f4ec69fa04ab02ac4c19ad/trackers/SODLT/sample_neg.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": "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": "function [cq mcq Xc]=getmeanquality(X,c,linkagetype)\n\n %point estimate cluster solution\n Y = pdist1(X);\n\n if exist('linkage.m', 'file') && exist('cluster.m', 'file')\n Z = linkage(Y,linkagetype);\n Xc = cluster(Z,c);\n else\n Z = linkage_t(Y,linkagetype);\n Xc = cluster_t(Z,c);\n end\n\n %convert X to X, binary input to doquality\n Xcx=makebinary(Xc)';\n\n %point estimate quality of each element;\n [cq center]=clustquality(Xcx,X); %cq is cluster quality of each element\n\n %mean cq\n if all(cq == 1)\n mcq = 0;\n else\n mcq = mean( cq(cq~=1) ); %don't include single element clusters in your quality estimate\n end\n\nend", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Statistics_tools/getmeanquality.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.49976403391817614}} {"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 [ hitsclean, polyidsclean, rayidsclean ] = invalidateintersections( pos_IMUinG, hits, polyids, rayids )\n%INVALIDATEINTERSECTIONS Will handle that a single ray hits many planes\n% We will go through each rayid and from there we will check to see which\n% of the given intersections for that ray are closest to the given\n% position of the LIDAR. We know that the closest ray would intersect\n% first so that is the only valid ray intersection.\n\n\n% Sort the arrays based on the rayid\n[rayids, indices] = sort(rayids);\nhits = hits(indices,:);\npolyids = polyids(indices,:);\n\n% Array to keep track of the max distance from our pos\nmaxdist = inf(1,max(rayids));\nmaxids = zeros(1,max(rayids));\n\n% Now we know we are sorted, so lets loop through each one and find the\n% shortest distance for the given ray ids\nfor ii=1:size(rayids,1)\n % compute the square difference between this point and the LIDAR pose\n diff = sqrt(sum((pos_IMUinG-hits(ii,1:3)).^2));\n % next lets see if it is the new min \n if diff < maxdist(rayids(ii,1))\n maxdist(rayids(ii,1)) = diff;\n maxids(rayids(ii,1)) = ii;\n end\nend\n\n\n% our output args\nhitsclean = [];\npolyidsclean = [];\nrayidsclean = [];\n\n\n% finally lets create the return values\ncleanct = 0;\nfor ii=1:size(maxdist,2)\n % if it is not inf then we have the min\n if maxdist(1,ii) ~= Inf\n hitsclean = [hitsclean; hits(maxids(1,ii),:)];\n polyidsclean = [polyidsclean; polyids(maxids(1,ii),:)];\n rayidsclean = [rayidsclean; rayids(maxids(1,ii),:)];\n cleanct = cleanct + 1;\n end \nend\n\n\n% Debug info\nfprintf('RAY: %d left after invalidation.\\n',cleanct)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nend\n\n", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/lips/invalidateintersections.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.49976402834962136}} {"text": "function Offspring = Operator(Problem,Particle,Pbest,Gbest)\n% \n% Particle swarm optimization in NMPSO\n\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 %% Parameter setting\n ParticleDec = Particle.decs;\n PbestDec = Pbest.decs;\n GbestDec = Gbest.decs;\n [N,D] = size(ParticleDec);\n ParticleVel = Particle.adds(zeros(N,D));\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 r3 = 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 C3 = repmat(unifrnd(1.5,2.5,N,1),1,D);\n OffVel = W.*ParticleVel + C1.*r1.*(PbestDec-ParticleDec) + C2.*r2.*(GbestDec-ParticleDec) + C3.*r3.*(GbestDec-PbestDec);\n OffDec = ParticleDec + OffVel;\n Offspring = Problem.Evaluation(OffDec,OffVel);\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/NMPSO/Operator.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.4997640279065118}} {"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": "function target = myConvolve(kConv, data, kernel, stride, task)\n% Matlab interfaces of alex fast convolution kernels.\n% There are are total 3 kinds of operations : given the two of (images,\n% filters, hidacts) to compute the remaining one. And for each operation,\n% there are two kernels : one for the second layer which is optimized\n% for one channel input and one for the other layers.\n\n% forward: (data,kernel) == (images, filters)\n% weight: (data,kernel) == (images, hidacts)\n% backward: (data,kernel) == (hidacts, filters)\n\n% interfaces for cuda code kFunctions.cu.\n\nif strcmp(task,'forward')\n numColors = size(data,5);\n if numColors == 1\n numFilters = size(kernel,1); filter_batch_size = 16;\n filter_batch_num = numFilters / filter_batch_size;\n assert(filter_batch_num == floor(filter_batch_num));\n \n numImages = size(data,1); imgSizeX = size(data,2); imgSizeY = size(data,3); imgSizeZ = size(data,4);\n filterSize = size(kernel,2); \n \n paddingStart = 0; moduleStride = stride; imgStride = numImages;\n numModulesX = (imgSizeX - filterSize) / stride + 1; numModulesY = (imgSizeY - filterSize) / stride + 1; numModulesZ = (imgSizeZ - filterSize) / stride + 1;\n target = zeros(numImages, numModulesX, numModulesY, numModulesZ, numFilters, 'single');\n for b = 1 : filter_batch_num\n filterPerThread = 4; imagePerThread = 1;\n kConv.ThreadBlockSize = [32, 4];\n kConv.GridSize = [ceil(numImages/(32 * imagePerThread)), numModulesX * numModulesY * numModulesZ * filter_batch_size / (filterPerThread * 4) ]; % filterPerThread, BlockSize.Y\n target_gpu = feval(kConv,...\n target(:,:,:,:,(b-1)*filter_batch_size+1 : b*filter_batch_size), data, kernel((b-1)*filter_batch_size+1 : b*filter_batch_size,:,:,:,:),...\n numImages, filter_batch_size, imgSizeZ, imgSizeY, imgSizeX, filterSize, ...\n paddingStart, moduleStride, numModulesZ, numModulesY, numModulesX, imgStride);\n target(:,:,:,:,(b-1)*filter_batch_size+1 : b*filter_batch_size) = gather(target_gpu);\n end\n else\n numImages = size(data,1); imgSizeX = size(data,2); imgSizeY = size(data,3); imgSizeZ = size(data,4); \n numFilters = size(kernel,1); filterSize = size(kernel,2); \n \n paddingStart = 0; moduleStride = stride; imgStride = numImages; numGroups = 1;\n numModulesX = (imgSizeX - filterSize) / stride + 1; numModulesY = (imgSizeY - filterSize) / stride + 1; numModulesZ = (imgSizeZ - filterSize) / stride + 1;\n\n filterPerThread = 8; imagePerThread = 1;\n\n kConv.ThreadBlockSize = [32, 4];\n kConv.GridSize = [ceil(numImages/(32 * imagePerThread)), numModulesX * numModulesY * numModulesZ * numFilters / (filterPerThread * 4) ]; % filterPerThread, BlockSize.Y\n\n target = zeros(numImages, numModulesX, numModulesY, numModulesZ, numFilters, 'single');\n\n target_gpu = feval(kConv,...\n target, data, kernel,...\n numImages, numFilters, imgSizeZ, imgSizeY, imgSizeX, filterSize, ...\n paddingStart, moduleStride, numModulesZ, numModulesY, numModulesX, imgStride, numColors, numGroups);\n\n target = gather(target_gpu);\n end\n \nelseif strcmp(task,'weight')\n numColors = size(data,5);\n if numColors == 1\n numImages = size(data,1); imgSizeX = size(data,2); imgSizeY = size(data,3); imgSizeZ = size(data,4); \n numModulesX = size(kernel,2); numModulesY = size(kernel,3); numModulesZ = size(kernel,4); numFilters = size(kernel,5); \n paddingStart = 0; moduleStride = stride; imgStride = numImages; partialSum = numModulesX * numModulesY * numModulesZ;\n filterSize = imgSizeX - stride * (numModulesX - 1);\n \n pixelsPerThread = 5; preLoadCases = 32; scaleOutput = 1 ./ (numImages * partialSum);\n\n kConv.ThreadBlockSize = [16, 8];\n kConv.GridSize = [numFilters*numModulesX*numModulesY*numModulesZ/partialSum/16, ceil(filterSize^3 /(8*pixelsPerThread))];\n\n target = zeros(numFilters, filterSize, filterSize, filterSize, numColors, 'single');\n target_gpu = feval(kConv, ....\n target, data, kernel,...\n numImages, numFilters, numModulesZ, numModulesY, numModulesX, imgSizeZ, imgSizeY, imgSizeX, ...\n filterSize, paddingStart, moduleStride, imgStride, partialSum, scaleOutput);\n\n target = gather(target_gpu);\n else\n numImages = size(data,1); imgSizeX = size(data,2); imgSizeY = size(data,3); imgSizeZ = size(data,4); \n numFilters = size(kernel,5); numModulesX = size(kernel,2); numModulesY = size(kernel,3); numModulesZ = size(kernel,4);\n paddingStart = 0; moduleStride = stride; imgStride = numImages; partialSum = numModulesX * numModulesY * numModulesZ;\n filterSize = imgSizeX - stride * (numModulesX - 1);\n\n preLoadCases = 32; filtersPerThread = 2; colorsPerThread = 8;\n scaleOutput = 1 ./ (numImages * partialSum); numGroups = 1;\n\n kConv.ThreadBlockSize = [16, 8];\n kConv.GridSize = [numFilters*numModulesX*numModulesY*numModulesZ/partialSum/16/filtersPerThread, ceil(filterSize^3 / 8) * (numColors / colorsPerThread)];\n\n target = zeros(numFilters, filterSize, filterSize, filterSize, numColors, 'single');\n target_gpu = feval(kConv, ....\n target, data, kernel,...\n numImages, numFilters, numModulesZ, numModulesY, numModulesX, imgSizeZ, imgSizeY, imgSizeX, ...\n filterSize, paddingStart, moduleStride, imgStride, numColors, numGroups, partialSum, scaleOutput);\n\n target = gather(target_gpu);\n end\nelseif strcmp(task,'backward')\n numColors = size(kernel,5);\n if numColors == 1\n numImages = size(data,1); numModulesX = size(data,2); numModulesY = size(data,3); numModulesZ = size(data,4); moduleStride = stride;\n numFilters = size(kernel,1); filterSize = size(kernel,2); \n\n imgSizeX = stride * (numModulesX - 1) + filterSize; imgSizeY = stride * (numModulesY - 1) + filterSize; imgSizeZ = stride * (numModulesZ - 1) + filterSize; \n paddingStart = 0; imgsPerThread = 2;\n\n kConv.ThreadBlockSize = [16, 16];\n kConv.GridSize = [ceil(numImages/(imgsPerThread *16)), imgSizeZ * ceil(imgSizeY/4) * ceil(imgSizeX/4)];\n\n target = zeros(numImages, imgSizeX, imgSizeY, imgSizeZ, numColors, 'single');\n target_gpu = feval(kConv,....\n target, data, kernel,...\n numModulesZ, numModulesY, numModulesX, numImages, numFilters, filterSize, ...\n imgSizeZ, imgSizeY, imgSizeX, paddingStart, moduleStride);\n\n target = gather(target_gpu);\n else\n numImages = size(data,1); numModulesX = size(data,2); numModulesY = size(data,3); numModulesZ = size(data,4); moduleStride = stride;\n numFilters = size(kernel,1); filterSize = size(kernel,2);\n\n imgSizeX = stride * (numModulesX - 1) + filterSize; imgSizeY = stride * (numModulesY - 1) + filterSize; imgSizeZ = stride * (numModulesZ - 1) + filterSize; \n paddingStart = 0; numGroups = 1;\n \n colorsPerThread = 4; imgsPerThread = 1;\n \n kConv.ThreadBlockSize = [32, 4];\n kConv.GridSize = [ceil(numImages/(imgsPerThread * 32)) * (numColors / (4 * colorsPerThread)), imgSizeZ * imgSizeY * imgSizeX];\n\n target = zeros(numImages, imgSizeX, imgSizeY, imgSizeZ, numColors, 'single');\n target_gpu = feval(kConv,....\n target, data, kernel,...\n numModulesZ, numModulesY, numModulesX, numImages, numFilters, filterSize, ...\n imgSizeZ, imgSizeY, imgSizeX, paddingStart, moduleStride, numColors, numGroups);\n\n target = gather(target_gpu);\n end\nend", "meta": {"author": "zhirongw", "repo": "3DShapeNets", "sha": "6a6cc71a9231051866092c94486ae967ac533d34", "save_path": "github-repos/MATLAB/zhirongw-3DShapeNets", "path": "github-repos/MATLAB/zhirongw-3DShapeNets/3DShapeNets-6a6cc71a9231051866092c94486ae967ac533d34/generative/myConvolve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.499725190906249}} {"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": "% This m-file takes care of synthetic division.\n% By giving one polynomial and one root this function returns \n% the polynomial formed with the other roots of the given polynomial excluding the given root.\n% Keerthi Venkateswara Rao\nfunction coeff_second=syn_division(coeff_function,fun_root_new)\norder_fun=size((coeff_function),2);\ncoeff_second=0;\nfor index=1:size((coeff_function),2)-1\n if index==1\n coeff_second(index)=coeff_function(index); \n else\n coeff_second(index)=coeff_function(index)+fun_root_new*coeff_second(index-1);\n end\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/4313-newton-raphson/syn_division.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.754914997895581, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.4996955164986828}} {"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 [p] = config_hog3x3(c)\n%\n% Copyright Aditya Khosla http://mit.edu/khosla\n%\n% Please cite this paper if you use this code in your publication:\n% A. Khosla, J. Xiao, A. Torralba, A. Oliva\n% Memorability of Image Regions\n% Advances in Neural Information Processing Systems (NIPS) 2012\n%\n\np.grid_spacing = 6; % distance between grid centers\np.patch_size = 24;\np.Mw = 2; % number of spatial scales for spatial pyramid histogram\np.descriptor = 'hog';\np.w = p.patch_size; % boundary for HOG\n\np.pyramid_levels = 2;\np.llcknn = 3;\np.maxsize = 400;\n\n% dictionary parameters\np.dictionary_size = 256;\np.num_images = 500;\np.descPerImage = 2000;\np.num_desc = 500000;\n\np.train_file = '%s/train_hog3x3_%d.mat';\np.test_file = '%s/test_hog3x3_%d.mat';\np.dictionary_file = '%s/dictionary_hog3x3_%d.mat';\n", "meta": {"author": "adikhosla", "repo": "feature-extraction", "sha": "290f3e54cfcb319ca6d1a82f8a0cea4fc31190f8", "save_path": "github-repos/MATLAB/adikhosla-feature-extraction", "path": "github-repos/MATLAB/adikhosla-feature-extraction/feature-extraction-290f3e54cfcb319ca6d1a82f8a0cea4fc31190f8/features/hog3x3/config_hog3x3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.49969549183002665}} {"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": "Wd = function (matvec)\n%take a 12 param matvec, typically WARPDRIVE_MATVEC_INV_000000 and\n%change it to a WARP_DATA\n%Used to test transformations needed to make AFNI use 3dWarpDrive's output\n%as a TLRC transform\n\nif (nargin == 0) matvec = [];\n\nif (isempty(matvec)),\n WARNING: Using preset matvecs!\\n\\n');\n %test case, matvecs from DemoSubj_SurfVol_Alnd_Exp_at2+tlrc\n if (0),\n matvec = [ 0.9709206 -0.04199445 0.01165925 -0.7014965\n 0.07297896 0.9860933 -0.08915191 -0.2648731\n 0.005342953 -0.02306779 0.9538299 -6.124281\n ];\n else\n %that would be WARPDRIVE_MATVEC_INV_000000\n %the proper one to use for WARP_DATA, the one that takes you\n %from +orig to +tlrc\n matvec = [ 1.026725 0.04352641 -0.008482005 0.6798272\n -0.07667368 1.013075 0.09562658 0.8001939\n -0.007605589 0.02425676 1.050765 6.436271\n ];\n end\nelse\n if (length(matvec) ~= 12),\n fprintf(2,'Error: matvec must be 12 elements long\\n');\n end\nend\n\nMfor = [matvec; 0 0 0 1]; %the forward transform\nMbac = inv(Mfor); %the inverse transform\n\n%begin transformation\nmfor = Mfor(1:3, 1:3);\nmbac = Mbac(1:3, 1:3);\nbvec = -Mfor(1:3,4); %Don't ask about the minus sign, see README.attributes:\n %Under WARP_DATA, The forward transformation is [x_map] = [mfor] [x_in] - [bvec];\n %Under Registration Attributes: [xyz_out] = [mat] ([xyz_in]-[xyz_cen]) + [vec] + [xyz_cen]\nsvec = -Mbac(1:3,4);\nbot = [-80 ; -80 ; -65]; %good enough for TT box\ntop = [80 ; 110 ; 85];\n\nWd = [reshape(mfor',1,9) reshape(mbac',1,9) reshape(bvec,1,3) reshape(svec,1,3) [bot'] [top']];\n\nfprintf(1,'Wd = \\n\\n');\nfprintf(1,' %g %g %g %g %g %g\\n',Wd)\nfprintf(1,'\\n\\n');\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/afni/MATVEC_to_WARP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.49969140116738875}} {"text": "function cost = costSymbolSeparation(par, sampleRate, iq)\n\nsymbols = computeSymbolsFromParams(par./[1 1 100 100], sampleRate, iq);\n\n%%\naa = mod(angle(symbols),(pi/4));\nbb = mod(abs(symbols),.25);\n\n%%\naa = min([aa; pi/4-aa]);\nbb = min([bb; .25-bb]);\n\n%%\ncost = sum([aa.^2, bb.^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/17263-developing-custom-modulation-schemes/costSymbolSeparation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240895276224, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.49966290154931575}} {"text": "function problem = prepare_speed_problem(speedpath,speedimgpath,imgidx,nrOutliers)\nload([speedpath,'keypoints-2.mat']);\nimgs = dir([speedimgpath,'*.jpg']);\nnrImgs = length(imgs);\nmodel_3d = double( model_3d' * 0.00000586 );\nnrLandmarks = 11;\ncamera_K = [3003.41, 0, 960;\n 0, 3003.41, 600;\n 0, 0, 1];\ncamera_Kinv = inv(camera_K);\nimg = imread([speedimgpath,imgs(imgidx).name]);\nkeypoints = double( squeeze(prediction_2d(imgidx,:,:))' );\nkeypoints(:,1:nrOutliers) = [1920 * rand(1,nrOutliers); 1200 * rand(1,nrOutliers)];\nkeypoints_2d = camera_Kinv * [keypoints;ones(1,nrLandmarks)];\nkeypoints_2d = keypoints_2d(1:2,:);\nR_gt = quat2rotm( gt_pose(imgidx,1:4) );\nt_gt = gt_pose(imgidx,5:end)';\n\nproblem.N = nrLandmarks;\nproblem.X = model_3d;\nproblem.x = keypoints_2d;\nproblem.FOV = 90;\nproblem.translationBound = 25.0;\nproblem.noiseBoundSq = (0.2)^2;\nproblem.noiseBound = sqrt(problem.noiseBoundSq);\nproblem.depthBound = 0.0;\nproblem.pixNoiseBound = 1e-2;\nproblem.R_gt = R_gt;\nproblem.t_gt = t_gt;\nproblem.img = img;\n\nproblem.keypoints_pix = keypoints;\n\nproblem.camera_K = camera_K;\n\nfprintf('SPEED: N: %d, num outliers: %d, noiseBound: %g.\\n',...\n problem.N,nrOutliers,problem.noiseBound);\n\nif ~check_translation(problem.t_gt,problem.translationBound,problem.FOV)\n error('Problem assumption wrong.')\nend\n\nend", "meta": {"author": "MIT-SPARK", "repo": "CertifiablyRobustPerception", "sha": "dd149d0c54093cfb72a8f912f4ae807635db6f3b", "save_path": "github-repos/MATLAB/MIT-SPARK-CertifiablyRobustPerception", "path": "github-repos/MATLAB/MIT-SPARK-CertifiablyRobustPerception/CertifiablyRobustPerception-dd149d0c54093cfb72a8f912f4ae807635db6f3b/AbsolutePoseEstimation/solvers/prepare_speed_problem.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4996628975353886}} {"text": "function [results] = trackerMain(p, im, bg_area, fg_area, area_resize_factor)\n%TRACKERMAIN contains the main loop of the tracker, P contains all the parameters set in runTracker\n %% INITIALIZATION\n num_frames = numel(p.img_files);\n % used for OTB-13 benchmark\n OTB_rect_positions = zeros(num_frames, 4);\n\tpos = p.init_pos;\n target_sz = p.target_sz;\n\tnum_frames = numel(p.img_files);\n % patch of the target + padding\n patch_padded = getSubwindow(im, pos, p.norm_bg_area, bg_area);\n % initialize hist model\n new_pwp_model = true;\n [bg_hist, fg_hist] = updateHistModel(new_pwp_model, patch_padded, bg_area, fg_area, target_sz, p.norm_bg_area, p.n_bins, p.grayscale_sequence);\n new_pwp_model = false;\n % Hann (cosine) window\n if isToolboxAvailable('Signal Processing Toolbox')\n hann_window = single(hann(p.cf_response_size(1)) * hann(p.cf_response_size(2))');\n else\n hann_window = single(myHann(p.cf_response_size(1)) * myHann(p.cf_response_size(2))');\n end\n % gaussian-shaped desired response, centred in (1,1)\n % bandwidth proportional to target size\n output_sigma = sqrt(prod(p.norm_target_sz)) * p.output_sigma_factor / p.hog_cell_size;\n y = gaussianResponse(p.cf_response_size, output_sigma);\n yf = fft2(y);\n \n %Context patches\n offset = [-target_sz(1) 0; 0 -target_sz(2); target_sz(1) 0; 0 target_sz(2)];\n elapsed_time =0; \n \n %% SCALE ADAPTATION INITIALIZATION\n if p.scale_adaptation\n % Code from DSST\n scale_factor = 1;\n base_target_sz = target_sz;\n scale_sigma = sqrt(p.num_scales) * p.scale_sigma_factor;\n ss = (1:p.num_scales) - ceil(p.num_scales/2);\n ys = exp(-0.5 * (ss.^2) / scale_sigma^2);\n ysf = single(fft(ys));\n if mod(p.num_scales,2) == 0\n scale_window = single(hann(p.num_scales+1));\n scale_window = scale_window(2:end);\n else\n scale_window = single(hann(p.num_scales));\n end;\n\n ss = 1:p.num_scales;\n scale_factors = p.scale_step.^(ceil(p.num_scales/2) - ss);\n\n if p.scale_model_factor^2 * prod(p.norm_target_sz) > p.scale_model_max_area\n p.scale_model_factor = sqrt(p.scale_model_max_area/prod(p.norm_target_sz));\n end\n\n scale_model_sz = floor(p.norm_target_sz * p.scale_model_factor);\n % find maximum and minimum scales\n min_scale_factor = p.scale_step ^ ceil(log(max(5 ./ bg_area)) / log(p.scale_step));\n max_scale_factor = p.scale_step ^ floor(log(min([size(im,1) size(im,2)] ./ target_sz)) / log(p.scale_step));\n end\n\n %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%\n %% MAIN LOOP\n for frame = 1:num_frames\n \n im = imread(fullfile(p.img_path, p.img_files{frame}));\n tic()\n \n if frame>1 \n \n\t %% TESTING step\n % extract patch of size bg_area and resize to norm_bg_area\n im_patch_cf = getSubwindow(im, pos, p.norm_bg_area, bg_area);\n pwp_search_area = round(p.norm_pwp_search_area / area_resize_factor);\n % extract patch of size pwp_search_area and resize to norm_pwp_search_area\n im_patch_pwp = getSubwindow(im, pos, p.norm_pwp_search_area, pwp_search_area);\n % compute feature map\n xt = getFeatureMap(im_patch_cf, p.feature_type, p.cf_response_size, p.hog_cell_size);\n % apply Hann window\n xt_windowed = bsxfun(@times, hann_window, xt);\n % compute FFT\n xtf = fft2(xt_windowed);\n % Correlation between filter and test patch gives the response\n % Solve diagonal system per pixel.\n if p.den_per_channel\n% \t\t\t\thf = hf_num ./ (hf_den + p.lambda);\n hf = hf_num ./ hf_den;\n else\n\t\t\t\t%hf = bsxfun(@rdivide, hf_num, sum(hf_den, 3)+p.lambda);\n hf = bsxfun(@rdivide, hf_num, sum(hf_den, 3));\n end\n %response_cf = ensure_real(ifft2(sum(conj(hf) .* xtf, 3)));\n response_cf = ensure_real(ifft2(sum(hf .* xtf, 3)));\n \n \n % Crop square search region (in feature pixels).\n response_cf = cropFilterResponse(response_cf, ...\n floor_odd(p.norm_delta_area / p.hog_cell_size));\n if p.hog_cell_size > 1\n % Scale up to match center likelihood resolution.\n response_cf = mexResize(response_cf, p.norm_delta_area,'auto');\n %response_cf = imresize(response_cf, p.norm_delta_area,'nearest');\n end\n\n [likelihood_map] = getColourMap(im_patch_pwp, bg_hist, fg_hist, p.n_bins, p.grayscale_sequence);\n % (TODO) in theory it should be at 0.5 (unseen colors shoud have max entropy)\n likelihood_map(isnan(likelihood_map)) = 0;\n\n % each pixel of response_pwp loosely represents the likelihood that\n % the target (of size norm_target_sz) is centred on it\n response_pwp = getCenterLikelihood(likelihood_map, p.norm_target_sz);\n\n %% ESTIMATION\n response = mergeResponses(response_cf, response_pwp, p.merge_factor, p.merge_method);\n [row, col] = find(response == max(response(:)), 1);\n center = (1+p.norm_delta_area) / 2;\n pos = pos + ([row, col] - center) / area_resize_factor;\n rect_position = [pos([2,1]) - target_sz([2,1])/2, target_sz([2,1])];\n\n %% SCALE SPACE SEARCH\n if p.scale_adaptation\n im_patch_scale = getScaleSubwindow(im, pos, base_target_sz, scale_factor * scale_factors, scale_window, scale_model_sz, p.hog_scale_cell_size);\n xsf = fft(im_patch_scale,[],2);\n scale_response = real(ifft(sum(sf_num .* xsf, 1) ./ (sf_den + p.lambda) ));\n recovered_scale = ind2sub(size(scale_response),find(scale_response == max(scale_response(:)), 1));\n %set the scale\n scale_factor = scale_factor * scale_factors(recovered_scale);\n\n if scale_factor < min_scale_factor\n scale_factor = min_scale_factor;\n elseif scale_factor > max_scale_factor\n scale_factor = max_scale_factor;\n end\n % use new scale to update bboxes for target, filter, bg and fg models\n target_sz = round(base_target_sz * scale_factor);\n avg_dim = sum(target_sz)/2;\n bg_area = round(target_sz + avg_dim);\n if(bg_area(2)>size(im,2)), bg_area(2)=size(im,2)-1; end\n if(bg_area(1)>size(im,1)), bg_area(1)=size(im,1)-1; end\n\n bg_area = bg_area - mod(bg_area - target_sz, 2);\n fg_area = round(target_sz - avg_dim * p.inner_padding);\n fg_area = fg_area + mod(bg_area - fg_area, 2);\n % Compute the rectangle with (or close to) params.fixed_area and\n % same aspect ratio as the target bboxgetScaleSubwindow\n area_resize_factor = sqrt(p.fixed_area/prod(bg_area));\n end\n\n if p.visualization_dbg==1\n mySubplot(2,1,5,1,im_patch_cf,'FG+BG','gray');\n mySubplot(2,1,5,2,likelihood_map,'obj.likelihood','parula');\n mySubplot(2,1,5,3,response_cf,'CF response','parula');\n mySubplot(2,1,5,4,response_pwp,'center likelihood','parula');\n mySubplot(2,1,5,5,response,'merged response','parula');\n drawnow\n end\n end\n\n %% TRAINING\n % extract patch of size bg_area and resize to norm_bg_area\n im_patch_bg = getSubwindow(im, pos, p.norm_bg_area, bg_area);\n % compute feature map, of cf_response_size\n xt = getFeatureMap(im_patch_bg, p.feature_type, p.cf_response_size, p.hog_cell_size);\n % apply Hann window\n xt = bsxfun(@times, hann_window, xt);\n % compute FFT\n xtf = fft2(xt);\n kf = (conj(xtf) .* xtf); %/ prod(p.cf_response_size);\n \n kfn = zeros([size(xtf) length(offset)]);\n for j=1:length(offset)\n %obtain a subwindow close to target for regression to 0\n\t\tim_patch_bgn = getSubwindow(im, pos+offset(j,:), p.norm_bg_area, bg_area);\n % compute feature map, of cf_response_size\n xtn = getFeatureMap(im_patch_bgn, p.feature_type, p.cf_response_size, p.hog_cell_size);\n % apply Hann window\n xtn = bsxfun(@times, hann_window, xtn);\n % compute FFT\n xtfn = fft2(xtn);\n kfn(:,:,:,j) = conj(xtfn) .*xtfn; %/ prod(p.cf_response_size);\n end\n \n %% FILTER UPDATE\n % Compute expectations over circular shifts,\n % therefore divide by number of pixels.\n\t\tnew_hf_num = bsxfun(@times, conj(xtf),yf); %/ prod(p.cf_response_size);\n\t\tnew_hf_den = kf + p.lambda + p.lambda2.*sum(kfn,4);\t\t\n \n if frame == 1\n % first frame, train with a single image\n\t\t hf_den = new_hf_den;\n\t\t hf_num = new_hf_num; \n\t\telse\n\t\t % subsequent frames, update the model by linear interpolation\n \thf_den = (1 - p.learning_rate_cf) * hf_den + p.learning_rate_cf * new_hf_den;\n\t \t \thf_num = (1 - p.learning_rate_cf) * hf_num + p.learning_rate_cf * new_hf_num;\n \n %% BG/FG MODEL UPDATE\n % patch of the target + padding\n [bg_hist, fg_hist] = updateHistModel(new_pwp_model, im_patch_bg, bg_area, fg_area, target_sz, p.norm_bg_area, p.n_bins, p.grayscale_sequence, bg_hist, fg_hist, p.learning_rate_pwp);\n end\n\n %% SCALE UPDATE\n if p.scale_adaptation\n im_patch_scale = getScaleSubwindow(im, pos, base_target_sz, scale_factor*scale_factors, scale_window, scale_model_sz, p.hog_scale_cell_size);\n xsf = fft(im_patch_scale,[],2);\n new_sf_num = bsxfun(@times, ysf, conj(xsf));\n new_sf_den = sum(xsf .* conj(xsf), 1);\n if frame == 1,\n sf_den = new_sf_den;\n sf_num = new_sf_num;\n else\n sf_den = (1 - p.learning_rate_scale) * sf_den + p.learning_rate_scale * new_sf_den;\n sf_num = (1 - p.learning_rate_scale) * sf_num + p.learning_rate_scale * new_sf_num;\n end\n end\n\n % update bbox position\n if frame==1, rect_position = [pos([2,1]) - target_sz([2,1])/2, target_sz([2,1])]; end\n\n rect_position_padded = [pos([2,1]) - bg_area([2,1])/2, bg_area([2,1])];\n\n OTB_rect_positions(frame,:) = rect_position;\n\n if p.fout > 0, fprintf(p.fout,'%.2f,%.2f,%.2f,%.2f\\n', rect_position(1),rect_position(2),rect_position(3),rect_position(4)); end\n\n elapsed_time = elapsed_time + toc();\n \n %% VISUALIZATION\n if p.visualization == 1\n if isToolboxAvailable('Computer Vision System Toolbox')\n im = insertShape(im, 'Rectangle', rect_position, 'LineWidth', 4, 'Color', 'black');\n im = insertShape(im, 'Rectangle', rect_position_padded, 'LineWidth', 4, 'Color', 'yellow');\n % Display the annotated video frame using the video player object.\n step(p.videoPlayer, im);\n else\n figure(1)\n imshow(im)\n rectangle('Position',rect_position, 'LineWidth',2, 'EdgeColor','g');\n rectangle('Position',rect_position_padded, 'LineWidth',2, 'LineStyle','--', 'EdgeColor','b');\n drawnow\n end\n end\n end\n \n % save data for OTB-13 benchmark\n results.type = 'rect';\n results.res = OTB_rect_positions;\n results.fps = num_frames/(elapsed_time );\nend\n\n% Reimplementation of Hann window (in case signal processing toolbox is missing)\nfunction H = myHann(X)\n H = .5*(1 - cos(2*pi*(0:X-1)'/(X-1)));\nend\n\n% We want odd regions so that the central pixel can be exact\nfunction y = floor_odd(x)\n y = 2*floor((x-1) / 2) + 1;\nend\n\nfunction y = ensure_real(x)\n assert(norm(imag(x(:))) <= 1e-5 * norm(real(x(:))));\n y = real(x);\nend\n", "meta": {"author": "thias15", "repo": "Context-Aware-CF-Tracking", "sha": "2b1198a24aea6420d28987f68622f50a2970ffac", "save_path": "github-repos/MATLAB/thias15-Context-Aware-CF-Tracking", "path": "github-repos/MATLAB/thias15-Context-Aware-CF-Tracking/Context-Aware-CF-Tracking-2b1198a24aea6420d28987f68622f50a2970ffac/STAPLE_CA/trackerMain.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.49966289352146104}} {"text": "%% ArUco Grid Board Image Demo\n% This example shows how to create an ArUco grid board image.\n%\n% Sources:\n%\n% * \n%\n\n%% Board\n\n% params\nmarkersX = 5; % Number of markers in X direction\nmarkersY = 7; % Number of markers in Y direction\nmarkerLength = 60; % Marker side length (in pixels)\nmarkerSeparation = 15; % Separation between two consecutive markers in the grid (in pixels)\ndictionaryId = '6x6_250'; % dictionary id\nmargins = markerSeparation; % Margins size (in pixels)\nborderBits = 1; % Number of bits in marker borders\n\nimageSize = [markersY, markersX] .* ...\n (markerLength + markerSeparation) - markerSeparation + 2 * margins;\n\n% create board\ndictionary = {'Predefined', dictionaryId};\nboard = {'GridBoard', ...\n markersX, markersY, markerLength, markerSeparation, dictionary};\n\n%% Display\n\n% show created board\nboardImage = cv.drawPlanarBoard(board, fliplr(imageSize), ...\n 'MarginSize',margins, 'BorderBits',borderBits);\nimshow(boardImage), title('GridBoard')\n\n% save image\nimwrite(boardImage, fullfile(tempdir(),'GridBoard.png'));\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/opencv_contrib/samples/aruco_create_board_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.49965715280950285}} {"text": "function angles = wrapMinusPiPifast(angles)\n\ntol = 0.001;\n\nangles(angles < -pi) = angles(angles < -pi) + 2*pi;\nangles(angles < -pi) = angles(angles < -pi) + 2*pi;\n\nangles(angles > pi) = angles(angles > pi) - 2*pi;\nangles(angles > pi) = angles(angles > pi) - 2*pi;\n\nangles(angles == pi) = angles(angles == pi) - tol;\nangles(angles == -pi) = angles(angles == -pi) + tol;\n\nassert(~any(angles > pi));\nassert(~any(angles < -pi));\n\nend", "meta": {"author": "eldar", "repo": "deepcut", "sha": "096e2d174ddf2fbdc61458d9e7e6c6e897eac16c", "save_path": "github-repos/MATLAB/eldar-deepcut", "path": "github-repos/MATLAB/eldar-deepcut/deepcut-096e2d174ddf2fbdc61458d9e7e6c6e897eac16c/lib/utils/wrapMinusPiPifast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.49965541488538884}} {"text": "function [Population,succ1,succ2,Fitness] = First_Stage_EnvironmentalSelection(Population,N,isOrigin)\n% The environmental selection of SPEA2\n\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 Kangjia Qiao\n\n %% Calculate the fitness of each solution\n if isOrigin==1\n Fitness = CalFitness(Population.objs,Population.cons);\n else\n Fitness = CalFitness(Population.objs);\n end\n\n %% Environmental selection\n Next = Fitness < 1;\n if sum(Next) < N\n [~,Rank] = sort(Fitness);\n Next(Rank(1:N)) = true;\n elseif sum(Next) > N\n Del = Truncation(Population(Next).objs,sum(Next)-N);\n Temp = find(Next);\n Next(Temp(Del)) = false;\n end\n\n % Population for next generation\n Population = Population(Next);\n Fitness = Fitness(Next);\n % Sort the population\n [Fitness,rank] = sort(Fitness);\n Population = Population(rank);\n\n %% calculate success rate1\n off_index = Next(1+N:2*N);\n succ1 = zeros(1,length(off_index));\n for j = 1:length(off_index)\n if off_index(j) == 1\n succ1(j)=1;\n end\n end\n %% calculate success rate2\n off_index = Next(1+2*N:end);\n succ2 = zeros(1,length(off_index));\n for j = 1:length(off_index)\n if off_index(j) == 1\n succ2(j)=1;\n end\n end\nend\n\nfunction Del = Truncation(PopObj,K)\n% Select part of the solutions by truncation\n\n %% Truncation\n Distance = pdist2(PopObj,PopObj);\n Distance(logical(eye(length(Distance)))) = inf;\n Del = false(1,size(PopObj,1));\n while sum(Del) < K\n Remain = find(~Del);\n Temp = sort(Distance(Remain,Remain),2);\n [~,Rank] = sortrows(Temp);\n Del(Remain(Rank(1))) = true;\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/URCMO/First_Stage_EnvironmentalSelection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.49965540723647406}} {"text": "%NUMROWS Number of rows in matrix\n%\n% NR = NUMROWS(M) is the number of rows in the matrix M.\n%\n% Notes::\n% - Readable shorthand for SIZE(M,1);\n%\n% See also NUMCOLS, SIZE.\n\n% Copyright (C) 1993-2019 Peter I. Corke\n%\n% This file is part of The Spatial Math Toolbox for MATLAB (SMTB).\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, including without limitation the rights\n% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n% of the Software, and to permit persons to whom the Software is furnished to do\n% so, subject to the following conditions:\n%\n% The above copyright notice and this permission notice shall be included in all\n% 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, FITNESS\n% FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n% COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n% IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n% CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n%\n% https://github.com/petercorke/spatial-math\n\nfunction r = numrows(m)\n\n\tr = size(m, 1);\n", "meta": {"author": "petercorke", "repo": "spatialmath-matlab", "sha": "6eeff4a79f14286705560b84f1fe72e0b7e0e7f7", "save_path": "github-repos/MATLAB/petercorke-spatialmath-matlab", "path": "github-repos/MATLAB/petercorke-spatialmath-matlab/spatialmath-matlab-6eeff4a79f14286705560b84f1fe72e0b7e0e7f7/numrows.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.4996554061816583}} {"text": "%% Copyright (C) 2016 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 besselj (@var{alpha}, @var{x})\n%% Symbolic Bessel function of the first kind.\n%%\n%% Example:\n%% @example\n%% @group\n%% syms n x\n%% A = 2*besselj(n,x)\n%% @result{} A = (sym) 2\u22c5besselj(n, x)\n%% diff(A)\n%% @result{} (sym) besselj(n - 1, x) - besselj(n + 1, x)\n%% @end group\n%% @end example\n%%\n%% @seealso{@@sym/bessely, @@sym/besseli, @@sym/besselk}\n%% @end defmethod\n\nfunction J = besselj(n, x)\n\n if (nargin ~= 2)\n print_usage ();\n end\n\n J = elementwise_op ('besselj', sym(n), sym(x));\n\nend\n\n\n%!test\n%! X = [1 2 3; 4 5 6];\n%! ns = [sym(0) 1 -2; sym(1)/2 -sym(3)/2 pi];\n%! n = double(ns);\n%! A = double(besselj(ns, X));\n%! B = besselj(n, X);\n%! assert (all (all (abs (A - B) < 50*eps*abs(A))))\n\n%!test\n%! % roundtrip\n%! syms x\n%! A = besselj(2, 10);\n%! q = besselj(2, x);\n%! h = function_handle(q);\n%! B = h(10);\n%! assert (abs (A - B) <= eps*abs(A))\n\n%!error besselj(sym('x'))\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/besselj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.4996554023572009}} {"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 fnew=removeisolatedsurf(v,f,maxdiameter)\n%\n% fnew=removeisolatedsurf(v,f,maxdiameter)\n%\n% remove disjointed surface fragment filtered by using mesh diameter\n%\n% author: Qianqian Fang, \n%\n% input:\n% v: list of nodes of the input surface\n% f: list of triangles of the input surface\n% maxdiameter: maximum bounding box size for surface removal\n%\n% ouput:\n% fnew: new face list after removing the components smaller than \n% maxdiameter\n%\n% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)\n%\n\nfc=finddisconnsurf(f);\nfor i=1:length(fc)\n xdia=v(fc{i},1);\n xdia=max(xdia(:))-min(xdia(:));\n if(xdia<=maxdiameter) fc{i}=[]; continue; end\n ydia=v(fc{i},2);\n ydia=max(ydia(:))-min(ydia(:));\n if(ydia<=maxdiameter) fc{i}=[]; continue; end\n zdia=v(fc{i},3);\n zdia=max(zdia(:))-min(zdia(:));\n if(zdia<=maxdiameter) fc{i}=[]; continue; end\nend\nfnew=[];\nfor i=1:length(fc)\n\tif(length(fc{i})) fnew=[fnew;fc{i}]; end\nend\nif(size(fnew,1)~=size(f,1))\n fprintf(1,'removed %d elements of small isolated surfaces',size(f,1)-size(fnew,1)); \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/iso2mesh/removeisolatedsurf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6723316860482762, "lm_q1q2_score": 0.49965540024756927}} {"text": "% Short test script for running algorithms related to the glottal source\n%\n% Please find the path management in the startup.m script in the root directory\n% of this repository. Note that by starting matlab in the root directory, this\n% script should automatically run. If it is not the case, you can also move to the\n% root directory and run this script manually. \n%\n% License\n% This file is under the LGPL license, you can\n% redistribute it and/or modify it under the terms of the GNU Lesser General \n% Public License as published by the Free Software Foundation, either version 3 \n% of the License, or (at your option) any later version. This file is\n% distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; \n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n% PARTICULAR PURPOSE. See the GNU Lesser General Public License for more\n% details.\n%\n% This function is part of the Covarep project: http://covarep.github.io/covarep\n%\n\nclear all;\n\n% Settings\nF0min = 80; % Minimum F0 set to 80 Hz\nF0max = 500; % Maximum F0 set to 80 Hz\nframe_shift = 10; % Frame shift in ms\n\n% Load soundfile\n[x,fs] = audioread(['howtos' filesep 'arctic_a0007.wav']);\n\n% Check the speech signal polarity\npolarity = polarity_reskew(x,fs);\nx=polarity*x;\n\n% Extract the pitch and voicing information\n[srh_f0,srh_vuv,srh_vuvc,srh_time] = pitch_srh(x,fs,F0min,F0max,frame_shift);\n\n% Extract the maximum voiced frequency\n[max_voiced_freq] = maximum_voiced_frequency(x,fs,srh_f0.*srh_vuv,srh_time);\n\n% Creaky probability estimation\nwarning off\ntry\n [creak_pp,creak_bin] = detect_creaky_voice(x,fs); % Detect creaky voice\n creak=interp1(creak_bin(:,2),creak_bin(:,1),1:length(x));\n creak(creak<0.5)=0; creak(creak>=0.5)=1;\n do_creak=1;\ncatch\n disp('Version or toolboxes do not support neural network object used in creaky voice detection. Creaky detection skipped.')\n creak=zeros(length(x),1);\n creak_pp=zeros(length(x),2);\n creak_pp(:,2)=1:length(x);\n do_creak=0;\nend\nwarning on\n\n% GCI estimation\nsd_gci = gci_sedreams(x,fs,median(srh_f0),1); % SEDREAMS\nse_gci = se_vq(x,fs,median(srh_f0),creak); % SE-VQ\n\n%res = lpcresidual(x,25/1000*fs,5/1000*fs,fs/1000+2); % LP residual\nres = maxlpresidual(x,fs,round(fs/1000)+2);\n\nm = mdq(res,fs,se_gci); % Maxima dispersion quotient measurement\n\nps = peakslope(x,fs); % peakSlope extraction\n\n[gf_iaif,gfd_iaif] = iaif_ola(x,fs); % Glottal flow (and derivative) by the IAIF method\n\ndgf_cc = complex_cepstrum(x,fs,sd_gci,srh_f0,srh_vuv); % Glottal flow derivative by the complex cesptrum-based method\n\n[NAQ,QOQ,H1H2,HRF,PSP] = get_vq_params(gf_iaif,gfd_iaif,fs,se_gci); % Estimate conventional glottal parameters\n\n% Estimate the Rd parameter of the Liljencrants-Fant (LF) model\nsrh_f0(find(srh_f0==0)) = 100;\nopt = sin_analysis();\nopt.fharmonic = true;\nopt.use_ls = false;\nopt.debug = 0;\nframes = sin_analysis(x, fs, [srh_time(:),srh_f0(:)], opt);\nrds = rd_msp(frames, fs);\n\n% Extract Cepstral Peak Prominence \nCPPv = cpp( x, fs, 1, 'mean' );\n\n% Plots\nt=(0:length(x)-1)/fs;\n\nfig(1) = subplot(311);\n plot(t,x, 'b');\n hold on\n plot(srh_time, srh_vuv, 'g');\n stem(sd_gci,ones(1,length(sd_gci))*-.1,'m');\n stem(se_gci,ones(1,length(se_gci))*-.1,'r');\n legend('Speech signal','Voicing (SRH)', 'GCI (SEDREAMS)','GCI (SE-VQ)');\n xlabel('Time [s]');\n ylabel('Amplitude');\n\nfig(2) = subplot(312);\n plot(srh_time, srh_f0, 'r');\n legend('f0 (SRH)');\n xlabel('Time [s]');\n ylabel('Hz');\n \nfig(3) = subplot(313);\n plot(srh_time, max_voiced_freq, 'g');\n legend('Maximum voiced frequency');\n xlabel('Time [s]');\n ylabel('Hz');\n\nlinkaxes(fig, 'x');\nxlim([0 srh_time(end)]);\nfigure\n \nfig(4) = subplot(311);\n plot(t,x, 'b');\n hold on\n plot(ps(:,1), ps(:,2),'--b');\n plot(m(:,1),m(:,2),'m');\n plot(rds(:,1), rds(:,2), 'r');\n legend('Speech signal','PeakSlope','MDQ','Rd');\n xlabel('Time [s]');\n\nfig(5) = subplot(312);\n plot(t,x, 'b');\n hold on\n plot(t,norm(x)*gf_iaif./norm(gf_iaif), 'g');\n plot(creak_pp(:,2)/fs,creak_pp(:,1),'r')\n xlabel('Time [s]');\n ylabel('Amplitude');\n legend('Speech signal','Glottal flow (IAIF)','Creaky voice probability','Location','NorthWest');\n \nfig(6) = subplot(313);\n plot(t,x, 'b');\n hold on\n plot(t,norm(x)*dgf_cc./norm(dgf_cc), 'r'); \n xlabel('Time [s]');\n ylabel('Amplitude');\n legend('Speech signal','Glottal flow derivative (CC)');\n\nlinkaxes(fig, 'x');\nxlim([0 srh_time(end)]);\n", "meta": {"author": "covarep", "repo": "covarep", "sha": "5a2be5d6b776f14a0b275c69fde90eb13849e60d", "save_path": "github-repos/MATLAB/covarep-covarep", "path": "github-repos/MATLAB/covarep-covarep/covarep-5a2be5d6b776f14a0b275c69fde90eb13849e60d/howtos/HOWTO_glottalsource.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.49965539747792787}} {"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 x = rbmup(rbm, x)\n x = sigm(repmat(rbm.c', size(x, 1), 1) + x * rbm.W');\nend\n", "meta": {"author": "rasmusbergpalm", "repo": "DeepLearnToolbox", "sha": "5df2801f2196a2afddb7a87f800e63e153c34995", "save_path": "github-repos/MATLAB/rasmusbergpalm-DeepLearnToolbox", "path": "github-repos/MATLAB/rasmusbergpalm-DeepLearnToolbox/DeepLearnToolbox-5df2801f2196a2afddb7a87f800e63e153c34995/DBN/rbmup.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891479496521, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4996140638452899}} {"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": " function [PhaseLockingData] = bz_PhaseModulation(varargin)\n% USAGE\n%[PhaseLockingData] = bz_PhaseModulation(varargin)\n% \n% INPUTS\n% spikes -spike time cellinfo struct\n%\n% lfp -lfp struct with a single channel from bz_GetLFP()\n%\n% passband -frequency range for phase modulation [lowHz highHz] form\n%\n% intervals -(optional) may specify timespans over which to calculate \n% phase modulation. Formats accepted: tstoolbox intervalSet\n% or a 2column matrix of [starts stops] in seconds\n%\n% samplingRate -specifies lfp sampling frequency default=1250\n%\n% method -method selection for how to generate phase, \n% possibilties are: 'hilbert' (default) or 'wavelet'\n%\n% powerThresh -integer power threshold to use as cut off, \n% measured in standard deviations (default = 2)\n%\n% plotting -logical if you want to plot, false if not, default=true\n%\n% saveMat -logical to save cellinfo .mat file with results, default=false\n%\n%\n% OUTPUTS\n%\n% phasedistros - Spike distribution perecentages for each cell in each bin\n% specified by phasebins\n%\n% phasebins - 180 bins spanning from 0 to 2pi\n%\n% phasestats - ncellsx1 structure array with following (via\n% CircularDistribution.m from FMAToolbox)\n% phasestats.m mean angle\n% phasestats.mode distribution mode\n% phasestats.k concentration\n% phasestats.p p-value for Rayleigh test\n% phasestats.r mean resultant length\n%\n% \n% Calculates distribution of spikes over various phases from a specified\n% cycle of an lfp vector. Phase 0 means peak of lfp wave.\n%\n% Brendon Watson 2015\n% edited by david tingley, 2017\n\n%% defaults\np = inputParser;\naddRequired(p,'spikes',@bz_isCellInfo);\naddRequired(p,'lfp',@bz_isLFP);\naddRequired(p,'passband',@isnumeric)\naddParameter(p,'intervals',[0 inf],@isnumeric)\naddParameter(p,'samplingRate',1250,@isnumeric)\naddParameter(p,'method','hilbert',@isstr)\naddParameter(p,'plotting',true,@islogical)\naddParameter(p,'numBins',180,@isnumeric)\naddParameter(p,'powerThresh',2,@isnumeric)\naddParameter(p,'saveMat',false,@islogical)\n\nparse(p,varargin{:})\n\nspikes = p.Results.spikes;\nlfp = p.Results.lfp;\npassband = p.Results.passband;\n\nintervals = p.Results.intervals; % interval(s) over which to calculate\nsamplingRate = p.Results.samplingRate; % sampling rate of continuous signal (LFP)\nmethod = p.Results.method; \nplotting = p.Results.plotting;\nnumBins = p.Results.numBins;\npowerThresh = p.Results.powerThresh;\nsaveMat = p.Results.saveMat;\n\n%% Get phase for every time point in LFP\nswitch lower(method)\n case ('hilbert')\n [b a] = butter(3,[passband(1)/(samplingRate/2) passband(2)/(samplingRate/2)],'bandpass'); % order 3\n% [b a] = cheby2(4,20,passband/(samplingRate/2));\n filt = FiltFiltM(b,a,double(lfp.data(:,1)));\n power = fastrms(filt,ceil(samplingRate./passband(1))); % approximate power is frequency band\n hilb = hilbert(filt);\n lfpphase = mod(angle(hilb),2*pi);\n clear fil\n case ('wavelet')% Use Wavelet transform to calulate the signal phases\n% nvoice = 12;\n% freqlist= 2.^(log2(passband(1)):1/nvoice:log2(passband(2)));\n% error('awt_freqlist, where did this come from?')\n% wt = awt_freqlist(double(lfp.data(:,1)), samplingRate, freqlist);\n% amp = (real(wt).^2 + imag(wt).^2).^.5;\n% phase = atan2(imag(wt),real(wt));\n% [~,mIdx] = max(amp'); %get index with max power for each timepiont\n% for i = 1:size(wt,1)\n% lfpphase(i) = phase(i,mIdx(i));\n% end\n% lfpphase = mod(lfpphase,2*pi);\n [wave,f,t,coh,wphases,raw,coi,scale,priod,scalef]=getWavelet(double(lfp.data(:,1)),samplingRate,passband(1),passband(2),8,0);\n [~,mIdx]=max(wave);%get index max power for each timepiont\n pIdx=mIdx'+[0;size(f,2).*cumsum(ones(size(t,1)-1,1))];%converting to indices that will pick off single maxamp index from each of the freq-based phases at eacht timepoint\n lfpphases=wphases(pIdx);%get phase of max amplitude wave at each timepoint\n lfpphases = mod(lfpphases,2*pi);%covert to 0-2pi rather than -pi:pi\n% % case ('peaks')\n % not yet coded\n % filter, smooth, diff = 0, diffdiff = negative\nend\n\n%% update intervals to remove sub-threshold power periods\ndisp('finding intervals below power threshold...')\nthresh = mean(power) + std(power)*powerThresh;\nminWidth = (samplingRate./passband(2)) * 2; % set the minimum width to two cycles\n\nbelow=find(power0;\n ends=find(diff(below)~=1);\n ends(end+1)=length(below);\n ends=sort(ends);\n lengths=diff(ends);\n stops=below(ends)./samplingRate;\n starts=lengths./samplingRate;\n starts = [1; starts];\n below_thresh(:,2)=stops;\n below_thresh(:,1)=stops-starts;\nelse\n below_thresh=[];\nend\n\n% now merge interval sets from input and power threshold\nintervals = SubtractIntervals(intervals,below_thresh); % subtract out low power intervals\n\nintervals = intervals(diff(intervals')>minWidth./samplingRate,:); % only keep min width epochs\n\n\n%% Get phases for each spike for each cell\nh = [];\n% cum_spkphases = [];\nphasebins=[];\nspkphases = cell(1,length(spikes.times));\nfor a = 1:length(spikes.times)\n \n bools = InIntervals(spikes.times{a},intervals);\n s =spikes.times{a}(bools);\n% s = spikes{a};\n if isempty(s) \n phasedistros(:,a) = zeros(numBins,1);\n phasestats.m(a) = nan;\n phasestats.r(a) = nan;\n phasestats.k(a) = nan;\n phasestats.p(a) = nan;\n phasestats.mode(a) = nan;\n spkphases{a} = nan;\n else\n spkphases{a} = lfpphase(ceil(s*samplingRate));\n\n% cum_spkphases = vertcat(cum_spkphases, spkphases{a});\n\n\n %% Gather binned counts and stats (incl Rayleigh Test)\n [phasedistros(:,a),phasebins,ps]=CircularDistribution(spkphases{a},'nBins',numBins);\n phasestats.m(a) = mod(ps.m,2*pi);\n phasestats.r(a) = ps.r;\n phasestats.k(a) = ps.k;\n phasestats.p(a) = ps.p;\n phasestats.mode(a) = ps.mode;\n\n %% plotting \n if plotting\n if ~exist('PhaseModulationFig','dir')\n mkdir('PhaseModulationFig');\n end\n h(end+1) = figure;\n hax = subplot(1,2,1); \n rose(spkphases{a})\n title(hax,['Cell #' num2str(a) '. Rayleigh p = ' num2str(phasestats.p(a)) '.'])\n\n hax = subplot(1,2,2); \n bar(phasebins*180/pi,phasedistros(:,a))\n xlim([0 360])\n set(hax,'XTick',[0 90 180 270 360]) \n hold on;\n plot([0:360],cos(pi/180*[0:360])*0.05*max(phasedistros(:,a))+0.95*max(phasedistros(:,a)),'color',[.7 .7 .7])\n set(h(end),'name',['PhaseModPlotsForCell' num2str(a)]);\n print(fullfile('PhaseModulationFig',['PhaseModPlotsForCell' num2str(a)]),'-dpng','-r0');\n end\n end\nend\n%% Cumulative effect across all spikes from all cells... not saving these stats for now\n% phasebins=[];\n% if length(cum_spkphases) > 10\n% [cpd,phasebins,cps]=CircularDistribution(cum_spkphases,'nBins',180);\n% cRp = cps.p;\n% \n% if plotting\n% h(end+1) = figure;\n% hax = subplot(1,2,1); \n% rose(cum_spkphases)\n% title(hax,['All Spikes/Cells Accumulated. Rayleigh p = ' num2str(cps.p) '.'])\n% \n% hax = subplot(1,2,2); \n% bar(phasebins*180/pi,cpd)\n% xlim([0 360])\n% set(hax,'XTick',[0 90 180 270 360]) \n% hold on;\n% plot([0:360],cos(pi/180*[0:360])*0.05*max(cpd)+0.95*max(cpd),'color',[.7 .7 .7])\n% set(h(end),'name',['PhaseModPlotsForAllCells']);\n% end\n% end\n\ndetectorName = 'bz_PhaseModulation';\nchannels = lfp.channels;\ndetectorParams = v2struct(intervals,samplingRate,method,plotting,numBins,...\n passband,powerThresh,channels);\n\nPhaseLockingData = v2struct(phasedistros,phasebins,...\n phasestats,spkphases,...\n detectorName, detectorParams);\nPhaseLockingData.region = spikes.region;\nPhaseLockingData.UID = spikes.UID;\nPhaseLockingData.sessionName = spikes.sessionName;\n\nif saveMat\n save([lfp.Filename(1:end-4) '.PhaseLockingData.cellinfo.mat'],'PhaseLockingData');\nend\n\nend\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/analysis/lfp_spikes/PhaseModulation/bz_PhaseModulation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.49961404796003084}} {"text": "function [f] = spm_fx_Lagrangian(P,M,U)\n% FORMAT [f] = spm_fx_Lagrangian(P,M,U)\n%\n% flow subfunction for Langrangian demo\n\n\n\n% Lagrangian and Q\n%==========================================================================\n[n m] = size(U);\n\nfor i = 1:m\n x = U(:,i);\n L = P.P{1};\n for j = 2:length(P.P)\n L = L + P.P{j}(:)'*x;\n x = kron(x,U(:,i));\n end\n \nend\n\n% estimate parameters of Lagrangian and Q\n%==========================================================================\nf = P.Q*dLdx;\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/spm_fx_Lagrangian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4995843004343756}} {"text": "% Batch script for sparse prediction\nclear all\n\n% --- training method ID\nmethod_id = 8;\n% 1: linear_sparse_space \n% 2: linear_sparse_space_vec\n% 3: linear_sparse_stepwise\n% 4: linear_sparse_stepwise_vec\n% 5: linear_sparse_stepwise_aa\n% 6: linear_sparse_seq\n% 7: linear_stepwise_reg_bayes\n\n% --- Basic Learning Parameters\nparm.Ntrain = 1000; % # of total training iteration\nparm.Nskip = 100;\t% skip steps for display info\n\n% --- Time delay embedding parameter\nparm.Tau = 1 ; % Lag time steps\nparm.Dtau = 3 ; % Number of embedding dimension\nparm.Tpred = 0 ; % Prediction time step : y(t+Tpred) = W * x(t)\n\n% --- Normalization parameter\nparm.data_norm = 1;\t% Normalize input and output\n\n% File name of old training result for retraining \nold_file = [];\n\n% File name for test data\ndatafile = ['./test/test.mat'];\nmodelfile = ['./test/model'];\nnewdata = 0; % = 1: make new data\n\n% --- Make or Load training & test data\nif newdata == 0 && exist(datafile,'file')\n\tload(datafile, ...\n\t\t'xdata','ydata','xtest','ytest')\nelse\n\t% Training & test data setting\n\tTdata = 1000 ; % # of training data\n\tTtest = 1000 ; % # of test data\n\t\n\tparm.Ydim = 4;\n\tparm.Xdim = 200; % Input dim\n\tparm.Meff = 30; % Effective Input\n\tparm.Sdim = 10; % number of sinusoidal input\n\tparm.Tmin = 50; % minimum period\n\tparm.Tmax = 200;% maximum period\n\tparm.SY = [0.3; 0.1; 0.5; 1.0];% output moise variance\n\tparm.Ntrial = 1;\n\n\tparm.sy = parm.SY;\n\t[xdata,ydata,Wout,Weff,Wrdn,Win,Wirr] = ...\n\t\tmake_train_data(parm, Tdata);\n\t\n\tparm.sy = 0.0;\n\t[xtest,ytest] = ...\n\t\tmake_train_data(parm, Ttest, Wout,Wrdn,Win,Wirr);\n\t\n\tif ~isempty(datafile)\n\t\tsave(datafile, ...\n\t\t\t'xdata','ydata','xtest','ytest','Wout','Weff','parm')\n\tend\nend\n\n% Normalize input data\n[X,nparm] = normalize_data(xdata, parm.data_norm);\nparm.xmean = nparm.xmean;\nparm.xnorm = nparm.xnorm;\n\n% Normalize output data\n[Y,nparm] = normalize_data(ydata, parm.data_norm);\nparm.ymean = nparm.xmean;\nparm.ynorm = nparm.xnorm;\n\n% Time alignment for prediction using embedding input\n[tx,ty] = pred_time_index(X,parm);\nX = X(:,tx,:);\nY = Y(:,ty,:);\n\n% --- Initialization of Model Parameters\nif ~isempty(old_file)\n\t% Start from old result\n\tload([old_file], 'Model')\nelse\n\tModel = [];\nend\n\n%profile_on = 1;\n%profile_start(profile_on);\n\n%\n% --- Sparse estimation\n%\nswitch\tmethod_id\ncase\t1\n\t[Model, Info] = linear_sparse_space(X, Y, Model, parm);\ncase\t2\n\t[Model, Info] = linear_sparse_space_vec(X, Y, Model, parm);\ncase\t3\n\t[Model, Info] = linear_sparse_stepwise(X, Y, Model, parm);\ncase\t4\n\t[Model, Info] = linear_sparse_stepwise_vec(X, Y, Model, parm);\ncase\t5\n\t[Model, Info] = linear_sparse_stepwise_aa(X, Y, Model, parm);\ncase\t6\n\t[Model, Info] = linear_sparse_seq(X, Y, Model, parm);\ncase\t7\n\t[Model, Info] = linear_stepwise_reg_bayes(X, Y, Model, parm);\ncase\t8\n\t[Model, Info] = linear_fit(X, Y, Model, parm);\ncase\t10\n\t% --- Delay embedding is done before training\n\tXd = delay_embed(X, parm.Tau, parm.Dtau);\n\t[Model, Info] = linear_map_sparse_cov(Xd, Y, Model, parm);\nend\n\n%\n% --- Estimate prediction error for test data\n%\n\n% Time alignment for prediction using embedding input\n[tx,ty] = pred_time_index(xtest,parm);\nxtest = xtest(:,tx,:);\nytest = ytest(:,ty,:);\n\n% Use normalization constant calculated by training data\nxtest = normalize_data(xtest, parm.data_norm, parm);\n\n% --- Prediction for test data\nypred = predict_output(xtest, Model, parm);\nerr = sum((ytest(:)-ypred(:)).^2)/sum(ytest(:).^2)\n\nif ~isempty(modelfile)\n\tfsave = [modelfile sprintf('_id%d.mat',method_id)];\n\tsave(fsave, 'Model', 'Info', 'parm');\nend\n\nplot_predict\n\n%profile_end(profile_on)\nreturn\n", "meta": {"author": "KamitaniLab", "repo": "GenericObjectDecoding", "sha": "c98f24370668109fd9978bc8b43a33bd43926f47", "save_path": "github-repos/MATLAB/KamitaniLab-GenericObjectDecoding", "path": "github-repos/MATLAB/KamitaniLab-GenericObjectDecoding/GenericObjectDecoding-c98f24370668109fd9978bc8b43a33bd43926f47/code/matlab/lib/SPR_2009_12_17/testjob_alt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.629774621301746, "lm_q1q2_score": 0.4994780000591351}} {"text": "function headmodel = ft_headmodel_singlesphere(mesh, varargin)\n\n% FT_HEADMODEL_SINGLESPHERE creates a volume conduction model of the\n% head by fitting a spherical model to a set of points that describe\n% the head surface.\n%\n% For MEG this implements Cuffin BN, Cohen D. \"Magnetic fields of\n% a dipole in special volume conductor shapes\" IEEE Trans Biomed Eng.\n% 1977 Jul;24(4):372-81.\n%\n% Use as\n% headmodel = ft_headmodel_singlesphere(mesh, ...)\n%\n% Optional arguments should be specified in key-value pairs and can include\n% conductivity = number, conductivity of the sphere\n%\n% See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD\n\n% FIXME document both EEG and MEG case\n\n% Copyright (C) 2012-2013, Donders Centre for Cognitive Neuroimaging, Nijmegen, NL\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\nconductivity = ft_getopt(varargin, 'conductivity', 1);\n\nif any(strcmp(varargin(1:2:end), 'unit')) || any(strcmp(varargin(1:2:end), 'units'))\n % the geometrical units should be specified in the input mesh\n ft_error('the ''unit'' option is not supported any more');\nend\n\nif isnumeric(mesh) && size(mesh,2)==3\n % assume that it is a Nx3 array with vertices\n % convert it to a structure, this is needed to determine the units further down\n mesh = struct('pos', mesh);\nelseif isstruct(mesh) && isfield(mesh,'bnd')\n % take the triangulated surfaces from the input structure\n mesh = mesh.bnd;\nend\n\n% replace pnt with pos\nmesh = fixpos(mesh);\n\nif ~isstruct(mesh) || numel(mesh)>1 || ~isfield(mesh, 'pos')\n ft_error('the input mesh should be a set of points or a single triangulated surface')\nend\n\nif numel(conductivity)~=1\n ft_error('the conductivity should be a single number')\nend\n\nif numel(mesh)~=1\n ft_error('fitting a single sphere requires a single mesh')\nend\n\n% start with an empty volume conductor\nheadmodel = [];\n\n% ensure that the mesh has units, estimate them if needed\nmesh = ft_determine_units(mesh);\n\n% copy the geometrical units into the volume conductor\nheadmodel.unit = mesh.unit;\n\n% fit a single sphere to all headshape points\n[single_o, single_r] = fitsphere(mesh.pos);\n\nheadmodel.r = single_r;\nheadmodel.o = single_o;\nheadmodel.cond = conductivity;\nheadmodel.type = 'singlesphere';\n\nfprintf('single sphere: radius = %.1f, conductivity = %f\\n', headmodel.r, headmodel.cond);\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/external/fieldtrip/forward/ft_headmodel_singlesphere.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.49947798903707796}} {"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 [mu, con, B] = clvm_Mstep(w, Y, YY, YTY, X, XX, XY, varargin)\n% MSTEP_CLG Compute ML/MAP estimates for a conditional linear Von Mises\n% [mu, Con, B] = clvm_Mstep(w, Y, YY, YTY, X, XX, XY, varargin)\n\n% This currently only accounts for conditions where there are no cts parents. \n% Dsc-->Cts is the structure that this can handle. \n\n% INPUTS:\n% w(i) = sum_t w(i,t) = responsibilities for each mixture component\n% If there is only one mixture component (i.e., Q does not exist),\n% then w(i) = N = nsamples, and \n% all references to i can be replaced by 1.\n% Y(:,i) = sum_t w(i,t) cos(y(:,t)) = weighted observations\n% YY(:,:,i) = sum_t w(i,t) sin(y(:,t)) = weighted outer product\n\n[cov_type, tied_cov, ...\n clamped_cov, clamped_mean, clamped_weights, cov_prior, ...\n xs, ys, post] = ...\n process_options(varargin, ...\n\t\t 'cov_type', 'full', 'tied_cov', 0, 'clamped_cov', [], 'clamped_mean', [], ...\n\t\t 'clamped_weights', [], 'cov_prior', [], ...\n\t\t 'xs', [], 'ys', [], 'post', []);\n\n[Ysz Q] = size(Y);\n\nif isempty(X) % no regression\n B2 = zeros(Ysz, 1, Q);\n for i=1:Q\n B(:,:,i) = B2(:,1:0,i); % make an empty array of size Ysz x 0 x Q\n end\n [mu, con] = mixvonMises_Mstep(w, Y, YY, YTY, varargin{:});\n return;\nend\n\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/KPMstats/clvm_Mstep.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4994779890370779}} {"text": "function [yarray0, dyarray0, tarray] = calctraj(via,dt,tacc)\nptlen = size(via,2);\ny0 = via(1,:);\nyarray0 = mstraj(via(2:end,:),ones(1,ptlen),[],y0,dt,tacc); % row vector for each xr\nyarray0 = [y0;yarray0];\ndyarray0 = [diff(yarray0)./dt;zeros(1,ptlen)];\ntarray = 0:dt:(size(yarray0,1)-1)*dt;\nend", "meta": {"author": "star2dust", "repo": "paper-simulation", "sha": "2d35e3beeccd2ce41f60c59e347b090f25960706", "save_path": "github-repos/MATLAB/star2dust-paper-simulation", "path": "github-repos/MATLAB/star2dust-paper-simulation/paper-simulation-2d35e3beeccd2ce41f60c59e347b090f25960706/Alonso2017Multi/calctraj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.4994779835260493}} {"text": "%%********************************************************\n%% Arrow: \n%% \n%% Fx = Arrow(pblk,f,x,options); \n%%\n%% if options == 0; \n%% Fx = Arr(F)*x\n%% if options == 1; \n%% Fx = Arr(F)^{-1}*x \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 Fx = Arrow(pblk,f,x,options); \n\n if nargin == 3; options = 0; end;\n\n s = 1 + [0, cumsum(pblk{2})]; \n idx1 = s(1:length(pblk{2})); \n if options == 0\n inprod = mexqops(pblk{2},f,x,1); \n Fx = mexqops(pblk{2},f(idx1),x,3) + mexqops(pblk{2},x(idx1),f,3); \n Fx(idx1) = inprod; \n else\n gamf2 = mexqops(pblk{2},f,f,2);\n gamprod = mexqops(pblk{2},f,x,2);\n alpha = gamprod./gamf2; \n Fx = mexqops(pblk{2},1./f(idx1),x,3) - mexqops(pblk{2},alpha./f(idx1),f,3); \n Fx(idx1) = alpha;\n end\n%%\n%%********************************************************\n\n\n\n\n\n\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/cvx-1.21.b795/sdpt3/Solver/Arrow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.4994428544730137}} {"text": "function [p, v, q] = ch_nav_equ_local_tan(p, v, q ,acc, gyr, dt, gN)\n% \u60ef\u5bfc\u89e3\u7b97\u66f4\u65b0\uff0c\u5f53\u5730\u76f4\u89d2\u5750\u6807\u7cfb\uff0c\u4e0d\u8003\u8651\u5730\u7403\u81ea\u8f6c\n% p \u4f4d\u7f6e XYZ \u5355\u4f4d m\n% v \u901f\u5ea6 XYZ \u5355\u4f4d m/s\n% q Qb2n\u59ff\u6001,\u56db\u5143\u6570\u8868\u793a\n% acc \u6bd4\u529b\uff0c \u52a0\u901f\u5ea6\u8ba1\u6d4b\u91cf\u503c \u5355\u4f4d (m/s^2), \n% gyr \u89d2\u901f\u5ea6 (rad/s)]\n% dt dt (s) \u79ef\u5206\u95f4\u9694\u5982 0.01s\n% gn \u5f53\u5730\u91cd\u529b\u5411\u91cf\n\nold_v = v;\n\nsf = acc;\n\n% \u59ff\u6001\u7ed3\u7b97\nq = ch_att_upt(q, gyr, dt);\n\n\n% \u901f\u5ea6\u89e3\u7b97\nsf = ch_qmulv(q, sf);\nsf = sf + gN;\nv = old_v + dt *sf;\n\n% \u4f4d\u7f6e\u89e3\u7b97\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% % \u59ff\u6001\u7ed3\u7b97\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% % \u901f\u5ea6\u89e3\u7b97\n% \n% x(4:6) = old_v + ((ch_qmulv(q_new, a_new) + ch_qmulv(q_old, a_old) )/2 + gN) *dt;\n% \n% % \u4f4d\u7f6e\u89e3\u7b97\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 y = psdscale(ud,x,K,transp)\n% y = psdscale(ud,x,K [,transp])\n%\n% PSDSCALE Computes length lenud (=sum(K.s.^2)) vector y.\n% !transp (default) then y[k] = vec(Ldk' * Xk * Ldk)\n% transp == 1 then y[k] = vec(Udk' * Xk * Udk)\n% Uses pivot ordering ud.perm if available and nonempty.\n%\n% ********** INTERNAL FUNCTION OF SEDUMI **********\n%\n% See also scaleK, factorK.\n\n% This file is part of SeDuMi 1.3 by Imre Polik and Oleksandr Romanko\n% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)\n%\n% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)\n% Dept. Econometrics & O.R., Tilburg University, the Netherlands.\n% Supported by the Netherlands Organization for Scientific Research (NWO).\n%\n% Affiliation SeDuMi 1.03 and 1.04Beta (2000):\n% Dept. Quantitative Economics, Maastricht University, the Netherlands.\n%\n% Affiliations up to SeDuMi 1.02 (AUG1998):\n% CRL, McMaster University, Canada.\n% Supported by the Netherlands Organization for Scientific Research (NWO).\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n% 02110-1301, USA\n\n%The function is quite dirty as the type and dimension of the inputs may\n%change, that is why we have so many subcases.\n\nKs = K.s;\nif isempty(Ks)\n y = [];\n return\nend\nif nargin < 4\n transp = false;\nend\nKq = Ks .* Ks;\nnr = K.rsdpN;\nnc = length(Ks);\nN = sum(Kq) + sum(Kq(nr+1:end));\ny = zeros(N,1);\nxi = length(x) - N;\nyi = 0;\nui = 0;\nif isstruct(ud)\n perm = ud.perm;\n if isempty(perm)\n prep = false;\n postp = false;\n else\n prep = ~transp;\n postp = transp;\n pi = 0;\n end\n ud = ud.u;\nelse\n prep = false;\n postp = false;\nend\nfor i = 1 : nc\n ki = Ks(i);\n qi = Kq(i);\n TT = ud(ui+1:ui+qi); ui=ui+qi;\n if i > nr\n TT = TT + 1i*ud(ui+1:ui+qi); ui=ui+qi;\n end\n TT = reshape(TT,ki,ki);\n if transp\n TT = triu(TT);\n else\n TT = tril(TT);\n end\n XX = x(xi+1:xi+qi); xi=xi+qi;\n if i > nr\n XX = XX + 1i*x(xi+1:xi+qi); xi=xi+qi;\n end\n XX = reshape(XX,ki,ki);\n if prep\n PP = perm(pi+1:pi+ki); pi=pi+ki;\n if any(diff(PP)~=1)\n XX = XX(PP,PP);\n end\n end\n if nnz(XX) < 0.1 * qi\n XX = sparse(XX);\n end\n XX = TT' * XX * TT;\n if postp\n PP = perm(pi+1:pi+ki); pi=pi+ki;\n if any(diff(PP)~=1)\n XX(PP,PP) = XX;\n end\n end\n y(yi+1:yi+qi) = real(XX); \n yi = yi+qi;\n if i > nr\n XX = imag(XX);\n % Needed, otherwise psdfactor() will sometimes fail.\n XX(1:ki+1:end) = 0;\n y(yi+1:yi+qi) = XX; \n yi = yi+qi;\n end\nend\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/sedumi/psdscale.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677622198946, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.49935899841281733}} {"text": "% The soacm code is modified on the basis of an implementation of C-V model, which is:\n% created on 04/26/2004\n% author: Chunming Li\n% email: li_chunming@hotmail.com\n% Copyright (c) 2004-2006 by Chunming Li\nfunction phi = evol_soacm(ort,img,phi_init,mu,nu,lambda_1,lambda_2,delta_t,epsilon)\n\n img = mirror_expand(img); \n \n phi = mirror_expand(phi_init); \n phi = mirror_ensure(phi);\n delta_h = Delta(phi,epsilon);\n cur = curvature(phi); % compute curvature of phi function\n [gray_c1,gray_c2] = binaryfit(phi,img,epsilon);\n \n if ort == -1 \n t1 = lambda_1 * (img-gray_c1).^2;\n t2 = lambda_2 * (img-gray_c2).^2; \n phi = phi + delta_t * delta_h .* ( mu*cur - nu - t1 + t2);\n else\n t3 = (img-ort).^2;\n phi = phi + delta_t * delta_h .* ( mu*cur - nu - t3);\n end\n \n phi = mirror_shrink(phi);\nend", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u68c0\u6d4b\u7b97\u6cd5/AirportDetection-master/grsl/soacm/evol_soacm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4993589961502648}} {"text": "function h = labelpoints (xpos, ypos, labels, varargin)\n% h = labelpoints (xpos, ypos, labels, position, buffer, adjust_axes, {parameters})\n%\n% Given x and y position vectors (xpos, ypos) and given \n% a vector of labels this script will label all data points \n% and output the label handles in vector, h. \n% \n% 'xpos' and 'ypos' are required to be the same length. However, if all labels\n% fall along the same horizontal or vertical line, the function will accept \n% a single number for that xpos or ypos (see examples). \n%\n% 'labels' should be a cell or numerical array of the \n% same length as xpos or ypos. Alternatively it can be a singleton\n% that will be replicated for all labels (see examples). \n%\n% 'position' (optional) describes the position of the labels\n% relative to their locations by entering one of the following\n% abbreviated compass directions in single quotes (default is 'NW').\n% N, S, E, W, NE, NW, SE, SW, center\n%\n% 'buffer' (optional) is a number between 0:1 that adds distance between\n% the label and the plotted point where 0 (default) is none and 1 is\n% 1/10th of the axis. Ignored for 'center' position.\n%\n% 'adjust_axes' (optional, default=0): depending on the positioning of labels, \n% some may fall beyond the axis limits. adjust_axes = 1 will readjust xlim \n% & ylim slightly so labels are not beyond axis limits.\n%\n% This function includes three optional parameters to label only the outliers.\n% This can come in handy when there are many points but only the outliers\n% should be labeled. (may require stats toolbox) (see examples)\n% 'outliers_SD', N - will only label points that are greater than N \n% standard deviations from the median of xpos or ypos.\n% 'outliers_Q', N - will only label points that are greater than N\n% times the interquartile range of xpos or ypos.\n% 'outliers_N', N - will calculate the distance of each point from the median \n% point(xpos,ypos) and will label the N-furthest points.\n% Alternatively, N can be a decimal to label N% of the points. \n%\n% The following parameters may also be entered in any order\n% 'FontSize', N - font size of all labels\n% 'Color', S - font color of all labels ('y' 'm' 'c' 'r' 'g' 'b' 'w' 'k')\n% 'rotation', N - will rotate the labels N degrees about label-center\n% (positive is counterclockwise).\n%\n%\n% Examples: \n% Fake Data:\n% x = 1:10; y=rand(1,10); \n% scatter(x,y)\n% labs = {'a' 'b' 'c' 'd' 'middle' 'f' 'g' 'h' 'i' 'last'};\n% \n% Label Examples\n% txt_h = labelpoints(x, y, labs); \n% txt_h = labelpoints(x, y, labs, 'E', 0.15); \n% txt_h = labelpoints(x, y, labs, 'E', 0.15, 1);\n% txt_h = labelpoints(x, y, labs, 'W', 0.15, 1, 'FontSize', 14, 'Color', 'r');\n% txt_h = labelpoints(x, y, labs, 'W', 0.15, 1, 'FontSize', 12, 'Color', 'm', 'rotation', 45);\n% \n% Also works for \n% labs = [1:1:10]; \n% labs = {'Sofia' '' '' '' 'Bucharest' '' '' 'Belgrade' '' 'Ankara'}\n% labs = '*'; \n% labs = 'string';\n%\n% When all labels share same xpos or ypos\n% boxplot(1:10)\n% labelpoints(0.8, [3, 5.5, 8], {'25%' '50%' '75%'}, 'center');\n%\n% Outlier Examples\n% Fake Data:\n% x = [rand(1,30), rand(1,8)*2];\n% y = [rand(1,30), rand(1,8)*2];\n% scatter(x, y)\n% labs = 1:38;\n% labelpoints(x, y, labs, 'N', 0.1, 1, 'outliers_N', 5); %will label 5 furthest points from median\n% labelpoints(x, y, labs, 'N', 0.1, 1, 'outliers_N', 0.1, 'Color', 'r'); %will label 10% of furthest points from median \n% labelpoints(x, y, labs, 'N', 0.1, 1, 'outliers_SD', 2); %will label all points > 2 SD from median\n% labelpoints(x, y, labs, 'N', 0.1, 1, 'outliers_Q', 1.5); %will label points greater that 1.5 x IQR\n% \n% Alternative use: \n% Density Distributions:\n% x = randn(1,100); y = 1:100; \n% scatter(x,y)\n% labs = '|';\n% txt_h = labelpoints(x, 8, labs, 'center');\n%\n% Single Labeling\n% x = 2004:2013; y=rand(1,10); \n% plot(x,y,'-o')\n% labs = 'acquisition';\n% labelpoints(x(3), y(3), labs, 'N', 0.2, 1);\n% labelpoints(2008.5, min(ylim), {['labelpoints.m ', datestr(now, 'mm/dd/yy')]}, 'N', 0.3, 0, 'fontsize', 12, 'color', 'm');\n%\n% Use labels instead of markers\n% x = randn(1,15); y = randn(1,15);\n% labs = char('a'+(1:15)-1)';\n% labelpoints(x, y, labs, 'center', 0, 1, 'color', 'b');\n% \n% 140331 v.1 \n% 141115 v.2\n% Copyright (c) 2014, Adam Danz\n%All rights reserved\n\n% source: http://www.mathworks.com/matlabcentral/fileexchange/46891-labelpoints\n\n% Changes history\n% 11/02/14 if labels are entered as char, they are convered to cell\n% 11/03/14 varargin added to accomodate auto_outlier feature\n% 11/03/14 convert inputs to row vector if they are column vectors\n% 11/04/14 now position in put is not case sensitive\n% 11/04/14 now 1 label can be entered to label multiple points\n% 11/04/14 now fontsize and color can be specified by params\n% 11/05/14 changed 'outlier' to 'outlier_SD' and added 'outlier_Q'\n% 11/07/14 added option to rotate test\n% 11/15/14 added 'outliers_N' input option and cleaned up text rotation section.\n% 11/19/14 curr_extent is not always a cell. fixed. \n% 11/20/14 when outliers_N is selected N is min(N, lenght(xpos));\n% 11/21/14 removes entire point and label when there is an 'inf' value\n\n\n%%\n% Check Class of 'labels'\n %If 'labels' are numberical, convert to cell\n if isnumeric(labels) == 1\n labels = num2cell(labels); \n end\n\n % if 'labels' are char, convert to cell\n if ischar(labels)\n labels = cellstr(labels);\n end\n \n% if all labels share the same xpos or ypos (only 1 value entered in 1 of the position vectors)\n if length(xpos)==1 && length(ypos)>1\n xpos = repmat(xpos, size(ypos));\n elseif length(ypos)==1 && length(xpos)>1\n ypos = repmat(ypos, size(xpos));\n end\n \n% if only one lable is entered for all points, replicate it\n if length(labels)==1 && length(xpos) > 1\n labels = repmat(labels, [1, length(xpos)]);\n end\n \n% ensures xpos, ypos, and labels are all row vectors \n if iscolumn(xpos); xpos = xpos'; end\n if iscolumn(ypos); ypos = ypos'; end\n if iscolumn(labels); labels = labels'; end\n\n%check that x, y, and labels are same length\n if isequal(length(xpos), length(ypos), length(labels)) == 0\n error('xpos, ypos, and labels must all be the same length unless using one input for labels.')\n end\n \n%if an 'inf' value is entered, this will remove that entire point and label\n xinf = find(xpos==inf);\n yinf = find(ypos==inf);\n findinf = [xinf yinf];\n if ~isempty(findinf)\n xpos(findinf)=[];\n ypos(findinf)=[];\n labels(findinf) = [];\n end \n\n%Validate inputs and optional parameters\n validPositions = {'N' 'NE' 'E' 'SE' 'S' 'SW' 'W' 'NW' 'center'};\n checkPosition = @(x) any(validatestring(x, validPositions));\n\n validColors = {'y' 'm' 'c' 'r' 'g' 'b' 'w' 'k'};\n checkColors = @(x) any(validatestring(x, validColors));\n\n p = inputParser;\n p.FunctionName = mfilename;\n addRequired(p, 'xpos', @isnumeric);\n addRequired(p, 'ypos', @isnumeric);\n addRequired(p, 'labels');\n addOptional(p, 'position', 'NW', checkPosition);\n addOptional(p, 'buffer', 0, @isnumeric);\n addOptional(p, 'adjust_axes', 0, @isnumeric);\n\n addParamValue(p, 'outliers_SD', 3, @isnumeric);\n addParamValue(p, 'outliers_Q', 1.5, @isnumeric);\n addParamValue(p, 'outliers_N', 1, @isnumeric);\n\n addParamValue(p, 'FontSize', 10, @isnumeric);\n addParamValue(p, 'Color', 'k', checkColors);\n addParamValue(p, 'rotation', 0, @isnumeric);\n parse(p, xpos, ypos, labels, varargin{:})\n\nmfile = [mfilename,'.m'];\n\n%calculate buffer\n a = axis/10;% I've somewhat arbitrarily divided by 10 to make 'buffer' more sensitive\n u1 = 0; %x offset\n u2 = 0; %y offset\n\n%assign position\n switch upper(p.Results.position) \n case 'E', va = 'middle'; ha = 'left'; u1 = a(2)-a(1); \n case 'W', va = 'middle'; ha = 'right'; u1 = (a(2)-a(1))*-1;\n case 'N', va = 'bottom'; ha = 'center'; u2 = a(4)-a(3);\n case 'S', va = 'top'; ha = 'center'; u2 = (a(4)-a(3))*-1;\n case 'NE', va = 'bottom'; ha = 'left'; u1 = (a(2)-a(1))/2; u2 = (a(4)-a(3))/2;\n case 'NW', va = 'bottom'; ha = 'right'; u1 = (a(2)-a(1))*-0.5; u2 = (a(4)-a(3))/2;\n case 'SE', va = 'top'; ha = 'left'; u1 = (a(2)-a(1))/2; u2 = (a(4)-a(3))*-0.5;\n case 'SW', va = 'top'; ha = 'right'; u1 = (a(2)-a(1))*-0.5; u2 = (a(4)-a(3))*-0.5;\n case 'CENTER', va = 'middle'; ha = 'center'; \n end\n\n%Factor in buffer\n u1 = u1*p.Results.buffer;\n u2 = u2*p.Results.buffer;\n\n\n%If outliers parameters are selected\n if sum(strcmp(varargin, 'outliers_SD')) == 1 || sum(strcmp(varargin, 'outliers_Q')) == 1 || sum(strcmp(varargin, 'outliers_N')) == 1\n if sum(strcmp(varargin, 'outliers_SD')) == 1\n outlier_idx = logical(abs(xpos - median(xpos)) > p.Results.outliers_SD*std(xpos) | abs(ypos - median(ypos)) > p.Results.outliers_SD*std(ypos)); %index of outliers\n \n elseif sum(strcmp(varargin, 'outliers_Q')) == 1\n xbounds = [prctile(xpos,25) - p.Results.outliers_Q * iqr(xpos) , prctile(xpos, 75) + p.Results.outliers_Q * iqr(xpos)]; %[lower upper] bounds of outliers\n ybounds = [prctile(ypos,25) - p.Results.outliers_Q * iqr(ypos) , prctile(ypos, 75) + p.Results.outliers_Q * iqr(ypos)]; %[lower upper] bounds of outliers\n outlier_idx = logical(yposybounds(2) | xposxbounds(2));\n \n elseif sum(strcmp(varargin, 'outliers_N')) == 1\n if p.Results.outliers_N<1; \n N = round(length(xpos) * p.Results.outliers_N); \n else\n N = min(p.Results.outliers_N, length(xpos)); %ensures that user cannot label more outliers than coordinates.\n end\n medianpoint = repmat([median(xpos) median(ypos)], [length(xpos),1]);\n paired = horzcat(xpos', ypos');\n distances = (((medianpoint(:,1)-paired(:,1)).^2) + ((medianpoint(:,2)-paired(:,2)).^2)).^(1/2); %all distances from median\n [~, idx] = sort(distances, 'descend');\n outlier_idx = false(1,length(xpos));\n outlier_idx(idx(1:N))=1; \n end\n \n xpos = xpos(outlier_idx); \n ypos = ypos(outlier_idx);\n labels = labels(outlier_idx);\n\n if any(outlier_idx) == 0; %dispay msg if there are no outliers to label\n disp(['There are no outliers to label in ', mfile,'.'])\n disp('Change outlier value for less sensitivity; See help file.'); \n end\n end\n\n%Label points\n h = text(xpos+u1 , ypos+u2, labels, 'VerticalAlignment',va, 'HorizontalAlignment',ha, 'FontSize', p.Results.FontSize, 'color', p.Results.Color);\n \n%Rotate text if specified\n if sum(strcmp(varargin, 'rotation')) == 1 %if rotation parameter is called in inputs\n xl = xlim; yl = ylim; %In case text rotation auto adjusts axes.\n curr_extent = get(h, 'extent'); %Need to store current center point of all labels since text rotation relocates position\n if iscell(curr_extent); cell2mat(curr_extent); end\n hold on\n curr_position = [curr_extent(:,1)+(curr_extent(:,3)/2),curr_extent(:,2)+(curr_extent(:,4)/2)]; %uses extent to locate center of label\n set(h, 'rotation', p.Results.rotation, 'VerticalAlignment','middle', 'HorizontalAlignment','center'); \t%note: text rotation changes alignment which is why they need to be centered back to specifications.\n for i = 1:length(h) %after rotation, reposition lables back to desired location \n set(h(i), 'position', curr_position(i,:))\n end\n set(gca, 'xlim', xl); set(gca, 'ylim', yl); %In case text rotation auto adjusts axes.\n end \n \n%Determine if any labels go beyond axis limits and adjust if desired (adjust_axes = 0 or 1)\n if p.Results.adjust_axes == 1 && ~isempty(h) \n x_adj = sign(u1+0.0000001); %the addition is to avoid '0'\n y_adj = sign(u2+0.0000001); %the addition is to avoid '0'\n\n labelextent = get(h, 'extent');\n if isequal(class(labelextent),'cell')\n labelextent = cat(1, labelextent{:});\n end\n xl = xlim; yl = ylim;\n lablimX = [min(labelextent(:,1)), max(labelextent(:,1)+(labelextent(:,3).*x_adj))] +u1;\n lablimY = [min(labelextent(:,2)), max(labelextent(:,2)+(labelextent(:,4).*y_adj))] +u2;\n\n xlim([min(min(xl), min(lablimX)), max(max(xl), max(lablimX))])\n ylim([min(min(yl), min(lablimY)), max(max(yl), max(lablimY))])\n end\n \nend\n\n\n%% Notes\n% a video (not mine) explaining this method: http://blogs.mathworks.com/videos/2012/05/30/how-to-label-a-series-of-points-on-a-plot-in-matlab/\n% Text properties : http://www.mathworks.com/help/matlab/ref/text_props.html\n% info on input parsing: http://www.mathworks.com/help/matlab/matlab_prog/parse-function-inputs.html\n% and http://www.mathworks.com/help/matlab/ref/inputparser-class.html\n% Outlier info : https://docs.oracle.com/cd/E17236_01/epm.1112/cb_statistical/frameset.htm?ch07s02s10s01.html\n\n", "meta": {"author": "zhouyuanzxcv", "repo": "Hyperspectral", "sha": "f32dcca86677f8d37596376f57e9c733058f8cff", "save_path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral", "path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral/Hyperspectral-f32dcca86677f8d37596376f57e9c733058f8cff/common/labelpoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.685949467848392, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.4993543758319971}} {"text": "%SerialLink.gravload Gravity load on joints\n%\n% TAUG = R.gravload(Q) is the joint gravity loading (1xN) for the robot R\n% in the joint configuration Q (1xN), where N is the number of robot\n% joints. Gravitational acceleration is a property of the robot object.\n%\n% If Q is a matrix (MxN) each row is interpreted as a joint configuration\n% vector, and the result is a matrix (MxN) each row being the corresponding\n% joint torques.\n%\n% TAUG = R.gravload(Q, GRAV) as above but the gravitational \n% acceleration vector GRAV is given explicitly.\n%\n% See also SerialLink.gravjac, SerialLink.rne, SerialLink.itorque, SerialLink.coriolis.\n\n\n\n\n\n% Copyright (C) 1993-2017, by Peter I. Corke\n%\n% This file is part of The Robotics Toolbox for MATLAB (RTB).\n% \n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with RTB. If not, see .\n%\n% http://www.petercorke.com\n\nfunction tg = gravload(robot, q, grav)\n\tassert(numcols(q) == robot.n, 'RTB:SerialLink:gravload:badarg', 'Insufficient columns in q');\n\n\tif nargin == 2\n\t\ttg = rne(robot, q, zeros(size(q)), zeros(size(q)));\n\telseif nargin == 3\n\t\ttg = rne(robot, q, zeros(size(q)), zeros(size(q)), grav);\n end\n", "meta": {"author": "petercorke", "repo": "robotics-toolbox-matlab", "sha": "bd7a9d75176c660f43fc799b24d838f70b02250c", "save_path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab/robotics-toolbox-matlab-bd7a9d75176c660f43fc799b24d838f70b02250c/@SerialLink/gravload.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.49935435776272463}} {"text": "function out = colorMatchingFunctions\n%colorMatchingFunctions Color-matching functions.\n% colorMatchingFunctions returns a table containing the color matching\n% functions for the CIE 1931 Standard Observer. The table contains the\n% variables lambda, x, y, and z. The color matching functions are\n% returned for wavelengths between 360nm and 830nm at intervals of 1nm.\n\n% Written by Steve Eddins to accompany Digital Image Processing Using\n% MATLAB, 3rd edition, Gatesmark Press, 2020,\n% http://imageprocessingplace.com.\n%\n% Copyright 2019 The MathWorks, Inc.\n% License: https://github.com/mathworks/matlab-color-tools/blob/master/license.txt\n\npersistent t\n\nif isempty(t)\n t = readtable('CIE 1931 Standard Observer (1nm).xlsx',...\n 'UseExcel',false);\nend\n\nout = t;\n", "meta": {"author": "dipum", "repo": "dipum-toolbox", "sha": "9ce653c4c0c4b7c56e46194c24bf152db4ab6832", "save_path": "github-repos/MATLAB/dipum-dipum-toolbox", "path": "github-repos/MATLAB/dipum-dipum-toolbox/dipum-toolbox-9ce653c4c0c4b7c56e46194c24bf152db4ab6832/dipum/mathworksLicensedFunctions/colorMatchingFunctions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.49935435713729687}} {"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 [grad_X, grad_W, grad_b] = B_weighting(prev_layer, curr_layer, future_layers)\n\ninput = prev_layer{1}.a;\nweight = curr_layer.W;\nnWeight = length(weight);\nD = size(input,1)/nWeight;\n\ngrad_X = 0; grad_W=0; grad_b=0;\nfuture_grad = GetFutureGrad(future_layers, curr_layer);\nif 0\n for i=1:length(future_layers)\n if curr_layer.update\n for j=1:size(input,2)\n curr_input = reshape(input(:,j), D, nWeight);\n grad_W = grad_W + curr_input' * future_layers{i}.grad(:,j);\n end\n if isfield(curr_layer, 'updateBias')== 0 || curr_layer.updateBias==1\n grad_b = grad_b + sum(future_layers{i}.grad,2);\n end\n end\n for j=1:size(input,2)\n grad_X = grad_X + future_layers{i}.grad(:,j)*weight';\n end\n end\nelse \n if curr_layer.update\n for j=1:size(input,2)\n curr_input = reshape(input(:,j), D, nWeight);\n grad_W = grad_W + curr_input' * future_grad(:,j);\n end\n if isfield(curr_layer, 'updateBias')== 0 || curr_layer.updateBias==1\n grad_b = grad_b + sum(future_grad,2);\n end\n end\n for j=1:size(input,2)\n grad_X = grad_X + future_grad(:,j)*weight';\n end\nend\ngrad_X = reshape(grad_X, prod(size(grad_X)), 1);\n\nend\n", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/graph/B_weighting.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4992775697559787}} {"text": "function linplus_test152 ( )\n\n%*****************************************************************************80\n%\n%% TEST152 tests R8BLT_INDICATOR.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 March 2009\n%\n% Author:\n%\n% John Burkardt\n%\n n = 6;\n ml = 2;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST152\\n' );\n fprintf ( 1, ' R8BLT_INDICATOR sets up a R8BLT indicator matrix.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Matrix order N = %d\\n', n );\n fprintf ( 1, ' Lower bandwidth ML = %d\\n', ml );\n%\n% Set the matrix.\n%\n a = r8blt_indicator ( n, ml );\n\n r8blt_print ( n, ml, a, ' The indicator matrix:' );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linplus/linplus_test152.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.4992775697559787}} {"text": "% Features computation for the Harmonic Model + Phase Distortion (HMPD)\n%\n% Octave compatible\n%\n% Please read the README.txt file for general information about HMPD before\n% using it.\n%\n% Inputs\n% frames : [Nxstruct] N structures containing the sinusoidal parameters,\n% as provided by hmpd_analysis_harmonic.m or another sinusoidal\n% analysis.\n% fs : [Hz] The sampling rate of the analyzed waveform\n% [opt] : Additional options (see code below)\n% Even though this argument is optional, it is highly recommended to\n% adapt the f0min and f0max options if no f0s argument is provided.\n% \n% Outputs\n% f0s : [s, Hz] [Nx2] A time/data column vector, as above, containing the\n% analysis instants and the f0 curve. \n% AE : [NxD] A matrix containing the amplitude envelope.\n% D is either opt.dftlen/2+1 (from hmpd_features_compute.m), or\n% opt.amp_order+1, depending if compression is disabled or enabled.\n% PDM : [NxD] A matrix containing the Phase Distortion Mean.\n% D is either opt.dftlen/2+1 or opt.pdm_order+1, depending if\n% compression is disabled or enabled.\n% PDD : [NxD] A matrix containing the Phase Distortion Deviation.\n% D is either opt.dftlen/2+1 or opt.pdd_order+1, depending if\n% compression is disabled or enabled.\n% opt : The options used for the analysis.\n%\n% Copyright (c) 2013 University of Crete - Computer Science Department (UOC-CSD)\n%\n% License\n% This file is under the LGPL license, you can\n% redistribute it and/or modify it under the terms of the GNU Lesser General \n% Public License as published by the Free Software Foundation, either version 3 \n% of the License, or (at your option) any later version. This file is\n% distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; \n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n% PARTICULAR PURPOSE. See the GNU Lesser General Public License for more\n% details.\n%\n% This function is part of the Covarep project: http://covarep.github.io/covarep\n%\n% Author\n% Gilles Degottex \n%\n\nfunction [f0s, AE, PDM, PDD, opt] = hmpd_analysis_features(frames, fs, opt)\n% keyboard\n if opt.debug>0; disp('HMPD Vocoder: Features computation ...'); end\n\n irregf0s = [[frames.t]', [frames.f0]']; % Retrieve f0 from the frames\n\n if opt.debug>0; disp(' Estimate amplitude envelope ...'); end\n [AE, frames] = hmpd_amplitude_envelope_estimate(frames, fs, opt);\n\n if opt.debug>0; disp(' Estimate phase envelope ...'); end\n rpspdopt = opt;\n rpspdopt.pd_method = 1;\n rpspdopt.pd_vtf_rm =false;% Already done in hmpd_amplitude_envelope_estimate\n rpspdopt.harm2freq = true;\n rpspdopt.usemex = opt.usemex;\n PE = phase_rpspd(frames, fs, rpspdopt);\n\n if opt.debug>0; disp(' Compute phase statistics ...'); end\n\n % Phase's mean\n PDM = hmpd_phase_mean(PE, opt.pdm_nbper*opt.sin_nbat); % Below 3, doubles the voice, why?\n\n % Phase's standard-deviation\n % Remove first the trend from PE, otherwise the std measure is overestimated\n PEtrend = hmpd_phase_smooth(PE, opt.pdd_nbper*opt.sin_nbat); % Compute the trend\n PE = PE - PEtrend;\n\n PDD = hmpd_phase_deviation(PE, opt.pdd_nbper*opt.sin_nbat);\n\n\n if opt.debug>0; disp(' Compress features ...'); end\n [AE, PDM, PDD] = hmpd_features_compress(irregf0s, AE, PDM, PDD, fs, opt);\n\n\n if opt.debug>0; disp(' Resample features with uniform sampling ...'); end\n uT = (0:opt.regularstepsize:irregf0s(end,1))'; % New uniform time instants\n\n % First, resample the f0 curve using uniform step size\n uf0s = exp(interp1(irregf0s(:,1), log(irregf0s(:,2)), uT, 'linear', NaN));\n\n % Drop the time instants outside of the features\n idx = find(~isnan(uf0s));\n uT = uT(idx);\n f0s = [uT, uf0s(idx)];\n\n % Then, resample amplitude, PD's mean and PD's deviation\n AE = irregsampling2uniformsampling(irregf0s(:,1), AE, uT, [], [], 'linear', NaN, opt.usemex);\n PDM = irregsampling2uniformsampling(irregf0s(:,1), PDM, uT, @unwrap, @wrap, 'linear', 0, opt.usemex);\n PDD = irregsampling2uniformsampling(irregf0s(:,1), PDD, uT, [], [], 'linear', 0, opt.usemex);\n\nreturn\n", "meta": {"author": "covarep", "repo": "covarep", "sha": "5a2be5d6b776f14a0b275c69fde90eb13849e60d", "save_path": "github-repos/MATLAB/covarep-covarep", "path": "github-repos/MATLAB/covarep-covarep/covarep-5a2be5d6b776f14a0b275c69fde90eb13849e60d/vocoder/hmpd/hmpd_analysis_features.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.49927756459904943}} {"text": "%MDL_JACO Create model of Kinova Jaco manipulator\n%\n% MDL_JACO is a script that creates the workspace variable jaco which\n% describes the kinematic characteristics of a Kinova Jaco manipulator\n% using standard DH conventions.\n%\n% Also define the workspace vectors:\n% qz zero joint angle configuration\n% qr vertical 'READY' configuration\n%\n% Reference::\n% - \"DH Parameters of Jaco\" Version 1.0.8, July 25, 2013.\n%\n% Notes::\n% - SI units of metres are used.\n% - Unlike most other mdl_xxx scripts this one is actually a function that\n% behaves like a script and writes to the global workspace.\n%\n% See also SerialLink, mdl_mico, mdl_puma560.\n\n% MODEL: Kinova, Jaco, 6DOF, standard_DH\n\n\n% Copyright (C) 1993-2015, by Peter I. Corke\n%\n% This file is part of The Robotics Toolbox for MATLAB (RTB).\n% \n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with RTB. If not, see .\n%\n% http://www.petercorke.com\n\nfunction r = mdl_jaco()\n \n deg = pi/180;\n \n % robot length values (metres)\n D1 = 0.2755;\n D2 = 0.4100;\n D3 = 0.2073;\n D4 = 0.0743;\n D5 = 0.0743;\n D6 = 0.1687;\n e2 = 0.0098;\n \n % alternate parameters\n aa = 30*deg;\n ca = cos(aa);\n sa = sin(aa);\n c2a = cos(2*aa);\n s2a = sin(2*aa);\n d4b = D3 + sa/s2a*D4;\n d5b = sa/s2a*D4 + sa/s2a*D5;\n d6b = sa/s2a*D5 + D6;\n \n % and build a serial link manipulator\n \n % offsets from the table on page 4, \"Mico\" angles are the passed joint\n % angles. \"DH Algo\" are the result after adding the joint angle offset.\n\n robot = SerialLink([\n Revolute('alpha', pi/2, 'a', 0, 'd', D1, 'flip')\n Revolute('alpha', pi, 'a', D2, 'd', 0, 'offset', -pi/2)\n Revolute('alpha', pi/2, 'a', 0, 'd', -e2, 'offset', pi/2)\n Revolute('alpha', 2*aa, 'a', 0, 'd', -d4b)\n Revolute('alpha', 2*aa, 'a', 0, 'd', -d5b, 'offset', -pi)\n Revolute('alpha', pi, 'a', 0, 'd', -d6b, 'offset', 100*deg)\n ], ...\n 'name', 'Jaco', 'manufacturer', 'Kinova');\n\n \n \n % place the variables into the global workspace\n if nargin == 1\n r = robot;\n elseif nargin == 0\n assignin('base', 'jaco', robot);\n assignin('base', 'qz', [0 0 0 0 0 0]); % zero angles\n assignin('base', 'qr', [270 180 180 0 0 0]*deg); % vertical pose as per Fig 2\n end\nend\n", "meta": {"author": "Allopart", "repo": "rbpf-gmapping", "sha": "affe0adc25fa446fc7af4902d699d92864bdba1b", "save_path": "github-repos/MATLAB/Allopart-rbpf-gmapping", "path": "github-repos/MATLAB/Allopart-rbpf-gmapping/rbpf-gmapping-affe0adc25fa446fc7af4902d699d92864bdba1b/rvctools/robot/mdl_jaco.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859596, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.4991291025590493}} {"text": "% ARROWH Draws a solid 2D arrow head in current plot.\n%\n%\t ARROWH(X,Y,COLOR,SIZE,LOCATION) draws a solid arrow head into\n%\t the current plot to indicate a direction. X and Y must contain\n%\t a pair of x and y coordinates ([x1 x2],[y1 y2]) of two points:\n%\n%\t The first point is only used to tell (in conjunction with the\n%\t second one) the direction and orientation of the arrow -- it\n%\t will point from the first towards the second.\n%\n%\t The head of the arrow will be located in the second point. An\n%\t example of use is\tplot([0 2],[0 4]); ARROWH([0 1],[0 2],'b')\n%\n%\t You may also give two vectors of same length > 2. The routine\n%\t will then choose two consecutive points from \"about\" the middle\n%\t of each vectors. Useful if you don't want to worry each time\n%\t about where to put the arrows on a trajectory. If x1 and x2\n%\t are the vectors x1(t) and x2(t), simply put ARROWH(x1,x2,'r')\n%\t to have the right direction indicated in your x2 = f(x1) phase\n%\t plane.\n%\n% (x2,y2)\n% --o\n% \\ |\n%\t \\|\n%\n%\n%\t\t o\n%\t (x1,y1)\n%\n%\t Please note that the following optional arguments need -- if\n%\t you want to use them -- to be given in that exact order. You\n%\t may pass on empty vectors \"[]\" to skip arguments you don't want\n%\t to set (if you want to access \"later\" arguments...).\n%\n%\t The COLOR argument is quite the same as for plots, i.e. either\n% a string like 'r' or an RGB value vector like [1 0 0]. If you\n% only want the outlines of the head (in other words a non-solid\n% arrow head), prefix the color string by 'e' or the color vector\n% by 0, e.g. to get only a red outline use 'er' or [0 1 0 0].\n%\n%\t The SIZE argument allows you to tune the size of the arrows. If\n%\t SIZE is a scalar, it scales the arrow proportionally. SIZE can\n%\t also be a two element vector, where the first element is the\n%\t overall scale (in percent), the second one controls the width\n%\t of the arrow head (again, in percent).\n%\n%\t The LOCAITON argument can be used to tweak the position of the\n% arrow head. If a time series of x and y coordinates are given,\n% you can use this argument to place the arrow head for instance\n% at 20% along the line. It can be a vector, if you want to have\n% more than one arrow head drawn.\n%\n%\t Both SIZE and LOCATION arguments must also be given in percent,\n%\t where 100 means standard size, 50 means half size, respectively\n%\t 100 means end of the vector, 0 beginning of it. Note that those\n%\t \"locations\" correspond to the cardinal position \"inside\" the\n%\t vector, in other words the \"index-wise\" position.\n%\n%\t This little tool is mainely intended to be used for indicating\n%\t \"directions\" on trajectories -- just give two consecutive times\n%\t and the corresponding values of a flux and the proper direction\n%\t of the trajectory will be shown on the plot. You may also pass\n%\t on two solution vectors, as described above.\n%\n%\t Note, that the arrow heads only look good in the original axis\n%\t settings (as in when the routine was actually started). If you\n%\t zoom in afterwards, the triangle will get distorted.\n%\n% HANDLES = ARROWH(...) will give you a vector with the handles\n% to the patches created by this function (if you want to modify\n% them later on, for instance).\n%\n%\t Examples of use:\n% \t x1 = [0:.2:2]; x2 = [0:.2:2]; plot(x1,x2); hold on;\n% \t arrowh(x1,x2,'r',[],20); % passing entire vectors\n% \t arrowh([0 1],[0 1],'eb',[300,75]); % passing 2 points\n% \t arrowh([0 1],[0 1],'eb',[300,75],25); % head closer to (x1,y1)\n\n%\t Author: Florian Knorn\n%\t Email: florian@knorn.org\n%\t Version: 1.14\n%\t Filedate: Jun 18th, 2008\n%\n%\t History: 1.14 - LOCATION now also works with lines\n% 1.13 - Allow for non-solid arrow heads\n% 1.12 - Return handle(s) of created patches\n% 1.11 - Possibility to change width\n%\t 1.10 - Buxfix\n%\t 1.09 - Possibility to chose *several* locations\n%\t 1.08 - Possibility to chose location\n%\t 1.07 - Choice of color\n%\t 1.06 - Bug fixes\n%\t 1.00 - Release\n%\n%\t ToDos: - Keep proportions when zooming or resizing; has to\n%\t be done with callback functions, I guess.\n%\n%\t Bugs: None discovered yet, those discovered were fixed\n%\n%\t Thanks: Thanks also to Oskar Vivero for using my humble\n%\t little program in his great MIMO-Toolbox.\n%\n%\t If you have suggestions for this program, if it doesn't work\n%\t for your \"situation\" or if you change something in it -- please\n%\t send me an email! This is my very first \"public\" program and\n%\t I'd like to improve it where I can -- your help is kindely\n%\t appreciated! Thank you!\n\nfunction handle = arrowh(x,y,clr,ArSize,Where)\n\n%-- errors\nif nargin < 2\n\terror('Please give enough coordinates !');\nend\nif (length(x) < 2) || (length(y) < 2),\n\terror('X and Y vectors must each have \"length\" >= 2 !');\nend\nif (x(1) == x(2)) && (y(1) == y(2)),\n\terror('Points superimposed - cannot determine direction !');\nend\nif nargin <= 2\n\tclr = 'b';\nend\nif nargin <= 3\n\tArSize = [100,100];\nend\n\nhandle = [];\n\n\n%-- check if variables left empty, deal width ArSize and Color\nif isempty(clr)\n\tclr = 'b'; nonsolid = false;\nelseif ischar(clr)\n\tif strncmp('e',clr,1) % for non-solid arrow heads\n\t\tnonsolid = true; clr = clr(2);\n\telse\n\t\tnonsolid = false;\n\tend\nelseif isvector(clr)\n\tif length(clr) == 4 && clr(1) == 0 % for non-solid arrow heads\n\t\tnonsolid = true;\n\t\tclr = clr(2:end);\n\telse\n\t\tnonsolid = false;\n\tend\nelse\n\terror('COLOR argument of wrong type (must be either char or vector)');\nend\n\nif nargin <= 4\n\tif (length(x) == length(y)) && (length(x) == 2)\n\t\tWhere = 100;\n\telse\n\t\tWhere = 50;\n\tend\nend\n\nif isempty(ArSize)\n\tArSize = [100,100];\nend\nif length(ArSize) == 2\n\tArWidth = 0.75*ArSize(2)/100; % .75 to make arrows it a bit slimmer\nelse\n\tArWidth = 0.75;\nend\nArSize = ArSize(1);\n\n%-- determine and remember the hold status, toggle if necessary\nif ishold,\n\tWasHold = 1;\nelse\n\tWasHold = 0;\n\thold on;\nend\n\n%-- start for-loop in case several arrows are wanted\nfor Loop = 1:length(Where),\n\n\t%-- if vectors \"longer\" then 2 are given we're dealing with time series\n\tif (length(x) == length(y)) && (length(x) > 2),\n\t\tj = floor(length(x)*Where(Loop)/100); %-- determine that location\n\t\tif j >= length(x), j = length(x) - 1; end\n\t\tif j == 0, j = 1; end\n\t\tx1 = x(j); x2 = x(j+1); y1 = y(j); y2 = y(j+1);\n\n\telse %-- just two points given - take those\n\t\tx1 = x(1); x2 = (1-Where/100)*x(1)+Where/100*x(2);\n\t\ty1 = y(1); y2 = (1-Where/100)*y(1)+Where/100*y(2);\n\tend\n\n\n\t%-- get axe ranges and their norm\n\tOriginalAxis = axis;\n\tXextend = abs(OriginalAxis(2)-OriginalAxis(1));\n\tYextend = abs(OriginalAxis(4)-OriginalAxis(3));\n\n\t%-- determine angle for the rotation of the triangle\n\tif x2 == x1, %-- line vertical, no need to calculate slope\n\t\tif y2 > y1,\n\t\t\tp = pi/2;\n\t\telse\n\t\t\tp= -pi/2;\n\t\tend\n\telse %-- line not vertical, go ahead and calculate slope\n\t\t%-- using normed differences (looks better like that)\n\t\tm = ( (y2 - y1)/Yextend ) / ( (x2 - x1)/Xextend );\n\t\tif x2 > x1, %-- now calculate the resulting angle\n\t\t\tp = atan(m);\n\t\telse\n\t\t\tp = atan(m) + pi;\n\t\tend\n\tend\n\n\t%-- the arrow is made of a transformed \"template triangle\".\n\t%-- it will be created, rotated, moved, resized and shifted.\n\n\t%-- the template triangle (it points \"east\", centered in (0,0)):\n\txt = [1\t-sin(pi/6)\t-sin(pi/6)];\n\tyt = ArWidth*[0\t cos(pi/6)\t-cos(pi/6)];\n\n\t%-- rotate it by the angle determined above:\n\txd = []; yd = [];\n\tfor i=1:3\n\t\txd(i) = cos(p)*xt(i) - sin(p)*yt(i);\n\t\tyd(i) = sin(p)*xt(i) + cos(p)*yt(i);\n\tend\n\n\t%-- move the triangle so that its \"head\" lays in (0,0):\n\txd = xd - cos(p);\n\tyd = yd - sin(p);\n\n\t%-- stretch/deform the triangle to look good on the current axes:\n\txd = xd*Xextend*ArSize/10000;\n\tyd = yd*Yextend*ArSize/10000;\n\n\t%-- move the triangle to the location where it's needed\n\txd = xd + x2;\n\tyd = yd + y2;\n\n\t%-- draw the actual triangle\n\thandle(Loop) = patch(xd,yd,clr,'EdgeColor',clr);\n\tif nonsolid, set(handle(Loop),'facecolor','none'); end\nend % Loops\n\n%-- restore original axe ranges and hold status\naxis(OriginalAxis);\nif ~WasHold,\n\thold off\nend\n\n%-- work done. good bye.", "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/33082-simplependulum/SimplePendulum/arrowh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.4991290887102828}} {"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 [B,elapse] = ITQ_compress(A, model)\n% This is a wrapper function of ITQ testing.\n%\n%\tUsage:\n%\t[B,elapse] = ITQ_compress(A, model)\n%\n%\t A: Rows of vectors of data points. Each row is sample point\n% model: The model generated by ITQ_learn.\n%\n%\t B: The binary code of the input data A. Each row is sample point\n% elapse: The coding time (testing time).\n%\n%\n%\n% version 2.0 --Nov/2016 \n% version 1.0 --Jan/2013 \n%\n% Written by Yue Lin (linyue29@gmail.com)\n% Deng Cai (dengcai AT gmail DOT com) \n% \n\ntmp_T = tic;\n\nYm = A * model.pc;\nYm = Ym * model.R;\nB = (Ym > 0);\n\nelapse = toc(tmp_T);\nend\n", "meta": {"author": "ZJULearning", "repo": "MatlabFunc", "sha": "97504df0f597c1980ab76ddc0c9c5d669043c6c9", "save_path": "github-repos/MATLAB/ZJULearning-MatlabFunc", "path": "github-repos/MATLAB/ZJULearning-MatlabFunc/MatlabFunc-97504df0f597c1980ab76ddc0c9c5d669043c6c9/ANNS/Hashing/Unsupervised/ITQ_compress.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.4991290852338524}} {"text": "%compute the ycoordinate of the center in the tails coordinate system\n\nfunction [data,units]=compute_ytailcentral_mm(trx,n)\n\nlarvae=trx.exp2flies{n};\nnumlarvae=numel(larvae);\nytailcentral_mm=cell(1,numlarvae);\n\nfor i=1:numlarvae\n larva=larvae(i);\n ytailcentral_mm{1,i}=trx(larva).ycentral_mm-trx(larva).ytail_mm;\nend\n\nunits=parseunits('mm');\ndata=ytailcentral_mm;\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/larva_compute_perframe_features/compute_ytailcentral_mm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.4991290852338524}} {"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 c = convv(a,b);\n%function c = convv(a,b);\n%\n%Convolves 3-D matrices a and b\n\n% S. de Waele, March 2003.\n\nsa = kingsize(a);\nsb = kingsize(b);\ns = sb;\ns(3) = sa(3)+sb(3)-1;\nb_z = zeros(s);\n\nb_z(:,:,1:sb(3)) = b;\nc = armafilterv(b_z,1,a);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/3680-automatic-spectral-analysis/AutomaticSpectra/Vectors/convv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6334102705979902, "lm_q1q2_score": 0.49908371184476386}} {"text": "function [V,D,permutation,failure] = dmpermblockeig(X,switchtosparse)\n \n[permutation,aux1,aux2,blocks] = dmperm(X+speye(length(X)));\nXpermuted = X(permutation,permutation);\n\nV = [];\nD = [];\nV = zeros(size(X,1),1);\ntop = 1;\nleft = 1;\nanycholfail = 0;\nfailure = 0;\n\nfor i = 1:length(blocks)-1\n Xi = Xpermuted(blocks(i):blocks(i+1)-1,blocks(i):blocks(i+1)-1);\n [R,fail] = chol(Xi);\n anycholfail = anycholfail | fail;\n if fail && nnz(Xi)>0\n if length(Xi) >= switchtosparse \n [vi,di,eigfail] = eigs(Xi,5,'SA'); \n if eigfail || isempty(di)\n res = 0;\n for j = 1:size(vi,2)\n res(j) = norm(Xi*vi(:,j)-vi(:,j)*di(j,j));\n end\n % We only trust these\n notfailed = abs(res) <= 1e-12;\n vi = vi(:,notfailed);\n di = di(notfailed,notfailed);\n if length(vi) == 0\n [vi,di,eigfail] = eigs(sparse(Xi),25,'SA'); \n if eigfail\n res = 0;\n for j = 1:size(vi,2)\n res(j) = norm(Xi*vi(:,j)-vi(:,j)*di(j,j));\n end\n % We only trust these\n notfailed = abs(res) <= 1e-12;\n vi = vi(:,notfailed);\n di = di(notfailed,notfailed);\n end\n end\n end\n else\n [vi,di] = eig(full(Xi));\n end\n for j = 1:length(di)\n if di(j,j)<=0\n V(top:top+length(Xi)-1,left)=vi(:,j);\n left = left + 1;\n D = blkdiag(D,di(j,j));\n end\n end\n end\n top = top + length(Xi);\nend\n\n\nif (anycholfail && isempty(V)) || (anycholfail && all(diag(D)>0)) \n % OK, we have a problem. The Cholesky factorization failed for some of\n % the matrices, but yet no eigenvalue decomposition revealed a negative\n % eigenvalue (due to convergence issues in the sparse eigs)\n failure = 1;\nend", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/modules/global/dmpermblockeig.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4990837063921617}} {"text": "function [oz] = l2oz(l)\n% Convert volume from liters to US liquid ounces. \n% Chad Greene 2012\noz = l*33.814022701;", "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/l2oz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.49907764885633754}} {"text": "function out = lsb_dec( wavin, pass )\n%LSB_DEC LSB Coding technique for WAV files using one bit to hide\n%\n% INPUT VARIABLES\n% wavin : Path of stego signal (wav input)\n% pass : Password for decryption\n%\n% OUTPUT VARIABLES\n% out : Retrieved message\n%\n% Kadir Tekeli (kadir.tekeli@outlook.com)\n\nif (nargin<2)\n pass = 'password123';\nend\n\n%Header = 1:40, Length = 41:43, Data = 44:end\nfid = fopen(wavin,'r'); \nheader = fread(fid,40,'uint8=>char');\ndsize = fread(fid,1,'uint32');\nstego = fread(fid,inf,'uint16');\nfclose(fid);\n%Control variable is read (1:8)\ncontrol = bitget(stego(1:8),1)';\n\nif b2d(control) == mod(sum(double(pass)),256)\n %Length of message is read (9:48)\n m = bitget(stego(9:48),1);\n len = b2d(m')*8;\n %Hidden message is read and decrypted (49:len)\n dat = xor(bitget(stego(49:48+len),1),prng(pass,len));\n bin = reshape(dat,len/8,8);\n out = char(b2d(bin))';\nelse\n warning('Password is wrong or message is corrupted!');\n out = [];\nend\nend\n\nfunction d = b2d(b)\n%B2D Minimal implentation of bi2de function\n if isempty(b)\n d = [];\n else \n d = b * (2 .^ (0:length(b(1,:)) - 1)');\n end\nend\n\nfunction out = prng( key, L )\n%PRNG Pseudorandom number generator for encryption/decryption\npass = sum(double(key).*(1:length(key)));\nrand('seed', pass);\nout = (rand(L, 1)>0.5);\nend", "meta": {"author": "ktekeli", "repo": "audio-steganography-algorithms", "sha": "695ae978cdec2537d64db771ed4a12887bda92f8", "save_path": "github-repos/MATLAB/ktekeli-audio-steganography-algorithms", "path": "github-repos/MATLAB/ktekeli-audio-steganography-algorithms/audio-steganography-algorithms-695ae978cdec2537d64db771ed4a12887bda92f8/03-LSB-Coding/lsb_dec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.49907764655809517}} {"text": "function mpc = ex_case3b\n%EX_CASE3B Three bus example system for stochastic unit commitment.\n% Same as EX_CASE3A with the following changes:\n% - Non-zero PMIN values for generators\n% - Linear (vs quadratic) generator costs\n% - Includes some STARTUP and SHUTDOWN costs\n% Please see CASEFORMAT for details on the case file format.\n\n% MOST\n% Copyright (c) 2015-2016, Power Systems Engineering Research Center (PSERC)\n% by Ray Zimmerman, PSERC Cornell\n%\n% This file is part of MOST.\n% Covered by the 3-clause BSD License (see LICENSE file for details).\n% See https://github.com/MATPOWER/most for more info.\n\n%% MATPOWER Case Format : Version 2\nmpc.version = '2';\n\n%%----- Power Flow Data -----%%\n%% system MVA base\nmpc.baseMVA = 100;\n\n%% bus data\n%\tbus_i\ttype\tPd\tQd\tGs\tBs\tarea\tVm\tVa\tbaseKV\tzone\tVmax\tVmin\nmpc.bus = [\n\t1\t3\t0\t0\t0\t0\t1\t1\t0\t135\t1\t1.05\t0.95;\n\t2\t2\t0\t0\t0\t0\t1\t1\t0\t135\t1\t1.05\t0.95;\n\t3\t2\t0\t0\t0\t0\t1\t1\t0\t135\t1\t1.05\t0.95;\n];\n\n%% generator data\n%\tbus\tPg\tQg\tQmax\tQmin\tVg\tmBase\tstatus\tPmax\tPmin\tPc1\tPc2\tQc1min\tQc1max\tQc2min\tQc2max\tramp_agc\tramp_10\tramp_30\tramp_q\tapf\nmpc.gen = [\n\t1\t125\t0\t25\t-25\t1\t100\t1\t200\t60\t0\t0\t0\t0\t0\t0\t0\t250\t250\t0\t0;\n\t1\t125\t0\t25\t-25\t1\t100\t1\t200\t65\t0\t0\t0\t0\t0\t0\t0\t250\t250\t0\t0;\n\t2\t200\t0\t50\t-50\t1\t100\t1\t500\t60\t0\t0\t0\t0\t0\t0\t0\t600\t600\t0\t0;\n\t3\t-450\t0\t0\t0\t1\t100\t1\t0\t-450\t0\t0\t0\t0\t0\t0\t0\t500\t500\t0\t0;\n];\n\n%% branch data\n%\tfbus\ttbus\tr\tx\tb\trateA\trateB\trateC\tratio\tangle\tstatus\tangmin\tangmax\nmpc.branch = [\n\t1\t2\t0.005\t0.01\t0\t300\t300\t300\t0\t0\t1\t-360\t360;\n\t1\t3\t0.005\t0.01\t0\t240\t240\t240\t0\t0\t1\t-360\t360;\n\t2\t3\t0.005\t0.01\t0\t300\t300\t300\t0\t0\t1\t-360\t360;\n];\n\n%%----- OPF Data -----%%\n%% generator cost data\n%\t1\tstartup\tshutdown\tn\tx1\ty1\t...\txn\tyn\n%\t2\tstartup\tshutdown\tn\tc(n-1)\t...\tc0\nmpc.gencost = [\n\t2\t0\t0\t2\t25\t0;\n\t2\t200\t200\t2\t30\t0;\n\t2\t3000\t600\t2\t40\t0;\n\t2\t0\t0\t2\t1000\t0;\n];\n\n%%----- Reserve Data -----%%\n%% reserve zones, element i, j is 1 if gen j is in zone i, 0 otherwise\nmpc.reserves.zones = [\n\t1\t1\t1\t0;\n];\n\n%% reserve requirements for each zone in MW\nmpc.reserves.req = 150;\n\n%% reserve costs in $/MW for each gen that belongs to at least 1 zone\n%% (same order as gens, but skipping any gen that does not belong to any zone)\n% mpc.reserves.cost = [\t5;\t5;\t21;\t];\n% mpc.reserves.cost = [\t5;\t5;\t16.25;\t];\n% mpc.reserves.cost = [\t0;\t0;\t11.25;\t];\nmpc.reserves.cost = [\t1;\t3;\t5;\t];\n\n%% OPTIONAL max reserve quantities for each gen that belongs to at least 1 zone\n%% (same order as gens, but skipping any gen that does not belong to any zone)\nmpc.reserves.qty = [\t100;\t100;\t200;\t];\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/most/lib/t/ex_case3b.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6688802603710085, "lm_q1q2_score": 0.4990776439313709}} {"text": "function totalEnergy = getEnergyDeposited(planC,structNum,doseNum)\n%function getEnergyDeposited(planC,structNum,doseNum)\n%\n%This function computes the total Energy deposited within a structure.\n%\n%APA, 04/21/2010\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by: Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n% This version of CERR is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR. If not, see .\n\nglobal stateS\nstateS.optS = opts4Exe([getCERRPath,'CERROptions.json']);\nstateS.MLVersion = getMLVersion;\n\nindexS = planC{end};\n\nscanNum = getStructureAssociatedScan(structNum,planC);\n\n%Get Uniformized dose matrix within the structure structNum\ndose3M = getUniformDose(doseNum, scanNum, structNum, planC);\n\nnumVoxels = length(find(dose3M > 0));\n\n%Get Uniformized scan matrix for scanNum\nscan3M = getUniformizedCTScan(1, scanNum, planC);\n\n[xV,yV,zV] = getUniformScanXYZVals(planC{indexS.scan}(scanNum));\n\ndx = abs(xV(1)-xV(2));\ndy = abs(yV(1)-yV(2));\ndz = abs(zV(1)-zV(2));\n\nvoxelVolume = dx * dy * dz;\n\ntotalEnergy = sum(dose3M(:).*scan3M(:))*voxelVolume*numVoxels;\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Utilities/getEnergyDeposited.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.49907764130464627}} {"text": "function [nodes, edges] = readGraph(fileName)\n%READGRAPH Read a graph from a text file.\n%\n% [NODES EDGES] = readGraph(FILENAME)\n%\n% Example\n% % create a basic graph, save it to a file, and read it again\n% nodes = [10 10;20 10;10 20;20 20;27 15];\n% edges = [1 2;1 3;2 4;2 5;3 4;4 5];\n% writeGraph(nodes, edges, 'simpleGraph.txt');\n% [n2 e2] = readGraph('simpleGraph.txt');\n% figure; drawGraph(n2, e2); axis equal; axis([0 40 0 30]);\n%\n% See also \n% writeGraph\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@grignon.inra.fr\n% Created: 2014-01-21, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2014-2022 INRA - Cepia Software Platform\n\n%% Open file and read header\n\n% open file for reading in text mode\nf = fopen(fileName, 'rt');\nif f == -1\n error(['could not open file for reading: ' fileName]);\nend\n\n% check header\nline = fgetl(f);\nif ~ischar(line) \n error(['can not read graph from empty file: ' fileName]);\nend\nif ~strcmpi(strtrim(line(2:end)), 'graph')\n error(['Wrong header line in file:' fileName]);\nend\n\n\n%% read node section\n\n% check sub-header\nline = fgetl(f);\nif ~strcmpi(strtrim(line(2:end)), 'nodes')\n error(['Could not interpret node section in file:' fileName]);\nend\n\n% read the number of nodes\nline = fgetl(f);\n[nNodesStr, line] = strtok(line);\nnNodes = str2double(nNodesStr);\n\n% read number of dimension, assumes 2 by default if not specified\nnDims = 2;\nif ~isempty(line)\n nDims = str2double(strtok(line));\nend\n\n% read node coordinates\n[nodes, nRead] = fscanf(f, '%g', [nDims nNodes]);\nassert(nRead == nNodes * nDims, ...\n 'Could not read all node info in file %s', fileName);\nnodes = nodes';\n\n% terminate the reading of current line\nfgetl(f);\n\n\n%% read edge section\n\n% check sub-header\nline = fgetl(f);\nif ~strcmpi(strtrim(line(2:end)), 'edges')\n error(['Could not interpret edge section in file:' fileName]);\nend\n\n% read the number of nodes\nline = fgetl(f);\nnEdgesStr = strtok(line);\nnEdges = str2double(nEdgesStr);\n\n% read node indices of each edge\n[edges, nRead] = fscanf(f, '%d %d\\n', [2 nEdges]);\nassert(nRead == nEdges * 2, ...\n 'Could not read all edge info in file %s', fileName);\nedges = edges';\n\n\n%% Clean up\n\nfclose(f);\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/graphs/readGraph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.4990776401555253}} {"text": "function mtrFigureSmoothness(kSmooth,saveDir)\n\n%Definitions\n%numSamples = 2000;\nbSaveImages = 1;\n\n% Create temp directory currently if none provided\n% if ieNotDefined(tempDir)\n% tempDir = 'temp';\n% end\n% mkdir(tempDir);\n% genPlotsSphDist(kSmooth,numSamples,tempDir);\ngenPlotsSphFunc(kSmooth);\nset(gcf,'Position',[504 751 354 195]);\nif bSaveImages\n figFilename = fullfile(saveDir,['smoothPdf.png']);\n set(gcf,'PaperPositionMode','auto');\n print('-dpng', figFilename);\nend\nreturn;\n\nfunction genPlotsSphFunc(kSmooth)\n % Going to color a sphere according to the desired distribution\nfigure;\n%cmap = [autumn(255); [.25 .25 .25]];\ncolormap(gray);\n[px py pz] = sphere(80);\ntestVec = [px(:) py(:) pz(:)]';\nwatValues = reshape(watsonPdf([0,0,1]',testVec,kSmooth),size(pz));\n% Get hemisphere\npz(pz<0) = 0;\nsurf(px,py,pz,reshape(watValues,size(px)),'EdgeAlpha',0,'FaceAlpha',1);\ncolorbar;\ncaxis([0,max(watValues(:))]);\naxis equal\naxis vis3d\ngrid on;\n\nreturn;\n\n\n\n\n\nfunction genPlotsSphDist(kSmooth,numSamples,tempDir)\n\n% Create script for sampling vectors according to desired distribution\ntempScriptFile = fullfile(tempDir,'tempRun.sh');\nfid = fopen(tempScriptFile,'wt');\nfprintf(fid,'#!/bin/bash\\n');\nfprintf(fid,'sphsample -pdf watson -k %g -ns %g -outputfile tempDist.Bdouble\\n',kSmooth,numSamples);\nfclose(fid);\ninput(['Run ' tempScriptFile ' then press [return] when finished to continue.']);\n\n% Cleanup and load the sample data\ndelete(tempScriptFile);\nfigure;\ncmap = [autumn(255); [.25 .25 .25]];\nsampleFile = fullfile(tempDir,'tempDist.Bdouble');\ndisplaySphDist(sampleFile,numSamples);\n%set(gca,'Postion',[0.13 0.11 0.775 0.815]);\ntitle(['\\DeltaS = ' num2str(round(180 / (pi*sqrt(kSmooth)))) ' \\circ']);\ndelete(sampleFile);\nreturn;\n\nfunction displaySphDist(sampleFile,numSamples)\n\nfid = fopen(sampleFile,'rb','b');\nd = fread(fid,'double'); fclose(fid);\nvecs = reshape(d,3,numSamples);\nsub_vecs = vecs(:,vecs(3,:)>0);\nplot3(sub_vecs(1,:), sub_vecs(2,:), sub_vecs(3,:), '.')\nhold on\n[px py pz] = sphere;\nsurf(px,py,pz,repmat(256,size(pz)),'EdgeAlpha',1,'FaceAlpha',0);\n%alpha(0.3)\naxis equal\naxis vis3d\ngrid off;\n% xlabel('x');\n% ylabel('y');\n% zlabel('z');\n\nreturn;", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrDiffusion/fiber/tractography/contrack/metrotrac/mtrFigureSmoothness.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.49907763408143746}} {"text": "function [M_, S_]=Prior2Posterior(M,Q,M_Q,S,G,S_G)\n\nM_=M+S*Q'*inv(Q*S*Q')*(M_Q-Q*M);\nS_=S+(S*G')*( inv(G*S*G')*S_G*inv(G*S*G') -inv(G*S*G') )*(G*S);\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/21307-fully-flexible-views-and-stress-testing/EntropyPooling/AnalyticalVsNumerical/Prior2Posterior.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869916479465, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.49906953926461056}} {"text": "load hershey\npalabra='D';\nsz=size(palabra);\nfigure\n%hold on\nxprev=0;\n%yprev=0;\n% accede a cada letra B\nfor i= 1:sz(2)\nB = hershey{palabra(i)};\n\n\n%Se muestran por pantalla las coordenadas y se marca con NaN cada uno de\n%los segmentos de la letra. Son los trazos que pueden dibujarse sin\n%levantar el lapiz de la superficie\nB.stroke;\n%X=[(B.stroke(1,:)+xprev+0.2) B.stroke(2,:)].*3; %Esfera\n%x= [2*X(1)/(1+X(1)^2+X(2)^2), 2*X(2)/(1+X(1)^2+X(2)^2), (-1+X(1)^2+X(2)^2)/(2+X(1)^2+X(2)^2)];\n\n%obten coordenadas \"unitarias\" x, y\nx=B.stroke(1,:)+xprev+0.2;\ny=B.stroke(2,:);\n\n%plotea mostrando las coordenadas de los puntos en coordenadas unitarias\n%%figure\nhold on\n%plot(x,y,'*')\nxprev=max(x);\n\nend\n% Con las lineas siguientes obtenemos una trayectoria que permite levantar\n% el lapiz cuando se finaliza cada trazo\npath = [ 0.25*B.stroke; zeros(1,size(B.stroke,2))]; \nk = find(isnan(path(1,:)));\npath(:,k) = path(:,k-1); \npath(3,k) = 0.2;\n\n% % plotea el camino\nplot3(path(1,:),path(2,:), path(3,:),'*')", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/demos/projects/draw_on_a_sphere/hershey_code_frase.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6442251201477015, "lm_q1q2_score": 0.4990060804326452}} {"text": "function tests = PGraphTest\n tests = functiontests(localfunctions);\nend\nfunction PGraph2_test(testCase)\n \n stream = RandStream.getGlobalStream;\n stream.reset()\n \n g = PGraph(2);\n\n % add first component, nodes 1-5\n g.add_node( rand(2,1));\n g.add_node( rand(2,1));\n g.add_node( rand(2,1));\n g.add_node( rand(2,1));\n g.add_node( rand(2,1));\n\n g.add_edge(1,2);\n g.add_edge(1,3);\n g.add_edge(1,4);\n g.add_edge(2,3);\n g.add_edge(2,4);\n g.add_edge(4,5);\n\n verifyEqual(testCase, g.n, 5);\n verifyEqual(testCase, g.ne, 6);\n verifyEqual(testCase, g.nc, 1);\n verifyEqual(testCase, g.neighbours(2), [3 4 1]);\n z = g.coord(1);\n %verifyEqual(testCase, g.distance(1,2), 0.6878, 'absTol',1e-4)\n% verifyEqual(testCase, g.distances([0 0]), ...\n% [0.6137 0.6398 0.9222 1.2183 1.3593], 'absTol',1e-4)\n\n D = g.degree();\n I = g.incidence();\n A = g.adjacency();\n L = g.laplacian();\n\n verifyEqual(testCase, D, diag([3 3 2 3 1]));\n verifyEqual(testCase, sum(I), [2 2 2 2 2 2]);\n verifyEqual(testCase, sum(I'), [3 3 2 3 1]);\n verifyEqual(testCase, max(max(A-A')), 0);\n \n verifyEqual(testCase, g.edgedir(1,3), 1);\n verifyEqual(testCase, g.edgedir(3,1), -1);\n verifyEqual(testCase, g.edgedir(2,5), 0);\n verifyEqual(testCase, g.neighbours_d(2), [-1 3 4]);\n\n\n s = g.char();\n\n % test node data\n g.setvdata(1, [1 2 3]);\n d = g.vdata(1);\n verifyEqual(testCase, d, [1 2 3]);\n \n % test edge data\n g.setedata(1, [4 5 6 7]);\n d = g.edata(1);\n verifyEqual(testCase, d, [4 5 6 7]);\n \n % add second component, nodes 6-8\n\n g.add_node( rand(2,1));\n g.add_node( rand(2,1), 6, 1);\n g.add_node( rand(2,1), 7);\n g.add_edge(6,7);\n g.add_edge(6,8);\n\n verifyEqual(testCase, g.nc, 2);\n\n clf\n g.plot('labels')\n g.plot('edgelabels')\n g.plot('componentcolor')\n\n [path,cost]=g.Astar(3,5);\n g.highlight_path(path);\n %verifyEqual(testCase, path, [3 2 4 5]);\n %verifyEqual(testCase, cost, 2.1536, 'absTol',1e-4)\n\n %verifyEqual(testCase, g.closest([0 0]), 4);\n\n g.setcost(1, 99);\n verifyEqual(testCase, g.cost(1), 99);\n \n g.Astar(3, 5);\n %verifyEqual(testCase, path, [3 2 4 5]);\nend\n\nfunction PGraph3_test(testCase)\n \n stream = RandStream.getGlobalStream;\n stream.reset()\n \n g = PGraph(3);\n\n g.add_node( rand(3,1));\n g.add_node( rand(3,1));\n g.add_node( rand(3,1));\n g.add_node( rand(3,1));\n g.add_node( rand(3,1));\n\n g.add_edge(1,2);\n g.add_edge(1,3);\n g.add_edge(1,4);\n g.add_edge(2,3);\n g.add_edge(2,4);\n g.add_edge(4,5);\n\n clf\n g.plot('labels')\n g.plot('edgelabels')\nend\n", "meta": {"author": "petercorke", "repo": "spatialmath-matlab", "sha": "6eeff4a79f14286705560b84f1fe72e0b7e0e7f7", "save_path": "github-repos/MATLAB/petercorke-spatialmath-matlab", "path": "github-repos/MATLAB/petercorke-spatialmath-matlab/spatialmath-matlab-6eeff4a79f14286705560b84f1fe72e0b7e0e7f7/unit_test/PGraphTest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.49900606702347655}} {"text": "function grad = B_SpatialCovMask(future_layers, prev_layers, curr_layer)\nmask = prev_layers{1}.a;\ndata = prev_layers{2}.a;\n[D,T,N] = size(mask);\n[D2,T,N] = size(data);\nnCh = D2/D;\ndata = reshape(data, D, nCh, T, N);\ndata = permute(data, [2 3 1 4]);\n% data = abs(data);\n\nmask_f = sum(mask,2); % sum of mask over time\n\nspatCov = curr_layer.a;\nspeechCov = reshape(spatCov(1:D*nCh^2,:,:,:), nCh^2,1,D,N);\nnoiseCov = reshape(spatCov(D*nCh^2+1:end,:,:,:), nCh^2,1,D,N);\n\nfuture_grad = GetFutureGrad(future_layers, curr_layer);\nfuture_grad_speech = reshape(future_grad(1:D*nCh^2,:,:), nCh^2,1,D,N);\nfuture_grad_noise = reshape(future_grad(D*nCh^2+1:end,:,:), nCh^2,1,D,N);\n\n% from speech covariance\nif 0 % slow implementation\n data = gather(data);\n data_cell = num2cell(data, [1]);\n tic; xx = cellfun(@(x) (reshape(x*x',nCh^2,1)), data_cell, 'UniformOutput', 0);toc;\n xx2 = cell2mat(xx);\nelse % really fast implementation\n xx2 = reshape(outProdND(data), nCh^2, T,D);\nend\n\ngradFromSpeech = bsxfun(@minus, xx2, speechCov);\ngradFromSpeech = bsxfun(@times, gradFromSpeech, future_grad_speech);\ngradFromSpeech = squeeze(sum(gradFromSpeech))';\ngradFromSpeech = bsxfun(@times, gradFromSpeech, 1./mask_f);\n\ngradFromNoise = bsxfun(@minus, xx2, noiseCov);\ngradFromNoise = bsxfun(@times, gradFromNoise, future_grad_noise);\ngradFromNoise = squeeze(sum(gradFromNoise))';\ngradFromNoise = bsxfun(@times, gradFromNoise, 1./(T-mask_f));\n\ngrad = gradFromSpeech - gradFromNoise;\n% we may get complex valued gradient for real valued mask, as the partial\n% derivative formula does not know that the mask must be real valued. To\n% preserve the real-valued property of the mask, we just take the real part\n% of the gradient, which represents the search direction of mask in the\n% real domain.\ngrad = real(grad); \n\nend", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/graph/B_SpatialCovMask.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.49900606702347655}} {"text": "classdef GradientVariationWithBoundaryComputer < handle\n \n properties (Access = public)\n error \n mean\n desv\n end\n \n properties (Access = private)\n levelSet\n curvature\n rPerimeter\n backgroundMesh\n boundaryMesh\n domainLength\n circleCase\n filePlotName \n circleMesh\n unfittedMesh \n integrator\n \n gradientCircunf\n nEpsilon\n end\n \n methods (Access = public)\n \n function obj = GradientVariationWithBoundaryComputer(cParams)\n obj.init(cParams)\n end\n \n function compute(obj) \n obj.createIntegrator();\n for iEpsilon = 1:obj.nEpsilon\n obj.computeGradientInCircunference(iEpsilon);\n obj.computeVariables(iEpsilon); \n end\n end\n \n end\n \n methods (Access = private)\n \n function init(obj,cParams)\n obj.filePlotName = cParams.filePlotName;\n obj.backgroundMesh = cParams.backgroundMesh;\n obj.circleMesh = cParams.circleMesh;\n obj.levelSet = cParams.levelSet;\n obj.curvature = cParams.curvature;\n obj.rPerimeter = cParams.regularizedPerimeter;\n obj.domainLength = cParams.domainLength;\n obj.circleCase = cParams.circleCase;\n obj.nEpsilon = size(obj.rPerimeter.epsilons,2);\n end\n \n function computeVariables(obj,iepsilon)\n int = obj.integrator;\n M = int.computeLHS(); \n k = obj.curvature;\n g = obj.gradientCircunf;\n obj.error(iepsilon) = (g-k)'*M*(g-k)/(k*sum(M(:))*k);\n obj.mean(iepsilon) = sum(int.integrate(g))/sum(int.integrate(ones(size(g))));\n obj.desv(iepsilon) = (g-obj.mean(iepsilon))'*M*(g-obj.mean(iepsilon))/(sum(M(:)));\n end\n \n function createIntegrator(obj)\n m = obj.circleMesh.mesh;\n m = m.computeCanonicalMesh(); \n s.type = 'SIMPLE';\n s.mesh = m; \n s.npnod = m.nnodes;\n s.globalConnec = m.connec;\n obj.integrator = Integrator.create(s); \n end \n \n function computeGradientInCircunference(obj,iepsilon)\n nCell = obj.circleMesh.mesh.nelem;\n gB = zeros(nCell,1); \n gD = obj.rPerimeter.perimetersGradient(:,iepsilon);\n switch obj.circleCase\n case 'interior'\n for icell = 1:nCell\n gNodalInCell = obj.computeFnodalInCell(icell,gD);\n xPos = obj.computeXpos(icell);\n gInXpos = obj.interpolateValue(xPos,gNodalInCell);\n gB(icell) = gInXpos;\n end\n case 'exterior'\n m = obj.circleMesh;\n gB = gD(m.nodesInBoxFaces,1);\n end\n obj.gradientCircunf = gB;\n end \n \n function fNodalInCell = computeFnodalInCell(obj,icell,fNodal)\n m = obj.circleMesh; \n cellGlobal = m.cellContainingSubcell(icell);\n nodeTriangle = obj.backgroundMesh.connec(cellGlobal,:);\n fNodalInCell = fNodal(nodeTriangle(:),:);\n end\n \n function x1pos = computeXpos(obj,icell)\n m = obj.circleMesh;\n x1pos = m.xCoordsIso(:,1,icell);\n x1pos = squeeze(x1pos);\n end\n \n function fInterp = interpolateValue(obj,xpos,fNodal)\n interp = Interpolation.create(obj.backgroundMesh,'LINEAR');\n interp.computeShapeDeriv(xpos);\n shape = interp.shape;\n fInterp = 0;\n for inode = 1:length(shape)\n fInterp = fInterp + fNodal(inode)*shape(inode);\n end\n end\n \n end \n \nend", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/Applications/PerimeterExperiments/GradientVariationWithBoundaryComputer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.49900606314622026}} {"text": "function vectors3d(varargin)\n%VECTORS3D Description of functions operating on 3D vectors\n%\n% Vectors are represented by their 3 Cartesian coordinates:\n% V = [VX VY VZ];\n%\n% List of vectors are represented by N-by-3 arrays, with the coordinates\n% of each vector on a row.\n%\n%\n% See also\n% vectorNorm3d, normalizeVector3d, crossProduct3d, vectorAngle3d\n% isParallel3d, isPerpendicular3d, createTranslation3d\n% drawVector3d\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2008-10-13, using Matlab 7.4.0.287 (R2007a)\n% Copyright 2008 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas.\n", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/matGeom/geom3d/vectors3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.49900139753032957}} {"text": "function test6\n%TEST6 test for BTF\n% Requires UFget\n% Example:\n% test6\n% See also btf, maxtrans, strongcomp, dmperm, UFget,\n% test1, test2, test3, test4, test5.\n\n% Copyright 2007, Timothy A. Davis, University of Florida\n\nquick2 = [ ...\n 1522 -272 1463 1521 460 1507 -838 1533 -1533 -1456 -1512 734 211 ...\n -385 -735 394 -397 1109 -744 ...\n -734 -375 -1200 -1536 -837 519 -519 520 -520 189 -189 454 385 ...\n 387 -387 384 -384 386 -386 388 -388 525 -525 526 -526 735 ...\n 1508 209 210 1243 -1243 1534 -840 1234 -1234 390 -390 392 -392 ...\n -394 1472 1242 -1242 389 -389 391 -391 393 -393 1215 -1215 1216 ...\n-1216 736 -736 737 -737 455 -455 -224 -839 1426 -1426 -1473 396 ...\n -396 398 -398 400 -400 402 -402 404 -404 -1531 395 -395 397 ...\n 399 -399 401 -401 403 -403 405 -405 -738 -739 1459 -1459 1111 ...\n 1110 376 -376 284 -284 -740 -742 -741 -743 1293 -1293 452 920 ...\n -745 -446 1462 -1461 448 -448 283 -283 1502 -1502 1292 -1292 1503 ...\n-1503 1291 -1291 445 -445 -746 -747 1300 -1300 435 -435 -1343 -1345 ...\n-1344 1305 -1305 921 -1513 1307 -1307 1369 -1369 1374 -1374 1377 ...\n-1377 748 -748 -749 1510 922 -922 ] ;\n\nindex = UFget ;\nnmat = length (quick2) ;\ndopause = 0 ;\n\nh = waitbar (0, 'BTF test 6 of 6') ;\n\ntry\n\n for k = 1:nmat\n\n waitbar (k/nmat, h) ;\n\n i = quick2 (k) ;\n Prob = UFget (abs (i), index) ;\n disp (Prob) ;\n if (i < 0)\n fprintf ('transposed\\n') ;\n A = Prob.A' ;\n [m n] = size (A) ;\n if (m == n)\n if (nnz (spones (A) - spones (Prob.A)) == 0)\n fprintf ('skip...\\n') ;\n continue ;\n end\n end\n else\n A = Prob.A ;\n end\n\n tic\n [p1,q1,r1,work1] = btf (A) ;\n t1 = toc ;\n n1 = length (r1) - 1 ;\n m1 = nnz (diag (A (p1, abs (q1)))) ;\n\n limit = work1/nnz(A) ;\n\n fprintf ('full search: %g * nnz(A)\\n', limit) ;\n\n works = linspace(0,limit,9) ;\n works (1) = eps ;\n nw = length (works) ;\n\n T2 = zeros (nw, 1) ;\n N2 = zeros (nw, 1) ;\n M2 = zeros (nw, 1) ;\n\n T2 (end) = t1 ;\n N2 (end) = n1 ;\n M2 (end) = m1 ;\n\n fprintf ('full time %10.4f blocks %8d nnz(diag) %8d\\n\\n', t1, n1, m1) ;\n\n subplot (3,4,4) ;\n drawbtf (A, p1, abs (q1), r1) ;\n title (Prob.name, 'Interpreter', 'none') ;\n\n for j = 1:nw-1\n\n maxwork = works (j) ;\n\n tic\n [p2,q2,r2,work2] = btf (A, maxwork) ;\n t2 = toc ;\n n2 = length (r2) - 1 ;\n m2 = nnz (diag (A (p2, abs (q2)))) ;\n T2 (j) = t2 ;\n N2 (j) = n2 ;\n M2 (j) = m2 ;\n\n fprintf ('%9.1f %10.4f blocks %8d nnz(diag) %8d\\n', ...\n maxwork, t2, n2, m2) ;\n\n subplot (3,4,4+j) ;\n drawbtf (A, p2, abs (q2), r2) ;\n title (sprintf ('%g', maxwork)) ;\n\n ss = [1:j nw] ;\n\n subplot (3,4,1) ;\n plot (works(ss), T2(ss), 'o-') ; title ('time vs work') ;\n axis ([0 limit 0 max(0.1,max(T2))]) ;\n\n subplot (3,4,2) ;\n plot (works(ss), N2(ss), 'o-') ; title ('blocks vs work') ;\n axis ([0 limit 0 n1]) ;\n\n subplot (3,4,3) ;\n plot (works(ss), M2(ss), 'o-') ; title ('nnz(diag) vs work') ;\n axis ([0 limit 0 m1]) ;\n drawnow\n\n end\n fprintf ('full time %10.4f blocks %8d nnz(diag) %8d\\n', t1, n1, m1) ;\n\n if (dopause)\n input ('hit enter: ') ;\n end\n\n end\n\ncatch\n % out-of-memory is OK, other errors are not\n disp (lasterr) ;\n if (isempty (strfind (lasterr, 'Out of memory')))\n error (lasterr) ; %#ok\n else\n fprintf ('test terminated early, but otherwise OK\\n') ;\n end\nend\n\nclose (h) ;\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/BTF/MATLAB/Test/test6.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300048, "lm_q2_score": 0.6825737279551493, "lm_q1q2_score": 0.49900137936907496}} {"text": "function timespderiv(options, flags)\n% TIMESPDERIV Measure the performance of SPINTERP with derivatives\n% TIMESPDERIV(OPTIONS) Script file to plot a graph showing the \n% ratio of computing BOTH interpolated values AND gradients to \n% computing interpolated values ONLY (at 100 points simultaneously). \n% By default, the Clenshaw-Curtis-grid with sparse indices data is \n% used. Alternatively, the Chebyshev grid and other options\n% may be selected using an OPTIONS structure created with SPSET.\n%\n% TIMESPDERIV(OPTIONS, FLAGS) FLAGS is an optional struct that \n% customizes the plots.\n% The following FLAGS are available:\n% continuousDerivatives [ 'on' | 'off' ] turns on the augmented\n% continuous derivatives available for the Clenshaw-Curtis \n% sparse grid.\n% absoluteTime [ 'on' | 'off' ] plots the absolute measured\n% time in seconds instead of the ratio.\n% nPoints [ integer {100} ] can be used to change the default\n% number of interpolated points.\n%\n% Examples:\n% Plot ratios for CC-Grid, discontinuous derivatives:\n% timespderiv;\n%\n% Plot ratios for CC-Grid, augmented continuous derivatives:\n% flags = struct('continuousDerivatives', 'on');\n% timespderiv([], flags);\n%\n% Plot ratios for CGL-Grid:\n% timespderiv(spset('GridType','Chebyshev')); \n%\n% Plot absolute time measurements for CGL-Grid:\n% flags = struct('absoluteTime', 'on');\n% timespderiv(spset('GridType','Chebyshev'), flags); \n% \n% See also SPSET, SPINTERP, TESTFUNCTIONS. \n\n% Author : Andreas Klimke, Universitaet Stuttgart\n% Version: 1.0\n% Date : July 8, 2006\n\n% ------------------------------------------------------------\n% Sparse Grid Interpolation Toolbox\n% Copyright (c) 2006 W. Andreas Klimke, Universitaet Stuttgart \n% Copyright (c) 2007-2008 W. A. Klimke. All Rights Reserved.\n% See LICENSE.txt for license. \n% email: klimkeas@ians.uni-stuttgart.de\n% web : http://www.ians.uni-stuttgart.de/spinterp\n% ------------------------------------------------------------\n\nif nargin < 1, options = []; end\nif nargin < 2, flags = []; end\n\ncontinuousDerivatives = 0;\nif isfield(flags, 'continuousDerivatives')\n\tif strcmpi(flags.continuousDerivatives, 'on')\n\t\tcontinuousDerivatives = 1;\n\tend\nend\n\nabsoluteTime = 0;\nif isfield(flags, 'absoluteTime')\n\tif strcmpi(flags.absoluteTime, 'on')\n\t\tabsoluteTime = 1;\n\tend\nend\n\n% Number of points to interpolate\nnsamplepoints = 100;\nif isfield(flags, 'nPoints')\n\tnsamplepoints = flags.nPoints;\nend\n\nsparseIndices = spget(options, 'SparseIndices', 'auto');\ngridtype = spget(options, 'GridType', 'Clenshaw-Curtis');\n\n% Set the problem dimensions and the maximum discretization levels\n% for each dimension.\nswitch lower(gridtype)\n case 'clenshaw-curtis'\n\td = [1,2,4,8,16];\n n = [17,13,10,6,4];\n case 'noboundary'\n\terror('MATLAB:timespderiv:badopt',['Computing derivatives not ' ...\n\t 'supported for grid type ''' gridtype '''.']);\n case 'maximum'\n\terror('MATLAB:timespderiv:badopt',['Computing derivatives not ' ...\n\t 'supported for grid type ''' gridtype '''.']);\n case 'chebyshev'\n\td = [1,2,4,8,16];\n n = [17,13,10,6,4];\n otherwise\n\terror('MATLAB:timespderiv:badopt','Unknown grid type.');\nend\n\nndims = length(n);\nmarkers = ['s', '.', 'd', '+', 'o', 'x', '*', 'v', '^'];\n\n% Compute random constants w and c for Gerz' test functions.\nw = rand(d(end),1);\nc = rand(d(end),1);\nsumc = sum(c,1);\nsumw = sum(w,1);\nc = 1.5.*c/sumc;\nw = w/sumw;\n\ntime = zeros(ndims,n(1)+1);\nnpoints = zeros(ndims,n(1)+1);\n\nfor k = 1:d(end)\n\tv{k} = rand(nsamplepoints,1);\nend\n\t\nfor m = 1:ndims\n\tdisp(['Current dim: ' num2str(d(m))]);\n\tz = [];\n\tfor l = 0:n(m)\n\t\tdisp(['Current level n = ' num2str(l) '...']);\n\t\toptions = spset('MinDepth',l,'MaxDepth',l,'Vectorized','on',...\n\t\t\t\t\t\t\t\t\t\t'GridType', gridtype, 'SparseIndices', ...\n\t\t\t\t\t\t\t\t\t\tsparseIndices, 'PrevResults', z);\n\t\tz = spvals('testfunctions',d(m),[],options,1,c(1:d(m)),w(1: ...\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\td(m)));\n\t\tt = z.surplusCompTime;\n\t\tdisp(['Computing sparse grid points and evaluating function took ' ...\n\t\t\t\t\tnum2str(z.fevalTime) ' [s].']);\n\t\tdisp(['Computing hierarchical surpluses took ' num2str(t) ' [s].']);\n\t\tnpoints(m,l+1) = z.nPoints;\n\t\tif continuousDerivatives\n\t\t\tz.continuousDerivatives = 'on';\n\t\tend\n\t\tt = 0; k = 0;\n\t\ttic;\n\t\twhile t < 0.5\n\t\t\ty = spinterp(z,v{1:d(m)});\n\t\t\tt = toc;\n\t\t\tk = k + 1;\n\t\tend\n\t\tt = t / k;\n\t\tt2 = 0; k = 0;\n\t\ttic;\n\t\twhile t2 < 0.5\n\t\t\t[y,dy] = spinterp(z,v{1:d(m)});\n\t\t\tt2 = toc;\n\t\t\tk = k + 1;\n\t\tend\n\t\tt2 = t2 / k;\n\t\tif absoluteTime\n\t\t\ttime(m,l+1) = t2;\n\t\telse\n\t\t\ttime(m,l+1) = t2/t;\n\t\tend\n\t\tdisp([num2str(nsamplepoints) ...\n\t\t\t\t\t' evals took ' num2str(t) ' [s], with gradients ' ...\n\t\t\t\t\tnum2str(t2) ' [s]. Ratio: ' num2str(t2/t)]);\n\t\tdisp(' ');\n\tend\n\tdisp('Done!');\n\tdisp(' ');\nend\n\n% Plot results\nclf;\nh = loglog(npoints',time','LineWidth',1);\nfor k = 1:ndims\n\tset(h(k), 'Marker', markers(k));\n\thold on;\nend\naxis tight;\nhold on;\n\n% Add legend and axis labels\nhold off;\nif absoluteTime\n\tif ~continuousDerivatives\n\t\ttitle(['Time to compute ' num2str(nsamplepoints) ...\n\t\t\t\t\t' values with gradients [' gridtype ' grid].']);\n\telse\n\t\ttitle(['Time to compute ' num2str(nsamplepoints) ...\n\t\t\t\t\t' vals with CONTINUOUS grads [' gridtype ' grid].']);\n\tend\n\tylabel('Time [s]')\nelse\n\tif ~continuousDerivatives\n\t\ttitle(['Ratio of interpolating ' num2str(nsamplepoints) ...\n\t\t\t\t\t' values with/without gradients [' gridtype ' grid].']);\n\telse\n\t\ttitle(['Ratio of interpol. ' num2str(nsamplepoints) ...\n\t\t\t\t\t' vals with/without CONTINUOUS grads [' gridtype ' grid].']);\n\tend\n\tylabel('Ratio [-]')\n\tset(gca,'YTick',[1,2,5,10,20,50]);\n\tset(gca,'YLim',[0.8,50]);\nend\nxlabel('number of nodes N')\ns = {};\nfor k = 1:ndims\n\ts{k} = ['d = ' num2str(d(k))];\nend\n\nif strcmpi(gridtype, 'chebyshev')\n\tlegend(s,2);\nelse\n\tlegend(s,1);\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/spinterp/examples/timespderiv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.7310585669110203, "lm_q1q2_score": 0.4990013666494311}} {"text": "function Im=RGB_YUV(Y,U,V)\n% This program transform YUV layers to RGB Layers in ome matrix 'Im'....\n% By Mohammed Mustafa Siddeq\n% Date 25/7/2010\n\nG=round((Y-(U+V)/4));\nR=U+G;\nB=V+G;\nIm(:,:,1)=R; Im(:,:,2)=G; Im(:,:,3)=B; \n%imshow(uint8(Im));\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/33352-convert-rgb-into-yuv-format/RGB_YUV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7577943822145997, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.49894508307742147}} {"text": "% extract the boundary vertices of all ROIs\n% NOTE: requires Matlab R2014b\n\n%%\n% load_data;\n\n%%\ntic\n\nfigure;\nxyz_ls=plot_ROI_3D(CONST,1:nCells);\nclose(gcf);\n\ns=0.7; % shrink parameter, not affecting much\nP=xyz_ls';\nP(:,2)=-P(:,2); % special treatment for y\nk_ls= boundary(P,s);\n\ndisplay('time to generate boundary:')\ntoc\n\n%%\nsave(['data/boundary_k_s',num2str(s),'.mat'],'k_ls','s');\nsave('data/xyz_ls.mat','xyz_ls');\n\n", "meta": {"author": "xiuyechen", "repo": "FishExplorer", "sha": "c61392cf0835480d64fc03c15f1992935fdc7106", "save_path": "github-repos/MATLAB/xiuyechen-FishExplorer", "path": "github-repos/MATLAB/xiuyechen-FishExplorer/FishExplorer-c61392cf0835480d64fc03c15f1992935fdc7106/old code/Yu Hu's code/plot_ROI_3D/plot_ROI_3D/gen_boundary.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.49894508095359763}} {"text": "% C = FindClustermeans(gIX,M);\n% [C_trialAvr,C_trialRes,C_score,C_d2var_perstim] = GetTrialAvrLongTrace(hGUI,C);\n\n%% Init load\nhfig = figure;\nInitializeAppData(hfig);\nResetDisplayParams(hfig);\n\n%% Load Fish8\ni_fish = 8;\n[cIX_load,gIX_load,M,stim,behavior,M_0] = LoadSingleFishDefault(i_fish,hfig,[1,1]);\n\nfishset = getappdata(hfig,'fishset');\nstim = getappdata(hfig,'stim');\nbehavior = getappdata(hfig,'behavior');\nfpsec = getappdata(hfig,'fpsec');\n\n%% crop\ncropIX = 3001:3600;\nstim_crop = stim(cropIX);\nbehavior_crop = behavior(:,cropIX);%(2,3001:3600);\n\n% stim z\nregressors_s = GetStimRegressor(stim_crop,fishset,i_fish);\nreg_s = regressors_s(8).im;\n% motor\nregressors_m = GetMotorRegressor(behavior_crop);\nreg_m = regressors_m(2).im; %1\nreg_motor_n = reg_m/sqrt(sum(reg_m.*reg_m));\n%%\nreg_stim_n = reg_s/sqrt(sum(reg_s.*reg_s));\n%%\n\n%% get tRes/tAvr\nC = reg_motor_n;\n% GetTrialAvrLongTrace\nperiod = 150; % 120 for PT, 150 for OMR\nC_3D_0 = reshape(C,size(C,1),period,[]);\n\n% C_3D = zscore(C_3D_0,0,2);\n% C_d2var_perstim = nanmean(nanstd(C_3D,0,3),2);\n% C_score = C_d2var_perstim;\n\nC_period = mean(C_3D_0,3);%prctile(C_3D_0,20,3);%mean(C_3D_0,3);\nnPeriods = round(size(C,2)/period);\nC_trialAvr = repmat(C_period,1,nPeriods);\n\nC_trialRes = C-C_trialAvr;\n\n%% tRes/tAvr demo trace plot\nxv = (1:600)/fpsec;\n\n% find vertical stim time-references\nx_stim = stim_crop';\nx_stim(x_stim~=11) = 9;\nxlines = xv(find(diff([0;x_stim])~=0));\n\n\nfigure('Position',[50,200,300,200]); hold on\n\n% plot vertical reference shadings\nfor i = 2:2:length(xlines)\n x_ = [xlines(i),xlines(i+1)];\n y_ = [-1,0.2];\n x = [x_(1),x_(2),x_(2),x_(1)];\n y = [y_(1),y_(1),y_(2),y_(2)];\n patch(x, y, [1,0.9,0.9],'Edgecolor','w');\nend\n\n% plot traces\nplot(xv,reg_stim_n,'k')\n\nyoffset = -0.3;\nplot(xv,reg_motor_n+yoffset,'k')\n\nyoffset = -0.6;\nplot(xv,C_trialAvr+yoffset,'k')\n\nyoffset = -0.9;\nplot(xv,C_trialRes+yoffset,'k')\n\nxlim([0,300])\n% xlabel('Time (sec)')\nax = gca;\nax.YTick = [-0.9,-0.6,-0.3,0];\nax.YTickLabel = {'trial-Res.','trial-Avr.','motor','stim.'};\n\nylim([-1.2,0.2]);\nset(gca,'xcolor','w','xtick',[]);\nset(gca,'TickLength',[0,0]);\n% plot scale bar\nplot([xv(1)+5,xv(40)+5],[-1.1,-1.1],'k','linewidth',1.5);\ntext(xv(1)+5,-1.2,'20 sec')\n\n%% figS3h: L/R demo trace plot\ni_fish = 2;\n[cIX_load,gIX_load,M,stim,behavior,M_0] = LoadSingleFishDefault(i_fish,hfig,[1,1]);\n\nfishset = getappdata(hfig,'fishset');\nstim = getappdata(hfig,'stim');\nbehavior = getappdata(hfig,'behavior');\nfpsec = getappdata(hfig,'fpsec');\n\n%% crop\ncropIX = 3001:3300;%3001:3600;\nstim_crop = stim(cropIX);\nbehavior_crop = behavior(:,cropIX);%(2,3001:3600);\nregressors_s = GetStimRegressor(stim_crop,fishset,i_fish);\nregressors_m = GetMotorRegressor(behavior_crop);\n\nreg_mL = regressors_m(1).im; %1\nreg_mR = regressors_m(2).im; %1\nreg_mL_n = reg_mL/sqrt(sum(reg_mL.*reg_mL));\nreg_mR_n = reg_mR/sqrt(sum(reg_mR.*reg_mR));\nlrAvr = 0.5*(reg_mL_n+reg_mR_n);\nlrAvr_n = lrAvr/sqrt(sum(lrAvr.*lrAvr));\nlrRes1 = reg_mL_n-lrAvr;\nlrRes_n1 = lrRes1/sqrt(sum(lrRes1.*lrRes1));\nlrRes2 = reg_mR_n-lrAvr;\nlrRes_n2 = lrRes2/sqrt(sum(lrRes2.*lrRes2));\n%%\nfigure('Position',[50,200,400,300]); hold on\nxv = (1:length(cropIX))/fpsec;\n\n% plot vertical reference shadings\n% for i = 2:2:length(xlines)\n% x_ = [xlines(i),xlines(i+1)];\n% y_ = [-1,0.2];\n% x = [x_(1),x_(2),x_(2),x_(1)];\n% y = [y_(1),y_(1),y_(2),y_(2)];\n% patch(x, y, [1,0.9,0.9],'Edgecolor','w');\n% end\n\n% plot traces\n% plot(xv,reg_stim_n,'k')\nspacing = 0.5;\nyoffset = 0;\nplot(xv,reg_mL_n+yoffset,'k')\n\nyoffset = yoffset-spacing;\nplot(xv,reg_mR_n+yoffset,'k')\n\nyoffset = yoffset-spacing;\nplot(xv,lrAvr_n+yoffset,'k')\n\nyoffset = yoffset-spacing;\nplot(xv,lrRes_n1+yoffset,'k')\n\nyoffset = yoffset-spacing;\nplot(xv,lrRes_n2+yoffset,'k')\n\n% xlim([0,300])\n% xlabel('Time (sec)')\nax = gca;\nax.YTick = [-spacing*4,-spacing*3,-spacing*2,-spacing,0];\nax.YTickLabel = {'R-Res.','L-Res.','LR-Avr.','R motor','L motor'};\n\nylim([-spacing*5,spacing]);\nset(gca,'xcolor','w','xtick',[]);\nset(gca,'TickLength',[0,0]);\n% plot scale bar\nplot([xv(1)+5,xv(40)+5],[-spacing*4.6,-spacing*4.6],'k','linewidth',1.5);\ntext(xv(1)+5,-spacing*4.9,'20 sec')\n", "meta": {"author": "xiuyechen", "repo": "FishExplorer", "sha": "c61392cf0835480d64fc03c15f1992935fdc7106", "save_path": "github-repos/MATLAB/xiuyechen-FishExplorer", "path": "github-repos/MATLAB/xiuyechen-FishExplorer/FishExplorer-c61392cf0835480d64fc03c15f1992935fdc7106/figure scripts/SensoryMotor/fig3a_illustration.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.49894508095359763}} {"text": "function showmesh3(node,elem,expr,varargin)\n%% SHOWMESH3 displays a tetrahedron mesh in 3-D.\n%\n% showmesh3(node,elem) displays a 3-dimensional tetrahderon mesh given\n% by node and elem matrices; see meshdoc for the data structure:\n% node and elem.\n%\n% showmesh3(node,elem,expr) displays parts of the mesh specificed by the\n% expression. For example, showmesh3(node,elem,'~(x>=0 & y>=0)') only\n% shows the tetrahedron not in the first quadrant. \n%\n% showmesh3(node,elem,expr,'param','value','param','value'...) allows\n% additional patch param/value pairs to be used when displaying the\n% mesh. For example, the default transparency parameter is set to 0.5.\n% You can overwrite this value by using the param pair ('FaceAlpha',\n% value). The value has to be a number between 0 and 1. Other parameters\n% include: 'Facecolor', 'Edgecolor' etc.\n% \n% For meshes with large data, the 3-D graphics is very slow. You may use\n% showboundary3 to display the boundary surface mesh only.\n%\n% Example:\n% % A mesh for a cube\n% node = [-1,-1,-1; 1,-1,-1; 1,1,-1; -1,1,-1; -1,-1,1; 1,-1,1; 1,1,1; -1,1,1]; \n% elem = [1,2,3,7; 1,6,2,7; 1,5,6,7; 1,8,5,7; 1,4,8,7; 1,3,4,7];\n% [node,elem] = uniformbisect3(node,elem);\n% subplot(1,2,1);\n% showmesh3(node,elem); pause(1)\n% subplot(1,2,2);\n% showmesh3(node,elem,'~(x>=0 & y>=0 & z>=0)','FaceAlpha',0.25); \n% axis on; view([59,20])\n%\n% See also showboundary3, showsolution3, showmesh.\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nif (nargin >= 3) && (any(expr))\n x = node(:,1); y = node(:,2); z = node(:,3); %#ok\n incl = find(eval(expr));\n elem = elem(any(ismember(elem,incl),2),:);\nend\nh = tetramesh(elem(:,1:4),node,ones(size(elem,1),1));\nif nargin > 3 \n set(h,varargin{1:end})\nelse % default display properties\n set(h,'FaceAlpha',0.4); \nend\nview(3);\naxis off; axis equal; axis tight", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/iFEM/tool/showmesh3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.49894507947589123}} {"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(:)) 2\n [coeff,score,latent,tsquared,explained,mu] = pca(vecs);\n explained\n vecs = score;\n end\n\n for i = 1:k\n iset = (idx == i);\n if size(vecs, 2) > 2\n scatter3(vecs(iset, 1), vecs(iset, 2), vecs(iset, 3));\n else\n scatter(vecs(iset, 1), vecs(iset, 2), styles{i});\n end\n end\nend", "meta": {"author": "eldar", "repo": "deepcut", "sha": "096e2d174ddf2fbdc61458d9e7e6c6e897eac16c", "save_path": "github-repos/MATLAB/eldar-deepcut", "path": "github-repos/MATLAB/eldar-deepcut/deepcut-096e2d174ddf2fbdc61458d9e7e6c6e897eac16c/lib/pose/cluster_rotation_classes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.49894507079512407}} {"text": "function pass = test_constructor( pref )\n% Test the Chebfun2v constructor when performing simple arithmetic\n% operations.\n\nif ( nargin < 1 )\n pref = chebfunpref;\nend\n\ntol = 100*pref.cheb2Prefs.chebfun2eps;\n\nD = [-1 1 -1 1; -2 3 0 1];\n\nfor kk = 1:size(D,1)\n d = D(kk,:);\n % Check the constructor works with lots of different syntax:\n f1 = @(x,y) cos(x.*y);\n f2 = @(x,y) sin(x) + cos(y);\n f3 = @(x,y) exp(x) - exp(-y) + x;\n g1 = chebfun2(f1, d);\n g2 = chebfun2(f2, d);\n g3 = chebfun2(f3, d);\n \n H1 = chebfun2v(f1, f2, d);\n H2 = chebfun2v(f1, g2, d);\n H3 = chebfun2v(g1, f2, d);\n H4 = chebfun2v(g1, g2, d);\n \n pass(1) = norm( H1 - H2 ) < tol;\n pass(2) = norm( H1 - H3 ) < tol;\n pass(3) = norm( H1 - H4 ) < tol;\n \n % Now try the same thing for three components:\n H1 = chebfun2v(f1, f2, f3, d);\n H2 = chebfun2v(f1, f2, g3, d);\n H3 = chebfun2v(f1, g2, f3, d);\n H4 = chebfun2v(g1, f2, f3, d);\n H5 = chebfun2v(g1, g2, f3, d);\n H6 = chebfun2v(g1, f2, g3, d);\n H7 = chebfun2v(f1, g2, g3, d);\n H8 = chebfun2v(g1, g2, g3, d);\n \n pass(4) = norm( H1 - H2 ) < tol;\n pass(5) = norm( H1 - H3 ) < tol;\n pass(6) = norm( H1 - H4 ) < tol;\n pass(7) = norm( H1 - H5 ) < tol;\n pass(8) = norm( H1 - H6 ) < tol;\n pass(9) = norm( H1 - H7 ) < tol;\n pass(10) = norm( H1 - H8 ) < tol;\n \nend\n\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/chebfun2v/test_constructor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.49894506571588715}} {"text": "function pstruct = tapas_kf_namep(pvec)\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2016 Christoph Mathys, TNU, UZH & ETHZ\n%\n% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or .\n\n\npstruct = struct;\n\npstruct.g_0 = pvec(1);\npstruct.mu_0 = pvec(2);\npstruct.om = pvec(3);\npstruct.pi_u = pvec(4);\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_kf_namep.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7577943603346811, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.49894506359206336}} {"text": "% MANIPULATOR TRAJECTORY GENERATION \n% Generates Joint space trajectories by performing inverse kinematics on\n% each waypoint and interpolating between the joint angles.\n%\n% Copyright 2019 The MathWorks, Inc.\n\n%% Setup\nclear, clc, close all\n\n% Define waypoint information\ncreateWaypointData;\n\n% Define IK\nik = inverseKinematics('RigidBodyTree',gen3);\nikWeights = [1 1 1 1 1 1];\nikInitGuess = jointAnglesHome';\nikInitGuess(ikInitGuess > 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 d = Ddiv(A,B)\n d = sum(sum(A .* log (A./B) - A + B));\nend", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/nmf/ddiergencev.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.49886366018309947}} {"text": "function test_example_SAE\nload mnist_uint8;\n\ntrain_x = double(train_x)/255;\ntest_x = double(test_x)/255;\ntrain_y = double(train_y);\ntest_y = double(test_y);\n\n%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN\n% Setup and train a stacked denoising autoencoder (SDAE)\nrand('state',0)\nsae = saesetup([784 100]);\nsae.ae{1}.activation_function = 'sigm';\nsae.ae{1}.learningRate = 1;\nsae.ae{1}.inputZeroMaskedFraction = 0.5;\nopts.numepochs = 1;\nopts.batchsize = 100;\nsae = saetrain(sae, train_x, opts);\nvisualize(sae.ae{1}.W{1}(:,2:end)')\n\n% Use the SDAE to initialize a FFNN\nnn = nnsetup([784 100 10]);\nnn.activation_function = 'sigm';\nnn.learningRate = 1;\nnn.W{1} = sae.ae{1}.W{1};\n\n% Train the FFNN\nopts.numepochs = 1;\nopts.batchsize = 100;\nnn = nntrain(nn, train_x, train_y, opts);\n[er, bad] = nntest(nn, test_x, test_y);\nassert(er < 0.16, 'Too big error');\n", "meta": {"author": "rasmusbergpalm", "repo": "DeepLearnToolbox", "sha": "5df2801f2196a2afddb7a87f800e63e153c34995", "save_path": "github-repos/MATLAB/rasmusbergpalm-DeepLearnToolbox", "path": "github-repos/MATLAB/rasmusbergpalm-DeepLearnToolbox/DeepLearnToolbox-5df2801f2196a2afddb7a87f800e63e153c34995/tests/test_example_SAE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989815306765, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.49884466540781686}} {"text": "function DirT = transformRTdir(Dir,Rt)\n\nDirT = Rt(1:3,1:3) * Dir;\n\n", "meta": {"author": "jianxiongxiao", "repo": "ProfXkit", "sha": "7376c50abf5ead846247774a36be026e6f24953c", "save_path": "github-repos/MATLAB/jianxiongxiao-ProfXkit", "path": "github-repos/MATLAB/jianxiongxiao-ProfXkit/ProfXkit-7376c50abf5ead846247774a36be026e6f24953c/SiftFu/SiftFu/transformRTdir.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49884239224596544}} {"text": "report_this_filefun(mfilename('fullpath'));\n\nclf\n[X,Y,Z] = meshgrid(gx,gy,gz);\nv = [];\ni = 0.05\nii = 0.05\nfor i3 = 1:2:length(gx)\n i3 = gx(i3);\n l = loc(1,:) == i3;\n re3 = reshape(as(l),length(gz),length(gy));\n r = reshape(loc(4,l),length(gz),length(gy));\n l = r > tresh;\n re3(l) = zeros(1,length(find(l)))*nan;\n rect = [i ii 0.15 0.15];\n i = i+0.20;\n if i > 0.9 ; i = 0.05 ; ii = ii + 0.20; end\n axes('position',rect)\n pcolor(gy,-gz,re3)\n caxis([min(as) max(as)])\n colormap(jet)\n title([ 'Long=' num2str(i3) ' km'],'FontSize',8)\n set(gca,'FontSize',8')\n hold on\n l = a.Longitude > i3-dx/2 & a.Longitude < i3+dx/2;\n plot3(a(l,2),-a(l,7),a(l,7)*0,'k.')\n shading interp\n % axis('off')\n hold on\nend\n%colorbar\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/map3dx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4988423822046092}} {"text": "function poly = boxToPolygon(box)\n%BOXTOPOLYGON Convert a bounding box to a square polygon.\n%\n% poly = boxToPolygon(box)\n% Utility function that convert box data in [XMIN XMAX YMIN YMAX] format\n% to polygon data corresponding to the box boundary. The resulting POLY\n% is a 4-by-2 array.\n%\n%\n% Example\n% box = [ 10 50 20 40];\n% poly = boxToPolygon(box)\n% poly = \n% 10 20\n% 50 20\n% 50 40\n% 10 40\n%\n% See also \n% boxes2d, polygons2d, boxToRect\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@nantes.inra.fr\n% Created: 2017-09-10, using Matlab 8.6.0.267246 (R2015b)\n% Copyright 2017-2022 INRA - Cepia Software Platform\n\n% extreme coordinates\nxmin = box(1); \nxmax = box(2);\nymin = box(3); \nymax = box(4);\n\n% convert to polygon\npoly = [...\n xmin ymin; ...\n xmax ymin; ...\n xmax ymax; ...\n xmin ymax];\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/geom2d/boxToPolygon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.4985983492701425}} {"text": "%% Copyright (C) 2014, 2016, 2018 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 conj (@var{z})\n%% Symbolic conjugate function.\n%%\n%% Examples:\n%% @example\n%% @group\n%% syms z\n%% conj(z)\n%% @result{} ans = (sym)\n%% _\n%% z\n%%\n%% @end group\n%% @group\n%% syms x real\n%% conj(x)\n%% @result{} ans = (sym) x\n%%\n%% conj(sym(pi) + 6i)\n%% @result{} ans = (sym) \u03c0 - 6\u22c5\u2148\n%% @end group\n%% @end example\n%%\n%% Unlike @ref{@@sym/ctranspose}, this command does not transpose\n%% a matrix:\n%% @example\n%% @group\n%% A = [1 z x; sym(4) 5 6+7i]\n%% @result{} A = (sym 2\u00d73 matrix)\n%% \u23a11 z x \u23a4\n%% \u23a2 \u23a5\n%% \u23a34 5 6 + 7\u22c5\u2148\u23a6\n%% conj(A)\n%% @result{} ans = (sym 2\u00d73 matrix)\n%% \u23a1 _ \u23a4\n%% \u23a21 z x \u23a5\n%% \u23a2 \u23a5\n%% \u23a34 5 6 - 7\u22c5\u2148\u23a6\n%% @end group\n%% @end example\n%%\n%% @seealso{@@sym/ctranspose, @@sym/real, @@sym/imag}\n%% @end defmethod\n\n\nfunction z = conj(x)\n\n if (nargin ~= 1)\n print_usage ();\n end\n\n % can just use .conjugate on matrix but avoids S.true err\n sf = { 'def _op(x):'\n ' if x in (S.true, S.false):'\n ' return x'\n ' return x.conjugate()' };\n\n z = elementwise_op (sf, x);\n\nend\n\n\n%!test\n%! a = sym(6);\n%! b = sym(5i);\n%! assert (isequal (conj(a), a))\n%! assert (isequal (conj(b), -b))\n%! assert (isequal (conj(a+b), a-b))\n\n%!test\n%! syms x\n%! assert (isequal (conj(conj(x)), x))\n\n%!test\n%! syms x real\n%! assert (isequal (conj(x), x))\n\n%!test\n%! % array\n%! syms x\n%! A = [x 6+1i; sym(1) x+2i];\n%! B = [conj(x) 6-1i; sym(1) conj(x)-2i];\n%! assert (isequal (conj(A), B))\n\n%!test\n%! % true/false\n%! t = sym(true);\n%! f = sym(false);\n%! assert (isequal ( conj(t), t))\n%! assert (isequal ( conj(f), f))\n\n%!test\n%! % round trip\n%! syms x\n%! d = 3 - 5i;\n%! f = conj (x);\n%! A = conj (d);\n%! h = function_handle (f);\n%! B = h (d);\n%! assert (A, B)\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/conj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.4985983318340832}} {"text": "%fill_mm_sub Proj. reconstruction of a normed sub-scene.\n%\n% When the central image concept is used, the information which image is\n% the central image is passed to this function as input.\n%\n% Parameters:\n%\n% Mfull .. complete known parts of the problem, used here for the best\n% estimate of the fundamental matrices\n\nfunction [P,X, lambda, u1,u2, info] = fill_mm_sub(Mfull, M, central,opt,info)\n\nI = ~isnan(M(1:3:end,:));\n[m n] = size(I);\nif isempty(central), central = 0; end\n\nP=[]; X=[]; lambda=[]; u1=1:m; u2=1:n;\n\n%estimate the fundamental matrices and epipoles with the method of [Har95]\n [F,ep,rows,nonrows] = M2Fe(Mfull, central);\n\n if ~isempty(nonrows),\n disp(sprintf('Used local images:%s.', sprintf(' %d', rows))); end\n if length(rows) < 2, return; end\n\n%determine scale faktors lambda_i_p\n if ~central, rows_central = 0; else rows_central = find(rows == central); end\n [lambda, Ilamb] = depth_estimation(M(k2i(rows),:),F,ep,rows, ...\n rows_central);\n\n % prepare info.show_prmm - for show_prmm function\n info.show_prmm.I = I;\n info.show_prmm.Idepths = zeros(m,n); info.show_prmm.Idepths(rows,:)=Ilamb;\n\n%build the rescaled measurement matrix B\n for i = 1:length(rows), B(k2i(i),:) = M(k2i(i),:).*([1;1;1]*lambda(i,:)); end\n\n%balance W by column-wise and \"triplet-of-rows\"-wise scalar multiplications\n B = balance_triplets(B, opt);\n\n%fit holes in JIM by Jacobs' algorithm\n [P,X, u1,u2, lambda1, info] = fill_prmm(B, Ilamb, central,opt,info);\n\nr1 = setdiff(1:length(rows),u1); r2 = setdiff(1:n,u2);\n\nlambda = lambda(r1,r2); % to fit P*X\nif ~isempty(lambda1),\n new = find(~Ilamb(r1,r2) & I(r1,r2)); lambda(new) = lambda1(new); end\n\nerror = eucl_dist_only(B(k2i(r1), r2), P*X, ~isnan(B(3*r1,r2)), 3);\nif opt.verbose, disp(sprintf('Error balanced: %f', error)); end\n\nu1 = union(nonrows, rows(u1));\n", "meta": {"author": "strawlab", "repo": "MultiCamSelfCal", "sha": "0a26c88c63d8513eab76553033a9a6fb15ba6575", "save_path": "github-repos/MATLAB/strawlab-MultiCamSelfCal", "path": "github-repos/MATLAB/strawlab-MultiCamSelfCal/MultiCamSelfCal-0a26c88c63d8513eab76553033a9a6fb15ba6575/MultiCamSelfCal/MartinecPajdla/fill_mm/fill_mm_sub.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.49858011156398213}} {"text": "function Population = archive(Population,N)\n% Select feasible and non-dominated solutions by using SPEA2-CDP\n\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 %% Select feasible solutions\n fIndex = all(Population.cons <= 0,2);\n Population = Population(fIndex);\n if isempty(Population)\n return\n elseif size(Population,2) > N\n Fitness = CalFitness(Population.objs,Population.cons);\n Next = Fitness < 1;\n Del = Truncation(Population(Next).objs,sum(Next)-N);\n Temp = find(Next);\n Next(Temp(Del)) = false;\n Population = Population(Next);\n end\nend\n\nfunction Del = Truncation(PopObj,K)\n% Select part of the solutions by truncation\n\n %% Truncation\n Distance = pdist2(PopObj,PopObj);\n Distance(logical(eye(length(Distance)))) = inf;\n Del = false(1,size(PopObj,1));\n while sum(Del) < K\n Remain = find(~Del);\n Temp = sort(Distance(Remain,Remain),2);\n [~,Rank] = sortrows(Temp);\n Del(Remain(Rank(1))) = true;\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/TriP/archive.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.49858010617067905}} {"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": "close all;\nclear all;\nclc;\n\ndata_file_path = 'bin/ra_mmv_phase_transition_snr_40db_s_8.mat';\noptions.export = true;\noptions.export_dir = 'bin';\noptions.export_name = 'ra_mmv_snr_40_db_s_8';\noptions.chosen_ks = [2, 4, 8, 16, 32, 64];\noptions.subtitle = 'Rank Aware, SNR=40dB s=8';\nspx.pursuit.PhaseTransitionAnalysis.print_results(data_file_path, ...\n 'CoSaMP', options);\n\n\n", "meta": {"author": "indigits", "repo": "sparse-plex", "sha": "43cae2978f62938d001baaa03308a2a717ee6c9b", "save_path": "github-repos/MATLAB/indigits-sparse-plex", "path": "github-repos/MATLAB/indigits-sparse-plex/sparse-plex-43cae2978f62938d001baaa03308a2a717ee6c9b/experiments/cosamp_mmv/print_ra_mmv_phase_transition_snr_40db_s_8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.4985800835320006}} {"text": "function C = spm_mesh_isoline(M, T, t)\n% Compute isolines on a triangular mesh\n% FORMAT C = spm_mesh_isoline(M, T, t)\n% M - a GIfTI object or patch structure\n% T - [vx1] data vector\n% t - isovalue [Default: 0]\n%\n% C - struct array of isolines with fields 'xdata', 'ydata', 'zdata' and\n% 'isopen'\n%__________________________________________________________________________\n%\n% M = gifti(fullfile(spm('Dir'),'canonical','cortex_20484.surf.gii'));\n% M = export(M,'patch');\n% M = spm_mesh_inflate(M);\n% T = randn(size(M.vertices,1),1);\n% T = spm_mesh_smooth(M,T,100);\n% H = spm_mesh_render('Disp',M);\n% H = spm_mesh_render('Overlay',H,T);\n% hold on\n% t = linspace(min(T),max(T),20);\n% for i=1:numel(t)\n% C = spm_mesh_isoline(M,T,t(i));\n% for j=1:numel(C)\n% plot3(C(j).xdata,C(j).ydata,C(j).zdata,'k-');\n% end\n% end\n%__________________________________________________________________________\n% Copyright (C) 2019 Wellcome Trust Centre for Neuroimaging\n\n% Guillaume Flandin\n% $Id: spm_mesh_isoline.m 7618 2019-06-17 12:29:46Z guillaume $\n\n\nif nargin < 3, t = 0; end\n\nC = spm_mesh_contour(M,struct('T',T,'t',t));\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_mesh_isoline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4985157451378339}} {"text": "function inpC = regCorrIntGradWiener(inp, Int, Noise);\n% regCorrIntGradWiener - corrects for the intensity gradient applying a\n% wiener-like filtering.\n%\n% inpC = regCorrIntGradWiener(inp, Int, Noise);\n% \n% INPUT:\n% inp - original inplanes\n% Int - estimated intensity\n% Noise - estimated power-spatial distribution of the noise\n%\n% Oscar Nestares - 5/99\n%\n\n% minimum noise\nsigma2 = mean(Noise(:))/2;\n\n% correction\ninpC = inp.*Int ./ (Int.^2 + Noise + sigma2);\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAlign/registrationOscar/regCorrIntGradWiener.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49851573950643224}} {"text": "function c = integrate(c)\n\n%INTEGRATE integrates each trace.\n%\n% C = INTEGRATE(C) integrates each trace. Prior to integrating, the trend\n% and mean of each trace is removed. Depending on the application, it is\n% recommended that users also consider applying a gentle high pass filter\n% to remove unwanted low frequencies that can dominate the integrated\n% waveforms.\n\n% Author: Michael West, Geophysical Institute, Univ. of Alaska Fairbanks\n% $Date$\n% $Revision$\n\nc.W = detrend(c.W);\nc.W = demean(c.W);\nc.W = integrate(c.W);", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/core/@correlation/integrate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49851573387503045}} {"text": "% Example_4_PRVI: Mesh the west North Atlantic Ocean with high resolution\n% around Puerto Rico and US Virgin Islands.\n% User beware: this is a very intensive mesh generation example, takes\n% around 1 hr. \nclc; clearvars\n\naddpath('..')\naddpath(genpath('../utilities/'))\naddpath(genpath('../datasets/'))\naddpath(genpath('../m_map/'))\n\n%% The constant parameters for all domains\nwl = 30; % elements to resolve M2 wavelength\ndt = 0; % use automatic timestep \ngrade = 0.25; \t\t% mesh grade in decimal percent.\nR = -5; \t\t% number of elements to resolve feature width.\nslp = 15; % 2*pi/number of elements to resolve slope\nfl = -50; % use filter equal to Rossby radius divided by 50\n\n%% For relatively coarse resolution west North Atlantic Ocean\nbbox = [-100 -53 \t % lon_min lon_max\n 5 52.5]; % lat_min lat_max\nmin_el = 1000; \t\t% minimum resolution in meters.\nmax_el = 10e3; \t% maximum resolution in meters. \n\ncoastline = 'GSHHS_f_L1';\ndem = 'SRTM15+.nc';\ngdat{1} = geodata('shp',coastline,...\n 'dem',dem,...\n 'bbox',bbox,...\n 'h0',min_el);\n \nfh{1} = edgefx('geodata',gdat{1},...\n 'fs',R,...\n 'wl',wl,...\n 'slp',slp,'fl',fl,...\n 'max_el',max_el,...\n 'dt',dt,...\n 'g',grade);\n\n%% For High Resolution around Puerto Rico and US Virgin Islands\ncoastline = [\"pr_1s_0m_contour\",\"usvi_0m_contour\",\"sj_0contour_closed\"];\n \ndems = [\"pr_1s.nc\",\"usvi_1_mhw_2014.nc\", \"san_juan_19_prvd02_2015.nc\"];\n \nfor ii = 1:length(dems)\n % use same parameters as coarse mesh, just change min_el\n if ii == length(dems)\n min_el = 10; % minimum resolution in meters.\n else\n min_el = 30; % minimum resolution in meters.\n end\n % bbox is taken automatically from the DEM\n gdat{ii+1} = geodata('shp',coastline{ii},...\n 'dem',dems{ii},...\n 'h0',min_el);\n fh{ii+1} = edgefx('geodata',gdat{ii+1},...\n 'fs',R,...\n 'wl',wl,...\n 'slp',slp,'fl',fl,...\n 'max_el',max_el,...\n 'dt',dt,...\n 'g',grade);\nend\n\n%% Pass your edgefx class objects along with some meshing options \n%% and build the mesh... \n% (note that the nested edgefxs will be smoothed together with this call)\nmshopts = meshgen('ef',fh,'bou',gdat,'plot_on',1,'itmax',50,...\n 'proj','lam'); \n \n% now build the mesh with your options and the edge function.\nmshopts = mshopts.build; \n\n% Get out the msh class from meshgen\nm = mshopts.grd;\n\n%% Interpolate on the bathy and gradients (automatically loops over all data)\nm = interp(m,gdat,'mindepth',1); % interpolate bathy to the mesh with minimum depth of 1 m\n\n%% Make the nodestrings\nm = make_bc(m,'auto',gdat{1}); % make the nodestring boundary conditions\n\n%% Plot and save the msh class object/write to fort.14\nplot(m,'type','bd'); % plot triangulation with boundary conditions\nplot(m,'type','b'); % plot the bathy\nplot(m,'type','reso','colormap',[10 0 10e3]) % plot the resolution\n% Save as a msh class\nsave('PRVI_msh.mat','m');\n% Write an ADCIRC fort.14 compliant file to disk.\nwrite(m,'PRVI_mesh')\n\n", "meta": {"author": "CHLNDDEV", "repo": "OceanMesh2D", "sha": "56222604a5c1fe897d10c8b08cb3380ef8b43740", "save_path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D", "path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D/OceanMesh2D-56222604a5c1fe897d10c8b08cb3380ef8b43740/Examples/Example_4_PRVI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789040926008, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49851573105932956}} {"text": "function Image_out=Intensity_adjust(Image_in);\n%This code extends the intensity limits of an image from [low_in; high_in]\n%to [0;255]. It is most convenient for applications where operations such \n%as edge detection or black to white transformations are to be performed\n%on a sequence of images. Threshold values are fixed for different images. \n% \n% CLASS SUPPORT\n% -------------\n% The input is an RGB image. \n% \n% \n% Syntaxes:\n% Image_out=Intensity_adjust('sky.jpg');\n% The output is an RGB image of the same size as the initial image. \n% This code is written by:\n% Nassim Khaled\n% American University of Beirut\n% Research and Graduate Assistant\n% \n% Developed under Matlab 7 Date: April,2005\n\na=imread(Image_in);\ns=rgb2gray(a);\nb=double(s);\nlow_in=min(b(:))/255;\nhigh_in=max(b(:))/255;\nImage_out = imadjust(a,[low_in; high_in],[0;1]);\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/7485-intensity-adjust/Intensity_adjust.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49851572824362855}} {"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": "function kern = polyardKernParamInit(kern)\n\n% POLYARDKERNPARAMINIT POLYARD kernel parameter initialisation.\n% The automatic relevance determination version of the polynomial\n% kernel is included for completeness, but its use is generally not\n% recommended.\n%\n% k(x_i, x_j) = sigma2*(w*x_i'*A*x_j+b)^d\n%\n% The kernel parameters are sigma2 (kern.variance), w\n% (kern.weightVariance), b (kern.biasVariance), A\n% (kern.inputScales) a diagonal matrix of input scales and d\n% (kern.degree). Only gradients of the first four are provided for\n% kernel optimisation, it is assumed that polynomial degree would\n% be set by hand.\n%\n% The kernel is not recommended as it is badly behaved when the\n% w*x_i'*A*x_j + b has a magnitude greater than one. \n%\n% SEEALSO : polyKernParamInit\n%\n% FORMAT\n% DESC initialises the automatic relevance determination polynomial\n% kernel structure with some default parameters.\n% ARG kern : the kernel structure which requires initialisation.\n% RETURN kern : the kernel structure with the default parameters placed in.\n%\n% SEEALSO : kernCreate, kernParamInit\n%\n% COPYRIGHT : Neil D. Lawrence, 2005, 2006\n\n% KERN\n\n\nkern.weightVariance = 1;\nkern.biasVariance = 1;\nkern.variance = 1;\n% These parameters are restricted to lie between 0 and 1.\nkern.inputScales = 0.999*ones(1, kern.inputDimension);\nkern.nParams = 3 + kern.inputDimension;\n\nkern.degree = 2;\n\nkern.transforms(1).index = [1 2 3];\nkern.transforms(1).type = optimiDefaultConstraint('positive');\nkern.transforms(2).index = [4:kern.nParams];\nkern.transforms(2).type = optimiDefaultConstraint('zeroone');\n\nkern.isStationary = false;\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/polyardKernParamInit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6187804407739558, "lm_q1q2_score": 0.498509440999508}} {"text": "function [X0,isYout] = VBA_spm_Xadjust(SPMfile,VOIfile,varthresh)\n% gets the effects of no interest, wrt to which the data has been adjusted\n% [X0,isYout] = spm_Xadjust(SPMfile,VOIfile,varthresh)\n% IN:\n% - SPMfile: name of the SPM file\n% - VOIfile: name of the VOI file\n% - varthresh: threshold for PCA on X0 (fraction of explained variance).\n% Default is 0.95.\n% OUT:\n% - X0: confounds matrix\n% - isYout: vector of indices of scans that were effectively removed from\n% the GLM using scan-nulling regressors included in the original\n% confounds matrix.\n\ntry, varthresh; catch, varthresh = 0.95; end\n\nload(SPMfile)\nload(VOIfile)\n\nif isequal(xY.Ic,0)\n X0 = [];\n isYout = [];\n return\nend\nFc = SPM.xCon(xY.Ic);\nind = sum(abs(Fc.c),2)==0;\nX0 = SPM.xX.X(:,ind);\n\n% remove scan-nulling regressors\nn0 = size(X0,2);\nremove = [];\nisYout = [];\nfor i=1:n0\n X0i = X0(:,i) - X0(1,i);\n i1 = find(X0i~=0);\n tmp = zeros(size(X0,1),1);\n tmp(i1) = 1;\n if isequal(X0i,tmp)\n remove = [remove;i];\n isYout = [isYout,i1];\n end\nend\nX0 = X0(:,setdiff(1:size(X0,2),remove));\nX0 = bsxfun(@minus,X0,mean(X0,1));\nX0 = bsxfun(@rdivide,X0,std(X0,[],1));\nif varthresh < 1\n [u,s,v] = svd(X0);\n s2 = diag(s).^2;\n ev = cumsum(s2./sum(s2));\n it = find(ev>=varthresh, 1 );\n X0 = [u(:,1:it),ones(size(X0,1),1)./sqrt(size(X0,1))];\nend\n\nreturn\n\n% the following reproduces the code in spm_regions.m:\n\n% sX = SPM.xX.xKXs;\n% X0 = sX.X*(eye(spm_sp('size',sX,2)) - spm_sp('xpx-',sX)*sf_H(Fc,sX));\n%\n% function H = sf_H(Fc,sX)\n% if sf_ver(Fc) > 1,\n% hsqr = sf_Hsqr(Fc,sX);\n% H = hsqr' * hsqr;\n% else\n% H = Fc.c * pinv(Fc.X1o' * Fc.X1o) * Fc.c';\n% end\n%\n% function hsqr = sf_Hsqr(Fc,sX)\n% if sf_ver(Fc) > 1,\n% hsqr = spm_sp('ox',spm_sp('set',Fc.X1o.ukX1o))' * spm_sp('cukx',sX);\n% else\n% hsqr = spm_sp('ox',spm_sp('set',Fc.X1o))'*spm_sp('x',sX);\n% end\n%\n% function v = sf_ver(Fc)\n% if isstruct(Fc.X0), v = 2; else v = 1; end\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/thrid-party/spm/VBA_spm_Xadjust.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812552, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4985094353358285}} {"text": "function gauss_seidel_test ( )\n\n%*****************************************************************************80\n%\n%% GAUSS_SEIDEL_TEST tests the GAUSS_SEIDEL library.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 November 2011\n%\n% Author:\n%\n% John Burkardt\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'GAUSS_SEIDEL_TEST\\n' );\n fprintf ( 1, ' MATLAB version.\\n' );\n fprintf ( 1, ' Test the GAUSS_SEIDEL library.\\n' );\n\n gauss_seidel_test01 ( );\n gauss_seidel_test02 ( );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'GAUSS_SEIDEL_TEST\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\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/gauss_seidel/gauss_seidel_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.49850943244815665}} {"text": "function component = partition(model, solver, algorithm)\n% swiftcc++ and fastcc++ augment swiftcc and fastcc by this preprocess\n%\n% USAGE:\n%\n% component = partition(model, solver, algorithm)\n%\n% INPUTS:\n% model: the metabolic network reconstruction\n% * .S - the associated sparse stoichiometric matrix\n% * .lb - feasible flux distribution lower bound\n% * .ub - feasible flux distribution uppper bound\n% * .rxns - cell array of reaction abbreviations\n% * .rev - the 0-1 indicator vector of the reversible reactions\n% solver: the LP solver to be used; the currently available options \n% are 'gurobi', 'linprog', and 'cplex' with the default value \n% of 'linprog'. It fallbacks to the COBRA LP solver interface \n% if another supported solver is called.\n% algorithm: the backend algorithm to be utilized between 'swift' and 'fast'\n%\n% OUTPUT:\n% component: the index set of the reactions constituting the maximum \n% flux consistent metabolic subnetwork\n%\n% NOTE:\n%\n% requires bioinformatics toolbox\n%\n% .. Authors:\n% - Mojtaba Tefagh, Stephen P. Boyd, 2019, Stanford University\n\n assert(license('test', 'bioinformatics_toolbox') == 1, ...\n 'The required Bioinformatics toolbox is not available!');\n S = model.S;\n rev = model.rev;\n lb = model.lb;\n ub = model.ub;\n c = model.c;\n rxns = model.rxns;\n [m, n] = size(S);\n \n %% constructing the directed graph\n DG = zeros(m+1);\n for i = 1:n\n head = S(:, i) > 0;\n if ~any(head)\n head = m+1;\n end\n tail = S(:, i) < 0;\n if ~any(tail)\n tail = m+1;\n end\n DG(head, tail) = 1;\n if rev(i)\n DG(tail, head) = 1;\n end\n end\n \n %% finding strongly or weakly connected components in the graph\n DG = sparse(DG);\n [~, C] = graphconncomp(DG, 'Directed', true);\n C = C(1:end-1);\n \n %% finding weakly connected components in the graph\n if range(C) == 0\n [~, C] = graphconncomp(max(DG, DG.'), 'Directed', false);\n C = C(1:end-1);\n end\n \n %% partitioning the metabolic network\n component = zeros(n, 1);\n for i = 1:n\n v = C(S(:, i) ~= 0);\n component(i) = all(v == v(1))*v(1);\n end\n if range(component) == 0\n component = zeros(n, 1);\n if strcmp(algorithm, 'fast')\n component(fastcc(model, getCobraSolverParams('LP', 'feasTol')*100)) = 1;\n elseif strcmp(algorithm, 'swift')\n component(swiftcc(S, rev, solver)) = 1;\n end\n else\n newcomponent = zeros(n, 1);\n for i = unique(component).'\n core = component == i;\n if sum(core) > 1\n model.S = S(:, core);\n model.rev = rev(core);\n model.lb = lb(core);\n model.ub = ub(core);\n model.c = c(core);\n model.rxns = rxns(core);\n newcomponent(core) = partition(model, solver, algorithm);\n end\n end\n component = newcomponent;\n end\nend", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/dataIntegration/transcriptomics/SWIFTCORE/partition.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.49850942956048483}} {"text": "% FILTER_FREQ Calculate center frequencies and bandwidths\n%\n% Usage\n% [psi_xi, psi_bw, phi_bw] = FILTER_FREQ(filt_opt)\n%\n% Input\n% filt_opt (struct): The parameters defining the filter bank.\n%\n% Output\n% psi_xi (numeric): The center frequencies of the wavelet filters.\n% psi_bw (numeric): The bandwidths of the wavelet filters.\n% phi_bw (numeric): The bandwidth of the lowpass filter.\n%\n% Description\n% Called by WAVELET_1D and WAVELET_LAYER_1D, this function provides the\n% center frequency and bandwidth of a mother wavelet, whose parameters\n% are specified in filt_opt. It operates as a mere disjunction between\n% SPLINE_FREQ_1D, and MORLET_FREQ_1D.\n%\n% See also\n% MORLET_FREQ_1D, SPLINE_FREQ_1D, WAVELET_1D, WAVELET_LAYER_1D\n\nfunction [psi_xi, psi_bw, phi_bw] = filter_freq(filter_options)\n\tif strcmp(filter_options.filter_type,'spline_1d') || ...\n strcmp(filter_options.filter_type,'selesnick_1d')\n\t\t[psi_xi,psi_bw,phi_bw] = dyadic_freq_1d(filter_options);\n\telseif strcmp(filter_options.filter_type,'morlet_1d') || ...\n\t\tstrcmp(filter_options.filter_type,'gabor_1d')\n\t\t[psi_xi,psi_bw,phi_bw] = morlet_freq_1d(filter_options);\n\telse\n\t\terror('Unknown filter type ''%s''', filter_options.filter_type);\n\tend\nend\n", "meta": {"author": "scatnet", "repo": "scatnet", "sha": "59d935afa20359845282a3518134e24244862c1f", "save_path": "github-repos/MATLAB/scatnet-scatnet", "path": "github-repos/MATLAB/scatnet-scatnet/scatnet-59d935afa20359845282a3518134e24244862c1f/filters/filter_freq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.49850942956048483}} {"text": "function mmse(filename,outfile,SPU)\n\n%\n% Implements the MMSE algorithm [1].\n% \n% Usage: mmse(noisyFile, outputFile, SPU)\n% \n% infile - noisy speech file in .wav format\n% outputFile - enhanced output file in .wav format\n% SPU - if 1, includes speech-presence uncertainty\n% if 0, doesnt include speech-presence uncertainty\n% \n%\n% Example call: mmse('sp04_babble_sn10.wav','out_mmse.wav',1);\n%\n% References:\n% [1] Ephraim, Y. and Malah, D. (1985). Speech enhancement using a minimum \n% mean-square error log-spectral amplitude estimator. IEEE Trans. Acoust., \n% Speech, Signal Process., ASSP-23(2), 443-445.\n% \n% Authors: Philipos C. Loizou\n%\n% Copyright (c) 2006 by Philipos C. Loizou\n% $Revision: 0.0 $ $Date: 10/09/2006 $\n%-------------------------------------------------------------------------\n\nif nargin<3\n fprintf('Usage: mmse(infile.wav,outfile.wav,SPU) \\n');\n fprintf('where SPU=1 - includes speech presence uncertainty\\n');\n fprintf(' SPU=0 - does not includes speech presence uncertainty\\n\\n');\n return;\nend;\n\nif SPU~=1 & SPU~=0\n error('ERROR: SPU needs to be either 1 or 0.');\nend\n\n[x, Srate, bits]= wavread( filename);\t\n\n\n% =============== Initialize variables ===============\n\nlen=floor(20*Srate/1000); % Frame size in samples\nif rem(len,2)==1, len=len+1; end;\nPERC=50; % window overlap in percent of frame size\nlen1=floor(len*PERC/100);\nlen2=len-len1;\n\nwin=hanning(len); % define window\nwin = win*len2/sum(win); % normalize window for equal level output \n\n% Noise magnitude calculations - assuming that the first 6 frames is noise/silence\n%\nnFFT=2*len;\nj=1;\nnoise_mean=zeros(nFFT,1);\nfor k=1:6\n noise_mean=noise_mean+abs(fft(win.*x(j:j+len-1),nFFT));\n j=j+len;\nend\nnoise_mu=noise_mean/6;\nnoise_mu2=noise_mu.^2;\n\n%--- allocate memory and initialize various variables\n\nk=1;\nimg=sqrt(-1);\nx_old=zeros(len1,1);\nNframes=floor(length(x)/len2)-1;\nxfinal=zeros(Nframes*len2,1);\n\n% --------------- Initialize parameters ------------\n%\nk=1;\naa=0.98;\neta= 0.15;\nmu=0.98;\nc=sqrt(pi)/2;\nqk=0.3;\nqkr=(1-qk)/qk;\nksi_min=10^(-25/10); % note that in Chap. 7, ref. [17], ksi_min (dB)=-15 dB is recommended\n\n%=============================== Start Processing =======================================================\n%\nfor n=1:Nframes\n\n insign=win.*x(k:k+len-1);\n\n %--- Take fourier transform of frame\n %\n spec=fft(insign,nFFT);\n sig=abs(spec); % compute the magnitude\n sig2=sig.^2;\n\n gammak=min(sig2./noise_mu2,40); % posteriori SNR\n if n==1\n ksi=aa+(1-aa)*max(gammak-1,0);\n else\n ksi=aa*Xk_prev./noise_mu2 + (1-aa)*max(gammak-1,0); \n % decision-direct estimate of a priori SNR\n ksi=max(ksi_min,ksi); % limit ksi to -25 dB\n end\n\n log_sigma_k= gammak.* ksi./ (1+ ksi)- log(1+ ksi); \n vad_decision= sum( log_sigma_k)/nFFT; \n if (vad_decision< eta) % noise only frame found\n noise_mu2= mu* noise_mu2+ (1- mu)* sig2;\n end\n % ===end of vad===\n\n vk=ksi.*gammak./(1+ksi);\n [j0,err]=besseli(0,vk/2);\n [j1,err2]=besseli(1,vk/2);\n if any(err) | any(err2)\n fprintf('ERROR! Overflow in Bessel calculation in frame: %d \\n',n);\n else\n C=exp(-0.5*vk);\n A=((c*(vk.^0.5)).*C)./gammak;\n B=(1+vk).*j0+vk.*j1;\n hw=A.*B;\n end\n\n\n % --- estimate speech presence probability\n %\n if SPU==1\n evk=exp(vk);\n Lambda=qkr*evk./(1+ksi);\n pSAP=Lambda./(1+Lambda);\n sig=sig.*hw.*pSAP;\n else\n sig=sig.*hw;\n end\n \n Xk_prev=sig.^2; % save for estimation of a priori SNR in next frame\n\n xi_w= ifft( sig .* exp(img*angle(spec)),nFFT);\n\n xi_w= real( xi_w);\n\n xfinal(k:k+ len2-1)= x_old+ xi_w(1:len1);\n x_old= xi_w(len1+ 1: len);\n\n k=k+len2;\n \nend\n%========================================================================================\n\n\nwavwrite(xfinal,Srate,16,outfile);\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/MATLAB_code/statistical_based/mmse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040853, "lm_q2_score": 0.5851011542032313, "lm_q1q2_score": 0.4984785765557846}} {"text": "function [results] = computeQualityMetrics(image)\n\n % Anisotrophy Test\n [gray,rgb] = biqaa.blindimagequality(image,8,6,0,'degree');\n results.biqaa_gray = gray;\n results.biqaa_rgb = rgb;\n\n % BIQI Test\n results.biqi = biqi.biqi(image);\n\n % Bliinds2 Test\n results.bliinds = bliinds2.bliinds2_score(image);\n\n % IQVG Test\n addpath('/Users/dsoellinger/Documents/git/uni/Matlab Toolbox/cjlin1_svnlib/libsvm/matlab');\n results.iqvg = iqvg.IQVG(image);\n rmpath('/Users/dsoellinger/Documents/git/uni/Matlab Toolbox/cjlin1_svnlib/libsvm/matlab');\n\n % NIQE Test\n results.niqe = niqe.niqe(image);\n\n % DIVINE Test\n addpath('/Users/dsoellinger/Documents/git/uni/Matlab Toolbox/gregfreeman_libsvm/libsvm/matlab');\n results.divine = divine.divine(image);\n rmpath('/Users/dsoellinger/Documents/git/uni/Matlab Toolbox/gregfreeman_libsvm/libsvm/matlab');\n\n % BRISQUE Test\n % Requires libsvm 3.22. Make sure that it is installed.\n results.brisque = brisque.brisquescore(image);\n\n\nend\n", "meta": {"author": "dsoellinger", "repo": "blind_image_quality_toolbox", "sha": "4d12c43c77bba538f684df0b62621e9350854c43", "save_path": "github-repos/MATLAB/dsoellinger-blind_image_quality_toolbox", "path": "github-repos/MATLAB/dsoellinger-blind_image_quality_toolbox/blind_image_quality_toolbox-4d12c43c77bba538f684df0b62621e9350854c43/computeQualityMetrics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4984785765557844}} {"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": "disp('Loading iris data');\nX = load('data/iris.mtx');\ny = load('data/iris.truth');\n\ndisp('Running ITML');\nnum_folds = 2;\nknn_neighbor_size = 4;\nacc = CrossValidateKNN(y, X, @(y,X) MetricLearningAutotuneKnn(@ItmlAlg, y, X), num_folds, knn_neighbor_size);\n\ndisp(sprintf('kNN cross-validated accuracy = %f', acc));\n\n", "meta": {"author": "zhunzhong07", "repo": "IDE-baseline-Market-1501", "sha": "8be027b5e45adce1d8ea381cc5a17ec20ed521e5", "save_path": "github-repos/MATLAB/zhunzhong07-IDE-baseline-Market-1501", "path": "github-repos/MATLAB/zhunzhong07-IDE-baseline-Market-1501/IDE-baseline-Market-1501-8be027b5e45adce1d8ea381cc5a17ec20ed521e5/market_evaluation/KISSME/toolbox/lib/itml/Test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7490872243177517, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.49845055345369593}} {"text": "function [same,sloc] = setset2(iset,jset)\n%SETSET2 a (much) faster variant of ISMEMBER for edge lists.\n% [IN] = SETSET2(ISET,JSET) returns an I-by-1 array IN,\n% with IN(K) = TRUE if ISET(K,:) is present in JSET. This \n% routine is essentially an optimised ISMEMBER variant de-\n% signed for processing lists of edge indexing. ISET is an\n% I-by-2 array of \"query\" edges, JSET is a J-by-2 array of\n% edges to test against.\n%\n% See also ISMEMBER \n\n% Darren Engwirda : 2017 --\n% Email : de2363@columbia.edu\n% Last updated : 29/01/2017\n\n%---------------------------------------------- basic checks\n if ( ~isnumeric(iset) || ~isnumeric(jset) )\n error('setset2:incorrectInputClass' , ...\n 'Incorrect input class.') ;\n end\n \n%---------------------------------------------- basic checks\n if (ndims(iset) ~= +2 || ndims(jset) ~= +2)\n error('setset2:incorrectDimensions' , ...\n 'Incorrect input dimensions.');\n end\n if (size(iset,2)~= +2 || size(jset,2)~= +2)\n error('setset2:incorrectDimensions' , ...\n 'Incorrect input dimensions.');\n end\n\n%---------------------------------------------- set v1 <= v2\n iset = sort(iset,2) ;\n jset = sort(jset,2) ; \n\n%-- this is the slow, but easy-to-undertsand version of what\n%-- is happening here... \n \n % if (nargout == +1)\n % same = ismember(iset,jset,'rows') ;\n % else\n % [same,sloc] = ...\n % ismember(iset,jset,'rows') ;\n \n%-- as above, the 'ROWS' based call to ISMEMBER can be sped\n%-- up by casting the edge lists (i.e. pairs of UINT32 valu-\n%-- es) to DOUBLE, and performing the sorted queries on vec-\n%-- tor inputs!\n if (nargout == +1)\n same = ismember( ...\n iset*[2^31;1], jset*[2^31;1]) ;\n else\n [same,sloc] = ismember( ...\n iset*[2^31;1], jset*[2^31;1]) ;\n end\n\nend\n\n\n\n", "meta": {"author": "CHLNDDEV", "repo": "OceanMesh2D", "sha": "56222604a5c1fe897d10c8b08cb3380ef8b43740", "save_path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D", "path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D/OceanMesh2D-56222604a5c1fe897d10c8b08cb3380ef8b43740/utilities/GEOM_UTIL/mesh-util/setset2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.4984505360584438}} {"text": "function dataout=modeDRAEC_BSS(nummics, numrefs, datain)\n%\n% Perform dr and aec together, then bss.\n% nummics: no. of mic channels\n% numrefs: no. of reference channels\n% datain: input data\n% dataout: output data\n%\n\n%% perform stft\naddpath('stft2');\n% fft size\nfftsize=512;\nstftshift=fftsize/2;\n\nM=nummics;\nR=numrefs;\nN=M;\n\nXtf=cell(M+R, 1);\nfor m=1:M+R\n Xtf{m}=stft(datain(:, m), stftshift, fftsize, false);\nend\n[K, T]=size(Xtf{1});\n\nYtf=cell(M, 1);\nfor m=1:M\n Ytf{m}=zeros(K, T);\nend\n\n%% params\n% dr filter length\nDR_FLEN=5;\n% forgetting factor for dr and aec\nDRAEC_FORGET=0.999;\n% forgetting factor for bss\nBF_FORGET=0.999;\n% the shape parameter of the source prior\nGAMMA=0.2;\n%\n% used to keep stable\n%\nVAR_BIAS=0.01;\nSTABLE_EPS=1e-3;\nDRAEC_DIAGLOAD=1e-6;\nBF_DIAGLOAD=1e-6;\n\n%% space for dr and aec\n% current mic data backup\nMiccurrent=zeros(K, M);\n% ref and delayed mic data\ndraecfsize=R+M*DR_FLEN;\nRefmicdelay=zeros(K, draecfsize);\n\n% mic-ref correlation\nCxr=cell(K, 1);\nfor k=1:K\n Cxr{k}=zeros(M, draecfsize);\nend\n\n% reference auto correlation\nCrr=cell(K, 1);\nfor k=1:K\n Crr{k}=zeros(draecfsize, draecfsize);\nend\n\n% reverb and echo path\nREPath=cell(K, 1);\nfor k=1:K\n REPath{k}=zeros(M, draecfsize);\nend\n\n%% space for bss\n% the weighted correlation matrices\nC1=cell(K, 1);\nC2=cell(K, 1);\nfor k=1:K\n C1{k}=STABLE_EPS*eye(M, M);\n C2{k}=STABLE_EPS*eye(M, M);\nend\n\n% demixing matrices\nDemix=cell(K, 1);\nfor k=1:K\n Demix{k}=eye(N, M);\nend\n\n%% perform iteration\nfor tau=1:T \n %% perform dr and aec together\n % direct nearend and early reverberation\n Early=zeros(K, M);\n \n %\n % shift in new data\n %\n % shift old mic data back\n Refmicdelay=circshift(Refmicdelay, M, 2);\n % shift in delayed mic data\n Refmicdelay(:, R+1:R+M)=Miccurrent;\n \n % mic data backup\n for m=1:M\n Miccurrent(:, m)=Xtf{m}(:, tau);\n end\n \n % shift in reference data\n for r=1:R\n Refmicdelay(:, r)=Xtf{M+r}(:, tau);\n end\n \n for k=1:K\n % calculate late reverberation and echo\n ref=Refmicdelay(k, :).';\n late=REPath{k}*ref;\n \n % direct nearend and early reverberation\n mic=Miccurrent(k, :).';\n early=mic-late;\n % output data\n Early(k, :)=early.';\n \n %\n % calculate nonlinearity\n %\n xsq=abs(mic).^2;\n ysq=abs(early).^2;\n \n phi=0;\n for m=1:M\n if ysq(m)<=xsq(m)\n phi=phi+ysq(m);\n else\n phi=phi+xsq(m);\n end\n end\n \n phi=(1-DRAEC_FORGET)*(phi+VAR_BIAS)^((GAMMA-2)/2);\n \n % update mic ref correlation\n Cxr{k}=DRAEC_FORGET*Cxr{k}+phi*(mic*ref');\n \n % update ref auto-correlation\n Crr{k}=DRAEC_FORGET*Crr{k}+phi*(ref*ref');\n \n % update echo and reverb path\n REPath{k}=Cxr{k}/(Crr{k}+DRAEC_DIAGLOAD*eye(draecfsize, draecfsize));\n end\n \n %% perform bss\n Bssout=zeros(K, M);\n \n %\n % calculate nonlinearity\n %\n phi1=0;\n phi2=0;\n \n for k=1:K\n x=Early(k, :).';\n y=Demix{k}*x;\n % output data\n Bssout(k, :)=y.';\n \n phi1=phi1+abs(y(1))^2;\n phi2=phi2+abs(y(2))^2;\n end\n \n phi1=(1-BF_FORGET)*(phi1+VAR_BIAS)^((GAMMA-2)/2);\n phi2=(1-BF_FORGET)*(phi2+VAR_BIAS)^((GAMMA-2)/2);\n \n % update the demixing matrices\n for k=1:K\n %\n % accumulate the weighted correlation\n %\n x=Early(k, :).';\n C1{k}=BF_FORGET*C1{k}+phi1*(x*x');\n C2{k}=BF_FORGET*C2{k}+phi2*(x*x');\n \n % solve gev problem\n D=heig2(BF_DIAGLOAD, C2{k}, C1{k});\n Demix{k}=D;\n end\n \n for m=1:M\n Ytf{m}(:, tau)=Bssout(:, m);\n end\nend\n\n%% perform istft and output signal\ndataout=zeros(dataLength(T, stftshift, fftsize ), N);\nfor n=1:N\n dataout(:, n)=istft(Ytf{n}, stftshift, false);\nend\n\nend\n", "meta": {"author": "nay0648", "repo": "unified2021", "sha": "006d3d99da7c0f9c535994ef58355ef36a83d510", "save_path": "github-repos/MATLAB/nay0648-unified2021", "path": "github-repos/MATLAB/nay0648-unified2021/unified2021-006d3d99da7c0f9c535994ef58355ef36a83d510/Experiment/modeDRAEC_BSS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.49842716524138886}} {"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": "classdef LIRCMOP6 < PROBLEM\n% \n% Constrained benchmark MOP with large infeasible regions\n\n%------------------------------- Reference --------------------------------\n% Z. Fan, W. Li, X. Cai, H. Huang, Y. Fang, Y. You, J. Mo, C. Wei, and E.\n% Goodman, An improved epsilon constraint-handling method in MOEA/D for\n% CMOPs with large infeasible regions, Soft Computing, 2019, 23:\n% 12491-12510.\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 Wenji Li\n \n methods\n %% Default settings of the problem\n function Setting(obj)\n obj.M = 2;\n if isempty(obj.D); obj.D = 30; end\n obj.lower = zeros(1,obj.D);\n obj.upper = ones(1,obj.D);\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 [popsize,variable_length] = size(X);\n sum1 = zeros(popsize,1);\n sum2 = zeros(popsize,1);\n for j = 2 : variable_length\n if mod(j,2) == 1\n sum1 = sum1+(X(:,j)-sin((0.5*j/variable_length*pi)*X(:,1))).^2;\n else\n sum2 = sum2+(X(:,j)-cos((0.5*j/variable_length*pi)*X(:,1))).^2;\n end\n end\n gx = 0.7057;\n PopObj(:,1) = X(:,1)+10*sum1+gx;\n PopObj(:,2) = 1-X(:,1).^2+10.*sum2+gx;\n Population = SOLUTION(X,PopObj,Constraint(PopObj),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(:,1) = linspace(0,1,N)';\n R(:,2) = 1 - R(:,1).^2;\n R = R + 0.7057;\n R(any(Constraint(R)>0,2),:) = [];\n end\n %% Generate the feasible region\n function R = GetPF(obj)\n [x,y] = meshgrid(linspace(0.7057,5,400));\n fes = all(Constraint([x(:),y(:)])<=0,2); \n z = nan(size(x));\n z(reshape(fes,size(z)) & (x-0.7057).^2+y>=1.7057) = 0;\n R = {x,y,z};\n end\n end\nend\n\nfunction PopCon = Constraint(PopObj)\n p = [1.8,2.8];\n q = [1.8,2.8];\n a = [2,2];\n b = [8,8];\n r = 0.1;\n theta = -0.25 * pi;\n for k = 1 : 2\n PopCon(:,k) = r - ((PopObj(:,1)-p(k))*cos(theta)-(PopObj(:,2)-q(k))*sin(theta)).^2/(a(k)^2) -...\n ((PopObj(:,1)-p(k))*sin(theta)+(PopObj(:,2)-q(k))*cos(theta)).^2/(b(k)^2);\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/LIR-CMOP/LIRCMOP6.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232480373843, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.49841844254444545}} {"text": "function [data, clamped] = mk_mutilated_samples(bnet, ncases, max_clamp, usecell)\n% GEN_MUTILATED_SAMPLES Do random interventions and then draw random samples\n% [data, clamped] = gen_mutilated_samples(bnet, ncases, max_clamp, usecell)\n%\n% At each step, we pick a random subset of size 0 .. max_clamp, and \n% clamp these nodes to random values.\n%\n% data(i,m) is the value of node i in case m.\n% clamped(i,m) = 1 if node i in case m was set by intervention.\n\nif nargin < 4, usecell = 1; end\n\nns = bnet.node_sizes;\nn = length(bnet.dag);\nif usecell\n data = cell(n, ncases);\nelse\n data = zeros(n, ncases);\nend\nclamped = zeros(n, ncases);\n\ncsubsets = subsets(1:n, max_clamp, 0); % includes the empty set\ndistrib_cset = normalise(ones(1, length(csubsets)));\n\nfor m=1:ncases\n cset = csubsets{sample_discrete(distrib_cset)};\n nvals = prod(ns(cset));\n distrib_cvals = normalise(ones(1, nvals));\n cvals = ind2subv(ns(cset), sample_discrete(distrib_cvals));\n mutilated_bnet = do_intervention(bnet, cset, cvals);\n ev = sample_bnet(mutilated_bnet);\n if usecell\n data(:,m) = ev;\n else\n data(:,m) = cell2num(ev);\n end\n clamped(cset,m) = 1;\nend\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/general/mk_mutilated_samples.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.49839821404413404}} {"text": "report_this_filefun(mfilename('fullpath'));\n\nl = isnan(tmap);\ntmap(l) = 1;\n\n%l = tmap < 0;\n%tmap(l) = 0;\n\n%l = Z < 0.12;\n%Z(l) = 0.14;\n\n[lat,lon] = meshgrat(tmap,tmapleg);\n%[lat,lon] = meshgrat(vlat,vlon);\n\n%[smap,smapleg] = country2mtx('peru',100);\n%[lat0, lon0] = meshgrat(smap,smapleg);\n\n%sw = interp2(lon0,lat0,smap,lon,lat);\n%l = isnan(sw) == 1 | sw == 2 ;\n\n\nren = interp2(X,Y,Z,lon,lat);\n\nmi = min(min(ren));\n\nren(l) = mi-0.01;\n\n\n\n% ren = interp2(X,Y,Z,lon,lat);\n\n% mi = min(min(ren));\nl = isnan(ren);\nren(l) = 0;\n\n\nfigure_w_normalized_uicontrolunits('pos',[150 500 1000 700])\n\nhold on; axis off\naxesm('MapProjection','eqaconic','MapParallels',[],...\n 'MapLatLimit',[s4_south s3_north],'MapLonLimit',[s2_west s1_east])\n\nmeshm(ren,tmapleg,size(tmap),tmap);\n\ndaspectm('m',10);\ntightmap\nview([0 90])\ncamlight; lighting phong\nset(gca,'projection','perspective');\n\nload worldlo\nh = displaym(POline); set(h(1),'color',[0.9 0.9 0.9],'Linewidth',2)\n% h2 = displaym(PPpoint);\n%h = displaym(PPtext); trimcart(h);\n\n%pl = plotm(lima(:,2),lima(:,1),'hw');\n%set(pl,'LineWidth',1.5,'MarkerSize',12,...\n% 'MarkerFaceColor','y','MarkerEdgeColor','k')\n\npl = plotm(dam(:,2),dam(:,1),'^w');\nset(pl,'LineWidth',1.5,'MarkerSize',12,...\n 'MarkerFaceColor','w','MarkerEdgeColor','k')\n%pl = plotm(coastline(:,2), coastline(:,1),'w','Linewidth',2);\n\nci = worldlo('PPpoint');\ncx = ci(1).long;\ncy = ci(1).lat;\nhold on\nplotm(cy,cx,'sk','Markersize',12,'Markerfacecolor',[ 1 1 1])\n\n\nri = worldlo('DNline');\nhold on\n\nrx = [ri(1).long ; ri(2).long];\nry = [ri(1).lat ; ri(2).lat ];\nhold on\n% plotm(ry,rx,'b','Linewidth',2);\n\n\nzdatam(handlem('allline'),10000) % keep line on surface\n%zdatam(handlem('alltext'),10000) % keep line on surface\n\nj = jet;\n%j = j(64:-1:1,:);\nj = [ [ 0.93 0.9 0.9] ; j];\n\ncaxis([0. 0.28])\ncolormap(j);\n\naxis off; set(gcf,'color','w')\n\nsetm(gca,'ffacecolor','k')\nsetm(gca,'fedgecolor','k','flinewidth',3);\n\nsetm(gca,'mlabellocation',3)\nsetm(gca,'meridianlabel','on')\nsetm(gca,'plabellocation',3)\nsetm(gca,'parallellabel','on')\nsetm(gca,'Fontcolor','k','Fontweight','bold','FontSize',12,'Labelunits','dm')\n\nh5 = colorbar;\nset(h5,'position',[0.86 0.35 0.01 0.3],'TickDir','out','Ycolor','k','Xcolor','k',...\n 'Fontweight','bold','FontSize',12);\n%set(gcf,'Inverthardcopy','off');\n\n\n\n\n\n\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/dramap_peru2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959543, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.49839820812332164}} {"text": "function out = DSLInit(startPos, endPos, map, scalling)\n \n%% generate shape pattern\n radius = 10/scalling;\n mat = zeros(radius*2,radius*2);\n dista = @(a,b) sqrt(a*a+b*b);\n\n shapePattern = [];\n\n for x = 1:1:2*radius\n for y =1:1:2*radius\n if dista(x-radius-0.5,y-radius-0.5) > radius -1 && dista(x-radius-0.5,y-radius-0.5) < radius \n mat(x,y) = 1;\n shapePattern = [shapePattern; floor(x-radius) floor(y-radius) 0 0];\n end\n end\n end\n \n neighbours = [\n 0 1 0 0;\n -1 0 0 0;\n 0 -1 0 0;\n 1 1 0 0;\n -1 -1 0 0;\n 1 0 0 0;\n 1 -1 0 0;\n -1 1 0 0;\n ]';\n \n\n%% prepare all data\n \n\t\tout.map = map;\n out.startPos = [startPos(2:-1:1); 0; 0];\n out.endPos = [endPos(2:-1:1); 0; 0];\n startPos = out.startPos;\n \n out.sacalling = scalling;\n out.pattern = shapePattern';\n out.ucc = neighbours;\n out.height = ceil(length(out.map(:,1)));\n out.width = ceil(length(out.map(1,:)));\n out.graph = zeros(out.height, out.width,5);\n out.graph(:,:,1:2) = inf;\n out.graph(:,:,3) = false;\n out.graph(:,:,5) = -1;\n out.kM = 0;\n SQRT2 = sqrt(2)-1;\n out.comparator = DStarcmp;\n out.stack = java.util.PriorityQueue(180247, out.comparator);\n\n setRhs(out.endPos, 0);\n setQ(out.endPos);\n out.endPos(3:4) = [heur(out.endPos); 0];\n add(out.stack, out.endPos);\n \n \n %-----------------------------------------------------------\n function setQ(s) \n out.graph(s(1), s(2), 3) = true;\n end\n function setg(s, val)\n out.graph(s(1), s(2),1) = val;\n end\n function setRhs(s, val)\n out.graph(s(1), s(2),2) = val;\n end\n function out = heur(s) \n k = abs(startPos - s);\n out = SQRT2*min(k(1:2)) + max(k(1:2));\n end\n \nend", "meta": {"author": "LazyFalcon", "repo": "D_star_PathPlanning", "sha": "2e0e97591e4cbaa6c77c0e9b9abcf16916238656", "save_path": "github-repos/MATLAB/LazyFalcon-D_star_PathPlanning", "path": "github-repos/MATLAB/LazyFalcon-D_star_PathPlanning/D_star_PathPlanning-2e0e97591e4cbaa6c77c0e9b9abcf16916238656/DSLInit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.49831006980049924}} {"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 \u00a9 2011 The General Hospital Corporation (Boston, MA) \"MGH\"\n%\n% Terms and conditions for use, reproduction, distribution and contribution\n% are found in the 'FreeSurfer Software License Agreement' contained\n% in the file 'LICENSE' found in the FreeSurfer distribution, and here:\n%\n% https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense\n%\n% Reporting: freesurfer@nmr.mgh.harvard.edu\n%\n\n\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": "\n%compare max, min a mean manipulability for vanilla\nload('/Users/arturogilaparicio/Desktop/arte/robots/RETHINK/sgo_v0.5/experiment1/mat/experiment1A.mat')\n\n[correct_manips]=eval_experiment(Gout, random_manips);\n\n[y,i]=max(sum(correct_manips'));\nmax_manip = correct_manips(i,:);\n\n[y,i]=min(sum(correct_manips'));\nmin_manip = correct_manips(i,:);\n\nmean_manip = mean(correct_manips);\n\n\nfigure, plot(max_manip), hold\nplot(min_manip)\nplot(mean_manip)\n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/lib/SCO_v0.5/Copy_of_experiment2bis/plot_figures1A.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.49821897807760573}} {"text": "classdef P1Function < FeFunction\n\n properties (Access = public)\n end\n\n properties (Access = private)\n interpolation\n end\n\n properties (Access = private)\n meshCoarse\n meshFine\n end\n\n methods (Access = public)\n\n function obj = P1Function(cParams)\n obj.init(cParams);\n obj.createInterpolation();\n end\n\n function fxV = evaluate(obj, xV)\n obj.interpolation.computeShapeDeriv(xV);\n shapes = obj.interpolation.shape;\n nNode = size(shapes,1);\n nGaus = size(shapes,2);\n nF = size(obj.fValues,2);\n nElem = size(obj.mesh.connec,1);\n fxV = zeros(nF,nGaus,nElem);\n for iGaus = 1:nGaus\n for iNode = 1:nNode\n node = obj.mesh.connec(:,iNode);\n Ni = shapes(iNode,iGaus);\n fi = obj.fValues(node,:);\n f(:,1,:) = Ni*fi';\n fxV(:,iGaus,:) = fxV(:,iGaus,:) + f;\n end\n end\n end\n\n function N = computeShapeFunctions(obj, quad)\n% obj.mesh.computeInverseJacobian(quad,obj.interpolation);\n xV = quad.posgp;\n obj.interpolation.computeShapeDeriv(xV);\n N = obj.interpolation.shape;\n end\n \n function dNdx = computeCartesianDerivatives(obj,quad)\n switch obj.mesh.type\n case 'LINE'\n invJ = obj.mesh.computeInverseJacobian(quad,obj.interpolation);\n nElem = obj.mesh.nelem;\n nNode = obj.interpolation.nnode;\n nDime = obj.mesh.ndim;\n nGaus = quad.ngaus;\n deriv = obj.mesh.interpolation.deriv(1,:,:,:);\n dShapes = deriv;\n dN = zeros(nDime,nNode,nElem,nGaus);\n for iGaus = 1:nGaus\n invJg = invJ(:,1);\n for iDim = 1:nDime\n for iNode = 1:nNode\n dShapeI(:,1) = squeeze(dShapes(1,iNode,iGaus,:));\n dN(iDim,iNode,:,iGaus) = invJg.*dShapeI;\n end\n end\n end\n dNdx = dN;\n \n otherwise\n nElem = size(obj.mesh.connec,1);\n nNode = obj.interpolation.nnode;\n nDime = obj.interpolation.ndime;\n nGaus = quad.ngaus;\n invJ = obj.mesh.computeInverseJacobian(quad,obj.interpolation);\n dShapeDx = zeros(nDime,nNode,nElem,nGaus);\n for igaus = 1:nGaus\n dShapes = obj.interpolation.deriv(:,:,igaus);\n for jDime = 1:nDime\n invJ_JI = invJ(:,jDime,:,igaus);\n dShape_KJ = dShapes(jDime,:);\n dSDx_KI = bsxfun(@times, invJ_JI,dShape_KJ);\n dShapeDx(:,:,:,igaus) = dShapeDx(:,:,:,igaus) + dSDx_KI;\n end\n end\n dNdx = dShapeDx;\n end\n end\n\n function gradFun = computeGradient(obj, quad)\n dNdx = obj.computeCartesianDerivatives(quad);\n nDimf = obj.ndimf;\n nDims = size(dNdx, 1); % derivX, derivY (mesh-related?)\n nNode = size(dNdx, 2);\n nElem = size(dNdx, 3);\n nGaus = size(dNdx, 4);\n \n grad = zeros(nDims,nDimf, nElem, nGaus);\n for iGaus = 1:nGaus\n dNdx_g = dNdx(:,:,:,iGaus);\n for iDims = 1:nDims\n for iNode = 1:nNode\n dNdx_i = squeeze(dNdx_g(iDims, iNode,:));\n nodes = obj.mesh.connec(:,iNode);\n f = obj.fValues(nodes,:);\n dfdx(1,:,:) = (dNdx_i.*f)';\n grad(iDims,:,:,iGaus) = grad(iDims,:,:,iGaus) + dfdx;\n end\n end\n end\n fVR = reshape(grad, [nDims*nDimf,nElem, nGaus]);\n% s.fValues = permute(fVR, [1 3 2]);\n s.fValues = fVR;\n s.mesh = obj.mesh;\n s.quadrature = quad;\n gradFun = FGaussDiscontinuousFunction(s);\n end\n\n function symGradFun = computeSymmetricGradient(obj,quad)\n grad = obj.computeGradient(quad);\n nDimf = obj.ndimf;\n nDims = size(grad.fValues, 1)/nDimf;\n nGaus = size(grad.fValues, 2);\n nElem = size(grad.fValues, 3);\n\n gradReshp = reshape(grad.fValues, [nDims,nDimf,nGaus,nElem]);\n gradT = permute(gradReshp, [2 1 3 4]);\n symGrad = 0.5*(gradReshp + gradT);\n \n rshp = reshape(symGrad, [nDims*nDimf,nGaus,nElem]);\n s.fValues = permute(rshp, [1 3 2]);\n s.quadrature = quad;\n s.mesh = obj.mesh;\n symGradFun = FGaussDiscontinuousFunction(s);\n end\n\n function divF = computeDivergence(obj,q)\n dNdx = obj.computeCartesianDerivatives(q);\n fV = obj.fValues;\n nodes = obj.mesh.connec;\n nNode = obj.mesh.nnodeElem;\n nDim = obj.mesh.ndim;\n divV = zeros(q.ngaus,obj.mesh.nelem);\n for igaus = 1:q.ngaus\n for kNode = 1:nNode\n nodeK = nodes(:,kNode);\n for rDim = 1:nDim\n dNkr = squeeze(dNdx(rDim,kNode,:,igaus));\n fkr = fV(nodeK,rDim);\n int(1,:) = dNkr.*fkr;\n divV(igaus,:) = divV(igaus,:) + int;\n end\n end\n end\n s.quadrature = q;\n s.mesh = obj.mesh;\n s.fValues(1,:,:) = divV;\n divF = FGaussDiscontinuousFunction(s);\n end\n\n function fdivF = computeFieldTimesDivergence(obj,q)\n fG = obj.evaluate(q.posgp);\n dfG = obj.computeDivergence(q);\n fdivFG = bsxfun(@times,dfG.fValues,fG);\n s.quadrature = q;\n s.mesh = obj.mesh;\n s.fValues = fdivFG;\n fdivF = FGaussDiscontinuousFunction(s);\n end\n\n function fFine = refine(obj,m,mFine)\n fNodes = obj.fValues;\n fEdges = obj.computeFunctionInEdges(m, fNodes);\n fAll = [fNodes;fEdges];\n s.mesh = mFine;\n s.fValues = fAll;\n fFine = P1Function(s);\n end\n\n function dofConnec = computeDofConnectivity(obj)\n conne = obj.mesh.connec;\n nDimf = obj.ndimf;\n nNode = size(conne, 2);\n nDofsE = nNode*nDimf;\n dofsElem = zeros(nDofsE,size(conne,1));\n for iNode = 1:nNode\n for iUnkn = 1:nDimf\n idofElem = nDimf*(iNode - 1) + iUnkn;\n globalNode = conne(:,iNode);\n idofGlobal = nDimf*(globalNode - 1) + iUnkn;\n dofsElem(idofElem,:) = idofGlobal;\n end\n end\n dofConnec = dofsElem;\n end\n\n function plot(obj) % 2D domains only\n\n switch obj.mesh.type\n case {'TRIANGLE','QUAD'}\n x = obj.mesh.coord(:,1);\n y = obj.mesh.coord(:,2);\n figure()\n for idim = 1:obj.ndimf\n subplot(1,obj.ndimf,idim);\n z = obj.fValues(:,idim);\n a = trisurf(obj.mesh.connec,x,y,z);\n view(0,90)\n % colorbar\n shading interp\n a.EdgeColor = [0 0 0];\n title(['dim = ', num2str(idim)]);\n end\n case 'LINE'\n x = obj.mesh.coord(:,1);\n y = obj.fValues;\n figure()\n plot(x,y)\n end\n end\n\n function plotArrowVector(obj)\n figure()\n a = obj.fValues;\n x = obj.mesh.coord(:,1);\n y = obj.mesh.coord(:,2);\n ax = a(:,1);\n ay = a(:,2);\n q = quiver(x,y,ax,ay);\n q.ShowArrowHead = 'off';\n end\n\n function print(obj, s)\n% s.mesh\n s.mesh = obj.mesh;\n s.fun = {obj};\n p = FunctionPrinter(s);\n p.print();\n end\n\n function [res, pformat] = getDataToPrint(obj)\n nNods = size(obj.fValues, 1);\n s.nDimf = obj.ndimf;\n s.nData = nNods;\n s.nGroup = nNods;\n s.fValues = obj.getFormattedFValues();\n fps = FunctionPrintingSettings(s);\n [res, pformat] = fps.getDataToPrint();\n end\n\n end\n\n methods (Access = public, Static)\n\n function p1 = create(mesh, ndimf)\n s.fValues = zeros(mesh.nnodes, ndimf);\n s.mesh = mesh;\n p1 = P1Function(s);\n end\n\n function fS = times(f1,f2)\n fS = f1.fValues.*f2.fValues;\n s.fValues = fS;\n s.mesh = f1.mesh;\n fS = P1Function(s);\n end\n\n function fS = sum(f1,f2)\n fS = f1.fValues+f2.fValues;\n s.fValues = fS;\n s.mesh = f1.mesh;\n fS = P1Function(s);\n end\n \n end\n\n methods (Access = private)\n\n function init(obj,cParams)\n obj.mesh = cParams.mesh;\n obj.fValues = cParams.fValues;\n obj.ndimf = size(cParams.fValues,2);\n obj.order = 'LINEAR';\n obj.meshCoarse = cParams.mesh;\n end\n\n function createInterpolation(obj)\n m.type = obj.mesh.type;\n obj.interpolation = Interpolation.create(m,'LINEAR');\n end\n\n % Printing\n function fM = getFormattedFValues(obj)\n fM = obj.fValues;\n end\n\n function f = computeFunctionInEdges(obj,m,fNodes)\n s.edgeMesh = m.computeEdgeMesh();\n s.fNodes = fNodes;\n eF = EdgeFunctionInterpolator(s);\n f = eF.compute();\n end\n\n end\n\nend", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/FEM/Functions/P1Function.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4982189780776057}} {"text": "function rgb=hsl2rgb(hsl_in)\n%Converts Hue-Saturation-Luminance Color value to Red-Green-Blue Color value\n%\n%Usage\n% RGB = hsl2rgb(HSL)\n%\n% converts HSL, a M [x N] x 3 color matrix with values between 0 and 1\n% into RGB, a M [x N] X 3 color matrix with values between 0 and 1\n%\n%See also rgb2hsl, rgb2hsv, hsv2rgb\n\n% (C) Vladimir Bychkovsky, June 2008\n% written using: \n% - an implementation by Suresh E Joel, April 26,2003\n% - Wikipedia: http://en.wikipedia.org/wiki/HSL_and_HSV\n\nhsl=reshape(hsl_in, [], 3);\n\nH=hsl(:,1);\nS=hsl(:,2);\nL=hsl(:,3);\n\nlowLidx=L < (1/2);\nq=(L .* (1+S) ).*lowLidx + (L+S-(L.*S)).*(~lowLidx);\np=2*L - q;\nhk=H; % this is already divided by 360\n\nt=zeros([length(H), 3]); % 1=R, 2=B, 3=G\nt(:,1)=hk+1/3;\nt(:,2)=hk;\nt(:,3)=hk-1/3;\n\nunderidx=t < 0;\noveridx=t > 1;\nt=t+underidx - overidx;\n \nrange1=t < (1/6);\nrange2=(t >= (1/6) & t < (1/2));\nrange3=(t >= (1/2) & t < (2/3));\nrange4= t >= (2/3);\n\n% replicate matricies (one per color) to make the final expression simpler\nP=repmat(p, [1,3]);\nQ=repmat(q, [1,3]);\nrgb_c= (P + ((Q-P).*6.*t)).*range1 + ...\n Q.*range2 + ...\n (P + ((Q-P).*6.*(2/3 - t))).*range3 + ...\n P.*range4;\n \nrgb_c=round(rgb_c.*10000)./10000; \nrgb=reshape(rgb_c, size(hsl_in));", "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/20292-hsl2rgb-and-rgb2hsl-conversion/hsl2rgb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.498208817495433}} {"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 check_FourierGrad\n\nS = mtexdata('dubna');\npf = S.pf;\nodf = calcODF(pf,'zeroRange');\nfodf = FourierODF(odf);\n\nori = orientation.rand(1000,pf.CS);\ng1 = fodf.grad(ori(:),'check','delta',0.1*degree);\ng2 = fodf.grad(ori(:));\n\nif max(norm(g1-g2)./norm(g1)) < 1e-2\n disp(' Fourier gradient test passed');\nelse\n disp(' Fourier gradient test failed');\nend\n\nreturn\n\n\n%% test 1 - check f_theta\ncs = crystalSymmetry('1');\nodf = fibreODF(Miller(0,0,1,cs),vector3d.Z,'halfwidth',40*degree);\nfodf = FourierODF(odf);\n\nomega = linspace(-179,179) * degree;\nori = rotation.byAxisAngle(vector3d(0,1,0),omega);\n\ng1 = fodf.grad(ori(:),'check','delta',0.1*degree);\ng2 = fodf.grad(ori(:));\n\nif max(norm(g1-g2)) < 1e-3, disp(' Test 1 passed'); end\n\n%% test 2\n\nori = rotation.byAxisAngle(vector3d(1,2,0)s,omega);\n\ng1 = fodf.grad(ori(:),'check','delta',0.1*degree);\ng2 = fodf.grad(ori(:));\n\nif max(norm(g1-g2)) < 1e-3, disp(' Test 2 passed'); end\n\n%% test 3 - check last line in grad composition\n\nori = rotation.byAxisAngle(vector3d(1,2,3),omega);\n\ng1 = fodf.grad(ori(:),'check','delta',0.1*degree);\ng2 = fodf.grad(ori(:));\n\nif max(norm(g1-g2)) < 1e-2\n disp(' Test 3 passed');\nelse\n disp(' Test 3 failed');\nend\n\n%% test 4 - final f_theta test\n\nori = orientation.rand(100,cs);\ng1 = fodf.grad(ori(:),'check','delta',0.1*degree);\ng2 = fodf.grad(ori(:));\n\nif max(norm(g1-g2)) < 1e-2\n disp(' Test 4 passed');\nelse\n disp(' Test 4 failed');\nend\n\n%% test 5 - f_phi1 test\n\nodf = fibreODF(Miller(0,1,0,cs),vector3d.Y,'halfwidth',40*degree);\nfodf = FourierODF(odf);\n\nori = orientation.byEuler(omega,89.9999*degree,0*degree,cs,'ABG');\n\n%odf.grad(rot)\ng1 = fodf.grad(ori(:),'check','delta',0.1*degree);\ng2 = fodf.grad(ori(:));\n\nif max(norm(g1-g2)) < 1e-2\n disp(' f_phi1 test passed');\nelse\n disp(' f_phi1 test failed');\nend\n\n\n%% test 6 - f_phi1 test\n\nodf = fibreODF(Miller(0,1,0,cs),vector3d.Y,'halfwidth',40*degree);\nfodf = FourierODF(odf);\n\nori = orientation.byEuler(0,89.9999*degree,omega,cs,'ABG');\n\n%odf.grad(rot)\ng1 = fodf.grad(ori(:),'check','delta',0.1*degree);\ng2 = fodf.grad(ori(:));\n\nif max(norm(g1-g2)) < 1e-2\n disp(' f_phi2 test passed');\nelse\n disp(' f_phi2 test failed');\nend\n\n\n\n\n\n%% test 5 - f_phi1 + f_phi_2 test\n\nodf = fibreODF(Miller(0,1,0,cs),vector3d.Y,'halfwidth',40*degree);\nfodf = FourierODF(odf);\n\nori = orientation.byAxisAngle(vector3d(0,1,100),omega);\n\n%odf.grad(rot)\ng1 = fodf.grad(ori(:),'check','delta',0.1*degree);\ng2 = fodf.grad(ori(:));\n\nif max(norm(g1-g2)) < 1e-2\n disp(' Test 6 passed');\nelse\n disp(' Test 6 failed');\nend\n\n%% test 6 - f_phi1 - f_phi_2 test\n\nodf = fibreODF(Miller(0,1,0,cs),vector3d.Y,'halfwidth',40*degree);\nfodf = FourierODF(odf);\n\nori = orientation.byAxisAngle(vector3d(0,1,100),omega);\n\n%odf.grad(rot)\ng1 = fodf.grad(ori(:),'check','delta',0.1*degree);\ng2 = fodf.grad(ori(:));\n\nif max(norm(g1-g2)) < 1e-2\n disp(' Test 6 passed');\nelse\n disp(' Test 6 failed');\nend\n\n%%\nfunction testing\n\ncs = crystalSymmetry('1');\n%ref = orientation.id(cs);\nref = orientation.rand(cs);\nodf = unimodalODF(ref,'halfwidth',40*degree);\n\nfodf = FourierODF(odf)\n\nomega = linspace(0,40)*degree;\n%omega = 5*degree;\nrot = ref*rotation(vector3d(1,1,1),omega)\n\ng2 = fodf.grad(rot,'check','delta',0.05*degree)\ng3 = odf.grad(rot)\ng1 = fodf.grad(rot)\n\nfodf.eval(rot)\nodf.eval(rot)\n\n%plot(norm(odf.grad(rot))\n\nend\n\n\n%%\nfunction test2\n\ncs = crystalSymmetry('1');\nodf = fibreODF(Miller(0,1,0,cs),vector3d.Y,'halfwidth',40*degree);\nfodf = FourierODF(odf)\n\nomega = 50*degree;\n%omega = linspace(0,179)*degree;\n%ori = orientation('axis',vector3d(0,1,100),'angle',omega,cs);\n%ori = orientation.byEuler(0*degree,0.01*degree,omega,cs,'ABG');\n\n% f_phi1 test with cos(Phi) == 0 --> ok\nori = orientation.byEuler(omega,89.9999*degree,30*degree,cs,'ABG')\n\n%%\n% f_phi2 test with cos(Phi) == 1\n\nomega = 80*degree\n%omega = linspace(0,89)*degree;\n\n\nodf = fibreODF(Miller(0,1,0,cs),vector3d.Z,'halfwidth',40*degree);\nfodf = FourierODF(odf)\n\n%ori = orientation.byEuler(0*degree,omega,[ 90]*degree,cs,'ABG');\n\n%ori = orientation.rand(100,cs);\n\nori = orientation.byEuler(0*degree,90*degree,45*degree,cs,'ABG');\n%ori = orientation.byEuler(10*degree,80*degree,[ 90]*degree,cs,'ABG');\n\ng2 = fodf.grad(ori(:))\ng1 = odf.grad(ori(:))\n\n\nd_Phi(odf,ori)\nd_phi1(odf,ori)\nd_phi2(odf,ori)\n\n\n%%\n\nfhat1 = zeros(3);% fhat1([4 6]) = [1 -1]*1i;\nfhat1 = zeros(3); %fhat1(9) = 1;\nfhat2 = zeros(5); %fhat2([6,8,10]) = 1;\nfhat2 = zeros(5); fhat2(4) = 1;\nfhat3 = zeros(7); %fhat3([22 24 26 28]) = [1 1 -1 -1]*1i;\nodf2 = FourierODF([1;fhat1(:);fhat2(:);fhat3(:)],cs);\n\n\n[g1,d1,d2,d3] = odf2.components{1}.grad(ori3);\ng1\ng2 = odf2.grad(ori3,'check')\n\n[d_phi1(odf2,ori3),d_Phi(odf2,ori3),d_phi2(odf2,ori3);...\n d1,d2,d3]\n\n%%\n\n%plot([norm(g1-g2)])\nplot([g1.z , g2.z]) % x anfangs ok dann zu schnell negativ\nplot([g1.y,g2.y]) % y - sollte konstant 0 sein\nplot([g2.z,g1.z]) % z - faktor 4 zu gro\u00df\nfodf.eval(ori)\nodf.eval(ori)\n\n%plot(norm(odf.grad(rot))\n\nend\n\nfunction test1\n\ncs = crystalSymmetry('1');\nodf = fibreODF(Miller(0,0,1,cs),vector3d.Z,'halfwidth',40*degree);\nfodf = FourierODF(odf)\n\nomega = 55*degree\n%omega = linspace(-179,179) * degree;\nori = rotation.byAxisAngle(vector3d(-1,1,3),omega)\n%ori = orientation.rand(cs);\n\n%odf.grad(rot)\ng1 = fodf.grad(ori(:),'check','delta',0.1*degree)\ng2 = fodf.grad(ori(:))\n\nplot([g1.y,g2.y])\n\nend\n\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/tests/check_FourierGrad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4981807793247829}} {"text": "function [mmps2] = cmps22mmps2(cmps2)\n% Convert acceleration from centimeters per square centimeter to \n% millimeters per second-squared\n% Chad A. Greene 2012\nmmps2 = cmps2*1e+1; \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/35258-unit-converters/unit_converters/cmps22mmps2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4981807732570775}} {"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 ra=lpcar2ra(ar)\n%LPCAR2RA Convert ar filter to inverse filter autocorrelation coefs. RA=(AR)\n\n\n% Copyright (C) Mike Brookes 1997\n% Version: $Id: lpcar2ra.m,v 1.4 2007/05/04 07:01:38 dmb Exp $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[nf,p1]=size(ar);\nra=zeros(nf,p1);\nfor i=1:p1\n ra(:,i)=sum(ar(:,1:p1+1-i).*ar(:,i:p1),2);\nend\n\n", "meta": {"author": "decouples", "repo": "Matlab_deep_learning", "sha": "1b823b82686080e32b03e1f1a4648896bd6e3c44", "save_path": "github-repos/MATLAB/decouples-Matlab_deep_learning", "path": "github-repos/MATLAB/decouples-Matlab_deep_learning/Matlab_deep_learning-1b823b82686080e32b03e1f1a4648896bd6e3c44/\u7b2c 19 \u7ae0 \u57fa\u4e8e\u8bed\u97f3\u8bc6\u522b\u7684\u4fe1\u53f7\u706f\u56fe\u50cf\u6a21\u62df\u63a7\u5236\u6280\u672f/voicebox/lpcar2ra.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4981807671893718}} {"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 [MFCC] = VAD_MFCC(wave,Fs)\n\n%% Extracts MFCC features from the speech signal\n\nframeL=30;\nframeshift=10;\n\nNfft=1024;\n\nStart=1;\nStop=round(frameL/1000*Fs);\nShift=round(frameshift/1000*Fs);\nInd=1;\nWin=blackman(Stop);\nEs=[];\n\nwave=filter([1 -0.97],1,wave);\n\nwhile Stop0); % mask for frames with a valid minimum\n if any(efmk)\n ef(efmk)=ef(efmk)-0.25*efb(efmk).^2./efa(efmk);\n end\n ef=min(min(ef,efm),efp);\nend\n\nem=ef==0; % mask for zero noise frames\nrm=rf==0; % mask for zero reference frames\nsnf=10*log10((rf+rm)./(ef+em));\nsnf(rm)=-snmax;\nsnf(em)=snmax;\n\n% select the frames to include\n\nif any(m=='w')\n vf=ones(1,nf); % include all frames\nelseif any(m=='v');\n vs=vadsohn(r,fs,'na');\n nvs=length(vs);\n [vss,vix]=sort([ifr'; vs(:,2)]);\n vjx=zeros(nvs+nf,5);\n vjx(vix,1)=(1:nvs+nf)'; % sorted position\n vjx(1:nf,2)=vjx(1:nf,1)-(1:nf)'; % prev VAD frame end (or 0 or nvs+1 if none)\n vjx(nf+1:end,2)=vjx(nf+1:end,1)-(1:nvs)'; % prev snr frame end (or 0 or nvs+1 if none)\n dvs=[vss(1)-mq; vss(2:end)-vss(1:end-1)]; % number of samples from previous frame boundary\n vjx(:,3)=dvs(vjx(:,1)); % number of samples from previous frame boundary\n vjx(1:nf,4)=vs(min(1+vjx(1:nf,2),nvs),3); % VAD result for samples between prev frame boundary and this one\n vjx(nf+1:end,4)=vs(:,3); % VAD result for samples between prev frame boundary and this one\n vjx(1:nf,5)=1:nf; % SNR frame to accumulte into\n vjx(vjx(nf+1:end,2)>=nf,3)=0; % zap any VAD frame beyond the last snr fram\n vjx(nf+1:end,5)=min(vjx(nf+1:end,2)+1,nf); % SNR frame to accumulate into\n vf=full(sparse(1,vjx(:,5),vjx(:,3).*vjx(:,4),1,nf))>kf/2; % accumulate into SNR frames and compare with threshold\nelse % default is 'V'\n [lev,af,fso,vad]=activlev(r,fs); % do VAD on reference signal\n vf=sum(reshape(vad(mq+1:ifl),kf,nf),1)>kf/2; % find frames that are mostly active\nend\nseg=mean(snf(vf));\nglo=10*log10(sum(rf(vf))/sum(ef(vf)));\n\nif ~nargout || any (m=='p')\n subplot(311);\n plot((1:length(s))/fs,s);\n ylabel('Signal');\n title(sprintf('SNR = %.1f dB, SNR_{seg} = %.1f dB',glo,seg));\n axh(1)=gca;\n subplot(312);\n plot((1:length(r))/fs,r);\n ylabel('Reference');\n axh(2)=gca;\n subplot(313);\n snv=snf;\n snv(~vf)=NaN;\n snu=snf;\n snu(vf>0)=NaN;\n plot([1 nr]/fs,[glo seg; glo seg],':k',((1:nf)*kf+(1-kf)/2)/fs,snv,'-b',((1:nf)*kf+(1-kf)/2)/fs,snu,'-r');\n ylabel('Frame SNR');\n xlabel('Time (s)');\n axh(3)=gca;\n linkaxes(axh,'x');\nend\n\n", "meta": {"author": "decouples", "repo": "Matlab_deep_learning", "sha": "1b823b82686080e32b03e1f1a4648896bd6e3c44", "save_path": "github-repos/MATLAB/decouples-Matlab_deep_learning", "path": "github-repos/MATLAB/decouples-Matlab_deep_learning/Matlab_deep_learning-1b823b82686080e32b03e1f1a4648896bd6e3c44/\u7b2c 19 \u7ae0 \u57fa\u4e8e\u8bed\u97f3\u8bc6\u522b\u7684\u4fe1\u53f7\u706f\u56fe\u50cf\u6a21\u62df\u63a7\u5236\u6280\u672f/voicebox/snrseg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4981663020117971}} {"text": "%filename='test2d_micro';\nfilename = 'MicroQuad';\nptype = 'MICRO';\nmethod = 'SIMPALL';\nmaterialType = 'ISOTROPIC';\ninitial_case = 'circleInclusion';\ncost={'chomog_alphabeta'};\nweights=[1];\nconstraint = {'volumeConstraint'};\nconstraint_case = 'EQUALITY';\n%incrementFactor = 1;\ndesignVariable = 'Density';\n%designVariable = 'LevelSet';\nfilterType = 'PDE';\nfracRadius = 0.51;\n%optimizer = 'IPOPT';\noptimizer = 'DualNestedInPrimal';\n%optimizer = 'AlternatingPrimalDual';\n\noptimizerUnconstrained = 'PROJECTED GRADIENT';\nline_search_initiator = 'INCREASING LAST STEP';\nincrementFactor = 1.95;\n\n%optimizerUnconstrained = 'SLERP';\n\n\nnsteps = 1;\nVfrac_final = 0.4;\nPerimeter_target=1;\noptimality_final = 0.2*1e-3;\nconstr_final =1e-12;\n\nVfrac_initial = 0.8;\noptimality_initial = 0.2*1e-3;\nconstr_initial = 1e-12;\n\nTOL.rho_plus = 1;\nTOL.rho_minus = 0;\nTOL.E_plus = 1;\nTOL.E_minus = 1e-3;\nTOL.nu_plus = 1/3;\nTOL.nu_minus = 1/3;\n\n%Micro\nepsilon_isotropy_initial=1e-1;\nepsilon_isotropy_final = 1e-3;\nmicro.alpha =[1 1 0]';\nmicro.beta =[1 1 0]';\n\n%nsteps = 10;\n\n% For all tests\nplotting = true;\nprinting = true;\nmonitoring = true;\nmonitoring_interval = 1;\nmaxiter = 200;", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/Applications/MaterialDesign/CompositeMaterialDesignQuadDensityPDE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406087, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.498166302011797}} {"text": "function [mi] = yd2mi(yd)\n% Convert length from yards to miles.\n% Chad Greene 2012\nmi = yd*0.0005681818181818;", "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/yd2mi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6548947425132314, "lm_q1q2_score": 0.4981461133276141}} {"text": "function [F1c,F2c,F1,F2,C1,C2,VT]=truncatedOctahedronMesh(varargin)\n\n% function [F1c,F2c,F1,F2,C1,C2,VT]=truncatedOctahedronMesh(r,nCopies)\n% ------------------------------------------------------------------------\n%\n% \n% \n% Kevin Mattheus Moerman\n% gibbon.toolbox@gmail.com\n% \n% 2019/02/08 Created\n% 2019/10/13 \n% ------------------------------------------------------------------------\n\n%% Parse input\n\nswitch nargin\n case 1\n r=varargin{1};\n nCopies=2;\n case 2\n r=varargin{1};\n nCopies=varargin{2};\nend\n\nif isempty(nCopies)\n nCopies=2;\nend\n\nif numel(nCopies)==1\n nCopies=nCopies*ones(1,3);\nend\n\n%%\n%Get truncated octahedron\n[Fs,Vs,~]=truncatedOctahedron(r);\nFs1=Fs{1}; %hexagon faces\nFs2=Fs{2}; %quadrilateral faces\n\n%Rotate\n[R,~]=euler2DCM([0 0 0.25*pi]); %Define rotation\nVs=Vs*R; %Rotate coordinates\n\n%Derive face centre points for offsets\n% Vn=patchCentre(Fs,Vs);\nXi=Vs(:,1); Yi=Vs(:,2); Zi=Vs(:,3);\nVn=[mean(Xi(Fs2),2) mean(Yi(Fs2),2) mean(Zi(Fs2),2)];\n\n%%\nnTotal=prod(nCopies); %Total number of copies\noffsetDirs=[1 2 6]; %Offset direction N.B. varying these affects the offsets/signs below\n\n%Create cell indices for vertices\nindC=ones(size(Vs,1),1)*(1:1:nTotal);\nindC=indC(:);\n[I,J,K] = ind2sub(nCopies,indC);\nI=I-1; J=J-1; K=K-1;\n\n%Create cell indices for quad faces\nindF1=ones(size(Fs1,1),1)*(1:1:nTotal);\nindF1=indF1(:);\nindF1=(indF1-1);\n\nindF2=ones(size(Fs2,1),1)*(1:1:nTotal);\nindF2=indF2(:);\nindF2=(indF2-1);\n\n%Defining the quad faces matrix\nF1=repmat(Fs1,nTotal,1)+size(Vs,1).*indF1(:,ones(1,size(Fs1,2))); \nF2=repmat(Fs2,nTotal,1)+size(Vs,1).*indF2(:,ones(1,size(Fs2,2))); \n\n%Defining offsets\nsK=iseven(K); %Shift is adjusted according to z coordinate to create a \"cube\"\nD1=I*2*Vn(offsetDirs(1),:)+(sK*Vn(offsetDirs(1),:)); % X offsets\nD2=J*2*Vn(offsetDirs(2),:)+(sK*Vn(offsetDirs(2),:)); % Y offsets\nD3=K*Vn(offsetDirs(3),:); % Z offsets\n \nD=D1+D2+D3;\n\n%Defining vertices matrix\nVT=repmat(Vs,nTotal,1)+D;\n\n%Merge points\n[F1,VT,~,ind2]=mergeVertices(F1,VT); \nF2=ind2(F2);\n\nC1=indF1+1; %Index or color number\nC2=indF2+1; %Index or color number\n\n%Split up face matrix in to cell groups\nF1c=mat2cell(F1,size(Fs1,1)*ones(1,nTotal),size(Fs1,2));\nF2c=mat2cell(F2,size(Fs2,1)*ones(1,nTotal),size(Fs2,2));\n\nend\n\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/truncatedOctahedronMesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.49814610308081025}} {"text": "function [outexpdir] = ConvertMWTContour2Trx(experiment_name,rootoutputdir,varargin)\n\n%% set parameters\n\n% default parameters\nrootdatadir = '/groups/branson/home/bransonk/behavioranalysis/code/Jdetect/data/larvae_mwt/rawdata';\ncontourext = 'outline';\ntrxfilestr = 'trx.mat';\nperframedirstr = 'perframe';\nMINDT = .001;\npxpermm = 11.111;\nmaxlength_mm = 5;\nDEBUG = false;\nmakesoftlink = true;\n\n\n[rootdatadir,contourext,trxfilestr,perframedirstr,DEBUG,maxlength_mm,pxpermm,makesoftlink] = ...\n myparse(varargin,...\n 'rootdatadir',rootdatadir,...\n 'contourext',contourext,...\n 'trxfilestr',trxfilestr,...\n 'perframedirstr',perframedirstr,...\n 'debug',DEBUG,...\n 'maxlength',maxlength_mm,...\n 'pxpermm',pxpermm,...\n 'makesoftlink',makesoftlink);\n\nmaxlength_px = ceil(maxlength_mm * pxpermm);\n\n%% names of files\n\n% find contour files for each trajectory\nfiles = dir(fullfile(rootdatadir,[experiment_name,'.*.',contourext]));\ncontournames = {};\nids = [];\nfor i = 1:numel(files),\n match = regexp(files(i).name,['\\.(\\d+)\\.',contourext,'$'],'tokens','once');\n if isempty(match),\n continue;\n end\n contournames{end+1} = fullfile(rootdatadir,files(i).name);\n ids(end+1) = str2double(match{1});\nend\n\nif isempty(contournames),\n error('Could not find any contours matching the pattern %s.*.%s',fullfile(rootdatadir,experiment_name),contourext);\nend\n\nncontours = numel(contournames);\n\n%% put all the contours into one trx file\n\n% read everthing in from the contour files\nalltimestamps = {};\ntrx = [];\narena = struct('x',nan,'y',nan,'r',nan);\nfor i = 1:ncontours,\n\n trk = struct('id',ids(i),'xcontour',{{}},'ycontour',{{}});\n timestamps = [];\n fid = fopen(contournames{i},'r');\n j = 1;\n while true,\n s = fgetl(fid);\n if ~ischar(s),\n break;\n end\n d = sscanf(s,'%f');\n if numel(d) < 3,\n warning('Contour line %s length < 3, skipping this line',s);\n continue;\n end\n if mod(numel(d),2) ~= 1,\n warning('Contour line %s length is not odd, skipping this line',s);\n continue;\n end\n d = d';\n timestamp = d(1);\n x = d(2:2:end-1);\n y = d(3:2:end);\n trk.xcontour{j} = x;\n trk.ycontour{j} = y;\n timestamps(j) = timestamp;\n j = j + 1;\n end\n fclose(fid);\n trk.arena = arena;\n alltimestamps{i} = timestamps;\n trx = structappend(trx,trk);\nend\n\n% make all the timestamps agree with each other\ntimestamps = union(alltimestamps{:});\ndts = diff(timestamps);\n% sanity check to look for rounding errors\nif any(dts < MINDT),\n error('Rounding error check failed: there are timestamps < %f apart',MINDT);\nend\nt0s = cellfun(@(x) x(1), alltimestamps);\nt1s = cellfun(@(x) x(end), alltimestamps);\nfps = nanmean(dts);\nfor i = 1:ncontours,\n trx(i).firstframe = find(t0s(i) >= timestamps,1);\n trx(i).endframe = find(t1s(i) >= timestamps,1,'last');\n trx(i).off = 1 - trx(i).firstframe;\n % sanity check to make sure this matches the number of frames\n n = trx(i).endframe - trx(i).firstframe + 1;\n if numel(trx(i).xcontour) ~= n,\n error('Number of frames check failed: Number of frames of contour data does not match start and end timestamps');\n end\n trx(i).dt = dts(trx(i).firstframe:trx(i).endframe-1);\n trx(i).nframes = n;\n trx(i).fps = fps;\nend\n\n%% fit ellipses\n\n[XGRID,YGRID] = meshgrid(0:maxlength_px-1,0:maxlength_px-1);\n\nfor i = 1:ncontours,\n \n trx(i).x = nan(1,trx(i).nframes);\n trx(i).y = nan(1,trx(i).nframes);\n trx(i).x_mm = nan(1,trx(i).nframes);\n trx(i).y_mm = nan(1,trx(i).nframes);\n trx(i).a = nan(1,trx(i).nframes);\n trx(i).b = nan(1,trx(i).nframes);\n trx(i).a_mm = nan(1,trx(i).nframes);\n trx(i).b_mm = nan(1,trx(i).nframes);\n trx(i).theta = nan(1,trx(i).nframes);\n trx(i).theta_mm = nan(1,trx(i).nframes);\n \n for t = 1:trx(i).nframes,\n \n % create an image \n xc = round(trx(i).xcontour{t}*pxpermm);\n yc = round(trx(i).ycontour{t}*pxpermm);\n minx = min(xc);\n maxx = max(xc);\n miny = min(yc);\n maxy = max(yc);\n nx = maxx-minx+1;\n ny = maxy-miny+1;\n bw = [inpolygon(XGRID(1:ny,1:nx),YGRID(1:ny,1:nx),[xc,xc(1)]-minx,[yc,yc(1)]-miny);false(maxlength_px-ny,nx)];\n \n % fit an ellipse\n x = XGRID(bw)+minx;\n y = YGRID(bw)+miny;\n mux = nanmean(x);\n muy = nanmean(y);\n S = cov([x,y],1);\n [a,b,theta] = cov2ell(S);\n % try and make theta be as continuous as possible\n if t > 1,\n dsame = abs(modrange(trx(i).theta(t-1)-theta,-pi,pi));\n dflip = abs(modrange(trx(i).theta(t-1)-theta+pi,-pi,pi));\n if dflip < dsame,\n theta = modrange(theta+pi,-pi,pi);\n end\n end\n \n % store quarter-major, quarter-minor axes\n a = a/2;\n b = b/2;\n mux_mm = mux / pxpermm;\n muy_mm = muy / pxpermm;\n a_mm = a / pxpermm;\n b_mm = b / pxpermm;\n trx(i).x(t) = mux_mm;\n trx(i).y(t) = muy_mm;\n trx(i).x_mm(t) = mux_mm;\n trx(i).y_mm(t) = muy_mm;\n trx(i).a(t) = a_mm;\n trx(i).b(t) = b_mm;\n trx(i).a_mm(t) = a_mm;\n trx(i).b_mm(t) = b_mm;\n trx(i).theta(t) = theta;\n trx(i).theta_mm(t) = theta;\n \n if DEBUG,\n hold off;\n plot(trx(i).xcontour{t},trx(i).ycontour{t},'k.-');\n hold on;\n drawellipse(trx(i).x(t),trx(i).y(t),trx(i).theta(t),trx(i).a(t)*2,trx(i).b(t)*2,'r');\n axis equal;\n title(num2str(t));\n drawnow;\n end\n \n end\n \nend\n\n%% plot the trajectories\n\nif DEBUG,\n\nnframes = numel(timestamps);\ncolors = jet(ncontours)*.7;\nfor t = 1:nframes,\n hold off;\n for i = 1:ncontours,\n if t > trx(i).endframe || t < trx(i).firstframe, \n continue;\n end\n j = t + trx(i).off;\n plot(trx(i).xcontour{j},trx(i).ycontour{j},'.-','color',colors(i,:));\n hold on;\n drawellipse(trx(i).x(j),trx(i).y(j),trx(i).theta(j),trx(i).a(j)*2,trx(i).b(j)*2,'color','r');\n end\n axis equal;\n drawnow;\nend\n\nend\n\n%% create output directory\n\n% make sure the root output directory exists\nif ~exist(rootoutputdir,'dir'),\n mkdir(rootoutputdir);\nend\n\n% create the experiment directory\noutexpdir = fullfile(rootoutputdir,experiment_name);\nif ~exist(outexpdir,'dir'),\n mkdir(outexpdir);\nend\n\n%% create the trx file\n\noutmatname = fullfile(outexpdir,trxfilestr);\nsave(outmatname,'trx');\n\n%% copy over the contour files\nfor i = 1:ncontours,\n [~,basename] = myfileparts(contournames{i});\n outcontourname = fullfile(outexpdir,basename);\n if isunix && makesoftlink,\n cmd = sprintf('ln -s %s %s',contournames{i},outcontourname);\n unix(cmd);\n else\n [success,msg] = copyfile(contournames{i},outcontourname);\n if ~success,\n error('Error copying file %s to %s: %s',moviename,outmoviename,msg);\n end\n end\nend\n\n%% save the per-frame features\nperframedir = fullfile(outexpdir,perframedirstr);\nif ~exist(perframedir,'dir'),\n mkdir(perframedir);\nend\n\n% to do: save choreography's per-frame features\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/ConvertMWTContour2Trx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.49814610308081014}} {"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": "function [stiffness]=assemble(stiffness,k,index)\n%----------------------------------------------------------\n% Purpose:\n% Assembly of element matrices into the system matrix\n%\n% Synopsis:\n% [stiffness]=assemble(stiffness,k,index)\n%\n% Variable Description:\n% stiffness - system matrix\n% k - element matri\n% index - d.o.f. vector associated with an element\n%-----------------------------------------------------------\n\n \n edof = length(index);\n for i=1:edof\n ii=index(i);\n for j=1:edof\n jj=index(j);\n stiffness(ii,jj)=stiffness(ii,jj)+k(i,j);\n end\n end\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/32519-stress-recovery/Stress Recovery/assemble.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.49814538385246454}} {"text": "function visualizeCellsRadial2D(phi)\n%VISUALIZECELLS plots the values of cell variable phi\n%\n% SYNOPSIS:\n%\n%\n% PARAMETERS:\n%\n%\n% RETURNS:\n%\n%\n% EXAMPLE:\n%\n% SEE ALSO:\n%\n\n% Written by Ali A. Eftekhari\n% See the license file\n\nL = phi.domain.cellcenters.x(end);\nx = [phi.domain.facecenters.x(1); phi.domain.cellcenters.x; phi.domain.facecenters.x(end)];\ny = [phi.domain.facecenters.y(1); phi.domain.cellcenters.y; phi.domain.facecenters.y(end)];\n[TH,R] = meshgrid(y, x);\n[X,Y] = pol2cart(TH,R);\nh = polar([0 2*pi], [0 L]);\ndelete(h);\nhold on\npcolor(X,Y,phi.value)\ncolorbar\nhold off\n", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/Visualization/visualizeCellsRadial2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.4981453820295804}} {"text": "function [qt] = gal2qt(gal)\n% Convert volume from US liquid gallons to US liquid quarts. \n% Chad Greene 2012\nqt = gal*4;", "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/gal2qt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.4981325186222006}} {"text": "function jed2 = jed_to_next_noon ( jed1 )\n\n%*****************************************************************************80\n%\n%% JED_TO_NEXT_NOON converts a JED to the JED of the next noon.\n%\n% Discussion:\n%\n% This is primarily to make a fair test of the weekday routines,\n% which have trouble when the JED is at midnight.\n%\n% Note that noon corresponds to an integral JED value.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 June 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real JED1, the Julian Ephemeris Date.\n%\n% Output, real JED2, the Julian Ephemeris Date\n% of the next noon.\n%\n jed2 = round ( jed1 );\n%\n% The integer part of JED1 is one of the two integers that\n% bracket JED1. If it's the smaller one (which it should\n% be as long as JED1 is positive), make it the bigger one.\n%\n% This correctly leaves undisturbed cases where JED1 is\n% already an integer, and where JED1 is negative (which\n% is not a case we expect to occur often).\n%\n if ( jed2 < jed1 )\n jed2 = jed2 + 1.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/calpak/jed_to_next_noon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.49813250551889077}} {"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": "function [b1, b2] = isManifoldMesh(varargin)\n%ISMANIFOLDMESH Check whether the input mesh may be considered as manifold.\n%\n% B = isManifoldMesh(V, F)\n% B = isManifoldMesh(V, E, F)\n% Checks if the specified mesh is a manifold. When mesh is a manifold,\n% all edges are connected to either 2 or 1 faces.\n%\n% [B, HASBORDER] = isManifoldMesh(V, E, F)\n% Also checks whether the mesh contains border faces. Border faces\n% contains at least one edge which is ajacent to only one face.\n%\n% Example\n% [V, F] = createOctahedron;\n% isManifoldMesh(V, F)\n% ans =\n% logical\n% 1\n%\n% See also\n% meshes3d, ensureManifoldMesh, trimMesh\n \n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2019-01-31, using Matlab 9.5.0.944444 (R2018b)\n% Copyright 2019 INRA - Cepia Software Platform.\n\nvertices = varargin{1};\nfaces = varargin{2};\n\n% compute edge to vertex array\nif nargin == 3\n edges = faces;\n faces = varargin{3};\nelse\n % compute edge to vertex array\n edges = meshEdges(faces);\nend\n\n\n% compute face to edge indices array\n% as a nFaces-by-3 array (each face connected to exactly three edges)\nfaceEdgeInds = meshFaceEdges(vertices, edges, faces);\n\n% compute number of faces incident each edge\nedgeFaces = trimeshEdgeFaces(faces);\nedgeFaceDegrees = sum(edgeFaces > 0, 2);\n\n% for each face, concatenate the face degree of each edge\nfaceEdgeDegrees = zeros(size(faces, 1), 3);\nfor iFace = 1:size(faces, 1)\n edgeInds = faceEdgeInds{iFace};\n faceEdgeDegrees(iFace, :) = edgeFaceDegrees(edgeInds);\nend\n\nregFaces = sum(ismember(faceEdgeDegrees, [1 2]), 2) == 3;\ninnerFaces = sum(faceEdgeDegrees == 2, 2) == 3;\nborderFaces = regFaces & ~innerFaces;\n\n% check if mesh is manifold: all faces are either regular or border\nb1 = all(regFaces);\n\n% check if some faces are border\nb2 = any(borderFaces);\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_geom3d/meshes3d/isManifoldMesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879992, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.4981072485291298}} {"text": "classdef GradientVariationExperiment < handle\n \n properties (Access = public)\n backgroundMesh\n boundaryMesh\n levelSet\n regularizedPerimeter\n domainLength\n end\n \n properties (Access = private)\n iMesh \n inputFile\n levelSetParams\n end \n \n methods (Access = public)\n \n function obj = GradientVariationExperiment(cParams)\n obj.init(cParams)\n obj.createBackgroundAndBoundaryMesh();\n obj.computeDomainLength();\n obj.createLevelSet();\n obj.createRegularizedPerimeters();\n end\n \n end\n \n methods (Access = protected)\n \n function init(obj,cParams)\n obj.inputFile = cParams.inputFile;\n obj.iMesh = cParams.iMesh;\n obj.levelSetParams = cParams.levelSetParams;\n end\n \n function createBackgroundAndBoundaryMesh(obj)\n s.inputFile = obj.inputFile;\n s.isBackgroundMeshRectangularBox = true;\n mCreator = BackgroundAndBoundaryMeshCreatorFromInputFile(s);\n obj.backgroundMesh = mCreator.backgroundMesh;\n obj.boundaryMesh = mCreator.boundaryMesh;\n end\n \n function createLevelSet(obj)\n s = obj.levelSetParams;\n s.coord = obj.backgroundMesh.coord;\n s.ndim = obj.backgroundMesh.ndim;\n lsCreator = LevelSetCreator.create(s);\n obj.levelSet = lsCreator.getValue();\n end\n \n function computeDomainLength(obj)\n x = obj.backgroundMesh.coord;\n d = max(x(:,1)) - min(x(:,1));\n obj.domainLength = d;\n end\n \n function createRegularizedPerimeters(obj)\n s.inputFile = obj.inputFile;\n s.backgroundMesh = obj.backgroundMesh;\n s.scale = 'MACRO';\n s.designVariable = obj.levelSet;\n s.outputFigureName = ['SmoothedCircleMesh',num2str(obj.iMesh)];\n s.plotting = false;\n s.printing = false;\n s.capturingImage = false;\n s.isRobinTermAdded = true;\n s.perimeterType = 'perimeterInterior';\n rPerimeter = RegularizedPerimeterComputer(s);\n rPerimeter.compute();\n obj.regularizedPerimeter = rPerimeter;\n end\n \n end\n \nend", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/Applications/PerimeterExperiments/GradientVariationExperiment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225276, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.4980314995708494}} {"text": "% test_cgal_tri_fillholes.m\n\n% Author: Ramon Casero \n% Copyright \u00a9 2013 University of Oxford\n% Version: 0.1.0\n%\n% University of Oxford means the Chancellor, Masters and Scholars of\n% the University of Oxford, having an administrative office at\n% Wellington Square, Oxford OX1 2JD, UK. \n%\n% This file is part of Gerardus.\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details. The offer of this\n% program under the terms of the License is subject to the License\n% being interpreted in accordance with English Law and subject to any\n% action against the University of Oxford being under the jurisdiction\n% of the English Courts.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see\n% .\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Basic\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% empty mesh\n[tri, n] = cgal_tri_fillholes([], [])\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Cube with one missing triangle\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% create a surface mesh that is a cube\nx = [\n 0 0 0\n 0 0 1\n 0 1 0\n 0 1 1\n 1 0 0\n 1 0 1\n 1 1 0\n 1 1 1\n ];\n\ntri = [\n 1 3 5\n 2 1 5\n 2 3 1\n 4 3 2\n 6 2 5\n 4 2 6\n 7 6 5\n 3 7 5\n 4 7 3\n 8 6 7\n 4 8 7\n 4 6 8\n ];\n\n% plot mesh\nhold off\ntrisurf(tri, x(:,1), x(:,2), x(:,3))\naxis([0 1 0 1 0 1])\n\n% make a hole by removing one of the triangles\ntri2 = tri;\ntri2(6, :) = [];\n\n% plot mesh\nhold off\ntrisurf(tri2, x(:,1), x(:,2), x(:,3))\naxis([0 1 0 1 0 1])\n\n% fill hole\n[tri2, n] = cgal_tri_fillholes(tri2, x);\ndisp(['Number of holes filled = ' num2str(n)])\n\n% check that the hole has been filled (expected result, and empty matrix)\nsetdiff(sort(tri, 2), sort(tri2, 2), 'rows')\n\n% plot mesh\nhold off\ntrisurf(tri2, x(:,1), x(:,2), x(:,3))\naxis([0 1 0 1 0 1])\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Cube with two triangles that form the upper face missing\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% create a surface mesh that is a cube\nx = [\n 0 0 0\n 0 0 1\n 0 1 0\n 0 1 1\n 1 0 0\n 1 0 1\n 1 1 0\n 1 1 1\n ];\n\ntri = [\n 1 3 5\n 2 1 5\n 2 3 1\n 4 3 2\n 6 2 5\n 4 2 6\n 7 6 5\n 3 7 5\n 4 7 3\n 8 6 7\n 4 8 7\n 4 6 8\n ];\n\n% plot mesh\nhold off\ntrisurf(tri, x(:,1), x(:,2), x(:,3))\naxis([0 1 0 1 0 1])\n\n% make a hole by removing one of the triangles\ntri2 = tri;\ntri2([6 12], :) = [];\n\n% plot mesh\nhold off\ntrisurf(tri2, x(:,1), x(:,2), x(:,3))\naxis([0 1 0 1 0 1])\n\n% fill hole\n[tri2, n] = cgal_tri_fillholes(tri2, x);\ndisp(['Number of holes filled = ' num2str(n)])\n\n% check that the hole has been filled (expected result, and empty matrix)\nsetdiff(sort(tri, 2), sort(tri2, 2), 'rows')\n\n% plot mesh\nhold off\ntrisurf(tri2, x(:,1), x(:,2), x(:,3))\naxis([0 1 0 1 0 1])\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Cube with two holes (missing two triangles)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% create a surface mesh that is a cube\nx = [\n 0 0 0\n 0 0 1\n 0 1 0\n 0 1 1\n 1 0 0\n 1 0 1\n 1 1 0\n 1 1 1\n ];\n\ntri = [\n 1 3 5\n 2 1 5\n 2 3 1\n 4 3 2\n 6 2 5\n 4 2 6\n 7 6 5\n 3 7 5\n 4 7 3\n 8 6 7\n 4 8 7\n 4 6 8\n ];\n\n% plot mesh\nhold off\ntrisurf(tri, x(:,1), x(:,2), x(:,3))\naxis([0 1 0 1 0 1])\n\n% make a hole by removing one of the triangles\ntri2 = tri;\ntri2([1 6], :) = [];\n\n% plot mesh\nhold off\ntrisurf(tri2, x(:,1), x(:,2), x(:,3))\naxis([0 1 0 1 0 1])\n\n% fill hole\n[tri2, n] = cgal_tri_fillholes(tri2, x);\ndisp(['Number of holes filled = ' num2str(n)])\n\n% check that the hole has been filled (expected result, and empty matrix)\nsetdiff(sort(tri, 2), sort(tri2, 2), 'rows')\n\n% plot mesh\nhold off\ntrisurf(tri2, x(:,1), x(:,2), x(:,3))\naxis([0 1 0 1 0 1])\n\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/test/test_cgal_tri_fillholes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.69925440852404, "lm_q2_score": 0.7122321781307375, "lm_q1q2_score": 0.4980314904505975}} {"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 [g, gdata, gprior] = rbfgrad(net, x, t)\n%RBFGRAD Evaluate gradient of error function for RBF network.\n%\n%\tDescription\n%\tG = RBFGRAD(NET, X, T) takes a network data structure NET together\n%\twith a matrix X of input vectors and a matrix T of target vectors,\n%\tand evaluates the gradient G of the error function with respect to\n%\tthe network weights (i.e. including the hidden unit parameters). The\n%\terror function is sum of squares. Each row of X corresponds to one\n%\tinput vector and each row of T contains the corresponding target\n%\tvector. If the output function is 'NEUROSCALE' then the gradient is\n%\tonly computed for the output layer weights and biases.\n%\n%\t[G, GDATA, GPRIOR] = RBFGRAD(NET, X, T) also returns separately the\n%\tdata and prior contributions to the gradient. In the case of multiple\n%\tgroups in the prior, GPRIOR is a matrix with a row for each group and\n%\ta column for each weight parameter.\n%\n%\tSee also\n%\tRBF, RBFFWD, RBFERR, RBFPAK, RBFUNPAK, RBFBKP\n%\n\n%\tCopyright (c) Ian T Nabney (1996-2001)\n\n% Check arguments for consistency\nswitch net.outfn\ncase 'linear'\n errstring = consist(net, 'rbf', x, t);\ncase 'neuroscale'\n errstring = consist(net, 'rbf', x);\notherwise\n error(['Unknown output function ', net.outfn]);\nend\nif ~isempty(errstring);\n error(errstring);\nend\n\nndata = size(x, 1);\n\n[y, z, n2] = rbffwd(net, x);\n\nswitch net.outfn\ncase 'linear'\n\n % Sum squared error at output units\n delout = y - t;\n\n gdata = rbfbkp(net, x, z, n2, delout);\n [g, gdata, gprior] = gbayes(net, gdata);\n\ncase 'neuroscale'\n % Compute the error gradient with respect to outputs\n y_dist = sqrt(dist2(y, y));\n D = (t - y_dist)./(y_dist+diag(ones(ndata, 1)));\n temp = y';\n gradient = 2.*sum(kron(D, ones(1, net.nout)) .* ...\n (repmat(y, 1, ndata) - repmat((temp(:))', ndata, 1)), 1);\n gradient = (reshape(gradient, net.nout, ndata))';\n % Compute the error gradient\n gdata = rbfbkp(net, x, z, n2, gradient);\n [g, gdata, gprior] = gbayes(net, gdata);\notherwise\n error(['Unknown output function ', net.outfn]);\nend\n\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/netlab3.3/rbfgrad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028205, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4979188082435052}} {"text": "%DEMOIMSHAPES2D Display various 2D demo shapes\n%\n% output = demoShapes2d(input)\n%\n% Example\n% demoImShapes\n%\n% See also\n%\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2011-06-29, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011 INRA - Cepia Software Platform.\n\n\n%% initialisations\n\n% generate cubic images\nlx = 1:100;\nly = 1:100;\n\n% choose a center not aligned with the grid\ncenter = [50+sqrt(2)-1 50+sqrt(3)-1];\n\nangles = [...\n 0; ...\n 10; ...\n 30; ...\n 45];\n\n\n\n%% Disc\n\n% sphere is defined by center and radius\ndisc = [center 40];\n\n% generation of 3D image\nimg = discreteDisc(lx, ly, disc);\n\n% display image\nf = figure; \nimshow(~img);\n \n% decorate\ntitle('Disc, radius=40');\n\n\n%% Ellipse\n\nfigure;\nfor i = 1:4\n % sphere is defined by center and radius\n ellipse = [center 40 20 angles(i)];\n\n % generation of 3D image\n img = discreteEllipse(lx, ly, ellipse);\n\n % display image\n subplot(2, 2, i); \n imshow(~img);\n\n % decorate\n title(sprintf('Ellipse, Th=%02d', angles(i)));\nend\n\n\n%% Square\n\nfigure;\nfor i = 1:4\n % sphere is defined by center and radius\n square = [center 60 angles(i)];\n\n % generation of 3D image\n img = discreteSquare(lx, ly, square);\n\n % display image\n subplot(2, 2, i); \n imshow(~img);\n\n % decorate\n title(sprintf('Square, Th=%02d', angles(i)));\nend\n\n\n%% Rectangle\n\nfigure;\nfor i = 1:4\n % sphere is defined by center and radius\n rect = [center 60 30 angles(i)];\n\n % generation of 3D image\n img = discreteRectangle(lx, ly, rect);\n\n % display image\n subplot(2, 2, i); \n imshow(~img);\n\n % decorate\n title(sprintf('Rectangle, Th=%02d', angles(i)));\nend\n\n\n%% Capsule\n\nfigure;\nfor i = 1:4\n % sphere is defined by center and radius\n [dx dy] = pol2cart(deg2rad(angles(i)), 30);\n caps = [center-[dx dy] center+[dx dy] 15];\n\n % generation of 3D image\n img = discreteCapsule(lx, ly, caps);\n\n % display image\n subplot(2, 2, i); \n imshow(~img);\n\n % decorate\n title(sprintf('Capsule, Th=%02d', angles(i)));\nend\n\n\n%% Egg\n\nfigure;\nfor i = 1:4\n % egg defined by a center, a size and an angle\n egg = [center 30 angles(i)];\n\n % generation of 3D image\n img = discreteEgg(lx, ly, egg);\n\n % display image\n subplot(2, 2, i); \n imshow(~img);\n\n % decorate\n title(sprintf('Egg, Th=%02d', angles(i)));\nend\n\n\n%% Trefoil\n\nfigure;\nfor i = 1:4\n % trefoil defined by a center, two radii and an angle\n trefoil = [center 40 15 angles(i)];\n\n % generation of 3D image\n img = discreteTrefoil(lx, ly, trefoil);\n\n % display image\n subplot(2, 2, i); \n imshow(~img);\n\n % decorate\n title(sprintf('Trefoil, Th=%02d', angles(i)));\nend\n\n\n%% Starfish\n\nfigure;\nfor i = 1:4\n % starfish defined by a center, two radii and an angle\n starfish = [center 40 20 angles(i)];\n\n % generation of 3D image\n img = discreteStarfish(lx, ly, starfish);\n\n % display image\n subplot(2, 2, i); \n imshow(~img);\n\n % decorate\n title(sprintf('Starfish, Th=%02d', angles(i)));\nend\n\n\n\n\n", "meta": {"author": "mattools", "repo": "matImage", "sha": "94d892c7beac0db32daadf2646ce37f58e894caf", "save_path": "github-repos/MATLAB/mattools-matImage", "path": "github-repos/MATLAB/mattools-matImage/matImage-94d892c7beac0db32daadf2646ce37f58e894caf/demos/imShapes/demoShapes2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.497905294239701}} {"text": "function tests = test_ft_preproc_padding\n\n% MEM 1gb\n% WALLTIME 00:10:00\n% DEPENDENCY ft_preproc_padding\n\nif nargout\n % assume that this is called by RUNTESTS\n tests = functiontests(localfunctions);\nelse\n % assume that this is called from the command line\n fn = localfunctions;\n for i=1:numel(fn)\n feval(fn{i});\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction testOptions(testCase)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nnchan = 8;\nnsample = 1000;\ndat = randn(nchan, nsample) + 1;\n\nresult = [];\nresult{end+1} = ft_preproc_padding(dat, 'zero', 10);\nresult{end+1} = ft_preproc_padding(dat, 'mean', 10);\nresult{end+1} = ft_preproc_padding(dat, 'localmean', 10);\nresult{end+1} = ft_preproc_padding(dat, 'edge', 10);\nresult{end+1} = ft_preproc_padding(dat, 'mirror', 10);\nresult{end+1} = ft_preproc_padding(dat, 'nan', 10);\nresult{end+1} = ft_preproc_padding(dat, 'remove', 10);\nresult{end+1} = ft_preproc_padding(dat, 'zero', 20);\nresult{end+1} = ft_preproc_padding(dat, 'mean', 20);\nresult{end+1} = ft_preproc_padding(dat, 'localmean', 20);\nresult{end+1} = ft_preproc_padding(dat, 'edge', 20);\nresult{end+1} = ft_preproc_padding(dat, 'mirror', 20);\nresult{end+1} = ft_preproc_padding(dat, 'nan', 20);\nresult{end+1} = ft_preproc_padding(dat, 'remove', 20);\nresult{end+1} = ft_preproc_padding(dat, 'zero', 10, 20);\nresult{end+1} = ft_preproc_padding(dat, 'mean', 10, 20);\nresult{end+1} = ft_preproc_padding(dat, 'localmean', 10, 20);\nresult{end+1} = ft_preproc_padding(dat, 'edge', 10, 20);\nresult{end+1} = ft_preproc_padding(dat, 'mirror', 10, 20);\nresult{end+1} = ft_preproc_padding(dat, 'nan', 10, 20);\nresult{end+1} = ft_preproc_padding(dat, 'remove', 10, 20);\n\nfor i=1:numel(result)\n % the number of samples should be larger, or smaller upon 'remove'\n assert(size(result{i},2)~=nsample);\nend\n\n% all iterations were done with (slightly) different options, hence the results should not be equal\nfor i=1:numel(result)\n for j=(i+1):numel(result)\n assert(~isequal(result{i}, result{j}), 'the results %d and %d should not be equal', i, j);\n end\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_ft_preproc_padding.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.4979052815714583}} {"text": "function x = sample_vector(p,col)\n%SAMPLE_VECTOR Sample from multiple categorical distributions.\n% X = SAMPLE_VECTOR(P) returns a row vector of cols(P) integers, where\n% X(I) = SAMPLE(P(:,I)).\n%\n% X = SAMPLE_VECTOR(P,COL) returns a row vector of length(COL) integers, where\n% X(I) = SAMPLE(P(:,COL(I))).\n% This is equivalent to SAMPLE_VECTOR(P(:,COL)), but faster.\n\n% Written by Tom Minka\n% (c) Microsoft Corporation. All rights reserved.\n\ncdf = cumsum(p);\nif nargin >= 2\n cdf = cdf(:,col);\nend\nif any(cdf(end,:) <= 0)\n error('distribution is all zeros');\nend\nu = rand(1,cols(cdf)).*cdf(end,:);\nx = col_sum(cdf < repmat(u,rows(cdf),1)) + 1;\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/libs/+lightspeed/sample_vector.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.4979052812826124}} {"text": "function [x,y]=simulate(a,b,c,d,x0,T)\n%Simulation of dynamical system\nx(1)=x0;\nfor t=2:T\nx(t)=random('normal',mx(a,x(t-1)),vx(b,x(t-1)));\ny(t)=random('normal',my(c,x(t)),vy(d,x(t-1)));\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/29905-particle-filter-comparison-with-smoothing-methods/ParticleMethods-Compare/simulate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4978811996314368}} {"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 fx = p00_fun ( problem, n, x )\n\n%*****************************************************************************80\n%\n%% P00_FUN evaluates the integrand for any problem.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 September 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer PROBLEM, the problem index.\n%\n% Input, integer N, the number of evaluation points.\n%\n% Input, real X(2,N), the evaluation points.\n%\n% Output, real FX(N,1), the integrand values.\n%\n fx = zeros ( n, 1 );\n\n if ( problem == 1 )\n fx = p01_fun ( n, x );\n elseif ( problem == 2 )\n fx = p02_fun ( n, x );\n elseif ( problem == 3 )\n fx = p03_fun ( n, x );\n elseif ( problem == 4 )\n fx = p04_fun ( n, x );\n elseif ( problem == 5 )\n fx = p05_fun ( n, x );\n elseif ( problem == 6 )\n fx = p06_fun ( n, x );\n elseif ( problem == 7 )\n fx = p07_fun ( n, x );\n elseif ( problem == 8 )\n fx = p08_fun ( n, x );\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'P00_FUN - Fatal error!\\n' );\n fprintf ( 1, ' Illegal problem index = %d\\n', problem );\n error ( 'P00_FUN - 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_int_2d/p00_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.4977286496989647}} {"text": "function g = restrict(f, s)\n%RESTRICT Restrict an UNBNDFUN to a subinterval.\n% RESCTRICT(F, S) returns a FUN object that is restricted to the subinterval\n% [S(1), S(2)] of the domain of F.\n%\n% If length(S) > 2, i.e., S = [S1, S2, ..., Sn], then RESCTRICT(F, S) returns\n% an array of FUN objects, where the cells contain F restricted to each of \n% the subintervals defined by S. If there is only one FUN to be returned,\n% that is, if length(S) == 2, then the FUN object g is returned. This \n% facilitates the use of the result by other functions, e.g. plot etc.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Deal with empty case:\nif ( isempty(f) )\n g = f;\n return\nend\n\n% Check if the argument s is actually a subinterval:\nif ( s(1) < f.domain(1) || s(end) > f.domain(2) || any(diff(s) <= 0) )\n error('CHEBFUN:UNBNDFUN:restrict:badInterval', 'Not a valid interval.')\nelseif ( numel(s) == 2 && all(s == f.domain) )\n % Nothing to do here!\n g = f;\n return\nend\n\n% Number of subdomains:\nnumSubDom = numel(s) - 1;\n\n% Preallocate the output cell:\ng = cell(1, numSubDom);\n\n% Any exponents?\nexps = [];\n\nif ( issing(f) )\n \n % Grab the exponents:\n exps = get(f, 'exponents');\n \n % If there is a non-trivial exponent:\n if ( any(exps) )\n \n % Interior exponents:\n interiorExps = zeros(1, numSubDom-1); \n \n % Insert the interior exponents:\n exps = [exps(1) interiorExps exps(2)];\n \n % Negate the exponents for infinite endpoint, since the exponents stored\n % in SINGFUN are the negated values of those supplied to the UNBNDFUN\n % constructor:\n \n if ( s(1) == -Inf )\n exps(1) = -exps(1);\n elseif ( f.domain(1) == -Inf )\n exps(1) = 0;\n end\n \n if ( s(end) == Inf )\n exps(end) = -exps(end);\n elseif ( f.domain(end) == Inf )\n exps(end) = 0;\n end\n\n end\n \nend\n\n% Grab the vscale:\nvscale = get(f, 'vscale');\n\n% Loop over each subdomain:\nfor k = 1:numSubDom\n \n % Initialize preferences:\n pref = chebfunpref();\n \n % Pass the information about exponents through preference:\n if ( ~isempty(exps) && any(exps(k:k+1)) )\n data.exponents = exps(k:k+1);\n \n if ( (k == 1) || (k == numSubDom) )\n pref.techPrefs.extrapolate = 1;\n end\n else\n data.exponents = [];\n end\n \n data.domain = s(k:k+1);\n data.vscale = vscale;\n g{k} = classicfun.constructor(@(x) feval(f, x), data, pref);\nend\n\n% When there is only one cell, return the UNBNDFUN instead:\nif ( numSubDom == 1 )\n g = g{1};\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/@unbndfun/restrict.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102956, "lm_q2_score": 0.7401743735019594, "lm_q1q2_score": 0.49764270394477267}} {"text": "function y = Fault_decision_system(u)\nglobal st14\n\n% Using model defined by the structure st14 to make decision about system fault\n\nu(3)=1e-10*u(3).*(u(end).^6);u=u(1:3);\nsker=st14.x2sup+(abs(u))'*abs(u)*ones(st14.Nlsup,1)-2*st14.xsup*abs(u);\ny=(st14.w)'*exp(-sker./(2*(st14.sigma).^2))+st14.b;\n\nif y>=0.8\n y=1;\nelse\n y=0;\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/35130-award-winning-fdi-solution-in-wind-turbines/FDI_WindTurbines_1st_award/Fault_decision_system.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382236515258, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.49753433108917344}} {"text": "function model = yalmip2scs(interfacedata);\n\nmodel.data.A = -interfacedata.F_struc(:,2:end);\nmodel.data.b = full(interfacedata.F_struc(:,1));\nmodel.data.c = interfacedata.c;\nmodel.cones = interfacedata.K;\nmodel.param = interfacedata.options.scs;\n\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/solvers/yalmip2scs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.49753432698304}} {"text": "function [pvec, pstruct] = tapas_hgf_binary_mab_transp(r, ptrans)\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\npvec = NaN(1,length(ptrans));\npstruct = struct;\n\nl = r.c_prc.n_levels;\n\npvec(1:l) = ptrans(1:l); % mu_0\npstruct.mu_0 = pvec(1:l);\npvec(l+1:2*l) = exp(ptrans(l+1:2*l)); % sa_0\npstruct.sa_0 = pvec(l+1:2*l);\npvec(2*l+1:3*l) = ptrans(2*l+1:3*l); % rho\npstruct.rho = pvec(2*l+1:3*l);\npvec(3*l+1:4*l-1) = exp(ptrans(3*l+1:4*l-1)); % ka\npstruct.ka = pvec(3*l+1:4*l-1);\npvec(4*l:5*l-1) = ptrans(4*l:5*l-1); % om\npstruct.om = pvec(4*l:5*l-1);\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_transp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.497519433438997}} {"text": "function im_scale = prep_im_for_blob_size(im_size, target_size, max_size)\n\n im_size_min = min(im_size(1:2));\n im_size_max = max(im_size(1:2));\n im_scale = double(target_size) / im_size_min;\n \n % Prevent the biggest axis from being more than MAX_SIZE\n if round(im_scale * im_size_max) > max_size\n im_scale = double(max_size) / double(im_size_max);\n end\nend", "meta": {"author": "ShaoqingRen", "repo": "faster_rcnn", "sha": "49ad0990512a5d6e34f56e3c6596eb5fbf22f651", "save_path": "github-repos/MATLAB/ShaoqingRen-faster_rcnn", "path": "github-repos/MATLAB/ShaoqingRen-faster_rcnn/faster_rcnn-49ad0990512a5d6e34f56e3c6596eb5fbf22f651/utils/prep_im_for_blob_size.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4975194283662686}} {"text": "function distMat = BagDistMat(data,bagModels)\n\ndistMat = zeros(size(data,1),length(bagModels)*length(bagModels{1}),'single');\ncount = 1;\nfor mno = 1:length(bagModels)\n curModel = bagModels{mno};\n for j = 1:length(curModel)\n curWk = curModel(j);\n dd = data(:,curWk.dim)*curWk.dir;\n tt = curWk.tr*curWk.dir;\n distMat(:,count) = sign( (dd>tt)-0.5)*curWk.alpha;\n count = count+1;\n end\nend\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/BagDistMat.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": "function drawCameraPly(PLYfilename,Rt,scale,w,h,f)\n\nif ~exist('w','var')\n w = 640;\nend\nif ~exist('h','var')\n h = 480;\nend\nif ~exist('f','var')\n f = 570.3422090067766703214147128164768218994140625;\nend\nif ~exist('scale','var')\n scale = 0.01;\nend\n\ncamera=[...\n0 -w/2 +w/2 +w/2 -w/2\n0 -h/2 -h/2 +h/2 +h/2\n0 f f f f];\n\ncamera = camera * scale;\ncamera = Rt(:,1:3) * camera + repmat(Rt(:,4),1,5);\nedges = [1 2; 1 3; 1 4; 1 5; 2 3;3 4;4 5;5 2]';\n\n\ngraph2ply(PLYfilename, camera, edges);\n\n%{\nplot3(camera(1,[2 3 4 5 2]),camera(2,[2 3 4 5 2]),camera(3,[2 3 4 5 2]),'-k'); hold on;\nfor i=2:5\n plot3(camera(1,[1 i]),camera(2,[1 i]),camera(3,[1 i]),'-k'); hold on;\nend\naxis equal\nxlabel('x');\nylabel('y');\nzlabel('z');\n%}", "meta": {"author": "jianxiongxiao", "repo": "ProfXkit", "sha": "7376c50abf5ead846247774a36be026e6f24953c", "save_path": "github-repos/MATLAB/jianxiongxiao-ProfXkit", "path": "github-repos/MATLAB/jianxiongxiao-ProfXkit/ProfXkit-7376c50abf5ead846247774a36be026e6f24953c/drawCamera/drawCameraPly.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": "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 s = getBehAssociation(Gamma,y,T,synch)\n% Returns, for each time point, how well the state time courses predict\n% the variable y across trials, which must have dimension (trials by 1)\n%\n% Author: Diego Vidaurre, OHBA, University of Oxford (2018)\n\nif ~all(T(1)==T)\n error('Synchronisity can only be measured if trials have the same length'); \nend \nN = length(T); \nttrial = size(Gamma,1)/N;\nif nargin<4, synch = zeros(1,T(1)); end\nK = size(Gamma,2);\nGamma = permute(reshape(Gamma,[ttrial N K]),[2 3 1]);\ns = zeros(1,ttrial);\nthese = ~isnan(y);\ny = y(these);\nN = length(y);\ny = zscore(y);\nfor t = 1:ttrial\n if synch(t)==1, continue; end\n x = [ones(N,1) Gamma(these,1:K-1,t)];\n beta = (x' * x + 1e-8 * eye(K) ) \\ (x' * y); \n s(t) = 1 - sum((y - x * beta).^2) / sum(y.^2);\nend\n\nend", "meta": {"author": "OHBA-analysis", "repo": "HMM-MAR", "sha": "bb0433b75482e473980791a2b30afe2012cf6578", "save_path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR", "path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR/HMM-MAR-bb0433b75482e473980791a2b30afe2012cf6578/task/monitoring/getBehAssociation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4975194131480821}} {"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": "%% dualClad\n% Below is a demonstration of the features of the |dualClad| function\n\n%% Syntax\n% |[Fq,Vq,Fc,Vc]=dualClad(F,V,shrinkFactor,cladMethod);|\n\n%% Description\n% This function creates patch data defining a cladding on a surface. The\n% cladding is obtained by shrinking the input faces around their mean and\n% by connecting the face sides to form new faces. The output faces cover\n% the edges of the dual of the input surface (hence the name). The output\n% is the set of shrunk faces (same type as input) and a set of new\n% quadrilateral faces connecting the shrunk faces. \n% The shrink factor, which can be a constant or a spatially varying metric\n% on the nodes or faces, defines the face and edge shrink used. The\n% clad method determines whether the output mesh is connected:\n% 1: From shrunk face to shrunk face\n% 2: From shrunk face to shrunk edge to shrunk face\n% 3: From shrunk face to shrunk face through edge (computes intersection at\n% edge which may not be the centre of edge. This method avoids potential\n% \"kinks\" seen for method 2. \n\n%% Examples\nclear; close all; clc;\n\n%%\n% Plot settings\n\nfigStruct.ColorDef='black';\nfigStruct.Color='k';\n\n%% \n% Specify test surface. Alter settings to test for different geometries and\n% surface types. \n\n%Testing settings\ntestCase=2; %1= sphere, 2=bunny, 3=dino\nmeshType=1; %1=triangles, 2=quadrilaterials\ncutMesh=0; %0=not cut, 1=cut in half\n\nswitch testCase\n case 1\n [F,V,~]=geoSphere(2,1); % Building a geodesic dome surface model\n shrinkFactor=0.25;\n case 2\n [F,V]=stanford_bunny('g'); %Bunny\n V_mean=mean(V,1);\n V=V-V_mean(ones(size(V,1),1),:);\n shrinkFactor=0.25;\n case 3\n [F,V]=parasaurolophus; %dino\n V_mean=mean(V,1);\n V=V-V_mean(ones(size(V,1),1),:);\n shrinkFactor=0.25;\n case 4\n defaultFolder = fileparts(fileparts(mfilename('fullpath')));\n pathName=fullfile(defaultFolder,'data','libSurf');\n \n dataStruct=load(fullfile(pathName,'sprocket.mat'));\n F=dataStruct.F;\n V=dataStruct.V;\n shrinkFactor=0.5;\n case 5\n defaultFolder = fileparts(fileparts(mfilename('fullpath')));\n pathName=fullfile(defaultFolder,'data','libSurf');\n \n dataStruct=load(fullfile(pathName,'enginePart_p1.mat'));\n F=dataStruct.F;\n V=dataStruct.V;\n shrinkFactor=0.5;\nend\n\nif meshType==2\n [F,V]=tri2quad(F,V);\nend\n\nif cutMesh==1\n logicKeep=V(:,1)1)=1;\n\n[Fq,Vq,Fc,Vc]=dualClad(F,V,shrinkFactor,cladMethod);\n\n%%\n% Animating the effect of the shrink factor\n\n%%\n% Initialize scene\nhf=cFigure(figStruct);\nhold on;\n\nhp1=gpatch(Fc,Vc,shrinkFactor,'k',1);\nhp2=gpatch(Fq,Vq,'r','none',1);\n\naxisGeom;\ncamlight headlight;\ncolormap(viridis(250));\nclim([0 1]);\ndrawnow;\naxis off\naxis manual; \n\n%%\n% Animate scene\n\nnSteps=40; %Number of animation steps\nanimStruct.Time=linspace(0,1,nSteps); %Create the time vector\n\nt=linspace(0,2,nSteps);\nshrinkFactor=-V(:,1);\nshrinkFactor=mean(shrinkFactor(F),2);\nshrinkFactor=shrinkFactor-min(shrinkFactor(:));\nshrinkFactor=shrinkFactor./max(shrinkFactor(:));\nshrinkFactor=shrinkFactor+1;\nminLevel=0.05;\n\nfor q=1:1:nSteps \n \n shrinkFactorNow=shrinkFactor;\n shrinkFactorNow=shrinkFactorNow-t(q);\n shrinkFactorNow(shrinkFactorNow1)=1;\n \n [Fq,Vq,Fc,Vc]=dualClad(F,V,shrinkFactorNow,cladMethod);\n\n %Set entries in animation structure\n animStruct.Handles{q}=[hp1 hp2 hp1]; %Handles of objects to animate\n animStruct.Props{q}={'Vertices','Vertices','CData'}; %Properties of objects to animate\n animStruct.Set{q}={Vc,Vq,shrinkFactorNow}; %Property values for to set in order to animate\nend\n\nanim8(hf,animStruct); %Initiate animation\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_dualClad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679957, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.49750165883550745}} {"text": "\n\nclear all; close all;\nI=imread('circles.png');\nJ=bwmorph(I, 'remove');\nfigure;\nsubplot(121); imshow(I);\nsubplot(122); imshow(J);\n\n", "meta": {"author": "HuangCongQing", "repo": "Algorithms_MathModels", "sha": "e15b0e9053b11f08b5ce1e3492c4acb444409c8b", "save_path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels", "path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels/Algorithms_MathModels-e15b0e9053b11f08b5ce1e3492c4acb444409c8b/\u300aMATLAB\u56fe\u50cf\u5904\u7406\u300b\u6e90\u6587\u4ef6/\u672c\u4e66\u6e90\u6587\u4ef6/chap12/chap12_21.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.4975016542289335}} {"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": "format compact\naddpath('src_release');\naddpath('build');\ntest_OMP\ntest_OMPMask\ntest_Lasso\ntest_LassoMask\ntest_LassoWeighted\ntest_CD\ntest_RidgeRegression\ntest_SparseProject\ntest_SOMP\ntest_L1L2BCD\ntest_TrainDL\ntest_TrainDL_Memory\ntest_StructTrainDL\ntest_nmf\ntest_ProximalFlat\ntest_ProximalTree\ntest_ProximalGraph\ntest_ProximalPathCoding\ntest_EvalPathCoding\ntest_FistaFlat\ntest_FistaTree\ntest_FistaGraph\ntest_FistaPathCoding\ntest_CalcAAt\ntest_CalcXAt\ntest_CalcXY\ntest_CalcXYt\ntest_CalcXtY\ntest_ConjGrad\ntest_InvSym\ntest_Normalize\ntest_Sort\ntest_CountConnexComponents\ntest_CountPathsDAG\ntest_RemoveCyclesGraph\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/AMICO/SPAMS/test_release/test_all.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.49750164137109737}} {"text": "function plotSigmoidalResponse_LGG(resp,Y,modelCI,nameOutcome,pathFig)\n% -------------------------------------------------------------------------\n% function plotSigmoidalResponse_LGG(resp,Y,modelCI,nameOutcome,pathFig)\n% -------------------------------------------------------------------------\n% DESCRIPTION: \n% This function plots the sigmoidal response (P(y=1|x)) of a linear \n% multivariable model response. See ref. [1] for more details.\n% -------------------------------------------------------------------------\n% REFERENCE:\n% [1] Vallieres, M. et al. (2015). A radiomics model from joint FDG-PET and \n% MRI texture features for the prediction of lung metastases in soft-tissue \n% sarcomas of the extremities. Physics in Medicine and Biology, 60(14), \n% 5471-5496. doi:10.1088/0031-9155/60/14/5471\n% -------------------------------------------------------------------------\n% INPUTS:\n% 1. resp: Column vector of size [nInst X 1] specifying the linear \n% multivariable model response, where 'nInst' refers to the number\n% of instances.\n% 2. Y: Column vector of size [nInst X 1] specifying the outcome status \n% (1 or 0) for all instances.\n% 3. modelCI: Column vector of size [nInst X 2] specifying the 95%\n% confidence interval on the multivariable model response as\n% defined by the 2.5 (modelCI(i,1)) and the 97.5 (modelCI(i,2))\n% percentiles, for the ith instance. To plot without CIs, use []\n% for the 3rd argument.See ref. [1] for more \n% details.\n% 4. nameOutcome: String specifying the name of the\n% modeled outcome.\n% --> Ex: 'progression'\n% 5. pathFig: (optional). Full path to where figure is saved without\n% displaying it. Put '' for displaying the figure and not \n% saving it to 'pathFig' (default).\n% --> Ex: ''\n% -------------------------------------------------------------------------\n% AUTHOR(S): Martin Vallieres \n% -------------------------------------------------------------------------\n% HISTORY:\n% - Creation: January 2017\n%--------------------------------------------------------------------------\n% STATEMENT:\n% This file is part of , \n% a package providing MATLAB programming tools for radiomics analysis.\n% --> Copyright (C) 2015-2017 Martin Vallieres\n%\n% This package is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This package is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this package. If not, see .\n% -------------------------------------------------------------------------\n\nstartpath = pwd;\n\nif nargin < 5\n pathFig = '';\nend\n\nprob = 1./(1 + exp(-resp)); % Sigmoidal response, or P(y=1|x)\nrespPos = resp(Y==1); \nrespNeg = resp(Y==0); \nprobPos = prob(Y==1);\nprobNeg = prob(Y==0);\nname = nameOutcome;\nsymbols = {'ob','xr'}; % First entry for positive instances, second entry for negative instances\n\nif isempty(pathFig)\n figure\nelse\n h = figure('visible','off');\nend\n[sortResp,~] = sort(resp);\nsigX = (sortResp(1)-5):0.1:sortResp(end)+5;\nsigY = 1./(1 + exp(-sigX));\nplot(sigX,sigY,'-k','LineWidth',3);\nhold on\nif ~isempty(modelCI)\n lowXpos = modelCI(Y==1,1); highXpos = modelCI(Y==1,2);\n lowXneg = modelCI(Y==0,1); highXneg = modelCI(Y==0,2);\n [~] = herrorbar(respPos,probPos,respPos-lowXpos,highXpos-respPos,'ob');\n hold on\n [~] = herrorbar(respNeg,probNeg,respNeg-lowXneg,highXneg-respNeg,'xr');\n legend('Sigmoidal response',['95% CI: ',name,' = 1'],['Status: ',name,' = 1'],['95% CI: ',name,' = 0'],['Status: ',name,' = 0'],'Location','NorthWest')\nelse\n plot(respPos,probPos,symbols{1},'LineWidth',6,'MarkerSize',18,'MarkerFaceColor',symbols{1}(end),'MarkerEdgeColor',symbols{1}(end));\n hold on\n plot(respNeg,probNeg,symbols{2},'LineWidth',6,'MarkerSize',20,'MarkerFaceColor',symbols{2}(end),'MarkerEdgeColor',symbols{2}(end));\n legend('Sigmoidal response',['Status: ',name,' = 1'],['Status: ',name,' = 0'],'Location','NorthWest')\nend\nxlabel('Multivariable model response','FontSize',30)\nylabel(['Probability that ',name,' = 1'],'FontSize',30)\naxis([sortResp(1)-0.33*abs(sortResp(1)),sortResp(end)+0.33*abs(sortResp(end)),-0.05,1.05])\nset(gca,'FontSize',24)\n\nif ~isempty(pathFig)\n cd(pathFig)\n saveas(h,['sigPlotResponse_',name],'fig')\nend\n\ncd(startpath)\nend\n", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/LGG_study/Functions/plotSigmoidalResponse_LGG.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4974225152885853}} {"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": "function f_x = ParFor3(in1)\n%PARFOR3\n% F_X = PARFOR3(IN1)\n\n% This function was generated by the Symbolic Math Toolbox version 8.2.\n% 20-Sep-2019 09:35:35\n\nu = in1(:,1);\nux = in1(:,4);\nuxx = in1(:,5);\nuxxx = in1(:,6);\nf_x = (u.*1.034220113405542e16+ux.*6.575036155887616e15+uxx.*1.215253266628608e17-uxxx.*4.601209472843776e15-u.*ux.*5.099459193028608e15+u.*uxx.*5.032641492680704e16+u.*uxxx.*4.967741975658496e15-2.603211137867776e15)./(u.*3.126267420934144e16+4.755897990407782e16);\n", "meta": {"author": "dynamicslab", "repo": "SINDy-PI", "sha": "42799b8e5a7585e400aa4bc3c83cfd659046cbb4", "save_path": "github-repos/MATLAB/dynamicslab-SINDy-PI", "path": "github-repos/MATLAB/dynamicslab-SINDy-PI/SINDy-PI-42799b8e5a7585e400aa4bc3c83cfd659046cbb4/Comparison/PDE_Comparison/Implicit_SINDy/TempFunctions/ParFor3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.49731912481119167}} {"text": "%returns the first component of the frequency representation of the signal\nclassdef SpectralSpread < Algorithm\n \n methods (Access = public)\n \n function obj = SpectralSpread()\n obj.name = 'SpectralSpread';\n obj.inputPort = DataType.kSignal;\n obj.outputPort = DataType.kFeature;\n end\n \n %receives a fourier transform\n function result = compute(~,Y)\n N = length(Y);\n Y = abs(Y) / N;\n Y = Y / max(Y);\n \n m = ((1/(2*N))*(1:N))';\n \n % compute the spectral spread\n C = sum(m .* Y) / (sum(Y)+eps);\n result = sqrt(sum(((m-C).^2) .* Y)/ (sum(Y)+eps));\n end\n \n function metrics = computeMetrics(~,input)\n n = size(input,1);\n flops = 11 * n;\n memory = n;\n outputSize = Constants.kFeatureBytes;\n metrics = Metric(flops,memory,outputSize);\n end\n end\nend\n", "meta": {"author": "avenix", "repo": "WDK", "sha": "c525222b02bd390b4758d30f1cd8b19af043108e", "save_path": "github-repos/MATLAB/avenix-WDK", "path": "github-repos/MATLAB/avenix-WDK/WDK-c525222b02bd390b4758d30f1cd8b19af043108e/ARC/algorithm/6-featureExtraction/frequency domain/SpectralSpread.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.49731911591672445}} {"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": "%%\nfunction Metrics = ...\n performCalcu(datasetStruct,algStructArray) \n\nevaluateSal = @(sMap,thresholds,gtMap) thresholdBased_HR_FR(sMap,thresholds,gtMap);\n\nthresholds = [255:-1:0]/255; % thresholding image from 0 - 255\nGTfiles=dir([datasetStruct.GTdir '/*.png']); % gather the GT files in png\nGTfiles = [GTfiles; dir([datasetStruct.GTdir '/*.jpg'])]; % gather the GT files in jpg\nGTfiles = [GTfiles; dir([datasetStruct.GTdir '/*.bmp'])]; % gather the GT files in bmp\n\nnumOfFiles = size(GTfiles,1); % totalImgNum*1\nnumOfAlgos = length(algStructArray); % num of algorithmos to be evaluated\n\n[hitRate, falseAlarm] = deal(zeros(numOfFiles,length(thresholds),numOfAlgos));%\n\n%% initial\n\n[IoU, TPR, FPR, Pre, Recall] = deal(zeros(numOfFiles,length(thresholds),numOfAlgos));\n\n[mean_Fmeasure] = deal(zeros(numOfFiles,3,numOfAlgos)); % totalImgNum*3*numOfAlgos [precision, recall, fmeasure]\n\n[MAE] = deal(zeros(numOfFiles,1,numOfAlgos)); % totalImgNum*1*numOfAlgos\n\n[S_measure] = deal(zeros(numOfFiles,1,numOfAlgos)); % totalImgNum*1*numOfAlgos\n\n%Iterate over images\nhwait = waitbar(0,['Processing ', num2str(numOfFiles),' images on ',datasetStruct.datasetName,': 0%']);\n\nfor imIndx=1:numOfFiles \n % read the ground truth files\n [~,base_name,ext] = fileparts(GTfiles(imIndx).name); \n \n gtMap = im2double(imread([datasetStruct.GTdir base_name ext]));\n gtSize = size(gtMap); \n if (length(gtSize) == 3)\n gtMap = rgb2gray(gtMap);\n gtSize(3)= [];\n end\n \n \n gtMap = logical(gtMap>=0.1); % get binary mask\n totalNum = numOfFiles* ones(numOfAlgos,1); %3*1 ( [totalImgNum;totalImgNum;totalImgNum;totalImgNum] ) \n for algIdx = 1:numOfAlgos % compute over each algorithms iteratively\n sMap = readSaliencyMap(algStructArray{algIdx},[base_name],gtSize);% read and resize saliency maps\n if sum(sum(sMap)) == 0\n totalNum(algIdx) = totalNum(algIdx) - 1;\n end\n \n [IoU(imIndx,:,algIdx), TPR(imIndx,:,algIdx), FPR(imIndx,:,algIdx), Pre(imIndx,:,algIdx), Recall(imIndx,:,algIdx), ... % calculate IoU, TPR, FPR, Pre, Recall, hitRate, falseAlarm\n hitRate(imIndx,:,algIdx), falseAlarm(imIndx,:,algIdx)] ...\n = evaluateSal(sMap,thresholds,gtMap);\n \n [mean_Fmeasure(imIndx,:,algIdx)] = Fmeasure_calu(sMap,gtMap,gtSize); % calculate F-measure using 2 x MeanValueOfSalMap [precision,recall,fmeasure]\n\n MAE(imIndx,:,algIdx) = CalMAE(sMap, gtMap); % clculate MAE\n\n S_measure(imIndx,:,algIdx) = StructureMeasure(sMap, gtMap); % calculate S-measure\n\n end\n pct = sprintf('%5.1f',imIndx/numOfFiles*100);\n waitbar(imIndx/numOfFiles,hwait,['Processing ', num2str(numOfFiles),...\n ' images on ',datasetStruct.datasetName,': ',pct,'%']); \nend %End of image loop\n\nclose(hwait);\n%Average across images -\nmmHitRate = permute( sum(hitRate,1),[2 3 1] );\nmmFalseAlarm = permute( sum(falseAlarm,1),[2 3 1]);\n\nnanind = isnan(Pre);\nPre(nanind) = 0;\nmmPre = permute( sum(Pre,1),[2 3 1]); \nmmRecall = permute( sum(Recall,1),[2 3 1]);\nmmTPR = permute( sum(TPR,1),[2 3 1]);\nmmFPR = permute( sum(FPR,1),[2 3 1]);\nmmIoU = permute( sum(IoU,1),[2 3 1]);\n\nmmmean_Fmeasure = permute( sum(mean_Fmeasure,1),[2 3 1]);\nmmMAE = zeros(1,numOfAlgos);\nmmS_measure = zeros(1,numOfAlgos);\n\nfor j=1:numOfAlgos\n nanind = isnan(MAE(:,1,j));\n mmmMAE = MAE(:,1,j);\n mmmMAE(nanind) = [];\n \n nanind = isnan(S_measure(:,1,j));\n mmmS_measure = S_measure(:,1,j);\n mmmS_measure(nanind) = [];\n \n mmHitRate(:,j) = mmHitRate(:,j)./totalNum(j);\n mmFalseAlarm(:,j) = mmFalseAlarm(:,j)./totalNum(j);\n mmPre(:,j) = mmPre(:,j)./totalNum(j);\n mmRecall(:,j) = mmRecall(:,j)./totalNum(j);\n mmTPR(:,j) = mmTPR(:,j)./totalNum(j);\n mmFPR(:,j) = mmFPR(:,j)./totalNum(j);\n mmIoU(:,j) = mmIoU(:,j)./totalNum(j);\n \n mmmean_Fmeasure(:,j) = mmmean_Fmeasure(:,j)./totalNum(j);\n mmMAE(:,j) = mean(mmmMAE,1);\n mmS_measure(:,j) = mean(mmmS_measure,1);\nend\nMetrics.HitRate = mmHitRate;\nMetrics.FalseAlarm = mmFalseAlarm;\nMetrics.Pre = mmPre;\nMetrics.Recall = mmRecall;\nMetrics.TPR = mmTPR;\nMetrics.FPR = mmFPR;\nMetrics.IoU = mmIoU;\n\nMetrics.mean_Fmeasure = mmmean_Fmeasure; \nMetrics.MAE = mmMAE; \nMetrics.S_measure = mmS_measure;\nMetrics.AUC = nan(1,size(Metrics.FalseAlarm,2));\nfor algIdx=1:numOfAlgos\n Metrics.AUC(algIdx) = trapz(Metrics.FalseAlarm(:,algIdx),Metrics.HitRate(:,algIdx));\nend\n\nMetrics.mean_Fmeasure_image = mean_Fmeasure;\nMetrics.MAE_image = MAE;\nMetrics.S_measure_image = S_measure;\nMetrics.TPR_image = TPR;\nMetrics.FPR_image = FPR;\nMetrics.Pre_image = Pre;\nMetrics.Recall_image = Recall;\n\nMetrics.Fmeasure_Curve = (1+0.3).*Metrics.Pre.*Metrics.Recall./...\n (0.3*Metrics.Pre+Metrics.Recall);\n[Metrics.MaxFmeasure, ind] = max(Metrics.Fmeasure_Curve, [], 1);\nMetrics.IoU_at_maxF = Metrics.IoU(ind);\n[Metrics.maxIoU, ~] = max(Metrics.IoU, [], 1);\nMetrics.meanIoU = mean(Metrics.IoU, 1);\nend\n\n\n\n%% Read Saliency Maps\n\n% Read and resize saliency map\nfunction sMap = readSaliencyMap(algStruct,base_name,gtSize)\nif strcmp(algStruct.dir(end-3:end),'DSR')\n algStruct.ext='jpg';\nelseif strcmp(algStruct.dir(end-12:end-10),'DSR')\n algStruct.ext='jpg';\nend\nfile_name = fullfile(algStruct.dir,[algStruct.prefix base_name algStruct.postfix '.' algStruct.ext]);\nsMap = imresize(im2double(imread(file_name)),gtSize(1:2));\nif (size(sMap,3)==3)\n sMap = rgb2gray(sMap);\nend\nsMap(sMap<0)=0;\nmaxnum = max(sMap(:));\nif maxnum==0\n sMap = zeros(gtSize(1:2));\nelse\n sMap = sMap./maxnum;\nend \n\nend\n\n%% Calculate the scores\nfunction [IoU, TPR, FPR, Pre, Recall, hitRate, falseAlarm] ...\n = thresholdBased_HR_FR(sMap,thresholds,gtMap) %calculate the threshold based scores\n gtPxlNum = sum(gtMap(:));\n totalNum = size(gtMap,1)*size(gtMap,2);\n targetHist = histc(sMap(gtMap), fliplr(thresholds));\n nontargetHist = histc(sMap(~gtMap), fliplr(thresholds));\n\n targetHist = flipud(targetHist);\n nontargetHist = flipud(nontargetHist);\n\n targetHist = cumsum( targetHist );\n nontargetHist = cumsum( nontargetHist );\n\n Pre = targetHist ./ (targetHist + nontargetHist);\n Recall = targetHist / gtPxlNum;\n TPR = Recall;\n FPR = nontargetHist / (totalNum-gtPxlNum);\n IoU = targetHist ./ (gtPxlNum + nontargetHist);\n hitRate = targetHist / gtPxlNum;\n falseAlarm = 1 - (repmat(totalNum-gtPxlNum,size(nontargetHist)) - nontargetHist)/(totalNum-gtPxlNum);\nend\n%%", "meta": {"author": "ArcherFMY", "repo": "sal_eval_toolbox", "sha": "b4696d6846611529ff5a246ff892a4fd548a70c2", "save_path": "github-repos/MATLAB/ArcherFMY-sal_eval_toolbox", "path": "github-repos/MATLAB/ArcherFMY-sal_eval_toolbox/sal_eval_toolbox-b4696d6846611529ff5a246ff892a4fd548a70c2/tools/Curve_BenchCode/performCalcu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.4972988634846359}} {"text": "function Sf = FreeBoundary(S,t,V,K,type)\n\nSf = zeros(1,length(t));\neps_star = K*1e-5;\n\nswitch type\n case 'put'\n for j = 1:length(t)\n Sf(j) = S(find(abs(V(:,j)-K+S)< eps_star, 1, 'last'));\n end\n case 'call'\n for j = 1:length(t)\n Sf(j) = S(find(abs(V(:,j)+K-S)< eps_star, 1, 'first'));\n end\nend\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/17523-american-option-prices-and-the-optimal-exercise-boundary/FreeBoundary.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.4972988634846358}} {"text": "classdef SimplAllTestExplicitVsImplicit < handle\n \n properties (Access = protected)\n rho\n matInterpExplicit\n matInterpImplicit\n materialPropertiesSettings\n nElem\n nGaus\n dim\n end\n \n methods (Access = public)\n \n function obj = SimplAllTestExplicitVsImplicit(dim)\n obj.dim = dim;\n obj.init();\n obj.createProperties();\n obj.computeExplicitMaterialInterpolation();\n obj.computeImplicitMaterialInterpolation();\n end\n \n function error = computeError(obj)\n mE = obj.matInterpExplicit;\n mI = obj.matInterpImplicit;\n err(1) = norm(mE.mu(:) - mI.mu(:));\n err(2) = norm(mE.kappa(:) - mI.kappa(:));\n err(3) = norm(mE.dmu(:) - mI.dmu(:));\n err(4) = norm(mE.dkappa(:) - mI.dkappa(:));\n error = max(err);\n end\n end\n\n methods (Access = protected)\n \n function init(obj)\n obj.nElem = 800;\n obj.nGaus = 4;\n obj.rho = rand(obj.nElem,obj.nGaus);\n end\n \n function createProperties(obj)\n sC = SettingsConstitutiveProperties();\n sC.E_plus = rand(1);\n sC.E_minus = rand(1);\n sC.nu_minus = rand(1);\n sC.nu_plus = rand(1);\n obj.materialPropertiesSettings = sC;\n end\n \n function computeExplicitMaterialInterpolation(obj)\n type = 'EXPLICIT';\n mI = obj.computeMaterialInterpolation(type);\n obj.matInterpExplicit = mI;\n end\n \n function computeImplicitMaterialInterpolation(obj)\n type = 'IMPLICIT';\n mI = obj.computeMaterialInterpolation(type);\n obj.matInterpImplicit = mI;\n end\n \n function p = computeMaterialInterpolation(obj,type)\n sC = obj.materialPropertiesSettings;\n s = SettingsInterpolation();\n s.constitutiveProperties = sC;\n s.nElem = obj.nElem;\n s.simpAllType = type;\n s.dim = obj.dim;\n mI = MaterialInterpolation.create(s);\n p = mI.computeMatProp(obj.rho);\n obj.matInterpExplicit = p;\n end\n\n end\n\nend", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/tests/Source/TopOptTests/SimplAllTestExplicitVsImplicit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.497298861641133}} {"text": "%% Copyright (C) 2015, 2016 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 ei (@var{x})\n%% Symbolic exponential integral (Ei) function.\n%%\n%% Definition and example:\n%% @example\n%% @group\n%% syms x\n%% f = ei(x)\n%% @result{} f = (sym) Ei(x)\n%% rewrite(f, 'Integral') % doctest: +SKIP\n%% @result{} (sym)\n%% x\n%% \u2320\n%% \u23ae t\n%% \u23ae \u212f\n%% \u23ae \u2500\u2500 dt\n%% \u23ae t\n%% \u2321\n%% -\u221e\n%% @end group\n%% @end example\n%% (@strong{Note} rewriting as an integral is not yet supported.)\n%%\n%% Other examples:\n%% @example\n%% @group\n%% diff(f)\n%% @result{} (sym)\n%% x\n%% \u212f\n%% \u2500\u2500\n%% x\n%% @end group\n%% @end example\n%%\n%% @seealso{@@sym/expint}\n%% @end defmethod\n\n\nfunction y = ei(x)\n if (nargin ~= 1)\n print_usage ();\n end\n y = elementwise_op ('Ei', x);\nend\n\n\n%!test\n%! syms x\n%! f = ei(sym(0));\n%! assert (double(f) == -inf)\n\n%!test\n%! D = [1.895117816355937 4.954234356001890];\n%! A = ei(sym([1 2]));\n%! assert (all (abs(double(A) - D) < 1e-15))\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/ei.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837743174789, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.49729886016098684}} {"text": "function bs = bct_toolbox_undirected_graph_metrics(bs, thresh, varargin)\n% bs = bct_toolbox_undirected_graph_metrics(bs)\n%\n% thresh = proportional link density threshold; 0 to 1 value. (.1 is a common value)\n%\n% Method for brainpathway_multisubject that extracts graph metrics using\n% the Sporns lab (et al.) BCT toolbox.\n% Uses bct_toolbox_undirected_graph_metrics\n% \n% Stores results in bs.graph_properties.regions\n% - Nodes x subjects matrix for each graph property\n% - Can do group stats/t-tests/etc on (matrices)'\n%\n% Examples:\n% ------------------------------------------------------------------\n% Load brainpathway_data_gsr_censoring_pipeline.mat % from OLP/Yoni\n% bs = bct_toolbox_undirected_graph_metrics(bs);\n% mean_degree = nanmean(bs.graph_properties.regions.degree')'; % mean degree for each node\n%\n% % Plot montage of mean degree on brain\n% fmri_dat_obj = brainpathway2fmri_data(bs, bs.graph_properties.regions.degree);\n% montage(mean(fmri_dat_obj));\n\n\nr = double(bs.connectivity.regions.r);\n\nn = size(r, 3); % subjects\nn_nodes = size(r, 1); % nodes\n\nbs.graph_properties.regions = table(); % clear out -- overwrite\n\nfprintf('Completed subject ');\n\nwarning off\nfor i = 1:n\n \n [graph_prop, graph_prop_glob] = bct_toolbox_undirected_graph_metrics(r(:, :, i), thresh, varargin{:});\n \n % nodal properties\n vnames = graph_prop.Properties.VariableNames; \n for j = 1:length(vnames)\n \n bs.graph_properties.regions.(vnames{j})(i, 1:n_nodes) = graph_prop.(vnames{j});\n \n end\n \n % global properties\n vnames = graph_prop_glob.Properties.VariableNames; \n for j = 1:length(vnames)\n \n bs.graph_properties.regions.(vnames{j})(i, 1) = graph_prop_glob.(vnames{j});\n \n end\n \n % print to update status\n fprintf('\\b\\b\\b\\b\\b\\b%5d\\n',i) \n\nend % subject loop\nwarning on\n\nend % function\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/@brainpathway_multisubject/bct_toolbox_undirected_graph_metrics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.4972988583174845}} {"text": "function [imgCrop, scaling, seg, warn, valid] = LMobjectnormalizedcrop(img, annotation, j, b, height, width)\n%\n% Crop object from image using a normalized frame\n% [imgCrop, scaling] = LMobjectnormalizedcrop(img, annotation, j, [bh bw], height, width)\n% [imgCrop, scaling] = LMobjectnormalizedcrop(img, [xmin ymin xmax ymax], j, [bh bw], height, width)\n% extract object index j from the annotation.\n%\n% ------------\n% | bh | b = [bh bw] = number of boundary pixels\n% | ---- | h = height inner bounding box\n% |bw | | | w = width inner bounding box\n% | |h | |\n% | ---- |\n% | w |\n% ------------\n%\n\nif length(b) == 1\n b = b *[1 1];\nend\nbh = b(1);\nbw = b(2);\n\nif isstruct(annotation)\n [X,Y,t] = getLMpolygon(annotation.object(j).polygon);\nelse\n xmin = annotation(1); % [xmin ymin xmax ymax]\n ymin = annotation(2); % [xmin ymin xmax ymax]\n xmax = annotation(3); % [xmin ymin xmax ymax]\n ymax = annotation(4); % [xmin ymin xmax ymax]\n X = [xmin xmin xmax xmax];\n Y = [ymin ymax ymax ymin];\n t = 1;\nend\nnumFrames = length(t);\n\nif nargin < 6\n % decide which dimension is larger and use \n Dx = max(X)-min(X);\n Dy = max(Y)-min(Y);\n if Dy>Dx\n width = round(height*Dx/Dy);\n else\n % if Dx>Dy, \n h = round(height*Dy/Dx);\n width = height;\n height = h;\n end\nend\n\nimgCrop = zeros([height+2*bh width+2*bw size(img,3) numFrames], 'uint8');\nseg = zeros([height+2*bh width+2*bw numFrames], 'uint8');\nvalid = zeros([height+2*bh width+2*bw numFrames], 'uint8');\nwarn = zeros(1, numFrames);\nfor f = t\n if numFrames>1\n i = find(t==f); i = i(1);\n x = X(:,i);\n y = Y(:,i);\n else\n i = 1;\n x = X;\n y = Y;\n end\n \n % bb = boundingbox = [xmin ymin xmax ymax]\n bb = [min(x) min(y) max(x) max(y)];\n \n % 1) Resize image so that object is normalized in size\n scaling = min(height/(bb(4)-bb(2)), width/(bb(3)-bb(1)));\n if numFrames>1\n [foo, I] = LMimscale([], img(:,:,:,f+1), scaling, 'bilinear');\n else\n [foo, I] = LMimscale([], img, scaling, 'bilinear');\n end\n bb = bb*scaling; x = x*scaling; y = y*scaling;\n \n % 2) pad image (just to make sure)\n margin = 5+max(width,height)+ceil(max(bh,bw)+1 + max([0 -bb(1) -bb(2) bb(4)-size(I,1) bb(3)-size(I,2)]));\n [foo, I] = LMimpad(foo, single(I), [size(I,1)+2*margin size(I,2)+2*margin], NaN);\n bb = bb+margin; x = x+margin; y = y+margin;\n \n % 2) Crop result\n cx = fix((bb(3)+bb(1))/2); cy = fix((bb(4)+bb(2))/2);\n \n bb = round([cx-width/2-bw+1 cy-height/2-bh+1 cx+width/2+bw cy+height/2+bh]);\n \n x = x - bb(1)+2; y = y - bb(2)+2;\n \n \n % Image crop:\n crop = I(bb(2):bb(4), bb(1):bb(3), :);\n imgCrop(:,:,:,i) = uint8(crop);\n \n [xx,yy] = meshgrid(1:size(imgCrop,2),1:size(imgCrop,1));\n seg(:,:,i) = uint8(255*double(inpolygon(xx, yy, x, y)));\n \n valid(:,:,i) = 1-isnan(sum(crop,3));\n\n % warnings by crops of scales\n warn(i) = (scaling>1) || (sum(isnan(crop(:)))>500);\nend\n\n", "meta": {"author": "CSAILVision", "repo": "LabelMeToolbox", "sha": "b8eb2179723d8c15a4331c1ea6da5c6cd64e75e2", "save_path": "github-repos/MATLAB/CSAILVision-LabelMeToolbox", "path": "github-repos/MATLAB/CSAILVision-LabelMeToolbox/LabelMeToolbox-b8eb2179723d8c15a4331c1ea6da5c6cd64e75e2/imagemanipulation/LMobjectnormalizedcrop.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.49729885315033306}} {"text": "function [Fmax, iMax] = bst_max(F, dim)\n% BST_MAX: Get the maximum in magnitude, but with the correct sign.\n% \n% USAGE: [Fmax, iMax] = bst_max(F, dim=1)\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2014\n\n% Parse inputs\nif (nargin < 2) || isempty(dim)\n dim = [];\nend\n\n% Get the sign of each maximum\nif isempty(dim)\n [Fmax, iMax] = max(abs(F(:)));\n Fmax = sign(F(iMax)) .* Fmax;\nelseif (dim <= 5)\n % Permute with first dimension\n if (dim > 1)\n permdim = [dim, 2:ndims(F)];\n permdim(dim) = 1;\n F = permute(F, permdim);\n end\n % Reshape to ensure that the matrix has 2 dimensions\n nd = ndims(F);\n if (nd > 2)\n oldSize = [size(F,1), size(F,2), size(F,3), size(F,4), size(F,5)];\n F = reshape(F, size(F,1), []);\n end\n % Get maximum absolute values\n [Fmax, iMax] = max(abs(F), [], 1);\n % Build indices of the values to read\n iF = sub2ind(size(F), iMax, 1:size(F,2));\n Fmax = sign(F(iF)) .* Fmax;\n % Restore initial shape\n if (nd > 2)\n Fmax = reshape(Fmax, 1, oldSize(2), oldSize(3), oldSize(4), oldSize(5));\n iMax = reshape(iMax, 1, oldSize(2), oldSize(3), oldSize(4), oldSize(5));\n end\n % Restore initial dimensions\n if (dim > 1)\n Fmax = permute(Fmax, permdim);\n iMax = permute(iMax, permdim);\n end\nelse\n error('Not supported yet.');\nend\n \n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/math/bst_max.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.497298853150333}} {"text": "function CM=ImaGIN_connectivity_matrix(N)\n% -=============================================================================\n% This function is part of the ImaGIN software: \n% https://f-tract.eu/\n%\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n%\n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE AUTHORS\n% DO NOT ASSUME ANY LIABILITY OR RESPONSIBILITY FOR ITS USE IN ANY CONTEXT.\n%\n% Copyright (c) 2000-2018 Inserm U1216\n% =============================================================================-\n%\n% Authors: Olivier David\n\nncouple\t= N*(N-1)/2;\nif ncouple>0\n CM\t= zeros(2,ncouple);\n cou\t= 0;\n for ii\t= 1:N-1\n j\t= ii+1;\n cou\t= cou+1;\n CM(1,cou)\t= ii;\n CM(2,cou)\t= j;\n while j < N\n j\t= j+1;\n cou\t= cou+1;\n CM(1,cou)\t= ii;\n CM(2,cou)\t= j;\n end\n end\nelse\n CM=[];\nend\nreturn\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/external/ImaGIN/private/ImaGIN_connectivity_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.4972988461396791}} {"text": "function spm_mvb_cvk_display(MVB)\n% model display for MVB with cross-validation\n% FORMAT spm_mvb_cvk_display(MVB)\n% MVB - multivariate Bayes structure, select one if not provided\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n \n% Christophe Phillips\n% $Id: spm_mvb_cvk_display.m 3806 2010-04-06 14:42:32Z ged $\n\nif nargin<1\n load(spm_select(1,'^MVB.*\\.mat','Select MVB to display'))\nend\nif ~isfield(MVB,'cvk')\n error(['No crossvalidation data available. ' ...\n 'Select another file or perform the crossvalidation']);\nend\n\n%-Get figure handles and set title\n%--------------------------------------------------------------------------\nFmvb = spm_figure('GetWin','MVB');\nspm_clf(Fmvb);\n \n% get stuff in place for display\n%--------------------------------------------------------------------------\nK = MVB.K;\nX = K*MVB.X;\nX0 = orth(K*MVB.X0);\nR = speye(length(X)) - X0*X0';\nR = orth(R);\npX = R*R'*X;\n \n% plot validation\n%--------------------------------------------------------------------------\nsubplot(2,2,1)\ns = 1:length(pX);\nplot(s,pX,s,MVB.cvk.qX,'-.')\nxlabel('sample')\nylabel('response (adjusted)')\ntitle('cross-validation')\naxis square\n \nsubplot(2,2,2)\nplot(pX,MVB.cvk.qX,'.')\nxlabel('true')\nylabel('predicted')\ntitle(sprintf('p-value (parametric) = %.5f',MVB.p_value))\naxis square\nabc = axis;\nhold on\nplot([max(abc([1 3])) min(abc([2 4]))],[max(abc([1 3])) min(abc([2 4]))],'k')\n\n% plot feature weights\n%--------------------------------------------------------------------------\nsubplot(2,2,3)\nimagesc(corrcoef(MVB.cvk.qE))\ncolorbar\ncaxis([0 1])\nxlabel('bipartition (k)')\ntitle({'correlations among';'k-fold feature weights'})\naxis square\n \nsubplot(2,2,4)\nif ~isempty(MVB.XYZ) && ~isempty(MVB.VOX)\n if isfield(MVB.cvk, 'P')\n spm_mip(prod(MVB.cvk.P,2),MVB.XYZ(1:3,:),MVB.VOX)\n title({[MVB.name ' (' MVB.contrast ')'];'prod( P(|weights| > 0) )'})\n else % reproduce plot from original spm_mvb_cvk2\n qe = mean(MVB.cvk.qE,2);\n qe = qe.*(qe > 0);\n spm_mip(qe,MVB.XYZ(1:3,:),MVB.VOX)\n title({[MVB.name ' (' MVB.contrast ')'];'mean (positive) weights'})\n end \nelse\n % (Allows MVB for non-spatial data, excluding smooth or compact priors)\n title('No spatial info in MVB')\nend\naxis square\n \nfprintf('\\np-value = %.4f; classification: %.1f%%; R-squared %.1f%%\\n', ...\n MVB.p_value,MVB.percent,MVB.R2)\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_mvb_cvk_display.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.4972409768926731}} {"text": "% Test file for chebfun constructor (basic).\n\nfunction pass = test_constructor_basic(pref)\n\nif ( nargin == 0 )\n pref = chebfunpref();\nend\n\n% Some basic test functions:\nFF = {@sin, @(x) [sin(x), cos(x)], @(x) [sin(x), cos(x), exp(-x)]};\n\nfor j = 1:numel(FF);\n % Initialise k:\n k = 0;\n\n % Pick the test function:\n F = FF{j};\n\n % Test on [-1 1]:\n f = chebfun(F, [-1, 1], pref);\n xx = linspace(-1, 1);\n err = norm(feval(f, xx) - F(xx), inf);\n pass(j, k+1) = err < 10*eps*vscale(f);\n pass(j, k+2) = err < 50*pref.chebfuneps;\n k = k + 2;\n\n % Test on [-1 1] (no domain passed):\n f = chebfun(F, pref);\n xx = linspace(-1, 1);\n err = norm(feval(f, xx) - F(xx), inf);\n pass(j, k+1) = err < 10*eps*vscale(f);\n pass(j, k+2) = err < 500*pref.chebfuneps;\n k = k + 2;\n\n % Test on [0 10000]:\n f = chebfun(F, [0, 10000], pref);\n xx = linspace(0, 10000);\n err = norm(feval(f, xx) - F(xx), inf);\n pass(j, k+1) = err < 1e4*eps*vscale(f);\n pass(j, k+2) = err < 1e2*hscale(f)*pref.chebfuneps;\n k = k + 2;\n \n\n % Test on piecewise domain:\n f = chebfun(F, [-1, 0, .5, sqrt(pi/4), 1], pref);\n xx = linspace(-1, 1);\n err = norm(feval(f, xx) - F(xx), inf);\n pass(j, k+1) = err < 10*eps*vscale(f);\n pass(j, k+2) = err < 100*pref.chebfuneps;\n k = k + 2;\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/tests/chebfun/test_constructor_basic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6442251201477015, "lm_q1q2_score": 0.4972409701306001}} {"text": "function point_num = sparse_grid_cc_size_old ( dim_num, level_max )\n\n%*****************************************************************************80\n%\n%% SPARSE_GRID_CC_SIZE_OLD sizes a sparse grid of Clenshaw Curtis points.\n%\n% Discussion:\n%\n% This function has been replaced by a much faster version.\n%\n% It is retained for historical interest only.\n%\n% The grid is defined as the sum of the product rules whose LEVEL\n% satisfies:\n%\n% 0 <= LEVEL <= LEVEL_MAX.\n%\n% This routine works on an abstract set of nested grids. \n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 July 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Fabio Nobile, Raul Tempone, Clayton Webster,\n% A Sparse Grid Stochastic Collocation Method for Partial Differential\n% Equations with Random Input Data,\n% SIAM Journal on Numerical Analysis,\n% Volume 46, Number 5, 2008, pages 2309-2345.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer LEVEL_MAX, the maximum value of LEVEL.\n%\n% Output, integer POINT_NUM, the total number of unique points in the grids.\n%\n\n%\n% Special case.\n%\n if ( level_max == 0 )\n point_num = 1;\n return\n end\n%\n% The outer loop generates LEVELs from 0 to LEVEL_MAX.\n%\n point_num = 0;\n\n for level = 0 : level_max\n%\n% The middle loop generates the next partition that adds up to LEVEL.\n%\n level_1d = [];\n more = 0;\n h = 0;\n t = 0;\n\n while ( 1 )\n\n [ level_1d, more, h, t ] = comp_next ( level, dim_num, level_1d, more, h, t );\n%\n% Transform each 1D level to a corresponding 1D order.\n%\n order_1d = level_to_order_closed ( dim_num, level_1d );\n%\n% The product of the 1D orders gives us the number of points in this grid.\n%\n order_nd = prod ( order_1d(1:dim_num) );\n%\n% The inner (hidden) loop generates all points corresponding to given grid.\n%\n grid_index = multigrid_index0 ( dim_num, order_1d, order_nd );\n%\n% Adjust these grid indices to reflect LEVEL_MAX.\n%\n grid_index = multigrid_scale_closed ( dim_num, order_nd, level_max, ...\n level_1d, grid_index );\n%\n% Determine the first level of appearance of each of the points.\n%\n grid_level = abscissa_level_closed_nd ( level_max, dim_num, order_nd, ...\n grid_index );\n%\n% Only keep those points which first appear on this level.\n%\n for point = 1 : order_nd\n\n if ( grid_level(point) == level )\n\n point_num = point_num + 1;\n\n end\n\n end\n\n if ( ~more )\n break\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/sparse_grid_cc/sparse_grid_cc_size_old.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.4972243802026098}} {"text": "function obj = updateImplicitFunctionSurface(obj, surfaceIndex)\n\n%-AXIS INDEX-%\naxIndex = obj.getAxisIndex(obj.State.Plot(surfaceIndex).AssociatedAxis);\n\n%-CHECK FOR MULTIPLE AXES-%\n[xsource, ysource] = findSourceAxis(obj,axIndex);\n\n%-SURFACE DATA STRUCTURE- %\nimage_data = get(obj.State.Plot(surfaceIndex).Handle);\nfigure_data = get(obj.State.Figure.Handle);\n\n%-AXIS DATA-%\neval(['xaxis = obj.layout.xaxis' num2str(xsource) ';']);\neval(['yaxis = obj.layout.yaxis' num2str(ysource) ';']);\n\n%-------------------------------------------------------------------------%\n\n%-surface xaxis-%\nobj.data{surfaceIndex}.xaxis = ['x' num2str(xsource)];\n\n%-------------------------------------------------------------------------%\n\n%-surface yaxis-%\nobj.data{surfaceIndex}.yaxis = ['y' num2str(ysource)];\n\n%-------------------------------------------------------------------------%\n \n%-surface type-%\nobj.data{surfaceIndex}.type = 'surface';\n\n%---------------------------------------------------------------------%\n\n%-getting x,y,z surface data-%\n\nstrf = func2str(image_data.Function);\nind1 = strfind(strf, '('); ind1 = ind1(1)+1;\nind2 = strfind(strf, ')'); ind2 = ind2(1)-1;\nvars = split(strf(ind1:ind2), ',');\n\nstrf = [strf(ind2+2:end) '==0'];\nstrf = replace(strf, vars{1}, 'Xx');\nstrf = replace(strf, vars{2}, 'Yy');\nstrf = replace(strf, vars{3}, 'Zz');\n\nsyms Xx Yy Zz;\nf = eval(strf);\ns = solve(f, Zz);\n\nx = image_data.XRange;\ny = image_data.YRange;\nz = image_data.ZRange;\nN = 400;\n\n[Xx,Yy] = meshgrid(linspace(x(1),x(2),N), linspace(y(1),y(2),N));\nX = []; Y = []; Z = [];\n\nfor n = 1:length(s)\n X = [X; Xx];\n Y = [Y; Yy];\n Z = [Z; eval(s(n))];\nend\n\nclear Xx Yy Zz;\nZ(Z < z(1)) = nan; Z(Z > z(2)) = nan;\nX(Z < z(1)) = nan; X(Z > z(2)) = nan;\nY(Z < z(1)) = nan; Y(Z > z(2)) = nan;\n\n%---------------------------------------------------------------------%\n\n%-surface x-%\nobj.data{surfaceIndex}.x = X;\n\n%---------------------------------------------------------------------%\n\n%-surface y-%\nobj.data{surfaceIndex}.y = Y;\n\n%---------------------------------------------------------------------%\n\n%-surface z-%\nobj.data{surfaceIndex}.z = Z;\n\n%---------------------------------------------------------------------%\n\n%- setting grid mesh by default -%\n% x-direction\nmden = image_data.MeshDensity;\nxsize = (x(2) - x(1)) / mden; \nobj.data{surfaceIndex}.contours.x.start = x(1);\nobj.data{surfaceIndex}.contours.x.end = x(2);\nobj.data{surfaceIndex}.contours.x.size = xsize;\nobj.data{surfaceIndex}.contours.x.show = true;\nobj.data{surfaceIndex}.contours.x.color = 'black';\n% y-direction\nysize = (y(2) - y(1)) / mden;\nobj.data{surfaceIndex}.contours.y.start = y(1);\nobj.data{surfaceIndex}.contours.y.end = y(2);\nobj.data{surfaceIndex}.contours.y.size = ysize;\nobj.data{surfaceIndex}.contours.y.show = true;\nobj.data{surfaceIndex}.contours.y.color = 'black';\n% z-direction\nzsize = (z(2) - z(1)) / mden;\nobj.data{surfaceIndex}.contours.z.start = z(1);\nobj.data{surfaceIndex}.contours.z.end = z(2);\nobj.data{surfaceIndex}.contours.z.size = zsize;\nobj.data{surfaceIndex}.contours.z.show = true;\nobj.data{surfaceIndex}.contours.z.color = 'black';\n\n%-------------------------------------------------------------------------%\n\n%-image colorscale-%\n\ncmap = figure_data.Colormap;\nlen = length(cmap)-1;\n\nfor c = 1: length(cmap)\n col = 255 * cmap(c, :);\n obj.data{surfaceIndex}.colorscale{c} = { (c-1)/len , ['rgb(' num2str(col(1)) ',' num2str(col(2)) ',' num2str(col(3)) ')' ] };\nend\n\n%-------------------------------------------------------------------------%\n\n%-image surfacescale-%\nobj.data{surfaceIndex}.surfacecolor = Z;\n\n%-------------------------------------------------------------------------%\n\n%-surface name-%\nobj.data{surfaceIndex}.name = image_data.DisplayName;\n\n%-------------------------------------------------------------------------%\n\n%-surface showscale-%\nobj.data{surfaceIndex}.showscale = false;\n\n%-------------------------------------------------------------------------%\n\n%-surface visible-%\nobj.data{surfaceIndex}.visible = strcmp(image_data.Visible,'on');\n\n%-------------------------------------------------------------------------%\n\nleg = get(image_data.Annotation);\nlegInfo = get(leg.LegendInformation);\n\nswitch legInfo.IconDisplayStyle\n case 'on'\n showleg = true;\n case 'off'\n showleg = false;\nend\n\nobj.data{surfaceIndex}.showlegend = showleg;\n\n%-------------------------------------------------------------------------%\n\nend\n", "meta": {"author": "plotly", "repo": "plotly_matlab", "sha": "a5595260ef2b165f24740838ea397ffd82a12623", "save_path": "github-repos/MATLAB/plotly-plotly_matlab", "path": "github-repos/MATLAB/plotly-plotly_matlab/plotly_matlab-a5595260ef2b165f24740838ea397ffd82a12623/plotly/plotlyfig_aux/handlegraphics/updateImplicitFunctionSurface.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.4972243743953785}} {"text": "function [bcx,bcy] = specific_flow(xbd,ybd)\n%forwardstep_flow Forward facing step inflow condition \n% [bcx,bcy] = specific_flow(xbd,ybd);\n% input\n% xbd x coordinate vector\n% ybd y coordinate vector \n%\n% specifies forward step flow boundary condition\n% IFISS function: DJS; 6 March 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \nbcx=0*xbd; bcy=0*xbd;\nk=find(xbd==5); bcx(k)=-0.5*(1+ybd(k)).*(1-ybd(k));\nreturn\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms866/stokes_flow/test_problems/forwardstep_flow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.4972243697416388}} {"text": "function varargout = plotlattice(varargin)\n%PLOTLATTICE Plots an integer lattice\n%\n% p = plotlattice(C,which,c,size,options)\n%\n% C : Constraint object\n% which: 'inner' (default) or 'outer'\n% color: color [double] ([r g b] format) or char from 'rymcgbk'\n% size : Size of marker\n% options: options structure from sdpsettings\n% Example\n% sdpvar x1 x2\n% plot(x1^2+x2^2 <= 1.5,'green');hold on\n% plotlattice(x1^2+x2^2 <= 1.5,'outer','yellow');\n% plotlattice(x1^2+x2^2 <= 1.5,'inner','black');\n\nh = ishold;\nhold on\nF = varargin{1};\nif nargin > 1 && ~isempty(varargin{2})\n which = varargin{2};\nelse\n which = 'inner';\nend\nif nargin > 2 && ~isempty(varargin{3})\n color = varargin{3};\nelse\n color = 'yellow';\nend\nif nargin > 3 && ~isempty(varargin{4})\n size = varargin{4};\nelse\n size = 5;\nend\nif nargin > 4 \n ops = varargin{5};\n if ~isempty(ops)\n ops = sdpsettings(ops,'verbose',0);\n else\n ops = sdpsettings('relax',2,'verbose',0); \n end\nelse\n ops = sdpsettings('relax',2,'verbose',0);\nend\n\nX = recover(depends(F));\n[~,L,U] = boundingbox(F,ops);\n\nx = floor(L(1)):ceil(U(1));\ny = floor(L(2)):ceil(U(2));\nThreeD = length(L)>2;\nif ThreeD\n z = floor(L(3)):ceil(U(3));\nelse\n z = 1;\nend\nV = [];\nfor i = x \n for j = y\n for k = z\n switch which\n case 'outer'\n if ThreeD\n l = plot3(i,j,k,'or','MarkerSize',size);\n else\n l = plot(i,j,'or','MarkerSize',size);\n end\n set(l,'MarkerFaceColor',color);\n V = [V [i;j;k]];\n case 'inner'\n if ThreeD\n assign(X,[i;j;k]); \n else\n assign(X,[i;j]); \n end\n p = check(F);\n if min(p) >= 0\n if ThreeD\n l = plot3(i,j,k,'or','MarkerSize',size,'MarkerFaceColor','yellow');\n V = [V [i;j;k]];\n else\n l = plot(i,j,'or','MarkerSize',size,'MarkerFaceColor','yellow');\n V = [V [i;j]];\n end\n set(l,'MarkerFaceColor',color);\n end\n otherwise\n error\n end\n end\n end\nend\nif ~h\n hold off;\nend\nif nargout > 0\n varargout{1} = V;\nend", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/extras/@lmi/plotlattice.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.4970904285204818}} {"text": "function OUT = TabPrint(DATA,hlabel,vlabel,approx)\n% =======================================================================\n% Prints a numerical table with labels, with specified numbers of decimal\n% digits\n% =======================================================================\n% OUT = TabPrint(DATA,hlabel,vlabel,approx)\n% -----------------------------------------------------------------------\n% INPUT\n% - DATA = a (TxN) matrix of numbers\n% -----------------------------------------------------------------------\n% OPTIONAL INPUT\n%\t- hlabel = a (Tx1) vector of horizontal labels \n%\t- vlabel = a (1xT) vector of vertical labels \n% - approx = number of decimal digits. Default = 2\n% -----------------------------------------------------------------------\n% OUTPUT\n% - OUT = a cell array with the formatted table\n% -----------------------------------------------------------------------\n% EXAMPLE\n% x = [1 2; 3 4; 5 6; 7 8; 9 10];\n% hlab = {'a';'b';'c';'d';'e';}\n% vlab = {'A','B'}\n% OUT = TabPrint(x,hlab,vlab)\n% =======================================================================\n% VAR Toolbox 3.0\n% Ambrogio Cesa-Bianchi\n% ambrogiocesabianchi@gmail.com\n% March 2012. Updated November 2020\n% -----------------------------------------------------------------------\n\n[n, m] = size(DATA);\n\nif ~exist('hlabel','var') || isempty(hlabel)\n hlabel = cell(1,m);\nend\n\nif ~exist('vlabel','var') || isempty(vlabel)\n vlabel = cell(n,1);\nend\n\nif ~exist('approx','var')\n approx = 2; \nend\n\nif length(hlabel)~=m\n error('ERROR: horizontal label has wrong dimension')\nend\n\nif length(vlabel)~=n\n error('ERROR: vertical label has wrong dimension')\nend\n\nOUT = roundnum2cell(DATA,approx); % Trasform matrix in cell wih approx decimal digits\n\nOUT = [hlabel ; OUT];\naux = cell(rows(hlabel),cols(vlabel));\nvlabel = [aux; vlabel];\nOUT = [vlabel, OUT];", "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/Utils/TabPrint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.49709041710600854}} {"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 [bnt_data, old_values] = transform_data_into_bnt_format(data,cnodes)\n% TRANSFORM_DATA_TO_BNT_FORMAT Ensures discrete variables have values 1,2,..,k\n% e.g., if the values of a discrete are [0 1 6], they must be mapped to [1 2 3]\n%\n% data(i,j) is the value for i-th node in j-th case.\n% bnt_data(i,j) is the new value.\n% old_values{i} are the original values for node i.\n% cnodes is the list of all continous nodes, e.g. [3 5] means the 3rd and 5th node is continuous\n%\n% Author: yimin.zhang@intel.com\n% Last updated: Jan. 22, 2002 by Kevin Murphy.\n\nnum_nodes=size(data,1);\nnum_cases=size(data,2);\nold_values=cell(1,num_nodes);\n\nfor i=1:num_nodes\n if (myismember(i,cnodes)==1) %cts nodes no need to be transformed \n %just copy the data\n bnt_data(i,:)=data(i,:);\n continue;\n end\n values = data(i,:);\n sort_v = sort(values); \n %remove the duplicate values in sort_v\n v_set = unique(sort_v); \n \n %transform the values\n for j=1:size(values,2)\n index = binary_search(v_set,values(j));\n if (index==-1)\n fprintf('value not found in tranforming data to bnt format.\\n'); \n return;\n end\n bnt_data(i,j)=index;\n end\n old_values{i}=v_set;\nend\n\n\n%%%%%%%%%%%%\n\nfunction index=binary_search(vector, value)\n% BI_SEARCH do binary search for value in the vector\n% Author: yimin.zhang@intel.com\n% Last updated: Jan. 19, 2002\n\nbegin_index=1;\nend_index=size(vector,2); \nindex=-1;\nwhile (begin_index<=end_index)\n mid=floor((begin_index+end_index)/2);\n if (isstr(vector(mid)))\n % need to write a strcmp to return three result (< = >)\n else\n if (value==vector(mid))\n index=mid;\n return;\n elseif (value>vector(mid))\n begin_index=mid+1; \n else\n end_index=mid-1;\n end\n end\nend\nreturn;\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/dtree/transform_data_into_bnt_format.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.49704924384987675}} {"text": "function [varargout]=spmax(varargin)\n\n% function [maxVal,maxInd]=spmax(A,B,vecdim,nanflag,logicRelevant,nanOut)\n% ------------------------------------------------------------------------\n%\n%\n% Kevin Moerman\n% ------------------------------------------------------------------------\n\n%%\n\nA=varargin{1};\n\nif nargin>=3\n dimDir=varargin{3};\nelse\n dimDir=1;\nend\n\nswitch nargin\n case 5 \n logicRelevant=varargin{5};\n varargin=varargin(1:4);\n nanOut=0;\n if isempty(varargin{4})\n varargin=varargin(1:3);\n end\n case 6\n logicRelevant=varargin{5};\n nanOut=varargin{6};\n varargin=varargin(1:4);\n if isempty(varargin{4})\n varargin=varargin(1:3);\n end\n otherwise\n logicRelevant=[];\n nanOut=0;\nend\n\nif isempty(logicRelevant)\n logicRelevant=A~=0;\nend\n\nlogicRelevantRow=full(any(logicRelevant,dimDir));\n\n%%\n\nminOffset=min(A(logicRelevant));\n\nA(logicRelevant)=A(logicRelevant)-minOffset; %Shift to negative to zeros loose\nvarargin{1}=A;\n[maxVal,maxInd]=max(varargin{:});\nmaxVal(logicRelevantRow)=maxVal(logicRelevantRow)+minOffset; %Shift back\nif nanOut==1\n maxVal(~logicRelevantRow)=NaN;\nend\n\n%% Collect output\nvarargout{1}=maxVal;\nvarargout{2}=maxInd;\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/spmax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.49704923593106193}} {"text": "function M = perform_lic(v, w, options)\n\n% perform_lic - perform line integral convolution\n%\n% M = perform_lic(v, w, options);\n%\n% v is a vector field (should be approximately of unit norm).\n% w is the length of the convolution (in pixels)\n% M is an image of filtered noise that illustrate well the flow of v.\n%\n% options.spot_size set the size of the features.\n%\n% Set options.flow_correction=1 in order to fix problem\n% around singularity points of the flow.\n%\n% The method is described in\n% Imaging vector fields using line integral convolution\n% Brian Cabral, Leith Casey Leedom\n% Siggraph 1993\n%\n% If the vector field is not oriented (e.g. if it is an eigenvector field\n% of a tensor field) then set options.isoriented=1. It will perform two\n% LIC (horizontal and vertical) and then average them. This trick is\n% explained in \n% Interactive Tensor Field Design and Visualization on Surfaces \n% Eugene Zhang, James Hays, and Greg Turk \n% IEEE Transactions on Visualization and Computer Graphics\n% Volume 13 , Issue 1, Pages: 94-107, 2007. \n% \n% Copyright (c) Gabriel Peyre 2007\n\nn = size(v,1);\n\noptions.null = 0;\nif isfield(options, 'M0')\n M0 = options.M0;\nelse\n M0 = randn(n);\n if isfield(options, 'spot_size')\n sigma = options.spot_size;\n else\n sigma = 2;\n end\n M0 = perform_blurring(M0, sigma, options);\nend\n\nif size(M0,3)>1\n % lic on each channel\n for i=1:size(M0,3)\n options.M0 = M0(:,:,i);\n M(:,:,i) = perform_lic(v, w, options);\n end\n return;\nend\n\nisoriented = getoptions(options, 'isoriented', 1);\n\nif isoriented==0\n % run twice the lic in each direction\n options.isoriented = 1;\n options.method = 'xproj';\n v = perform_vf_reorientation(v, options);\n M1 = perform_lic(v, w, options);\n options.method = 'yproj';\n v = perform_vf_reorientation(v, options);\n M2 = perform_lic(v, w, options);\n % weight\n v = perform_vf_normalization(v);\n T = v(:,:,1).^2;\n M = T.*M1 + (1-T).*M2;\n return;\nend\n\nif isfield(options, 'niter_lic') && options.niter_lic>1\n M = options.M0;\n niter_lic = options.niter_lic;\n options.niter_lic = 1;\n for i=1:niter_lic\n options.M0 = M;\n M = perform_lic(v, w, options);\n end\n return;\nend\n\nhistogram = getoptions(options, 'histogram', 'gaussian');\nflow_correction = getoptions(options, 'flow_correction', 1);\n\nif isstr(histogram)\n switch histogram\n case 'linear'\n hist = linspace(0,1, 100^2);\n case 'gaussian'\n hist = randn(100); hist = hist(:);\n otherwise\n error('Unkown kind of histograms');\n end\nelse\n hist = histogram;\nend\n\nif isfield(options, 'dt')\n dt = options.dt;\nelse\n dt = 0.5;\nend\n\n% perform integration of the vector field: Forward\nT_list = 0:dt:w/2;\nH = perform_vf_integration(v, dt, T_list, options );\n\n% perform integration of the vector field: Backward\nT_list(1) = [];\nH1 = perform_vf_integration(-v, dt, T_list, options );\nH = cat(4, H1(:,:,:,end:-1:1), H );\np = size(H,4);\n\n% try to remove sampling problems\nif flow_correction\n A = H(:,:,:,(end+1)/2);\n dX = H(:,:,1,:)-repmat(A(:,:,1,:), [1 1 1 p]);\n dY = H(:,:,2,:)-repmat(A(:,:,2,:), [1 1 1 p]);\n dX(dX>n/2) = dX(dX>n/2)-(n-1); dX(dX<-n/2) = dX(dX<-n/2)+(n-1);\n dY(dY>n/2) = dY(dY>n/2)-(n-1); dY(dY<-n/2) = dY(dY<-n/2)+(n-1);\n d = sqrt(dX.^2 + dY.^2);\n d = repmat( mean(mean(d)), [n n 1] ) - d;\n % threshold on the distance map deviation\n eta = 0.5;\nend\n\n% compute averaging\nM = zeros(n);\n[Y,X] = meshgrid(1:n,1:n);\nW = zeros(n);\nfor i=1:p\n A = interp2(1:n,1:n, M0, H(:,:,2,i), H(:,:,1,i) );\n if flow_correction\n w = d(:,:,i) Inf].\n%\n% EXAMPLE\n%\n% pos = data.getPositions();\n% groupIndices = general.groupByTime(pos, 'half'); % divide data into halves\n% positionsOfFirstGroup = pos(groupIndices == 1, :);\n%\n% general.groupByTime(pos, 1); % divide data into groups each duration of 1 second\n%\nfunction [groupIndices, edges] = groupByTime(pos, groupParam)\n if nargin < 2\n error('BNT:numArgs', 'Incorrect number of parameters (type ''help general.groupByTime'' for details).');\n end\n\n if size(pos, 2) < 3\n error('BNT:arg', 'Incorrect argument ''pos'' (type ''help general.groupByTime'' for details).');\n end\n\n duration = pos(end, 1) - pos(1, 1);\n\n if ischar(groupParam)\n if ~strcmpi(groupParam, 'half')\n error('Incorrect argument ''groupParam'' (type ''help general.groupByTime'' for details).');\n end\n midPoint = pos(1, 1) + round(duration / 2);\n edges = [0 midPoint inf];\n else\n grpInterval = groupParam;\n if ~helpers.isdscalar(grpInterval, '>0')\n error('Incorrect argument ''groupParam'' (type ''help general.groupByTime'' for details).');\n end\n edges = [0:grpInterval:duration];\n edges(end+1) = inf;\n end\n\n [~, groupIndices] = histc(pos(:, 1), edges);\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/+general/groupByTime.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.6150878555160666, "lm_q1q2_score": 0.4970323294970125}} {"text": "%%*********************************************************************\n%% sortA: sort columns of At{p} in ascending order according to the \n%% number of nonzero elements. \n%%\n%% [At,C,b,X0,Z0,permA,permZ] = sortA(blk,At,C,b,X0,Z0);\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 [At,C,X0,Z0,permA,permZ] = sortA(blk,At,C,b,X0,Z0);\n\n global spdensity smallblkdim\n%%\n if isempty(spdensity); spdensity = 0.4; end\n if isempty(smallblkdim); smallblkdim = 50; end\n%%\n numblk = size(blk,1); \n m = length(b); \n nnzA = zeros(numblk,m); \n permA = kron(ones(numblk,1),[1:m]); \n permZ = cell(size(blk,1),1);\n%%\n for p=1:size(blk,1)\n pblk = blk(p,:); \n n = sum(pblk{2}); \n numblk = length(pblk{2}); \n if strcmp(pblk{1},'s') & (max(pblk{2}) > smallblkdim)\n n2 = sum(pblk{2}.*pblk{2}); n22 = sum(pblk{2}.*(pblk{2}+1))/2; \n m1 = size(At{p,1},2); \n if (length(pblk{2}) == 1) \n tmp = abs(C{p}) + abs(Z0{p});\n if (~isempty(At{p,1}))\n tmp = tmp + smat(blk(p,:),abs(At{p,1})*ones(m1,1),1);\n end\n if (nnz(tmp) < spdensity*n22); \n per = symamd(tmp); \n invper = zeros(n,1); invper(per) = [1:n]; \n permZ{p} = invper;\n if (~isempty(At{p,1})) \n isspAt = issparse(At{p,1});\n for k = 1:m1\n Ak = smat(pblk,At{p,1}(:,k),1); \n At{p,1}(:,k) = svec(pblk,Ak(per,per),isspAt); \n end\n end\n C{p} = C{p}(per,per); \n Z0{p} = Z0{p}(per,per); \n X0{p} = X0{p}(per,per); \n else\n per = [];\n end \n if (length(pblk) > 2) & (~isempty(per)) \n m2 = length(pblk{3}); \n P = spconvert([(1:n)', per', ones(n,1)]);\n At{p,2} = P*At{p,2};\n end\n end\n if ~isempty(At{p,1}) & (mexnnz(At{p,1}) < m*n22/2)\n for k = 1:m1\n Ak = At{p,1}(:,k); \n nnzA(p,k) = length(find(abs(Ak) > eps)); \n end \n [dummy,permAp] = sort(nnzA(p,1:m1)); \n At{p,1} = At{p,1}(:,permAp); \n permA(p,1:m1) = permAp; \n end\n elseif strcmp(pblk{1},'q') | strcmp(pblk{1},'l') | strcmp(pblk{1},'u'); \n if ~issparse(At{p,1});\n At{p,1} = sparse(At{p,1}); \n end\n end\n end\n%%*********************************************************************\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/cvx-1.21.b795/sdpt3/Solver/sortA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4970323294970124}} {"text": "clear;\nclc\nclose all;\n\n\n%% EXAMPLE 2.3 Calculation of Gravity at various latitudes and heights\nlat = deg2rad(45);\nlon = 0;\nhgt = 10000;\n\n[~, ~, ~, ~, gravity]= ch_earth(lat, lon, hgt);\ngravity", "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/study/Principles_of_GNSS_Inertial_and_Multi-Sensor_Integrated_Navigation_System_Second/example2_3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4970323294970124}} {"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": "% Re-rank the top k candidates by searching a transformation when given camera intrinsics\n% pred: the prediction 3D pose\n% M_pool: the 2D pose library for matching\n% GT_pool: the 3D pose library\n% k: the number of extracted nearest candidates\n% cameraParams: a camera object compatible with Matlab \nfunction j_NN = kNN_cam_align(M_pool,GT_pool,pred,k,cameraParams)\n temp = zeros(1,28);\n temp_root = 0.5 * (pred(9,:) + pred(12,:));\n for a = 1:14\n temp(1,a*2-1) = pred(a,1) - temp_root(1);\n temp(1,a*2) = pred(a,2) - temp_root(2);\n y_c(a) = temp(1,2*a);\n end\n scale = max(y_c)-min(y_c);\n temp = temp / scale;\n m_idx = knnsearch(M_pool,temp,'k',k);\n e = zeros(1,k);\n for ii=1:k\n j_2d = GT_pool(m_idx(ii),:);\n j_2d = reshape(j_2d,3,14);\n j_2d = double(j_2d'); \n \n %scale = (max(j_2d(:,2))-min(j_2d(:,2)))/(max(pred(:,2))-min(pred(:,2)));\n [r,~] = extrinsics(pred(:,1:2),j_2d,cameraParams);\n \n p2d = j_2d*r*cameraParams.IntrinsicMatrix';\n [~,Z] = procrustes(p2d,pred(:,1:2));\n su = j_2d(:,1:2)-Z(:,1:2);\n Sum = zeros(size(su,1),1);\n for i = 1:size(su,2)\n Sum = Sum+su(:,i).^2;\n end\n e(ii) = mean(sqrt(Sum));\n \n %e(ii) = MPJPE_procrus(pred(:,1:2),j_2d(:,1:2));\n %e(ii) = MPJPE_procrus([pred(:,1:2)*scale, j_2d(:,3)] ,j_2d);\n \n end\n \n [~,iid] = min(e);\n j_2d = GT_pool(m_idx(iid),:);\n j_2d = reshape(j_2d,3,14);\n j_NN = double(j_2d'); \nend", "meta": {"author": "flyawaychase", "repo": "3DHumanPose", "sha": "ef2d085fe575224dd79aabcef214611de78068e0", "save_path": "github-repos/MATLAB/flyawaychase-3DHumanPose", "path": "github-repos/MATLAB/flyawaychase-3DHumanPose/3DHumanPose-ef2d085fe575224dd79aabcef214611de78068e0/Tools/kNN_cam_align.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6187804407739559, "lm_q1q2_score": 0.49698823572781503}} {"text": "%compute length of tailinflvector\n\nfunction [data,units]=compute_tailinflmag(trx,n)\n\n\nlarvae=trx.exp2flies{n};\nnumlarvae=numel(larvae);\ntailinflmag=cell(1,numlarvae);\n\nfor i=1:numlarvae\n larva=larvae(i);\n tailinflmag{1,i}=bsxfun(@hypot,trx(larva).xinflection_mm-trx(larva).xtail_mm,trx(larva).yinflection_mm-trx(larva).ytail_mm);\nend\n\nunits=parseunits('mm');\ndata=tailinflmag;\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/larva_compute_perframe_features/compute_tailinflmag.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6187804407739559, "lm_q1q2_score": 0.496988235727815}} {"text": "function L = obslikepoisson(X,hmm)\n%\n% Evaluate likelihood of data given observation model, for one continuous trial\n%\n% INPUT\n% X N by ndim data matrix\n% hmm hmm data structure\n%\n% OUTPUT\n% B Likelihood of N data points\n%\n% Author: Cam Higgins, OHBA, University of Oxford\n\nK = hmm.K;\n[T,ndim] = size(X);\n\nL = zeros(T,K); \n\nfor k=1:K\n constterm = -gammaln(X + 1);\n % note the expectation of log(lambda) is -log(lambda_b) + psigamma(lambda_a)\n num = (X.*(repmat(psi(hmm.state(k).W.W_shape),T,1) - log(hmm.state(k).W.W_rate))) - ...\n repmat(hmm.state(k).W.W_mean,T,1);\n L(:,k) = sum(num + constterm,2);\nend\nL = exp(L);\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/train/obslikepoisson.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.49698823008141824}} {"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 + (ht1000\n split=round(size(imdb.images.data,4)/1000);\nelse\n split=1;\nend\n\nretall=[];\nfor kk=1:split\n each=ceil(size(imdb.images.data,4)/split);\n res=vl_simplenn(net,imdb.images.data(:,:,:,(kk-1)*each+1:min(kk*each,size(imdb.images.data,4))));\n \n ret=[];\n for i=1:OP.nclass\n for j=1:size(res(end).x,4)\n ret(i,j)=res(end).x(1,1,i,j);\n end\n end\n retall=[retall,ret];\nend\n% probability of CNN output\nret=retall;\n\nxtest=[];\nfor i=1:size(ret,1)\n xtest(:,end+1)=ret(i,:);\nend\nfor i=1:13\n if i~=6 % remove DFA feature\n xtest(:,end+1)=imdb.meta.features(:,i);\n end\nend\nxtest(:,end+1)=sqi;\n\n% SVM prediction\n[predict_label, accuracy_test, ytest_out] = svmpredict(ones(size(xtest,1),1), xtest, model,'-b 1');\nend\n\n\n \n \n \n\n\n \n\n\n\n", "meta": {"author": "cliffordlab", "repo": "PhysioNet-Cardiovascular-Signal-Toolbox", "sha": "eec46e75e0b95c379ecb68cb0ebee0c4c9f54605", "save_path": "github-repos/MATLAB/cliffordlab-PhysioNet-Cardiovascular-Signal-Toolbox", "path": "github-repos/MATLAB/cliffordlab-PhysioNet-Cardiovascular-Signal-Toolbox/PhysioNet-Cardiovascular-Signal-Toolbox-eec46e75e0b95c379ecb68cb0ebee0c4c9f54605/Tools/Sleep_ECG/CNN_SVM_prediction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.49697243034907845}} {"text": "\nfunction [GAmp,GTime]=GxTrapezoid(p)\n\ntStart=p.tStart; % start time ms\ntEnd=p.tEnd; % end time ms\ntRamp=p.tRamp; % ramp duration time ms\nsRamp=p.sRamp; % ramp steps \nGxAmp=p.GxAmp; % Gx amplitude\nDuplicates=max(1,p.Duplicates);\nDupSpacing=max(0,p.DupSpacing);\n\n[GAmp,GTime]=StdTrap(tStart-tRamp, ...\n tEnd+tRamp, ...\n tStart, ...\n tEnd, ...\n GxAmp,max(2,sRamp),2,max(2,sRamp));\n\n[GTime,m,n]=unique(GTime);\nGAmp=GAmp(m);\n\n% Create Duplicates\nif Duplicates~=1 & DupSpacing ~=0\n GAmp=repmat(GAmp,[1 Duplicates]);\n TimeOffset = repmat(0:DupSpacing:(Duplicates-1)*DupSpacing,[length(GTime) 1]);\n GTime=repmat(GTime,[1 Duplicates]) + (TimeOffset(:))';\nend\n\nend\n", "meta": {"author": "leoliuf", "repo": "MRiLab", "sha": "5cdcf1f7b67759700685d3a26ffeb70e55325567", "save_path": "github-repos/MATLAB/leoliuf-MRiLab", "path": "github-repos/MATLAB/leoliuf-MRiLab/MRiLab-5cdcf1f7b67759700685d3a26ffeb70e55325567/Macro/SeqElem/GxR/GxTrapezoid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.49697241926264046}} {"text": "function qout = vgg_quat_mul(r,q)\n% VGG_QUAT_MUL Quaternion multiplication\n% pq = vgg_quat_mul(p,q)\n\n% awf@robots.ox.ac.uk, 30/01/05\n\nqout = ...\n [(r(1)*q(1) - r(2)*q(2) - r(3)*q(3) - r(4)*q(4)) \n (r(1)*q(2) + r(2)*q(1) + r(3)*q(4) - r(4)*q(3)) \n (q(3)*r(1) - q(4)*r(2) + q(1)*r(3) + q(2)*r(4)) \n (q(4)*r(1) + q(3)*r(2) - q(2)*r(3) + q(1)*r(4)) ];\n", "meta": {"author": "jmmanley", "repo": "VGG-Multiple-View-Geometry", "sha": "f114712de03082bb97229eaf2a65981908b64127", "save_path": "github-repos/MATLAB/jmmanley-VGG-Multiple-View-Geometry", "path": "github-repos/MATLAB/jmmanley-VGG-Multiple-View-Geometry/VGG-Multiple-View-Geometry-f114712de03082bb97229eaf2a65981908b64127/vgg_numerics/vgg_quat_mul.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.49697241926264046}} {"text": "function res = bf_sources_grid(BF, S)\n% Generate beamforming grid\n% Copyright (C) 2012 Wellcome Trust Centre for Neuroimaging\n\n% Vladimir Litvak\n% $Id: bf_sources_grid.m 7703 2019-11-22 12:06:29Z guillaume $\n\n%--------------------------------------------------------------------------\nif nargin == 0 \n resolution = cfg_entry;\n resolution.tag = 'resolution';\n resolution.name = 'Grid resolution';\n resolution.strtype = 'n';\n resolution.num = [1 1];\n resolution.val = {5};\n resolution.help = {'Select the resolution of the grid (in mm)'};\n \n space = cfg_menu;\n space.tag = 'space';\n space.name = 'Coordinate system';\n space.help = {'Select the coordinate system in which the grid should be generated'};\n space.labels = {'MNI template', 'MNI-aligned', 'Head', 'Native'};\n space.values = {'MNI template', 'MNI-aligned', 'Head', 'Native'};\n space.val = {'MNI template'};\n \n constrain = cfg_menu;\n constrain.tag = 'constrain';\n constrain.name = 'Coordinate sources to';\n constrain.help = {'The boundary to which the grid is confined'};\n constrain.labels = {'Inner skull', 'Scalp'};\n constrain.values = {'iskull', 'scalp'};\n constrain.val = {'iskull'};\n\n grid = cfg_branch;\n grid.tag = 'grid';\n grid.name = 'Grid';\n grid.val = {resolution, space, constrain};\n \n res = grid;\n \n return\nelseif nargin < 2\n error('Two input arguments are required');\nend\n\nif ~isfield(S, 'constrain')\n S.constrain = 'iskull';\nend\n\nswitch S.constrain\n case 'iskull'\n constraint = export(gifti(BF.data.mesh.tess_iskull), 'ft');\n case 'scalp'\n constraint = export(gifti(BF.data.mesh.tess_scalp), 'ft');\nend\n\nM1 = BF.data.transforms.toNative;\n\nswitch S.space\n case 'MNI template'\n M1 = BF.data.transforms.toMNI/M1;\n M2 = inv(BF.data.transforms.toMNI);\n case 'MNI-aligned'\n M1 = BF.data.transforms.toMNI_aligned/M1;\n M2 = inv(BF.data.transforms.toMNI_aligned);\n case 'Head'\n M1 = BF.data.transforms.toHead/M1;\n M2 = inv(BF.data.transforms.toHead);\n case 'Native'\n M2 = inv(M1);\n M1 = eye(4);\nend\n\nconstraint = ft_convert_units(ft_transform_geometry(M1, constraint));\n\nmn = min(constraint.pnt);\nmx = max(constraint.pnt);\n\nresolution = S.resolution;\n\nif isequal(constraint.unit, 'm')\n resolution = 1e-3*resolution;\nend\n\n% If zero is inside the brain, make sure grid points fall on multiples of\n% resolution to ease simulating data from points on the grid\nif mn(1)<0 && mx(1)>0\n grid.xgrid = [fliplr(0:-resolution:mn(1)) resolution:resolution:mx(1)];\nelse\n grid.xgrid = mn(1):resolution:mx(1);\nend\n\nif mn(2)<0 && mx(2)>0\n grid.ygrid = [fliplr(0:-resolution:mn(2)) resolution:resolution:mx(2)];\nelse\n grid.ygrid = mn(2):resolution:mx(2);\nend\n\nif mn(3)<0 && mx(3)>0\n grid.zgrid = [fliplr(0:-resolution:mn(3)) resolution:resolution:mx(3)];\nelse\n grid.zgrid = mn(3):resolution:mx(3);\nend\n\ngrid.dim = [length(grid.xgrid) length(grid.ygrid) length(grid.zgrid)];\n[X, Y, Z] = ndgrid(grid.xgrid, grid.ygrid, grid.zgrid);\n\npos = [X(:) Y(:) Z(:)];\n\ninside = ft_inside_headmodel(pos, struct('bnd', constraint));\n\npos = spm_eeg_inv_transform_points(M2, pos);\n\ngrid.allpos = pos;\ngrid.inside = find(inside);\ngrid.outside = find(~inside);\n\ngrid.pos = pos(inside, :);\n\nres = grid;", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/DAiSS/bf_sources_grid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4969606441545574}} {"text": "function varargout = plot_spline(P,C)\n % PLOT_SPLINE Plot a cubic Bezier spline.\n %\n % [pe,p] = plot_spline(P,C)\n %\n % Inputs:\n % P #P by dim list of control point locations\n % C #C by 4 list of indices into P of cubic Bezier curves\n % Outputs:\n % pe plot handles for UI\n % p plot handle for curves\n % Example:\n % cellfun(@(pe) arrayfun(@(p) set(p,'Color','r'),pe),plot_spline(P,C))\n p = {};\n pe = {};\n ish = ishold;\n for c = 1:size(C,1)\n [pe{c},p{c}] = plot_cubic(P(C(c,:),:));\n hold on;\n end\n hold off;\n if ish\n hold on\n end\n if nargout>=1\n varargout{1} = pe;\n if nargout >= 2\n varargout{2} = p;\n end\n end\nend\n\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_gptoolbox/mesh/plot_spline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.49689692542090574}} {"text": "function inc = crswap ( a, c, c_size, m, k, n, critvl, i1, i2, c1, c2, ...\n iswitch )\n\n%*****************************************************************************80\n%\n%% CRSWAP determines the effect of swapping two objects.\n%\n% Discussion:\n%\n% This computation is very inefficient. It is only set up so that we\n% can compare algorithm ASA 113 to the K-means algorithms ASA 058 and\n% ASA 136.\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% Reference:\n%\n% Colin Banfield, LC Bassill,\n% Algorithm AS 113:\n% A transfer for non-hierarchichal classification,\n% Applied Statistics,\n% Volume 26, Number 2, 1977, pages 206-210.\n%\n% Parameters:\n%\n% Input, real A(M,N), the data values. There are M objects,\n% each having spatial dimension N.\n%\n% Input, integer C(M), the classification of each object.\n%\n% Input, integer C_SIZE(K), the number of objects in each class.\n%\n% Input, integer M, the number of objects.\n%\n% Input, integer K, the number of classes.\n%\n% Input, integer N, the number of spatial dimensions, or variates,\n% of the objects.\n%\n% Input, real CRITVL, the current value of the criterion.\n%\n% Input, integer I1, I2, the objects to be swapped.\n%\n% Input, integer C1, C2, the current classes of objects I1 and I2.\n%\n% Input, integer ISWITCH:\n% 1, indicates that I1 and I2 should be temporarily swapped, the\n% change in CRITVL should be computed, and then I1 and I2 restored.\n% 2, indicates that I1 and I2 will be swapped.\n%\n% Output, real INC, the change to CRITVL that would occur if I1 and\n% I2 were swapped. This is only computed for ISWITCH = 1.\n%\n if ( iswitch == 2 )\n inc = 0;\n return\n end\n%\n% Move object I1 from class C1 to class C2.\n% Move object I2 from class C2 to class C1.\n%\n c(i1) = c2;\n c(i2) = c1;\n%\n% Define the critical value as the sum of the squares of the distances\n% of the points to their cluster center.\n%\n for i = 1 : k\n c_size(i) = 0;\n for j = 1 : n\n c_center(i,j) = 0.0;\n end\n end\n\n for i = 1 : m\n ci = c(i);\n c_size(ci) = c_size(ci) + 1;\n for j = 1 : n\n c_center(ci,j) = c_center(ci,j) + a(i,j);\n end\n end\n\n for i = 1 : k\n for j = 1 : n\n c_center(i,j) = c_center(i,j) / c_size(i);\n end\n end\n\n for i = 1 : k\n wss(i) = 0.0;\n end\n\n for i = 1 : m\n ci = c(i);\n for j = 1 : n\n wss(ci) = wss(ci) + ( a(i,j) - c_center(ci,j) )^2;\n end\n end\n\n critvl_new = 0.0;\n for i = 1 : k\n critvl_new = critvl_new + wss(i);\n end\n\n inc = critvl_new - critvl;\n%\n% Move object I1 from class C2 to class C1.\n% Move object I2 from class C1 to class C2.\n%\n c(i1) = c1;\n c(i2) = c2;\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/asa113/crswap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.49689692542090574}} {"text": "% demo_example_lmgp_data - demonstration script file for LMGP model identification. \n%\n%% Description\n% Demo to present how to obtain and compose data for the identification\n% of GP model with incorporated local models (LMGP model). \n% \n% There are two options how to obtain local model data: \n% a. analytically (set fIdentifyLm to 0) \n% b. with identification (set fIdentifyLm to 1) \n% \n% It can be used only with the Gaussian covariance function and\n% with the white noise model (sum of covSEard and covNoise). \n%\n% See Also\n% example.m, demo_example_LMGP_training.m, demo_example_LMGP_simulation.m,\n% example_LM_ident.m, example_derivative.m\n%\n%% \n% Written by K. Azman, 2007\n%\n% Changelog:\n%\n% 16.2.2015, Martin Stepancic:\n%\t\t \t-included the gathering of both equilibrium and non-equilibrium\n%\t\t\t points in the same matlab script;\n%\t\t\t-changed .mat filenames and their structure contents to: \n%\t\t\t {train|valid}_data.{x|u|y}\n%\nclear;\nglobal flag_LM_data_ident\n% LM generation data \nflag_LM_data_ident = 0; % 0=calculated, 1=identified using IV\n\nme = mfilename; % what is my filename\nmydir = which(me); mydir = mydir(1:end-2-numel(me)); % where am I located\naddpath([mydir 'system']);\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Points at Equilibrium %%%%\n\n% local model ident \nord = 1; % order of identified LMs \neq.U = [-1.5 -1.1 -0.7 -0.3 0 0.3 0.7 1.1 1.5]'; \ndU = 0.1; % depending on diference between the elements of eq.U, valid only if LMs identified! \n\nnoiseStd = 0.1; \n% lm calculated/identified \nif (flag_LM_data_ident)\n % *** local model's parameters identified and not calculated *** \n \n for ii = 1:length(eq.U)\n [lm{ii},y0] = demo_example_LM_ident(eq.U(ii), dU, noiseStd, 2000+ii);\n \n eq.Y(ii,1) = y0; \n eq.dfdy(ii,1) = -lm{ii}.a(2); \n eq.dfdu(ii,1) = -lm{ii}.b(2); \n end\n eq.lm = lm; \n \n filename = 'example_data_lmgp_eq_ident';\n \nelse\n % *** local model's parameters calculated ***\n [eq.dfdy, eq.dfdu, eq.Y] = demo_example_derivative(eq.U); \n \n filename = 'example_data_lmgp_eq_anal';\n \nend\n\nfigure('Name', 'EQ Curve');\nplot(eq.U,eq.Y);\n\nsave(filename,'eq');\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Non-eqilibrium points %%%%\numax = 1.5; \numin = -umax; \nN_training_points = 200; \nN_validation_points = 200; \nnoise_std = 0.05; \n\nutrain = sig_prs_minmax(N_training_points,2,umin,umax); % create input singal\n\n% simulate example system, to obtain delayed outputs and delayed outputs \n[ytrain, xtrain, utrain] = demo_example(utrain); \n% add noise to training data \n[ytrain, ytrain_no_noise] = add_noise_to_vector(ytrain, noise_std); \nfigure('Name', 'Training Input Signal');\nt=1:length(utrain);\nplot(t, utrain, t, xtrain);\nlegend('u', 'y');\ngrid on;\n\n% validation data --> less excited signal \nuvalid = sig_prs_minmax(N_validation_points,5,umin,umax); \n[yvalid, xvalid, uvalid] = demo_example(uvalid); \n\nfigure('Name', 'Validation Input Signal');\nplot(uvalid);\n\n% training data \ntrain_data.u = utrain; \ntrain_data.x = xtrain; \ntrain_data.y = ytrain; \n\n% validation data \nvalid_data.u = uvalid; \nvalid_data.x = xvalid; \nvalid_data.y = yvalid; \n\nsave example_data_lmgp_oeq valid_data train_data umax umin noise_std\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\nsave(filename,'eq')\nrmpath([mydir 'system'])\nreturn\n", "meta": {"author": "Dynamic-Systems-and-GP", "repo": "GPdyn", "sha": "343c20a28a0f95f488db4a086c43fafab5423bda", "save_path": "github-repos/MATLAB/Dynamic-Systems-and-GP-GPdyn", "path": "github-repos/MATLAB/Dynamic-Systems-and-GP-GPdyn/GPdyn-343c20a28a0f95f488db4a086c43fafab5423bda/gpdyn-demos/demo_example_lmgp_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.49689691131891167}} {"text": "function [labelErrors, labelSharingErrors, wrongIndices] = findLabelErrors(realLabels, predLabels)\n\n% FINDLABELERRORS Find the number of errors in the predicted vs the real\n% labels\n% COPYRIGHT: Andreas C. Damianou, 2012\n% VARGPLVM\n\n%%% WARNING: This function only works if there are no multi-label examples!\n\n% First, transform any encoding to binary\n% (e.g. if it is 1 -1 -1 -> 1 0 0)\nlb = min(min(realLabels));\nub = max(max(realLabels));\nrealLabels(realLabels == lb) = 0;\nrealLabels(realLabels == ub) = 1;\n\npredLabels(predLabels >= 0.5) = 1;\npredLabels(predLabels < 0.5) = 0;\n\n% %--- Old code\n% realUb = find(realLabels == ub);\n% predUb = predLabels(realUb);\n% % The number of times that a true label wasn't found\n% labelErrors = length(realUb) - sum(predUb); %equivalent to: length(find(~predUb))\n% \n % The number of times more than one label was found\n \n labelSharingErrors = sum((sum(predLabels,2)>1));\n \n %--\n realLabels2 = transformLabels(realLabels);\n predLabels2 = transformLabels(predLabels);\n uniqueLabels = unique(realLabels2);\n labelErrors = 0;\n for j=1:length(uniqueLabels)\n trueClassInd = find(realLabels2 == uniqueLabels(j));\n wrongIndices{j} = find(~(predLabels2(trueClassInd) == uniqueLabels(j)));\n labelErrors = labelErrors + length(wrongIndices{j});\n end\n\n", "meta": {"author": "SheffieldML", "repo": "vargplvm", "sha": "480201fde5ac84ff36e4a9f06d3fafeafa8ef06d", "save_path": "github-repos/MATLAB/SheffieldML-vargplvm", "path": "github-repos/MATLAB/SheffieldML-vargplvm/vargplvm-480201fde5ac84ff36e4a9f06d3fafeafa8ef06d/vargplvm/matlab/utils/findLabelErrors.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.49687950117194396}} {"text": "function min_f = minf(datafe,dataor)\nT=length(dataor);\nsum=0;\nfor i=1:T\n sum=sum+ abs((datafe(i)-dataor(i))*100/dataor(i));\nend\n\nmin_f=sum;\n", "meta": {"author": "sfvsfv", "repo": "Mathematical-modeling", "sha": "cef1a3688246851f067777b3599b1b3831d3d948", "save_path": "github-repos/MATLAB/sfvsfv-Mathematical-modeling", "path": "github-repos/MATLAB/sfvsfv-Mathematical-modeling/Mathematical-modeling-cef1a3688246851f067777b3599b1b3831d3d948/\u7f8e\u8d5bC\u9898\u5e38\u89c1\u4ee3\u7801/\u3010\u516c\u4f17\u53f7\uff1a\u73a9\u8f6c\u5927\u6570\u636e\u3011\u5fae\u7c92\u7fa4\u7b97\u6cd5\u7ed3\u5408\u7070\u8272\u7cfb\u7edf\u7406\u8bba\u8fdb\u884c\u9884\u6d4b/minf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.49687949807882664}} {"text": "function dat = probability_maps_to_region_index(dat)\n% Use dat.probability_maps to rebuild integer vector of index labels (dat.dat)\n%\n% dat = probability_maps_to_region_index(dat)\n%\n\n% Start: dat has one image per region, with probability values\n% convert to integer vector\n\n[maxval, condf] = max(double(full(dat.probability_maps)),[], 2); % double is safer\n\nallempty = all(dat.probability_maps == 0, 2) | isnan(maxval); % some out-of-mask values may get NaNs\n\ncondf(allempty) = 0;\n\ndat.dat = int32(condf);\n\nend\n\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/@atlas/probability_maps_to_region_index.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.4968794957970369}} {"text": "%-------------------------------------------------------------------------------------------------------------------%\n%\n% IB2d is an Immersed Boundary Code (IB) for solving fully coupled \n% \tfluid-structure interaction models. This version of the code is based off of\n%\tPeskin's Immersed Boundary Method Paper in Acta Numerica, 2002.\n%\n% Author: Nicholas A. Battista\n% Email: nickabattista[at]gmail.com\n% IB2d Created: May 27th, 2015\n% Institution: TCNJ\n%\n% This code is capable of creating Lagrangian Structures using:\n% \t1. Springs\n% \t2. Beams (*torsional springs or non-invariant beams*)\n% \t3. Target Points\n%\t4. Muscle-Model (combined Force-Length-Velocity model, \"HIll+(Length-Tension)\")\n% .\n% .\n% .\n%\n% One is able to update those Lagrangian Structure parameters, e.g., spring constants, resting lengths, etc\n% \n% There are a number of built in Examples, mostly used for teaching purposes. \n% \n% If you would like us to add a specific muscle model, please let Nick (nickabattista[at]gmail.co) know.\n%\n%--------------------------------------------------------------------------------------------------------------------%\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: updates the target point positions\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction targets = update_Target_Point_Positions(dt,current_time,targets)\n\n\n%IDs = targets(:,1); % Stores Lag-Pt IDs in col vector\n%xPts= targets(:,2); % Original x-Values of x-Target Pts.\n%yPts= targets(:,3); % Original y-Values of y-Target Pts.\n%kStiffs = targets(:,4); % Stores Target Stiffnesses \n%N_target = length(targets(:,1)); % Gives total number of target pts!\n\n\nt1 = 0.01; % Period A->B (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": "function r8lib_test119 ( )\n\n%*****************************************************************************80\n%\n%% R8LIB_TEST119 tests R8VEC_EVEN3.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n nold = 4;\n nval = 12;\n\n xold = [ 0.0, 5.1, 7.0, 10.0 ];\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8LIB_TEST119\\n' );\n fprintf ( 1, ' R8VEC_EVEN3 tries to evenly interpolate new data\\n' );\n fprintf ( 1, ' between old values.\\n' );\n \n r8vec_print ( nold, xold, ' Original vector:' );\n\n xval = r8vec_even3 ( nold, nval, xold );\n \n r8vec_print ( nval, xval, ' New vector:' );\n \n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8vec_even3_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.4968388093400872}} {"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": "function linplus_test527 ( )\n\n%*****************************************************************************80\n%\n%% TEST527 tests R8PP_INDICATOR.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 March 2009\n%\n% Author:\n%\n% John Burkardt\n%\n n = 5;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST527\\n' );\n fprintf ( 1, ' R8PP_INDICATOR sets up a R8PP indicator matrix.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Matrix order N = %d\\n', n );\n%\n% Set the matrix.\n%\n a = r8pp_indicator ( n );\n\n r8pp_print ( n, a, ' The R8PP indicator matrix:' );\n \n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linplus/linplus_test527.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.4968388033636104}} {"text": "eeg_file= fullfile(BTB.DataDir, 'demoMat', 'VPiac_10_10_13', ...\n 'calibration_CenterSpellerMVEP_VPiac');\n\n% Load data\ntry\n [cnt, mrk, mnt] = file_loadMatlab(eeg_file);\ncatch\n error('You need to run ''demo_convert_ERPSpeller'' first');\nend\n\n\nnBlocks= 6;\n\n% define 'nBlocks' intervals ranging from the first to the last marker:\ninter = linspace( mrk.time(1), mrk.time(end), nBlocks+1 );\nblk = struct( 'ival', [inter(1:end-1)' inter(2:end)'] );\n\n% define marker structure: one marker every second\nmrkblk = mrk_evenlyInBlocks( blk, 1000 );\n% assign class labels for each marker corresponding to the block\nmrkblk.y = util_classind2labels( mrkblk.event.blkno );\nmrkblk.className= str_cprintf('block %d', 1:6);\n\n% calculate spectra (average within the defined blocks)\nspec = proc_segmentation( cnt, mrkblk, [0 1000] );\nspec = proc_spectrum( spec, [5 40], kaiser(cnt.fs,2) );\n\n% visualize the block-wise spectra\nfig_set(1);\ncmap= cmap_hsvFade(nBlocks, [0 5/6], 1, 1);\ngrid_plot( spec, mnt , defopt_spec, 'ColorOrder',cmap );\n\n% increasing noise level can be observed, e.g. in channels C6 and T8\n", "meta": {"author": "bbci", "repo": "bbci_public", "sha": "2e6fe9481537dcfee702e74544191dcf737f02ce", "save_path": "github-repos/MATLAB/bbci-bbci_public", "path": "github-repos/MATLAB/bbci-bbci_public/bbci_public-2e6fe9481537dcfee702e74544191dcf737f02ce/demos/demo_check_quality_over_time.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.496838802255742}} {"text": "function ni = niftiCheckQto(ni)\n% Changes the qto_* or/and sto_* fields in the NIFTI hearder if not properly\n% set. Also changes other fields see below.\n% \n% ni = niftiCheckQto(ni)\n%\n% We expect these fields to be set at some coordinates inside the image\n% volume. If the NIFTI file was created without setting these files this\n% function starts up the fields by setting the center of the coordinate\n% system of the image to the middle of the image.\n%\n% Does a simple sanity-check on the xform. Right now, we check the origin to\n% make sure it is well- within the image volume. If not, the qto xform\n% fields of the NIFTI struct ni will be adjusted to set the origin to the\n% center of the image. The updated struct is returned and a message is\n% printed to the command line indicating the fix. \n%\n% it will update the follwing fields:\n% 'qform_code'\n% 'qto_xyz'\n% 'qto_ijk'\n% 'quatern_b'\n% 'quatern_c'\n% 'quatern_d'\n% 'qoffset_x'\n% 'qoffset_y'\n% 'qoffset_z'\n% 'qfac'\n% 'pixdim'\n%\n% (c) Stanford Vista Team 2012\n\n% if(isfield(ni,'data')&&~isempty(niftiGet(ni, 'data')))\n% % sanity-check ni.dim\n% sz = size(niftiGet(ni, 'data'));\n% if(any(ni.dim(1:3)~=sz(1:3)))\n% fprintf('[%s] NIFTI volume dim wrong- setting it to the actual data size.\\n',mfilename);\n% ni.dim(1:3) = sz(1:3);\n% end\n% end\n\nif(niftiGet(ni, 'qform_code')==0 && niftiGet(ni, 'sform_code')~=0)\n fprintf('[%s] ni.qform_code is zero and sform_code ~=0. Setting ni.qto_* from ni.sto_*...\\n',mfilename);\n ni = niftiSetQto(ni, niftiGet(ni, 'sto_xyz'));\nend\n\nqto_ijk = niftiGet(ni, 'qto_ijk');\norigin = [qto_ijk(1:3,:)*[0 0 0 1]']';\n\nnidim = niftiGet(ni, 'dim');\nif(any(origin<2)||any(origin>nidim(1:3)-2))\n [t,r,s,k] = affineDecompose(qto_ijk);\n t = nidim/2;\n fprintf('[%s] NIFTI header origin is at or outside the image volume.\\n',mfilename)\n fprintf('[%s] Origin to the image center [%2.3f,%2.3f,%2.3f] pix.\\n',mfilename,t(1),t(2),t(3));\n ni = niftiSetQto(ni, inv(affineBuild(t,r,s,k)));\nend\n\nreturn;", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/fileFilters/nifti/niftiCheckQto.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867729389246, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.49683879926750363}} {"text": "function [specGlobal] = doa_srp(x,method, Param)\n%% \nif(~any(strcmp(method, {'SRP-PHAT' 'SRP-NON'})))\n error('ERROR[doa_srp]: method\u53c2\u6570\u9519\u8bef'); \nend\n%% STFT\nX = ssl_stft(x.',Param.window, Param.noverlap, Param.nfft, Param.fs);\nX = X(2:end,:,:);\n%% \nif strcmp(method,'SRP-PHAT')\n specGlobal = ssl_srpPhat(X,Param);\nelse\n specGlobal = ssl_srp_nonlin(X,Param);\nend\n\nend\n\nfunction X=ssl_stft(x,window,noverlap,nfft,fs)\n\n% Inputs:x: nchan x nsampl window = blackman(wlen);\n% Output:X: nbin x nfram x nchan matrix \n\n[nchan,~]=size(x);\n[Xtemp,F,T,~] = spectrogram(x(1,:),window,noverlap,nfft,fs); % S nbin x nframe\nnbin = length(F);\nnframe = length(T);\nX = zeros(nbin,nframe,nchan);\nX(:,:,1) = Xtemp;\nfor ichan = 2:nchan\n X(:,:,ichan) = spectrogram(x(ichan,:),window,noverlap,nfft,fs); \nend\n\nend\n\nfunction [specGlobal] = ssl_srpPhat(X,Param)\n[~,nFrames,~] = size(X);\nspecInst = zeros(Param.nGrid, nFrames);\n\nfor i = 1:Param.nPairs\n spec = srpPhat_spec(X(Param.freqBins,:,Param.pairId(i,:)), Param.f(Param.freqBins), Param.tauGrid{i}); % NV % [freq x fram x local angle for each pair]\n specSampledgrid = (shiftdim(sum(spec,1)))';\n specCurrentPair = interp1q(Param.alphaSampled{i}', specSampledgrid, Param.alpha(i,:)');\n specInst(:,:) = specInst(:,:) + specCurrentPair;\nend\n\nswitch Param.pooling\n case 'max'\n specGlobal = shiftdim(max(specInst,[],2));\n case 'sum'\n specGlobal = shiftdim(sum(specInst,2));\nend\nend\n\nfunction [specGlobal] = ssl_srp_nonlin(X,Param)\n\nalpha_meth = (10*Param.c)./(Param.d*Param.fs);\n[~,nFrames,~] = size(X);\nspecInst = zeros(Param.nGrid, nFrames);\n\nfor i = 1:Param.nPairs\n spec = srpNonlin_spec(X(Param.freqBins,:,Param.pairId(i,:)), Param.f(Param.freqBins), alpha_meth(i), Param.tauGrid{i});\n specSampledgrid = (shiftdim(sum(spec,1)))';\n specCurrentPair = interp1q(Param.alphaSampled{i}', specSampledgrid, Param.alpha(i,:)');\n specInst = specInst + specCurrentPair;\nend\n\nswitch Param.pooling\n case 'max'\n specGlobal = shiftdim(max(specInst,[],2));\n case 'sum'\n specGlobal = shiftdim(sum(specInst,2));\nend\nend\n\n", "meta": {"author": "WenzheLiu-Speech", "repo": "sound-source-localization-algorithm_DOA_estimation", "sha": "9f7e91bce217d69a110441af939cf041c8f26cd9", "save_path": "github-repos/MATLAB/WenzheLiu-Speech-sound-source-localization-algorithm_DOA_estimation", "path": "github-repos/MATLAB/WenzheLiu-Speech-sound-source-localization-algorithm_DOA_estimation/sound-source-localization-algorithm_DOA_estimation-9f7e91bce217d69a110441af939cf041c8f26cd9/ssl_tools/doa_srp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4968099085823291}} {"text": "% Add baseline measure as Data Quality measure\n% part of the ERPLAB Toolbox\n% axs May 2019\n%\n% Format:\n% baseline_measure = dq_baseline(ERP);\n% or baseline_measure = dq_baseline(ERP,start_time, end_time, subtract_mean_flag)\n%\n% INPUT: * - mandatory\n% * ERP - an ERP structure\n%\nfunction [dq_struct, baseline_measure] = dq_baseline(ERP, start_ms, end_ms, subtract_mean_flag)\n\n% Check input\ntry\n assert(isfield(ERP,'bindata'))\ncatch\n warning('Making Data Quality baseline measures requires an ERPSET')\n beep\n return\nend\n\n\n% Populate any empty args with defaults\nif exist('start_ms','var') == 0 || isempty(start_ms)\n start_ms = ERP.times(1);\nend\nif exist('end_ms','var') == 0 || isempty(end_ms)\n end_ms = 0;\nend\nif exist('subtract_mean_flag','var') == 0 || isempty(subtract_mean_flag)\n subtract_mean_flag = 1;\nend\n\n\n% Check desired times are within availible times\ngood_start = start_ms >= ERP.times;\ngood_end = end_ms <= ERP.times;\ntry\n assert(any(good_start)==1)\n assert(any(good_end)==1)\ncatch\n beep\n warning('The times requested for Data Quality baseline are not available in this ERPset.')\n return\nend\n\nstart_dp = find(abs(ERP.times-start_ms)==min(abs(ERP.times-start_ms))); % datapoint closest to desired ms\nstart_dp = start_dp(1); % if it's a tie, take the first element\nend_dp = find(abs(ERP.times-end_ms)==min(abs(ERP.times-end_ms)));\nend_dp = end_dp(1);\n\n%\n\nb_sd_1 = std(ERP.bindata(1,start_dp:end_dp,1));\n\nbaseline_data = ERP.bindata(:,start_dp:end_dp,:);\n\n\n\nif subtract_mean_flag == 1\n % Measure Standard Deviation, which removes mean\n baseline_measure = std(baseline_data,0,2);\n \nelseif subtract_mean_flag == 0 \n % use rms, not removing mean\n baseline_measure = rms(baseline_data,2);\n \nelseif subtract_mean_flag == 2\n %Corrected SD\n nTimes = size(baseline_data,2);\n baseline_measure_biased = std(baseline_data,0,2);\n baseline_measure = ((baseline_measure_biased * sqrt((nTimes-1)))/ sqrt((nTimes-(3/2)+(1/(8*(nTimes-1))))));\n \nend\n\n% quick plot of baseline sd\n%imagesc(squeeze(baseline_measure))\n\n\n% Prepare dq_struct\nif subtract_mean_flag == 1\n dq_struct.type = 'Baseline Measure - SD';\nelseif subtract_mean_flag == 0 \n dq_struct.type = 'Baseline Measure - RMS';\nelseif subtract_mean_flag == 2\n dq_struct.type = 'Baseline Measure - SD (Corrected)';\nend\n\ndq_struct.times = [start_ms end_ms];\ndq_struct.data = baseline_measure;\n\n", "meta": {"author": "ucdavis", "repo": "erplab", "sha": "e4f66f7a512c4dee2f7596982318e44bb1b72644", "save_path": "github-repos/MATLAB/ucdavis-erplab", "path": "github-repos/MATLAB/ucdavis-erplab/erplab-dd2f60aa41b01c866fcec342efafc48323523cc2/functions/dq_baseline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.49680990318031243}} {"text": "function pklt( noisy_file, outfile)\n%\n% Implements a perceptually-motivated subspace algorithm [1].\n% \n%\n% Usage: pklt(noisyFile, outputFile)\n% \n% infile - noisy speech file in .wav format\n% outputFile - enhanced output file in .wav format\n% \n%\n% Example call: pklt('sp04_babble_sn10.wav','out_pklt.wav');\n%\n% References:\n% [1] Jabloun, F. and Champagne, B. (2003). Incorporating the human hearing\n% \t properties in the signal subspace approach for speech enhancement. IEEE\n% \t Trans. on Speech and Audio Processing, 11(6), 700-708.\n% \n% Authors: Yi Hu and Philipos C. Loizou\n%\n% Copyright (c) 2006 by Philipos C. Loizou\n% $Revision: 0.0 $ $Date: 10/09/2006 $\n%-------------------------------------------------------------------------\n\nif nargin<2\n fprintf('Usage: pklt(noisyfile.wav,outFile.wav) \\n\\n');\n return;\nend\n\nvad_thre= 1.2; % 2.378 is the value from Mittal's paper\nmu_vad= 0.98; % mu to use in vad\n\n[noisy_speech, Srate, NBITS]= wavread( noisy_file);\nsubframe_dur= 4; %subframe length is 4 ms\nlen= floor( Srate* subframe_dur/ 1000); \nP= len; % sub-frame length - for 8k sampling rate, len is 32\nframe_dur= 32; % frame length in msecs\nN= frame_dur* Srate/ 1000; \nNover2= N/ 2; % window overlap in 50% of frame size\nK= N;\nframe_window= hamming( N);\nsubframe_window= hamming( P); \neta_v= .08; % used for gain values calc. \n\n\n\n% ====noise covariance matrix estimation\nL120=floor( 120* Srate/ 1000); \n% assume the first 120ms is noise only\nnoise= noisy_speech( 1: L120);\n\nnoise_autoc= xcorr( noise, len- 1, 'biased'); \n% from -(len- 1) to (len- 1)\n% obtain the autocorrelation functions\nRn= toeplitz( noise_autoc( len: end));\n% form a Toeplitz matrix to obtain the noise signal covariance matrix\nbartlett_win= bartlett( 2* len- 1);\nn_autoc_win= noise_autoc.* bartlett_win; \n\nfor k= 0: N- 1\n Phi_w( k+ 1)= n_autoc_win( P: 2*P-1)' * 2* ...\n cos( 2* pi* k* (0: P- 1)'/ N)- n_autoc_win( P); \nend\nPhi_w= Phi_w';\n% make Phi_w column vector\n\nn_start= 1;\n\nNframes= floor( length( noisy_speech)/ (N/ 2))- 1; % number of frames \nx_overlap= zeros( Nover2, 1);\n\n%=============================== Start Processing =====================\n\n\nfor n=1: Nframes \n \n noisy= noisy_speech( n_start: n_start+ N- 1); \n noisy_autoc= xcorr( noisy, len- 1, 'biased');\n Ry= toeplitz( noisy_autoc( len: 2* len- 1)); \n \n % Use simple VAD algorithm to update noise cov matrix, Rn\n %\n vad_ratio= Ry(1,1)/ Rn(1,1); \n if (vad_ratio<= vad_thre) % noise dominant\n Rn= mu_vad* Rn+ (1- mu_vad)* Ry; \n noise_autoc_sc= Rn( 1, :)';\n % single sided noise autocorrelation\n noise_autoc= [flipud( noise_autoc_sc( 2: end)); ...\n noise_autoc_sc];\n n_autoc_win= noise_autoc.* bartlett_win;\n % compute Phi_w\n for k= 0: N- 1\n Phi_w( k+ 1)= n_autoc_win( P: 2*P-1)' * 2* ...\n cos( 2* pi* k* (0: P- 1)'/ N)- n_autoc_win( P);\n end \n % Phi_w is column vector \n end\n % =================\n\n Rx= Ry- Rn;\n \n [U, D]= eig( Rx);\n dD= diag( D); % retrieving diagonal elements\n dD_Q= find( dD> 0); % index for those eigenvalues greater than 0\n Lambda= dD( dD_Q); \n U1= U( :, dD_Q); \n % eigenvector for those eigenvalues greater than 0 \n \n U1_fft= fft( U1, N); \n V= abs( U1_fft).^ 2; \n Phi_B= V* Lambda/ P; \n \n %==calculating masking threshold\n Phi_mask= mask( Phi_B( 1: N/ 2+ 1), N, Srate, NBITS);\n Phi_mask= [Phi_mask; flipud( Phi_mask( 2: N/ 2))]; \n \n Theta= V'* Phi_mask/ K; \n Ksi= V'* Phi_w/ K; \n \n gain_vals= exp( -eta_v* Ksi./ min( Lambda, Theta)); \n G= diag( gain_vals);\n H= U1* G* U1';\n \n % first step of synthesis for subframe\n sub_start= 1; \n sub_overlap= zeros( P/2, 1);\n for m= 1: (2*N/P- 1)\n sub_noisy= noisy( sub_start: sub_start+ P- 1);\n enhanced_sub_tmp= (H* sub_noisy).* subframe_window;\n enhanced_sub( sub_start: sub_start+ P/2- 1)= ...\n enhanced_sub_tmp( 1: P/2)+ sub_overlap; \n sub_overlap= enhanced_sub_tmp( P/2+1: P);\n sub_start= sub_start+ P/2;\n end\n enhanced_sub( sub_start: sub_start+ P/2- 1)= sub_overlap; \n \n xi= enhanced_sub'.* frame_window; \n xfinal( n_start: n_start+ Nover2- 1)= x_overlap+ xi( 1: Nover2); \n x_overlap= xi( Nover2+ 1: N); \n \n n_start= n_start+ Nover2; \n \nend\n\nxfinal( n_start: n_start+ Nover2- 1)= x_overlap; \n\n\nwavwrite(xfinal, Srate, NBITS, outfile);\n\n\n%=======================E N D ===================================\n\nfunction M= mask( Sx, dft_length, Fs, nbits)\n% Author: Patrick J. Wolfe\n% Signal Processing Group\n% Cambridge University Engineering Department\n% p.wolfe@ieee.org\n% Johnston perceptual model initialisation\nframe_overlap= dft_length/ 2; \nfreq_val = (0:Fs/dft_length:Fs/2)';\nhalf_lsb = (1/(2^nbits-1))^2/dft_length;\n\nfreq= freq_val;\nthresh= half_lsb;\ncrit_band_ends = [0;100;200;300;400;510;630;770;920;1080;1270;...\n 1480;1720;2000;2320;2700;3150;3700;4400;5300;6400;7700;...\n 9500;12000;15500;Inf];\n\n% Maximum Bark frequency\n%\nimax = max(find(crit_band_ends < freq(end)));\n\n% Normalised (to 0 dB) threshold of hearing values (Fletcher, 1929) \n% as used by Johnston. First and last thresholds are corresponding \n% critical band endpoint values, elsewhere means of interpolated \n% critical band endpoint threshold values are used.\n%\nabs_thr = 10.^([38;31;22;18.5;15.5;13;11;9.5;8.75;7.25;4.75;2.75;...\n 1.5;0.5;0;0;0;0;2;7;12;15.5;18;24;29]./10);\nABSOLUTE_THRESH = thresh.*abs_thr(1:imax);\n\n% Calculation of tone-masking-noise offset ratio in dB\n%\nOFFSET_RATIO_DB = 9+ (1:imax)';\n\n% Initialisation of matrices for bark/linear frequency conversion\n% (loop increments i to the proper critical band)\n%\nnum_bins = length(freq);\nLIN_TO_BARK = zeros(imax,num_bins);\ni = 1;\nfor j = 1:num_bins\n while ~((freq(j) >= crit_band_ends(i)) & ...\n (freq(j) < crit_band_ends(i+1))),\n i = i+1;\n end\n LIN_TO_BARK(i,j) = 1;\nend\n\n% Calculation of spreading function (Schroeder et al., 82)\n\nspreading_fcn = zeros(imax);\nsumm = 0.474:imax;\nspread = 10.^((15.81+7.5.*summ-17.5.*sqrt(1+summ.^2))./10);\nfor i = 1:imax\n for j = 1:imax\n spreading_fcn(i,j) = spread(abs(j-i)+1);\n end\nend\n\n% Calculation of excitation pattern function\n\nEX_PAT = spreading_fcn* LIN_TO_BARK;\n\n% Calculation of DC gain due to spreading function\n\nDC_GAIN = spreading_fcn* ones(imax,1);\n\n\n%Sx = X.* conj(X);\n\nC = EX_PAT* Sx;\n\n% Calculation of spectral flatness measure SFM_dB\n%\n[num_bins num_frames] = size(Sx);\nk = 1/num_bins;\nSFM_dB = 10.*log10((prod(Sx).^k)./(k.*sum(Sx)+eps)+ eps);\n\n% Calculation of tonality coefficient and masked threshold offset\n%\nalpha = min(1,SFM_dB./-60);\nO_dB = OFFSET_RATIO_DB(:,ones(1,num_frames)).*...\n alpha(ones(length(OFFSET_RATIO_DB),1),:) + 5.5;\n\n% Threshold calculation and renormalisation, accounting for absolute \n% thresholds\n\nT = C./10.^(O_dB./10);\nT = T./DC_GAIN(:,ones(1,num_frames));\nT = max( T, ABSOLUTE_THRESH(:, ones(1, num_frames)));\n\n% Reconversion to linear frequency scale \n\n%M = 1.* sqrt((LIN_TO_BARK')*T);\nM= LIN_TO_BARK'* T;\n", "meta": {"author": "jtkim-kaist", "repo": "Speech-enhancement", "sha": "84f1a3c1273fb4952522b911dd62cbb4476a534d", "save_path": "github-repos/MATLAB/jtkim-kaist-Speech-enhancement", "path": "github-repos/MATLAB/jtkim-kaist-Speech-enhancement/Speech-enhancement-84f1a3c1273fb4952522b911dd62cbb4476a534d/SE/lib/sub_lib/MATLAB_code/subspace/pklt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936438, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.49680989777829554}} {"text": "function linplus_test485 ( )\n\n%*****************************************************************************80\n%\n%% TEST485 tests R8PBU_INDICATOR.\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 n = 9;\n mu = 3;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST485\\n' );\n fprintf ( 1, ' R8PBU_INDICATOR sets up a R8PBU indicator matrix.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Matrix order N = %d\\n', n );\n fprintf ( 1, ' Bandwidth MU = %d\\n', mu );\n\n a = r8pbu_indicator ( n, mu );\n\n r8pbu_print ( n, mu, a, ' The R8PBU indicator matrix:' );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linplus/linplus_test485.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.49680988616034755}} {"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": "%==============================================================================\n% This code is part of the Matlab-based toolbox\n% FAIR - Flexible Algorithms for Image Registration. \n% For details see \n% - https://github.com/C4IR and\n% - http://www.siam.org/books/fa06/\n% ##2\n%==============================================================================\n% \n% - data 3d-brains, Omega=(0,20)x(0,10)x(0,20), level=3:6, m=[128,64,128]\n% - viewer imgmontage\n% - interpolation linearInter\n% - distance SSD\n% - pre-registration affine3D\n% - regularizer mfElastic\n% - optimizer Trust-Region\n% ===============================================================================\n\nsetup3DbrainData;\n\n% prepare the plot\nFAIRplots('clear')\nDshow = @(T,R,omega,m) viewIP(abs(T-R),omega,m,'colormap',gray(256));\nFAIRplots('set','Dshow',Dshow);\n\n% finally: \n% run the MultiLevel Non-Parametric Image Registration\n% Trust Region (multigrid preconditioner for conjugate gradient solver)\n% no pre-registration\n\nNPIRpara = optPara('TrustRegion','preconditioner',@MGsolver)\n[yc,wc,his] = MLIR(ML,'NPIRpara',NPIRpara,'parametric',0);\n\n%==============================================================================\n", "meta": {"author": "C4IR", "repo": "FAIR.m", "sha": "975edebd37b833ae76696792870de5c05efcb9cb", "save_path": "github-repos/MATLAB/C4IR-FAIR.m", "path": "github-repos/MATLAB/C4IR-FAIR.m/FAIR.m-975edebd37b833ae76696792870de5c05efcb9cb/kernel/examples/E9_3Dbrain_TR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.49666812047833653}} {"text": "function ica_input = compute_spatiotemporal_ica_input(pca_filters, pca_traces, mu)\n\n\tnum_PCs = size(pca_traces,1);\n\n\t% Create concatenated input for spatio-temporal ICA\n\tif (mu == 1) % Pure temporal\n\t ica_input = pca_traces;\n\telseif (mu == 0) % Pure spatial\n\t ica_input = pca_filters;\n\telse % Spatio-temporal\n\t ica_input = [(1-mu)*pca_filters, mu*pca_traces];\n\t for pc_idx = 1:num_PCs % Renormalize\n\t ica_input_row = ica_input(pc_idx,:);\n\t ica_input(pc_idx,:) = ica_input_row / sqrt(norm(ica_input_row));\n\t end\n\tend\nend", "meta": {"author": "bahanonu", "repo": "ciatah", "sha": "f25f27660d985795ccb1012a799ab7e0d7afc596", "save_path": "github-repos/MATLAB/bahanonu-ciatah", "path": "github-repos/MATLAB/bahanonu-ciatah/ciatah-f25f27660d985795ccb1012a799ab7e0d7afc596/+ciapkg/+signal_extraction/+pca_ica_2/compute_spatiotemporal_ica_input.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059609645723, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4965828172638057}} {"text": "classdef prtBrvDpMixture < prtBrvMixture\n % ds = prtDataGenOldFaithful; x = ds.getX;\n %\n % mm = prtBrvDpMixture('components',repmat(prtBrvMvn,25,1));\n % mm.vbConvergenceThreshold = 1e-6;\n % mm.vbVerboseText = true;\n % mm.vbVerbosePlot = true;\n % mm.vbVerboseMovie = true;\n % [mmLearned, training] = mm.vb(x);\n\n\n\n\n\n methods\n\n function obj = prtBrvDpMixture(varargin)\n obj.mixing = prtBrvDiscreteStickBreaking;\n \n if nargin < 1\n return\n end\n obj = constructorInputParse(obj,varargin{:});\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/]beta/brv/prtBrvDpMixture.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.496582811140023}} {"text": "function obj = get_metric(obj)\n\nglobal Metric Nk Nt Nr Ns n;\n\nV_equal = zeros(Nt,Ns);\nW_equal = zeros(Nr,Ns,Nk);\n\nif obj.V_RF == 0\n V_equal = obj.V_B;\n W_equal = obj.W_B;\n \nelse\n for k = 1:Nk\n V_equal = obj.V_RF*obj.V_B;\n W_equal(:,:,k) = obj.W_RF*obj.W_B(:,:,k);\n end\nend\n\nif (Metric.rate)\n [obj.rate(n),obj.A(:,n)] = get_scrate(V_equal,W_equal);\nend\n\nif (Metric.mse)\n obj.mse(n)= get_scmse(V_equal,W_equal);\nend\n\nif (Metric.ber)\n [obj.ber(n),obj.suberror(:,n)] = get_scber(V_equal,W_equal);\nend\n ", "meta": {"author": "Zzhaoxingyu", "repo": "hybrid-beamforming-for-three-scenes", "sha": "396ae70db7dd464a65458f274a65aa113ed73c8b", "save_path": "github-repos/MATLAB/Zzhaoxingyu-hybrid-beamforming-for-three-scenes", "path": "github-repos/MATLAB/Zzhaoxingyu-hybrid-beamforming-for-three-scenes/hybrid-beamforming-for-three-scenes-396ae70db7dd464a65458f274a65aa113ed73c8b/singcarrier/metric/get_metric.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.4965828056069147}} {"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": "filename='Arch_triangle_coarse';\n ptype = 'MACRO';\nmethod = 'SIMPALL';\nmaterialType = 'ISOTROPIC';\ninitial_case = 'full';\ncost = {'compliance';'perimeter'};\nweights = [1, 0.1];\nconstraint = {'volumeConstraint'};\noptimizer = 'MMA'; incrementFactor = 1;\nfilterType = 'P1';\n\nnsteps = 5;\nVfrac_final = 0.4;\nPerimeter_target = 1;\noptimality_final = 1e-3;\nconstr_final =1e-3;\n\nVfrac_initial = 1;\noptimality_initial = 1e-2;\nconstr_initial = 1e-3;\nTOL.rho_plus = 1;\nTOL.rho_minus = 0;\nTOL.E_plus = 1;\nTOL.E_minus = 1e-3;\nTOL.nu_plus = 1/3;\nTOL.nu_minus = 1/3;\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/Benchmarks/Arch/ArchTriangleCoarse_Case_3_2_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.49654618926567284}} {"text": "function Rb2s = flu2rdf\n\n% FLU2RDF Camera body to camera sensor rotation matrix.\n% FLU2RDF computes the rotation matrix for a camera whos body\n% is in the FLU frame (x-front, y-left, z-up) and its sensor in\n% the RDF frame (x-right, y-down, z-front).\n\n% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\n\nRb2s = e2R([-pi/2 0 -pi/2]');\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/FrameTransforms/Rotations/flu2rdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4965461840031006}} {"text": "% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n%function tfrpmht\n%TFRPMHT Unit test for the time frequency representation TFRPMH.\n\n% O. Lemoine - March 1996. \n\n% We test each property of the corresponding TFR :\n\nN=128;\n\n% Covariance by translation in time \nt1=55; t2=70; f=0.3;\nsig1=amgauss(N,t1).*fmconst(N,f,t1); \nsig2=amgauss(N,t2).*fmconst(N,f,t2); \ntfr1=tfrpmh(sig1); \ntfr2=tfrpmh(sig2); \n[tr,tc]=size(tfr1);\nnu=round(f*(tc-1)*2)+1;\ntfr=tfr1-tfr2(:,modulo((1:tc)-t1+t2,tc));\nif any(any(abs(tfr)>sqrt(eps))),\n error('tfrpmh test 1 failed');\nend\n\n\n% Reality of the TFR\nsig=noisecg(N);\ntfr=tfrpmh(sig);\nif sum(any(abs(imag(tfr))>sqrt(eps)))~=0,\n error('tfrpmh test 2 failed');\nend\n\n\n% Energy conservation\nsig=noisecg(N);\ntfr=tfrpmh(sig);\nEs=norm(sig)^2;\nEtfr=sum(mean(tfr));\nif abs(Es-Etfr)>sqrt(eps),\n error('tfrpmh test 3 failed');\nend\n\n\n% Time-marginal\nsig=noisecg(N);\ntfr=tfrpmh(sig);\nip1=abs(sig).^2;\nip2=mean(tfr)';\nif any(abs(ip1-ip2)>sqrt(eps)),\n error('tfrpmh test 4 failed');\nend\n\n\n% Conservation of the time support (wide-sense)\nsig=[zeros(N/4,1);noisecg(N/2);zeros(N/4,1)];\ntfr=tfrpmh(sig);\nif sum(any(abs(tfr(:,1:N/4-1))>sqrt(eps))) | ...\n sum(any(abs(tfr(:,(3*N/4+1):N))>sqrt(eps))),\n error('tfrpmh test 5 failed');\nend\n\n\n% time localization\nt0=30; sig=((1:N)'==t0);\ntfr=tfrpmh(sig);\n[ik,jk]=find(tfr~=0.0);\nif any(jk~=t0)|any(ik'-(1:N)),\n error('tfrpmh test 6 failed');\nend;\n\n\n% A PMHD with a constant window is a MHD\nsig=fmlin(N).*amgauss(N);\ntfr1=tfrpmh(sig,1:N,N,ones(2*N+1,1));\ntfr2=tfrmh(sig);\nif max(max(abs(tfr1-tfr2)))>1e-5,\n error('tfrpmh test 7 failed');\nend\n\n\nN=131;\n\n% Covariance by translation in time \nt1=55; t2=70; f=0.3;\nsig1=amgauss(N,t1).*fmconst(N,f,t1); \nsig2=amgauss(N,t2).*fmconst(N,f,t2); \ntfr1=tfrpmh(sig1); \ntfr2=tfrpmh(sig2); \n[tr,tc]=size(tfr1);\nnu=round(f*(tc-1)*2)+1;\ntfr=tfr1-tfr2(:,modulo((1:tc)-t1+t2,tc));\nif any(any(abs(tfr)>sqrt(eps))),\n error('tfrpmh test 8 failed');\nend\n\n\n% Reality of the TFR\nsig=noisecg(N);\ntfr=tfrpmh(sig);\nif sum(any(abs(imag(tfr))>sqrt(eps)))~=0,\n error('tfrpmh test 9 failed');\nend\n\n\n% Energy conservation\nsig=noisecg(N);\ntfr=tfrpmh(sig);\nEs=norm(sig)^2;\nEtfr=sum(mean(tfr));\nif abs(Es-Etfr)>sqrt(eps),\n error('tfrpmh test 10 failed');\nend\n\n\n% Time-marginal\nsig=noisecg(N);\ntfr=tfrpmh(sig);\nip1=abs(sig).^2;\nip2=mean(tfr)';\nif any(abs(ip1-ip2)>sqrt(eps)),\n error('tfrpmh test 11 failed');\nend\n\n\n% Conservation of the time support (wide-sense)\nsig=[zeros(round(N/4),1);noisecg(round(N/2));zeros(round(N/4),1)];\ntfr=tfrpmh(sig);\nif sum(any(abs(tfr(:,1:round(N/4)-1))>sqrt(eps))) | ...\n sum(any(abs(tfr(:,(round(3*N/4)+2):N))>sqrt(eps))),\n error('tfrpmh test 12 failed');\nend\n\n\n% time localization\nt0=30; sig=((1:N)'==t0);\ntfr=tfrpmh(sig);\n[ik,jk]=find(tfr~=0.0);\nif any(jk~=t0)|any(ik'-(1:N)),\n error('tfrpmh test 13 failed');\nend;\n\n\n% A PMHD with a constant window is a MHD\nsig=fmlin(N).*amgauss(N);\ntfr1=tfrpmh(sig,1:N,N,ones(2*N+1,1));\ntfr2=tfrmh(sig);\nif max(max(abs(tfr1-tfr2)))>1e-5,\n error('tfrpmh test 14 failed');\nend\n\n", "meta": {"author": "HeLiangHIT", "repo": "time_frequency", "sha": "09c2abe92355ff5cd867bdb169229682e9d7af7c", "save_path": "github-repos/MATLAB/HeLiangHIT-time_frequency", "path": "github-repos/MATLAB/HeLiangHIT-time_frequency/time_frequency-09c2abe92355ff5cd867bdb169229682e9d7af7c/tf_tool_box/tftb-0.2/tests/tfrpmht.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300048, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.49651942394960086}} {"text": "function y = polycomb(varargin)\n\n% Simplified Version of Combvec (Mark Beale, 12-15-93)\n\ny = varargin{1};\nfor i=2:length(varargin)\n z = varargin{i};\n y = [copy_blocked(y,size(z,2)); copy_interleaved(z,size(y,2))];\nend\n\n%=========================================================\nfunction b = copy_blocked(m,n)\n\n[mr,mc] = size(m);\nb = zeros(mr,mc*n);\nind = 1:mc;\nfor i=[0:(n-1)]*mc\n b(:,ind+i) = m;\nend\n%=========================================================\n\nfunction b = copy_interleaved(m,n)\n\n[mr,mc] = size(m);\nb = zeros(mr*n,mc);\nind = 1:mr;\nfor i=[0:(n-1)]*mr\n b(ind+i,:) = m;\nend\nb = reshape(b,mr,n*mc);\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/15-polybase/polycomb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629465, "lm_q2_score": 0.7310585786300048, "lm_q1q2_score": 0.4965194239496008}} {"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": "function angles2d\n%ANGLES2D Description of functions for manipulating angles.\n%\n% Angles are normalized in an interval of width 2*PI. Most geom2d\n% functions return results in the [0 2*pi] interval, but it can be\n% convenient to consider the [-pi pi] interval as well. See the\n% normalizeAngle function to switch between conventions.\n%\n% Angles are usually oriented. The default orientation is the CCW\n% (Counter-Clockwise) orientation.\n%\n% See also \n% normalizeAngle, angleDiff, angleAbsDiff, angleSort\n% angle2Points, angle3Points, vectorAngle, lineAngle, edgeAngle\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@inrae.fr\n% Created: 2010-03-31, using Matlab 7.4.0.287 (R2007a)\n% Copyright 2010-2022 INRA - Cepia Software Platform\n\nhelp('angles2d');\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/geom2d/angles2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.4965194009806335}} {"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": "% tiny\n%d = 10;\n% medium\nd = 100;\n% big\n%d = 500;\nn = 3*d;\n%n = 2*d;\n\nif 1\n clear run\nif 0\n % experiment 1\n w = randn(d,1);\n % this ensures about 16% training error\n w = sqrt(2)*w/norm(w);\n % training data\n x = randn(d,n);\n s = 1./(1+exp(-w'*x));\n y = (rand(1,n) < s);\n y = 2*y-1;\n if 0\n % test data\n xt = randn(d,1e4);\n s = 1./(1+exp(-w'*xt));\n yt = (rand(1,cols(xt)) < s);\n yt = 2*yt-1;\n end\nelseif 1\n % experiment 2\n % positive data\n x = dirichlet_sample(ones(d,1),n);\n w = dirichlet_sample(ones(d,1),2);\n w = log(w(:,1)./w(:,2));\n \n s = 1./(1+exp(-w'*x));\n y = (rand(1,n) < s);\n y = 2*y-1;\n if 1\n % test data\n xt = dirichlet_sample(ones(d,1),n);\n s = 1./(1+exp(-w'*xt));\n yt = (rand(1,cols(xt)) < s);\n yt = 2*yt-1;\n end\nelse\n % Collins's generator\n x = randn(d,n);\n w = randn(d,1);\n y = sign(w'*x);\n x = x + randn(d,n)*sqrt(0.8);\nend\n\nif 0\n % shift the data\n c = 10;\n x = [x+c; ones(1,n)];\n w = [w; -c*sum(w)];\nend\nend\n[d,n] = size(x);\n\n\ni1 = find(y > 0);\ni0 = find(y < 0);\nfigure(1)\nplot(x(1,i1), x(2,i1), 'o', x(1,i0), x(2,i0), 'x')\nif d == 2\n draw_line_clip(w(1),w(end),-w(2),'Color','k');\nend\n\nw0 = zeros(d,1);\nxy = scale_cols(x,y);\n\nif 0\n xyt = scale_cols(xt,yt);\n % find the best lambda\n lambdas = exp(linspace(-4,4,20));\n f = [];\n for i = 1:length(lambdas)\n w = train_newton(xy,w0,lambdas(i));\n f(i) = logProb(xyt,w);\n end\n figure(1)\n semilogx(lambdas,f)\n axis_pct;\n [dummy,i] = max(f);\n lambda = lambdas(i);\nelse\n lambda = 1e-2;\nend\nfprintf('lambda = %g\\n',lambda)\n\nif exist('run') ~= 1 | ~isfield(run,'Newton')\n disp('Newton')\n [w,run.Newton] = train_newton(xy,w0,lambda);\n wbest = w;\n ebest = run.Newton.e(end);\n % training errors\n s = 1./(1+exp(-wbest'*x));\n fprintf('%g training error\\n', mean((s > 0.5) ~= (y > 0)))\nend\n\nif ~isfield(run,'Coord')\n disp('Coord')\n %[w,run.Coord] = train_newton2(xy,w0,lambda);\nend\nif ~isfield(run,'CG')\n disp('CG')\n [w,run.CG] = train_cg(xy,w0,lambda);\nend\n%disp(length(cg.run.e))\n%[w,cg2.run] = train_cg2(xy,w0);\n%disp(length(cg2.run.e))\nif 0\n % compare by iteration\n figure(3)\n i = 1:length(cg2.run.e);\n plot(i, cg.run.e(i), i, cg2.run.e(i))\n legend('CG','CG2',4)\n return\nend\n\nif ~isfield(run,'BFGS')\n disp('BFGS')\n [w,run.BFGS] = train_bfgs(xy,w0,lambda);\nend\n%[w,run.lmBFGS] = train_lmbfgs(xy,w0,lambda);\n\n%[w,run.sg] = train_sg(xy,w0);\nif 0\n fprintf('max(sg.run.e) = %g\\n',max(sg.run.e))\n fprintf('max(cg.run.e) = %g\\n',max(cg.run.e))\n figure(1)\n plot(sg.run.step)\n figure(2)\n hold on, plot(cg.run.e,'g'), hold off\n figure(3)\n plot(sg.run.w(1,:),sg.run.w(2,:)) \n hold on, plot(cg.run.w(1,:),cg.run.w(2,:),'g'), hold off\n return\nend\n\nif ~isfield(run,'FixedH')\n disp('FixedH')\n [w,run.FixedH] = train_bohning(xy,w0,lambda);\nend\n\nif ~isfield(run,'Dual') & lambda > 0\n disp('Dual')\n [w,run.Dual] = train_dual(xy,w0,lambda,1);\nend\n%[w,run.Dual2] = train_dual(xy,w0,lambda,1);\n%[w,run.Dual2] = train_dual_cg(xy,w0,lambda);\n\nif ~isfield(run,'MIS') & lambda == 0\n [w,run.MIS] = train_mis(xy,w0,lambda);\nend\nif ~isfield(run,'IS') & lambda == 0\n %[w,run.IS] = train_is(x,y,w0,lambda);\nend\n\ncolor.Newton = 'k';\ncolor.CG = 'g';\ncolor.BFGS = 'r';\ncolor.lmBFGS = 'm';\ncolor.cg2 = 'r';\ncolor.sg = 'g';\ncolor.Coord = 'm';\ncolor.FixedH = 'c';\ncolor.Dual = 'b';\ncolor.Dual2 = 'm';\ncolor.MIS = 'g';\ncolor.IS = 'k';\n\nlinespec.Newton = 'b-.';\nlinespec.CG = 'g--';\nlinespec.Coord = 'g-';\nlinespec.FixedH = 'c-';\nlinespec.BFGS = 'r-.';\nlinespec.lmBFGS = 'm-.';\nlinespec.Dual = 'y-.';\nlinespec.Dual2 = 'm-.';\nlinespec.MIS = 'm--';\nlinespec.IS = 'k--';\n\n% plot cost vs. accuracy\nfigure(2)\nebest = -Inf;\nfor f = fieldnames(run)'\n thisrun = getfield(run,char(f));\n ebest = max([ebest max(thisrun.e)]);\nend\nfor f = fieldnames(run)'\n thisrun = getfield(run,char(f));\n %semilogx(thisrun.flops, thisrun.e, getfield(linespec,char(f)));\n thisrun.err = (ebest - thisrun.e)/n;\n run = setfield(run,char(f),thisrun);\n loglog(thisrun.flops, thisrun.err, getfield(color,char(f)));\n hold on\nend\nhold off\nxlabel('FLOPS')\n%ylabel('Log-likelihood')\nylabel('Difference from optimal log-likelihood')\naxis_pct;\nif 1\n ax = axis;\n ax(3) = 1e-10;\n axis(ax);\nend\nf = fieldnames(run);\nlegend(f,4)\nif 0\n legend off\n f = fieldnames(run);\n h = mobile_text(f{:});\nend\nset(gcf,'paperpos',[0.25 2.5 8 6])\n%print -dpsc expt1_d100_n300.ps\n%print -dpsc expt2_d100_n300.ps\n%print -dpsc expt25_d100_n300.ps\n%print -dpsc expt25_d500_n1500.ps\n%print -dpsc expt3_d100_n300.ps\n%print -dpsc expt4_d100_n300.ps\n% print -dpsc expt2_d300_n1500.ps\n% save expt4.mat x y run\n\nif 0\n% cosine distance from the best solution\nwbest = wbest/norm(wbest);\nfigure(3)\nfor f = fieldnames(run)'\n thisrun = getfield(run,char(f));\n thisrun.w = scale_cols(thisrun.w, 1./sqrt(sum(thisrun.w.^2,1)));\n thisrun.acc = sqrt(clip(sqdist(wbest, thisrun.w)));\n run = setfield(run,char(f),thisrun);\n loglog(thisrun.flops, thisrun.acc, getfield(color,char(f)));\n hold on\nend\nhold off\nlegend(fieldnames(run),4)\nend\n\nfor f = fieldnames(run)'\n thisrun = getfield(run,char(f));\n %i = convergence(thisrun.e);\n i = min(find(thisrun.err < 1e-4));\n fprintf('%-9s %11d\\n',char(f),thisrun.flops(i))\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/test1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.496488769206136}} {"text": "function a = r8sto_indicator ( n )\n\n%*****************************************************************************80\n%\n%% R8STO_INDICATOR sets up a R8STO indicator matrix.\n%\n% Discussion:\n%\n% The R8STO storage format is used for a symmetric Toeplitz matrix.\n% It stores the N elements of the first row.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n% N must be positive.\n%\n% Output, real A(N), the R8STO matrix.\n%\n fac = 10^( i4_log_10 ( n ) + 1 );\n\n i = 1;\n k = 0;\n for j = 1 : n\n k = k + 1;\n a(k) = fac * i + j;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linplus/r8sto_indicator.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.49648876425537725}} {"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 V = par_read_volume(info)\n% Function for reading the volume of a Philips Par / Rec MR V4.* file \n%\n% volume = par_read_volume(file-header)\n%\n% examples:\n% 1: info = par_read_header()\n% V = par_read_volume(info);\n% imshow(squeeze(V(:,:,round(end/2),1)),[]);\n%\n% 2: V = par_read_volume('test.par');\n\nif(~isstruct(info)), info=par_read_header(info); end\n\n% Open file\nfid=fopen(info.FilenameREC','rb','ieee-le');\n% Skip header\nfseek(fid,0,'bof');\n\ndatasize=prod(info.Dimensions)*info.BitDepth/8;\n\n% Read the Data\nswitch(info.BitDepth)\n case 8\n info.DataType='char';\n case 16\n info.DataType='short';\n case 32\n info.DataType='float';\n case 64\n info.DataType='double';\nend\n\nswitch(info.DataType)\n case 'char'\n V = int8(fread(fid,datasize,'char=>int8'));\n case 'uchar'\n V = uint8(fread(fid,datasize,'uchar=>uint8'));\n case 'short'\n V = int16(fread(fid,datasize,'short=>int16'));\n case 'ushort'\n V = uint16(fread(fid,datasize,'ushort=>uint16'));\n case 'int'\n V = int32(fread(fid,datasize,'int=>int32'));\n case 'uint'\n V = uint32(fread(fid,datasize,'uint=>uint32'));\n case 'float'\n V = single(fread(fid,datasize,'float=>single'));\n case 'double'\n V = double(fread(fid,datasize,'double=>double'));\nend\n\nfclose(fid);\nV = reshape(V,info.Dimensions);\n\n\n", "meta": {"author": "tomdoel", "repo": "pulmonarytoolkit", "sha": "09688a006d548fb85795df0338d1ed4f4a010fb9", "save_path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit", "path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit/pulmonarytoolkit-09688a006d548fb85795df0338d1ed4f4a010fb9/External/ReadData3D/par/par_read_volume.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.4964887593046185}} {"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_metricT || 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\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\nif isempty(noise_space) % 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\nelse % 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_2.1/bss_decomp_tvfilt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637397236823, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.49645182530872856}} {"text": "% UPDATE_POSTERIOR updates GPML posterior given a new observation.\n%\n% This function provides a fast update for a GPML posterior structure\n% given a single new observation, avoiding O(N^3) retraining time.\n% This implementation assumes exact inference (inf = @infExact) and a\n% Gaussian likelihood (lik = @likGauss). It will not work correctly\n% for other combinations of likelihood and inference!\n%\n% Usage:\n%\n% new_posterior = update_posterior(hyperparameters, mean_function, ...\n% covariance_function, x, posterior, x_star, y_star)\n%\n% Inputs:\n%\n% hyperparameters: a GPML hyperparameter struct\n% mean_function: a GPML mean function\n% covariance_function: a GPML covariance function\n% x: the previous observations (N x D)\n% posterior: a GPML posterior struct\n% x_star: the new observation location (1 x D)\n% y_star: the new observation value\n%\n% Output:\n%\n% new_posterior: the updated GPML posterior struct for the GP\n% conditioned on ([x; x_star], [y; y_star]).\n%\n% See also INFMETHODS.\n\n% Copyright (c) 2013--2014 Roman Garnett.\n\nfunction new_posterior = update_posterior(hyperparameters, mean_function, ...\n covariance_function, x, posterior, x_star, y_star, y_sd)\n\n % check input\n if (numel(y_star) > 1)\n error('gpml_extensions:not_supported', ...\n 'update_posterior only supports rank-one updates!');\n end\n \n % Need to decide how to deal with noise\n if nargin < 8; y_sd = []; end\n\n noise_variance = exp(2 * hyperparameters.lik);\n\n k = feval(covariance_function{:}, hyperparameters.cov, x_star);\n k_star = feval(covariance_function{:}, hyperparameters.cov, x, x_star);\n\n [m_star, v_star] = gp(hyperparameters, [], mean_function, ...\n covariance_function, [], x, posterior, x_star);\n\n % update posterior.L; handle both high- and low-noise\n % parameterizations of posterior\n if (is_chol(posterior.L))\n % high-noise parameterization: posterior.L contains chol(K / sigma^2 + I)\n \n alpha_update = solve_chol(posterior.L, k_star) * (1 / noise_variance);\n\n new_L_column = linsolve(posterior.L, k_star, ...\n struct('UT', true, 'TRANSA', true)) * (1 / noise_variance);\n new_posterior.L = [posterior.L, new_L_column; ...\n zeros(1, size(posterior.L, 1)), ...\n sqrt(1 + k / noise_variance - new_L_column' * new_L_column)];\n else\n % low-noise parameterization: posterior.L contains -inv(K + \\sigma^2 I)\n\n alpha_update = -posterior.L * k_star;\n\n v = -alpha_update / v_star;\n new_posterior.L = [posterior.L + v * alpha_update', -v; -v', -1 / v_star];\n end\n\n % alpha_update now contains (K + \\sigma^2 I) \\ k*\n new_posterior.alpha = ...\n [posterior.alpha; 0] + ...\n (m_star - y_star) / v_star * [alpha_update; -1];\n\n % noise vector is constant; just add one more entry\n new_posterior.sW = posterior.sW([1; (1:end)']);\n\nend\n\n%--------------------------------------------------------------------------\nfunction result = is_chol(L)\n\n result = (ismatrix(L) && ...\n (size(L, 1) == size(L, 2)) && ...\n isreal(diag(L)) && ...\n all(diag(L) > 0) && ...\n isequal(L, triu(L)));\n\nend", "meta": {"author": "acerbilab", "repo": "bads", "sha": "019f0b432b9e157a31defbbd303aadcdf57862e7", "save_path": "github-repos/MATLAB/acerbilab-bads", "path": "github-repos/MATLAB/acerbilab-bads/bads-019f0b432b9e157a31defbbd303aadcdf57862e7/utils/update_posterior.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": "function g = lfmGradientUpsilon(gamma,sigma2,gradThetaGamma,t1, t2, mode)\n\n% LFMGRADIENTUPSILON Gradient of the function \\upsilon(z) with respect to\n% one of the hyperparameters of the kernel: m_k, C_k, D_k, m_r, C_r or D_r.\n% FORMAT\n% DESC Computes the gradient of the function \\upsilon(z) with respect to\n% one of the parameters of the system (mass, spring or damper).\n% ARG gamma : Gamma value of the system.\n% ARG sigma2 : length scale of latent process.\n% ARG gradThetaGamma : Vector with the gradient of gamma1 and gamma2 with\n% respect to the desired parameter.\n% ARG Tt1 : first time input (number of time points 1 x number of time points 2).\n% ARG Tt2 : second time input (number of time points 1 x number of time points 2).\n% ARG mode : indicates in which way the variables t1 and t2 must be\n% transposed\n% RETURN g : Gradient of the kernel with respect to the desired\n% parameter.\n%\n% COPYRIGHT : David Luengo, Mauricio Alvarez 2008\n%\n% SEEALSO : lfmKernGradient, lfmXlfmKernGradient, lfmGradientH\n\n% KERN\n\n\n%Parameters of the function\n\nsigma = sqrt(sigma2);\n\n% Initialization of vectors and matrices\n\nswitch mode\n case 1\n % In this mode the Tt1 is actually the Tt1 and Tt2 is actually Tt2\n % Z1 is a matrix with order given by Tt1 and z2 is a vector with\n % order given by Tt2\n Tt11 = repmat(t1, 1, size(t2, 1));\n Tt22 = repmat(t2', size(t1, 1), 1);\n Z1 = (Tt11-Tt22)/sigma - sigma*gamma/2;\n z2 = t2/sigma + sigma*gamma/2;\n Z2 = repmat(z2.', size(t1, 1), 1);\n [preFactorZ1, gradPreFactorZ1] = quadrantWofzGrad(Z1, sigma,1);\n [preFactorz2, gradPreFactorz2] = quadrantWofzGrad(z2, sigma,1);\n Tt1minusTt2 = Tt11 - Tt22;\n preFactor1 = exp(sigma2*(gamma^2)/4 - gamma*(Tt1minusTt2)...\n + log(sigma2*gamma - 2*(Tt1minusTt2)) + log(gradThetaGamma));\n preFactor2 = exp(-(Tt1minusTt2).*(Tt1minusTt2)/sigma2 ...\n + log(gradThetaGamma) + log(gradPreFactorZ1));\n preFactor3 = exp(repmat((-t2.*t2/sigma2).',size(t1, 1), 1) ...\n - gamma*Tt11 + log(gradThetaGamma)...\n + log(Tt11.*repmat(preFactorz2.',size(t1, 1), 1) ...\n + repmat((gradPreFactorz2).',size(t1, 1), 1)));\n case 2\n\n % In this mode the Tt1 is actually the Tt2 and Tt2 is actually Tt1\n % Z1 is a matrix with the order given by Tt2 and z2 is a vector\n % with the order given by Tt1\n\n Tt11 = repmat(t2', size(t1, 1), 1);\n Tt22 = repmat(t1, 1, size(t2, 1));\n Z1 = (Tt11-Tt22)/sigma - sigma*gamma/2;\n z2 = t1/sigma + sigma*gamma/2;\n Z2 = repmat(z2, 1, size(t2, 1));\n [preFactorZ1, gradPreFactorZ1] = quadrantWofzGrad(Z1, sigma,1);\n [preFactorz2, gradPreFactorz2] = quadrantWofzGrad(z2, sigma,1);\n Tt1minusTt2 = Tt11 - Tt22;\n preFactor1 = exp(sigma2*(gamma^2)/4 - gamma*(Tt1minusTt2)...\n + log(sigma2*gamma - 2*(Tt1minusTt2)) + log(gradThetaGamma));\n preFactor2 = exp(-(Tt1minusTt2).*(Tt1minusTt2)/sigma2 ...\n + log(gradThetaGamma) + log(gradPreFactorZ1));\n preFactor3 = exp( repmat(-t1.*t1/sigma2,1, size(t2, 1))...\n - gamma*Tt11 + log(gradThetaGamma) ...\n + log(Tt11.*repmat(preFactorz2,1, size(t2, 1)) + repmat(gradPreFactorz2,1, size(t2, 1))));\n\n\n case {3,4}\n\n % In this mode Tt1 is actually Tt1 and Tt2 is zero.\n % Z1 is a vector and Z2 is a scalar\n z1 = t1/sigma - sigma*gamma/2;\n z2 = sigma*gamma/2;\n Z1 = repmat(z1, 1, size(t2,1));\n Z2 = repmat(z2, size(t1, 1), size(t2,1));\n [preFactorz1, gradPreFactorz1] = quadrantWofzGrad(z1, sigma,1);\n [preFactorz2, gradPreFactorz2] = quadrantWofzGrad(z2, sigma,1);\n preFactor1 = repmat(exp(sigma2*(gamma^2)/4 - gamma*(t1) ...\n + log(sigma2*gamma - 2*t1) + log(gradThetaGamma)), 1, size(t2, 1));\n preFactor2 = repmat(exp(-t1.*t1/sigma2 + log(gradThetaGamma)...\n + log(gradPreFactorz1)), 1, size(t2, 1));\n preFactor3 = repmat(exp(- gamma*t1 + log(gradThetaGamma) ...\n + log(t1*preFactorz2 + gradPreFactorz2)),1, size(t2, 1));\n\nend\n\ng = zeros(size(preFactor1));\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% 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": "function X=diag(X,k)\n%DIAG (overloaded)\n\nn = X.dim(1);\nm = X.dim(2);\n\nif nargin == 1\n k = 0;\nend\n\nif min([n m])==1\n Y = X;\n\tdiagX = diag(X.basis(:,1),k);\n\tY.basis = diagX(:);\n\tfor i = 1:length(X.lmi_variables)\n\t\tdiagX = diag(X.basis(:,i+1),k);\n\t\tY.basis(:,i+1) = diagX(:);\n end\n\tY.lmi_variables = X.lmi_variables;\n\tY.dim(1) = size(diagX,1);\n\tY.dim(2) = size(diagX,2);\n X=Y;\nelse\n index = diag(reshape(1:n*m,n,m),k);\n X.basis = X.basis(index,:);\n\tX.dim(1) = length(index);\n\tX.dim(2) = 1;\n X = clean(X);\nend\n% Reset info about conic terms\nif isa(X,'sdpvar')\n X.conicinfo = [0 0];\nend", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/extras/@ncvar/diag.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.49642937091764944}} {"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 [M, TF] = padcat(varargin)\n% PADCAT - concatenate vectors with different lengths by padding with NaN\n%\n% M = PADCAT(V1, V2, V3, ..., VN) concatenates the vectors V1 through VN\n% into one large matrix. All vectors should have the same orientation,\n% that is, they are all row or column vectors. The vectors do not need to\n% have the same lengths, and shorter vectors are padded with NaNs.\n% The size of M is determined by the length of the longest vector. For\n% row vectors, M will be a N-by-MaxL matrix and for column vectors, M\n% will be a MaxL-by-N matrix, where MaxL is the length of the longest \n% vector.\n%\n% Examples:\n% a = 1:5 ; b = 1:3 ; c = [] ; d = 1:4 ;\n% padcat(a,b,c,d) % row vectors\n% % -> 1 2 3 4 5\n% % 1 2 3 NaN NaN\n% % NaN NaN NaN NaN NaN\n% % 1 2 3 4 NaN\n% CC = {d.' a.' c.' b.' d.'} ;\n% padcat(CC{:}) % column vectors\n% % 1 1 NaN 1 1\n% % 2 2 NaN 2 2\n% % 3 3 NaN 3 3\n% % 4 4 NaN NaN 4\n% % NaN 5 NaN NaN NaN\n%\n% [M, TF] = PADCAT(..) will also return a logical matrix TF with the same\n% size as R having true values for those positions that originate from an \n% input vector. This may be useful if any of the vectors contain NaNs.\n%\n% Example:\n% a = 1:3 ; b = [] ; c = [1 NaN] ;\n% [M,tf] = padcat(a,b,c)\n% % find the original NaN\n% [Vev,Pos] = find(tf & isnan(M))\n% % -> Vec = 3 , Pos = 2\n%\n% This second output can also be used to change the padding value into\n% something else than NaN.\n%\n% [M, tf] = padcat(1:3,1,1:4) \n% M(~tf) = 99 % change the padding value into 99\n%\n% Scalars will be concatenated into a single column vector.\n%\n% See also CAT, RESHAPE, STRVCAT, CHAR, HORZCAT, VERTCAT, ISEMPTY\n% NONES, GROUP2CELL (Matlab File Exchange)\n\n% for Matlab 2008 and up (tested in R2011a)\n% version 1.2 (oct 2011)\n% (c) Jos van der Geest\n% email: jos@jasen.nl\n\n% History\n% 1.0 (feb 2009) created\n% 1.1 (feb 2011) improved comments\n% 1.2 (oct 2011) added help on changing the padding value into something\n% else than NaN\n\n% Acknowledgements:\n% Inspired by padadd.m (feb 2000) Fex ID 209 by Dave Johnson\n\nerror(nargchk(1,Inf,nargin)) ;\n\n% check the inputs\nSZ = cellfun(@size,varargin,'UniformOutput',false) ; % sizes\nNdim = cellfun(@ndims,varargin) ; % \n\nif ~all(Ndim==2)\n error([mfilename ':WrongInputDimension'], ...\n 'Input should be vectors.') ;\nend\n\nTF = [] ; % default second output so we do not have to check all the time\n\n% for 2D matrices (including vectors) the size is a 1-by-2 vector\nSZ = cat(1,SZ{:}) ;\nmaxSZ = max(SZ) ; % probable size of the longest vector\n% maxSZ equals :\n% - [1 1] for all scalars input\n% - [X 1] for column vectors\n% - [1 X] for all row vectors\n% - [X Y] otherwise (so padcat will not work!)\n\nif ~any(maxSZ == 1), % hmm, not all elements are 1-by-N or N-by-1\n % 2 options ...\n if any(maxSZ==0),\n % 1) all inputs are empty\n M = [] ;\n return\n else\n % 2) wrong input \n % Either not all vectors have the same orientation (row and column\n % vectors are being mixed) or an input is a matrix.\n error([mfilename ':WrongInputSize'], ...\n 'Inputs should be all row vectors or all column vectors.') ;\n end\nend\n\nif nargin == 1,\n % single input, nothing to concatenate ..\n M = varargin{1} ;\nelse\n % Concatenate row vectors in a row, and column vectors in a column.\n dim = (maxSZ(1)==1) + 1 ; % Find out the dimension to work on\n X = cat(dim, varargin{:}) ; % make one big list\n\n % we will use linear indexing, which operates along columns. We apply a\n % transpose at the end if the input were row vectors.\n\n if maxSZ(dim) == 1,\n % if all inputs are scalars, ...\n M = X ; % copy the list\n elseif all(SZ(:,dim)==SZ(1,dim)),\n % all vectors have the same length\n M = reshape(X,SZ(1,dim),[]) ;% copy the list and reshape\n else\n % We do have vectors of different lengths.\n % Pre-allocate the final output array as a column oriented array. We\n % make it one larger to accommodate the largest vector as well.\n M = zeros([maxSZ(dim)+1 nargin]) ;\n % where do the fillers begin in each column\n M(sub2ind(size(M), SZ(:,dim).'+1, 1:nargin)) = 1 ;\n % Fillers should be put in after that position as well, so applying\n % cumsum on the columns\n % Note that we remove the last row; the largest vector will fill an\n % entire column.\n M = cumsum(M(1:end-1,:),1) ; % remove last row\n\n % If we need to return position of the non-fillers we will get them\n % now. We cannot do it afterwards, since NaNs may be present in the\n % inputs.\n if nargout>1,\n TF = ~M ;\n % and make use of this logical array\n M(~TF) = NaN ; % put the fillers in\n M(TF) = X ; % put the values in\n else\n M(M==1) = NaN ; % put the fillers in\n M(M==0) = X ; % put the values in\n end\n end\n\n if dim == 2,\n % the inputs were row vectors, so transpose\n M = M.' ;\n TF = TF.' ; % was initialized as empty if not requested\n end\nend % nargin == 1\n\nif nargout > 1 && isempty(TF),\n % in this case, the inputs were all empty, all scalars, or all had the\n % same size.\n TF = true(size(M)) ;\nend\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/22909-padcat/padcat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.49640366333401026}} {"text": "function [cc] = in32cc(in3)\n% Convert volume from cubic inches to cubic centimeters*. \n% * Not to be confused with cubic cubits.\n% Chad Greene 2012\ncc = in3*16.387064;", "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/in32cc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.4964036599251532}} {"text": "function w = ymdf_to_weekday_republican ( y, m, d, f )\n\n%*****************************************************************************80\n%\n%% YMDF_TO_WEEKDAY_REPUBLICAN returns the weekday of a Republican YMDF date.\n%\n% Discussion:\n%\n% The Republican calendar used a 10 day week.\n% There was a final \"month\" of 5 or 6 days.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 March 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer Y, M, D, real F, the YMDF date.\n%\n% Output, integer W, the day of the week of the date.\n% The days are numbered from Sunday through Saturday, 1 through 7.\n%\n w = i4_wrap ( d, 1, 10 );\n\n return\nend", "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/ymdf_to_weekday_republican.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.4964036529616676}} {"text": "function varargout = spm_resels_vol(varargin)\n% computes the number of resels in a volume - a compiled routine\n% FORMAT R = spm_resels_vol(V,W)\n% V - is a memory mapped image volume.\n% Finite and non-zero values are considered to be part of\n% the search volume.\n% W - smoothness of the component fields {FWHM in voxels}.\n% R - Resel counts, where:\n% R(1) - Euler Characteristic of the volume (number of connected\n% components - number of holes).\n% R(2) - Resel Diameter (average over all rotations of the\n% distance between two parallel planes tangent to the\n% volume in resel space).\n% R(3) - Resel Surface Area (half the surface area of the\n% volume in resel space).\n% R(4) - Resel Volume (the volume in resel space).\n%_______________________________________________________________________\n%\n% Reference : Worsley KJ et al 1996, Hum Brain Mapp. 4:58-73\n%_______________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% John Ashburner\n% $Id: spm_resels_vol.m 1143 2008-02-07 19:33:33Z spm $\n\n\n%-This is merely the help file for the compiled routine\nerror('spm_resels_vol.c not compiled - see Makefile')\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_resels_vol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127417985637, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4963821159480646}} {"text": "%fsqfindewq(lambda,mu,c,m)\n% This function finds the average waiting time in the queue\n% (ewq) for a machine repair problem (finite source queue)\n\nfunction out = fsqfindewq(lambda,mu,c,m)\n\nld = fsqfindld(lambda,mu,c,m);\nlu = fsqfindlu(lambda,mu,c,m);\n\newq = ld/(lambda*lu);\n\nout = ewq;", "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/1250-queueing-systems-toolbox/fsqfindewq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.496360377769754}} {"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 f = not(f)\n%~ CLASSICFUN logical NOT.\n% NOT(F) returns a CLASSICFUN which evaluates to one at all points where F is\n% zero and one otherwise. F cannot have any roots in its domain. If F\n% does have roots, then LOGICAL(F) will return garbage with no warning. F may\n% be complex.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nf.onefun = not(f.onefun);\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/@classicfun/not.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7577943603346811, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.49627552717687}} {"text": "function varargout=phaseplot(f,varargin)\n%PHASEPLOT Phase plot\n% Usage: phaseplot(f,op1,op2, ... );\n% phaseplot(f,fs,op1,op2, ... );\n%\n% `phaseplot(f)` plots the phase of f using a |dgt|.\n%\n% `phaseplot(f,fs)` does the same for a signal with sampling rate *fs* Hz.\n%\n% `phaseplot` should only be used for short signals (shorter than the\n% resolution of the screen), as there will otherwise be some visual\n% aliasing, such that very fast changing areas will look very smooth.\n% `phaseplot` always calculates the phase of the full time/frequency plane\n% (as opposed to |sgram|), and you therefore risk running out of memory\n% for long signals.\n%\n% `phaseplot` takes the following flags at the end of the line of input\n% arguments:\n%\n% 'tfr',v Set the ratio of frequency resolution to time resolution.\n% A value $v=1$ is the default. Setting $v>1$ will give better\n% frequency resolution at the expense of a worse time\n% resolution. A value of $01)>1\n error('Input must be a vector.');\nend;\n\ndefinput.import={'ltfattranslate','setnorm','tfplot'};\n% Override the setting from tfplot, because phaseplot only uses the 'lin'\n% plotting.\ndefinput.flags.log={'lin'};\ndefinput.importdefaults={'lin'};\n\n% Define initial value for flags and key/value pairs.\ndefinput.flags.wlen={'nowlen','wlen'};\ndefinput.flags.tc={'notc','tc'};\n\ndefinput.flags.fmax={'nofmax','fmax'};\ndefinput.flags.phase={'timeinv','freqinv'};\n\nif isreal(f)\n definput.flags.posfreq={'posfreq','nf'};\nelse\n definput.flags.posfreq={'nf','posfreq'};\nend;\n\ndefinput.keyvals.tfr=1;\ndefinput.keyvals.wlen=0;\ndefinput.keyvals.fmax=[];\ndefinput.keyvals.thr=[];\n\n[flags,kv,fs]=ltfatarghelper({'fs'},definput,varargin);\n\n% Downsample\nif ~isempty(kv.fmax)\n if ~isempty(fs)\n resamp=kv.fmax*2/fs;\n else\n resamp=kv.fmax*2/length(f);\n end;\n\n f=fftresample(f,round(length(f)*resamp));\n kv.fs=2*kv.fmax;\nend;\n\n% Always do the full STFT\nL=length(f);\na=1;\nb=1;\nM=L;\nN=L;\n\n% Set an explicit window length, if this was specified.\nif flags.do_wlen\n kv.tfr=kv.wlen^2/L;\nend;\n\ng={'gauss',kv.tfr,flags.norm};\n\nif flags.do_nf\n coef=dgt(f,g,a,M,flags.phase);\nelse\n coef=dgtreal(f,g,a,M,flags.phase);\nend;\n\nif ~isempty(kv.thr)\n % keep only the largest coefficients.\n maxc=max(abs(coef(:)));\n mask=abs(coef)0\n varargout={coef};\nend;\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/gabor/phaseplot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943603346811, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.49627552717687}} {"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": "function [data,net] = prepare_data(P,Y,net,P0,Y0)\n% \tPrepare Input Data for the use for NN Training and check for errors\n% \t\t\n% \tArgs:\n% \t\tP:\t\tneural network Inputs\n% \t\tY: \t\tneural network Targets\n% \t\tP0:\t\tprevious input data\n% \t\tY0:\t\tprevious output data\n% \t\tnet: \tneural network\n% \tReturns:\n% \t\tdata:\tstruct containing data for training or calculating putput\n\nif ~exist('P0', 'var')\n P0 = [];\nend\nif ~exist('Y0', 'var')\n Y0 = [];\nend\n\n% Ceck if input and output data match structure of NN\t\nif size(P,1) ~= net.nn(1)\n error('Dimension of Input Data P does not match number of inputs of the NN')\nend\nif size(Y,1) ~= net.nn(end)\n error('Dimension of Output Data Y does not match number of outputs of the NN')\nend\nif size(Y,2) ~= size(P,2)\n error('Input P and output Y must have same number of datapoints Q')\nend\n\n%check if previous data is given\nif (~isempty(P0)) && (~isempty(Y0))\n % Ceck if input and output of prevoius data match structure of NN\t\n if size(P0,1) ~= net.nn(1)\n error('Dimension of previous Input Data P0 does not match number of inputs of the NN')\n end\n if size(Y0,1) ~= net.nn(end)\n error('Dimension of previous Output Data Y0 does not match number of outputs of the NN')\n end\n if size(Y,2) ~= size(P,2)\n error('Previous Input and output data P0 and Y0 must have same number of datapoints Q0')\n end\n \n q0 = size(P0,2); %number of prevoius Datapoints given \n a=cell(q0,net.M); %initialise layer outputs\n for i=1:q0\n for j=1:net.M-1\n a{i,j}=zeros(net.nn(j+1),1); %layer ouputs of hidden layers are unknown -> set to zero\n end\n a{i,net.M}=Y0(:,i)./net.normY; %set layer ouputs of output layer \n end\n %add previous inputs and outputs to inpu/output matrices\n P_ = [P0,P];\n Y_ = [Y0,Y];\nelse\n\t%add previous inputs and outputs to inpu/output matrices\n P_ = P;\n Y_ = Y;\n q0=0;\n a={};\nend\n\n% normalize\nP_norm = P_;\nY_norm = Y_;\nif isfield(net, 'normP')==0\n normP = ones(size(P_,1),1);\n for p = 1:size(P_,1)\n normP(p) = max(max(abs(P_(p,:))),1.0);\n P_norm(p,:) = P_(p,:)./normP(p);\n end\n normY = ones(size(Y_,1),1);\n for y = 1:size(Y_,1)\n normY(y) = max(max(abs(Y_(y,:))),1.0);\n Y_norm(y,:) = Y_(y,:)./normY(y);\n end\n net.normP = normP;\n net.normY = normY;\nelse\n for p = 1:size(P_,1)\n P_norm(p,:) = P_(p,:)./net.normP(p);\n end\n for y = 1:size(Y_,1)\n Y_norm(y,:) = Y_(y,:)./net.normY(y);\n end\nend\n\n%Create data dict\ndata = {};\t\t\ndata.P = P_norm;\ndata.Y = Y_norm;\ndata.a = a;\ndata.q0 = q0;\n\nend\n", "meta": {"author": "yabata", "repo": "pyrenn", "sha": "fdf48ca8dda83b6e66aeab1da5f36b421100a6dd", "save_path": "github-repos/MATLAB/yabata-pyrenn", "path": "github-repos/MATLAB/yabata-pyrenn/pyrenn-fdf48ca8dda83b6e66aeab1da5f36b421100a6dd/matlab/prepare_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.49622589377379944}} {"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": "% demo code for 3D human pose estimation from a monocular RGB image\n% this demo code uses CPM (Convolutional Pose Machines) for 2D pose\n% estimation, however, any 2D pose estimator from image can be applied.\n% prediction: The 2D pose, a 14X2 matrix, 14 corresponding position as\n% listed in the following order, 3 columns with [x y] coordinates.\n% (head)\n% (neck)\n% (right shoulder)\n% (right elbow)\n% (right wrist)\n% (left shoulder)\n% (left elbow)\n% (left wrist)\n% (right hip)\n% (right knee)\n% (right ankle)\n% (left hip)\n% (left knee)\n% (left ankle)\n\n%% setup\n% param = model_config();\nload('3D_library.mat');\n\n%% input image path\ntest_image = ['imgs/im0371.jpg'];\nim = imread(test_image);\n\n% load the precomputed 2D pose derived by Convolutional Pose Machines,\n% other 2D pose estimation methods is applicable, format the 2D pose in the\n% definition described above\nload('0371.mat');\n\n%{\n% get image size\n[H,W,~] = size(im);\n\n%% detect human using CPM\nrectangle(1) = 1; \nrectangle(2) = 1;\nrectangle(3) = W-1;\nrectangle(4) = H-1;\n[heatMaps, human_c] = applyModel_human3d(test_image, param, rectangle, 2);\n\n%% 2D pose estimation using CPM with the bounding box specified by the\n% detected human postition\nrectangle(1) = human_c(1) - 0.5*W;\nrectangle(2) = human_c(2) - 0.5*H;\nrectangle(3) = 1*W;\nrectangle(4) = 1*H;\n[heatMaps, prediction] = applyModel_human3d(test_image, param, rectangle, 1);\n%}\nPrediction{1}=prediction;\n\n% manually adjust two hips' position due to the variation across MPII and\n% H36M\nprediction(9,2) = prediction(9,2) - 20;\nprediction(12,2) = prediction(12,2) - 20;\n\n%% extract the nearest neighbor \n[j_p] = NN_pose(s1_s9_2d_n,s1_s9_3d,prediction);\n% [j_p] = kNN_pose_procrus(s1_s9_2d_n,s1_s9_3d,prediction, 10);\n\n% compute the scale between pixel and real world to recover real size of\n% prediction\nscale = (max(j_p(:,2))-min(j_p(:,2)))/(max(prediction(:,2))-min(prediction(:,2)));\n\n% predict the depth of each joint by the exemplar\nprediction(:,3) = j_p(:,3)/scale;\n\n\n%% visualization\nH=figure(); \nsubplot(1,3,[1 2]);imshow(im);\n% self-defined ground plane\nprediction(:,3) = prediction(:,3) - min(prediction(:,3)) + 1300;\nan_x_m = min(prediction(:,1));\nan_x_M = max(prediction(:,1));\nan_y_M = max(prediction(11,2),prediction(14,2));\nx = [an_x_m-100 an_x_M+100 an_x_m-100 an_x_M+100];\ny = [an_y_M-10 an_y_M-10 an_y_M+40 an_y_M+40];\nz = [min(prediction(:,3)-120) min(prediction(:,3)-120) max(prediction(:,3)+120) max(prediction(:,3)+120)];\nA = [x(:) y(:) z(:)];\n% solve for the ground plane\n[n,v,m,aved]=plane_fit(A);\n\n% draw the prediction on the input image\nvis_2d(prediction);\n\n% draw the 3D pose\nsubplot(1,3,3);\nvis_3d(prediction);\n\n% draw the ground plane\nplaneplot(A,n,m)\n\n% draw camera\nscale = 50;\nP = scale*[0 0 0;0.5 0.5 0.8; 0.5 -0.5 0.8; -0.5 0.5 0.8;-0.5 -0.5 0.8];\ncen = mean(prediction);P1=(P+repmat([cen(1:2), 800],[5,1]));\nline([P1(1,1) P1(2,1)],[P1(1,2) P1(2,2)],[P1(1,3) P1(2,3)],'color','k')\nline([P1(1,1) P1(3,1)],[P1(1,2) P1(3,2)],[P1(1,3) P1(3,3)],'color','k')\nline([P1(1,1) P1(4,1)],[P1(1,2) P1(4,2)],[P1(1,3) P1(4,3)],'color','k')\nline([P1(1,1) P1(5,1)],[P1(1,2) P1(5,2)],[P1(1,3) P1(5,3)],'color','k')\n\nline([P1(2,1) P1(3,1)],[P1(2,2) P1(3,2)],[P1(2,3) P1(3,3)],'color','k')\nline([P1(3,1) P1(5,1)],[P1(3,2) P1(5,2)],[P1(3,3) P1(5,3)],'color','k')\nline([P1(5,1) P1(4,1)],[P1(5,2) P1(4,2)],[P1(5,3) P1(4,3)],'color','k')\nline([P1(4,1) P1(2,1)],[P1(4,2) P1(2,2)],[P1(4,3) P1(2,3)],'color','k')\n\n% adjust the viewing angle\nview(26,-56);\naxis equal\naxis off", "meta": {"author": "flyawaychase", "repo": "3DHumanPose", "sha": "ef2d085fe575224dd79aabcef214611de78068e0", "save_path": "github-repos/MATLAB/flyawaychase-3DHumanPose", "path": "github-repos/MATLAB/flyawaychase-3DHumanPose/3DHumanPose-ef2d085fe575224dd79aabcef214611de78068e0/demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.49622588314475397}} {"text": "function kern = sdrbfKernParamInit(kern)\n\n% SDRBFKERNPARAMINIT SDRBF kernel initialization\n% FORMAT\n% DESC\n% Initializes the switching dynamical latent force model structure with\n% some initial parameters for the RBF underlying kernels. The initial \n% parameters are passed through an option in kern.\n% RETURN kern : the kernel structure with the default parameters placed in.\n% ARG kern : the kernel structure which requires initialisation.\n%\n% SEEALSO : kernCreate, kernParamInit, rbfKernParamInit\n%\n% COPYRIGHT : Mauricio A. Alvarez, 2010\n\n% KERN\n\n% Create the basic structure based on the lfm kernel.\nkern = rbfKernParamInit(kern);\n\n\nif isfield(kern, 'options') && isfield(kern.options, 'isNormalised') && ...\n kern.options.isNormalised,\n kern.isNormalised = 1;\nend\n\nif isfield(kern, 'options') && isfield(kern.options, 'nIntervals')\n kern.nIntervals = kern.options.nIntervals;\n if isfield(kern.options, 'nlfPerInt')\n kern.nlfPerInt = kern.options.nlfPerInt;\n else\n kern.nlfPerInt = 1;\n end\n kern.inverseWidth = ones(kern.nlfPerInt, kern.nIntervals); % Total number of inverse widths.\n % An option for the initialization of the switching times\n if isfield(kern.options, 'switchingTimes')\n if kern.nIntervals == length(kern.options.switchingTimes)\n kern.switchingTimes = kern.options.switchingTimes;\n else\n error('The number of intervals does not match the information of the swicthing time points')\n end\n else\n partition = linspace(-0.1,1, kern.nIntervals + 1);\n kern.switchingTimes = partition(1:end-1);\n end\nelse\n kern.nIntervals = 1;\n kern.switchingTimes = -0.1;\n warning('LFM:Instead:SDLFM', 'Use the LFM kernel instead.')\nend\n\n% Number of parameters computed as: inverseWidth (= nlf*nIntervals) and the\n% switching points (= nIntervals). The variance, which is a parameter in \n% the original rbf kernel, is not counted as a parameter. It's left here, \n% so that it can be used when making sdrbf kernel computations and gradients.\n\nkern.nParams = kern.nlfPerInt*kern.nIntervals + kern.nIntervals;\ndimParam = [kern.nlfPerInt*kern.nIntervals kern.nIntervals];\nkern.inverseWidthIndx = 1:dimParam(1);\nkern.switchingTimesIndx = dimParam(1)+1:sum(dimParam(1:2));\n%kern.transforms.index = 1:(kern.nlfPerInt*kern.nIntervals);\nkern.transforms.index = [1:(kern.nlfPerInt*kern.nIntervals) (kern.nlfPerInt*kern.nIntervals)+2:kern.nParams];\nkern.transforms.type = optimiDefaultConstraint('positive');\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/sdrbfKernParamInit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.629774621301746, "lm_q1q2_score": 0.4962190766201866}} {"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": "% This script test under 10-fold Cross Validation, divided by ID, how dtfv works\nfunction prob = test_dtfv_CV(part,feaMap, method)\naddpath('../../../toolbox/libsvm/matlab');\n%part = 1;\n%fea_path = '../dataset_trial/FVs';\ntrainfile = ['../Scripts_by_ID/trainVideo',num2str(part),'.txt'];\ntestfile = ['../Scripts_by_ID/testVideo',num2str(part),'.txt'];\n\nfid = fopen(trainfile);\nC = textscan(fid, '%s');\nfclose(fid);\nfea_types = {'mbhx','mbhy'};\nfea_dim = 24576*2;%+24576+27648;\n\nnum_v = length(C{1})/2;\ntrain_fea = zeros(num_v, fea_dim);\ntrain_lab = zeros(num_v, 1);\nfor i = 1:num_v\n [pathstr,name,ext] = fileparts(C{1}{2*i-1});\n videoname = [name,ext];\n s = findstr(name, 'lie');\n lab = isempty(s);\n fea = [];\n for j = 1: length(fea_types)\n %fea_file = fullfile(fea_path,[videoname,'.',fea_types{j},'.fv.txt']);\n %disp(fea_file)\n %fea = [fea, importdata(fea_file)];\n fea = [fea, feaMap([videoname,'.',fea_types{j},'.fv.txt'])];\n end\n train_fea(i,:) = fea;\n train_lab(i) = lab;\nend\n\n%% test phase\nfid = fopen(testfile);\nC = textscan(fid, '%s');\nfclose(fid);\nnum_v = length(C{1})/2;\ntest_fea = zeros(num_v, fea_dim);\ntest_lab = zeros(num_v, 1);\nfor i = 1:num_v\n [pathstr,name,ext] = fileparts(C{1}{2*i-1});\n videoname = [name,ext];\n s = findstr(name, 'lie');\n lab = isempty(s);\n fea = [];\n for j = 1: length(fea_types)\n %fea_file = fullfile(fea_path,[videoname,'.',fea_types{j},'.fv.txt']);\n %fea = [fea, importdata(fea_file)];\n fea = [fea, feaMap([videoname,'.',fea_types{j},'.fv.txt'])];\n end\n test_fea(i,:) = fea;\n test_lab(i) = lab;\nend\n\nswitch(method)\ncase 'NN'\n net = feedforwardnet(10);\n net.trainFcn = 'trainscg';\n net = configure(net, train_fea', train_lab');\n net = train(net, train_fea', train_lab');\n prob = net(test_fea');\ncase 'tree'\n tc = fitctree(train_fea, train_lab);\n [label,score,node,cnum] = predict(tc, test_fea);\n prob = score(:,1);\ncase 'randforest'\n BaggedEnsemble = TreeBagger(50,train_fea,train_lab,'OOBPred','On');\n [label,scores] = predict(BaggedEnsemble, test_fea);\n prob = scores(:,1);\ncase 'bayes'\n flag = bitand(var(train_fea(train_lab==1,:))>1e-10,var(train_fea(train_lab==0,:))>1e-10); %clear 0 variance features\n O1 = fitNaiveBayes(train_fea(:,flag), train_lab);\n C1 = posterior(O1, test_fea(:,flag));\n prob = C1(:,1);\ncase 'log'\n B = glmfit(train_fea, [train_lab ones(size(train_lab,1),1)], 'binomial', 'link', 'logit')\n Z = repmat(B(1), size(test_lab,1),1) + test_fea*B(2:end);\n prob = 1 ./ (1 + exp(-Z));\n prob = 1-prob;\ncase 'boost'\n ens = fitensemble(train_fea,train_lab,'AdaBoostM1',100,'Tree')\n [~, prob] = predict(ens,test_fea)\n prob = prob(:,1);\ncase 'linearsvm'\n %model = svmtrain(train_lab, train_fea, '-t 0 -b 1 -q')\n %fprintf('Finished training.\\n');\n %[pred, acc, prob] = svmpredict(test_lab,test_fea, model, '-b 1 -q');\n %prob = prob(:,2);\n\n model = svmtrain(train_lab, train_fea, '-t 0 -q')\n [pred, acc, prob] = svmpredict(test_lab,test_fea, model, ' -q');\n lie_id = find(prob<0); % find score <0 sample\n if ~isempty(lie_id) % if have such sample\n if pred(lie_id(1)) == 0 % if pred of the sample is deceptive, reverse the score\n isign = -1;\n else\n isign = 1;\n end\n else % if all sample scores >0\n if pred(1) == 1 % if pred is truthful, then reverse all scores\n isign = -1;\n else\n isign = 1;\n end\n end\n \n prob = isign*prob;\ncase 'kernelsvm'\n %model = svmtrain(train_lab, tmptrain_fea, '-t 0 -q -b 1');\n %fprintf('Finished training.\\n');\n %[pred, acc, prob] = svmpredict(test_lab, tmptest_fea, model, '-q -b 1');\n %prob = prob(:,2);\n model = svmtrain(train_lab, train_fea, '-t 1 -c 1 -g 1 -q');\n [pred, acc, prob] = svmpredict(test_lab, test_fea, model, '-q');\n\n lie_id = find(prob<0);\n if ~isempty(lie_id)\n if pred(lie_id(1)) == 0\n isign = -1;\n else\n isign = 1;\n end\n else\n if pred(1) == 1\n isign = -1;\n else\n isign = 1;\n end\n end\n prob = isign*prob;\nend\n\n", "meta": {"author": "Doubaibai", "repo": "DARE", "sha": "db991afa90629477b96918884fbb353e29383620", "save_path": "github-repos/MATLAB/Doubaibai-DARE", "path": "github-repos/MATLAB/Doubaibai-DARE/DARE-db991afa90629477b96918884fbb353e29383620/test_dtfv_CV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.4962190586004141}} {"text": "function vivmRunDataSet(dataSetName, invariance, experimentNo, ...\n selectionCriterion, dVal, seedVal);\n \n% VIVMRUNDATASET Try the virtual IVM on a data set and save the results.\n\n% IVM\n\nif nargin < 6\n seedVal = [];\n randn('seed', 1e5)\n rand('seed', 1e5)\nelse\n randn('seed', seedVal);\n rand('seed', seedVal);\nend\n\njobId = getenv('PBS_JOBID');\njobName = getenv('PBS_JOBNAME');\nfprintf('Seed %2.0e\\n', seedVal);\n\nif isempty(seedVal)\n [X, y, XTest, yTest] = mapLoadData(dataSetName);\nelse\n [X, y, XTest, yTest] = mapLoadData(dataSetName, seedVal);\nend\n\ncapitalName = dataSetName;\ncapitalName(1) = upper(capitalName(1));\n\noptions = ivmOptions;\noptions.extIters = 0; % don't optimise parameters\nmu = zeros(size(yTest));\nvarSigma = zeros(size(yTest));\n\nload(['dem' capitalName '_' ...\n num2str(experimentNo) '_' ...\n num2str(seedVal) '.mat'])\n\n% Create new training set with virtual SVs.\norigIndex = ivmInfoStore.I;\n[X, y] = ivmVirtual(X(ivmInfoStore.I, :), y(ivmInfoStore.I, ...\n :), invariance);\ntic\nmodel = ivmRun(X, y, kernStore, ...\n noiseStore, selectionCriterion, dVal, ...\n options);\n \nrunTime = toc;\nif ~isempty(XTest) & ~isempty(yTest);\n yPred = ivmOut(model, XTest);\n testError = 1-sum(yPred==yTest)/size(yTest, 1);\n fprintf('Data set %s, test error %2.4f\\n', dataSetName, testError);\nend\n[kern, noise, ivmInfo] = ivmDeconstruct(model);\nsave(['dem' capitalName '_' invariance '_' num2str(experimentNo) '_d' num2str(dVal) '_seed' num2str(seedVal)], 'testError', ...\n 'ivmInfo', 'kern', 'noise', 'runTime', 'jobId', ...\n 'jobName', 'origIndex')\n\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/ivm/vivmRunDataSet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.49621905312534326}} {"text": "% VL_DEMO_SIFT_MATCH Demo: SIFT: basic matching\n\npfx = fullfile(vl_root,'figures','demo') ;\nrandn('state',0) ;\nrand('state',0) ;\nfigure(1) ; clf ;\n\n% --------------------------------------------------------------------\n% Create image pair\n% --------------------------------------------------------------------\n\nIa = imread(fullfile(vl_root,'data','a.jpg')) ;\nIb = imread(fullfile(vl_root,'data','b.jpg')) ;\n\n% --------------------------------------------------------------------\n% Extract features and match\n% --------------------------------------------------------------------\n\n[fa,da] = vl_sift(im2single(rgb2gray(Ia))) ;\n[fb,db] = vl_sift(im2single(rgb2gray(Ib))) ;\n\n[matches, scores] = vl_ubcmatch(da,db) ;\n\n[drop, perm] = sort(scores, 'descend') ;\nmatches = matches(:, perm) ;\nscores = scores(perm) ;\n\nfigure(1) ; clf ;\nimagesc(cat(2, Ia, Ib)) ;\naxis image off ;\nvl_demo_print('sift_match_1', 1) ;\n\nfigure(2) ; clf ;\nimagesc(cat(2, Ia, Ib)) ;\n\nxa = fa(1,matches(1,:)) ;\nxb = fb(1,matches(2,:)) + size(Ia,2) ;\nya = fa(2,matches(1,:)) ;\nyb = fb(2,matches(2,:)) ;\n\nhold on ;\nh = line([xa ; xb], [ya ; yb]) ;\nset(h,'linewidth', 1, 'color', 'b') ;\n\nvl_plotframe(fa(:,matches(1,:))) ;\nfb(1,:) = fb(1,:) + size(Ia,2) ;\nvl_plotframe(fb(:,matches(2,:))) ;\naxis image off ;\n\nvl_demo_print('sift_match_2', 1) ;\n", "meta": {"author": "jianxiongxiao", "repo": "ProfXkit", "sha": "7376c50abf5ead846247774a36be026e6f24953c", "save_path": "github-repos/MATLAB/jianxiongxiao-ProfXkit", "path": "github-repos/MATLAB/jianxiongxiao-ProfXkit/ProfXkit-7376c50abf5ead846247774a36be026e6f24953c/SiftFu/SiftFu/SIFTransac/vlfeat/toolbox/demo/vl_demo_sift_match.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.496219048447552}} {"text": "%==============================================================================\n% This code is part of the Matlab-based toolbox\n% FAIR - Flexible Algorithms for Image Registration. \n% For details see \n% - https://github.com/C4IR and\n% - http://www.siam.org/books/fa06/\n%==============================================================================\n%\n% KERNEL/REGULARIZERS\n%\n% Contents of FAIR's Reguarization Toolbox\n% \n% general purpose tools:\n% contents - this file\n% regularizer - the specific regularizer used in FAIR\n% initialize: regularizer('reset','regularizer','mbElastic',...\n% 'alpha',1e3,'mu',1,'lambda',0);\n% use: [Sc,dS,d2S] = regularizer(yc-yRef,omega,m);\n%\n% The regularizers for NPIR are:\n% ------------------------------\n% curvature curvature regularizer (cell-centered grid, requires parameter alpha)\n% see, e.g., E10_2Ddisc2C_curvature\n% curvaturemexC matrix free C version of curvature regularizer\n% curvatureDiagMex matrix free access to the diagonal of the operator\n% curvatureHessianMex matrix free access to the second derivative of the operator\n \n% elastic (linear) elastic regularizer (staggered grid)\n% initialize: 'alpha', 'mu', 'lambda'\n% see, e.g., E10_2Ddisc2C_elastic\n% hyperelastic hyperelastic regularizer (nodal grid)\n% initialize: 'alphaLength', 'alphaArea', 'alphaVolume'\n% see, e.g., E10_2Ddisc2C_hyperElastic\n%\n% (linear) Differential operators are built in:\n%\n% getCurvatureMatrix generates curvature regularizer matrix (cell-centered grid)\n% getElasticMatrixNodal generates elastic regularizer matrix (nodal grid)\n% getElasticMatrixStg generates elastic regularizer matrix (staggeres grid)\n% getGradientNodal generates gradient operator matrix (nodal grid)\n%\n% For (nonlinear) hyperelastic regularization area and volume of tetrahedral partition \n% are computed in\n% geometry contains areas and volumes functions\n% used in hyperElastic\n% geometrymexC.h / .cpp MEX version of area and volume computation\n%\n%\n% =============================================================================\n\nfunction debit = contents\nif nargout == 0, help(mfilename); return; end;\n\ndebit = {\n 'contents.m'\n\n 'regularizer.m'\n \n 'elastic.m'\n 'getElasticMatrixNodal.m'\n 'getElasticMatrixStg.m'\n \n 'curvature.m'\n 'curvatureMexC.cpp'\n 'getCurvatureMatrix.m'\n 'curvatureDiagMex.cpp'\n 'curvatureHessianMex.cpp' \n\n 'geometry.m'\n 'geometryMexC.cpp'\n 'geometryMexC.h'\n 'geometryC.cpp'\n 'geometryC.h'\n 'hyperElastic.m'\n \n 'getGradientNodal.m'\n 'testRegularizers.m'\n };\n%==============================================================================\n", "meta": {"author": "C4IR", "repo": "FAIR.m", "sha": "975edebd37b833ae76696792870de5c05efcb9cb", "save_path": "github-repos/MATLAB/C4IR-FAIR.m", "path": "github-repos/MATLAB/C4IR-FAIR.m/FAIR.m-975edebd37b833ae76696792870de5c05efcb9cb/kernel/regularizers/contents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.496219048447552}} {"text": "function x = FMdemod(y,beta)\n\n[r, c] = size(y);\nif r*c == 0\n y = [];\n return;\nend;\nif (r == 1)\n y = y(:);\n len = c;\nelse\n len = r;\nend;\n\nFc = 40000;\nFs = 8000*20;\npi2 = 2*pi;\n\n [num, den] = butter(5, Fc * 2 / Fs);\n \n sen = 2*pi*beta*100;\n \n %pre-process the filter.\n if abs(den(1)) < eps\n error('First denominator filter coefficient must be non-zero.');\n else\n num = num/den(1);\n if (length(den) > 1)\n den = - den(2:length(den)) / den(1);\n else\n den = 0;\n end;\n num = num(:)';\n den = den(:)';\n end;\n len_den = length(den);\n len_num = length(num);\n\n x = y;\n y = 2 * y;\n\n ini_phase = pi/2;\n for ii = 1 : size(y, 2)\n z1 = zeros(length(den), 1);\n s1 = zeros(len_num, 1);\n intgl = 0;\n\n memo = 0;\n for i = 1:size(y, 1)\n %start with the zero-initial condition integer.\n vco_out = cos(pi2 * intgl+ini_phase);\n if len_num > 1\n s1 = [y(i, ii) * vco_out; s1(1:len_num-1)];\n else\n s1 = y(i, ii);\n end\n tmp = num * s1 + den * z1;\n if len_den > 1\n z1 = [tmp; z1(1:len_den-1)];\n else\n z1 = tmp;\n end;\n intgl = rem(((tmp*sen + Fc)/ Fs + intgl), 1);\n x(i, ii) = tmp;\n end;\n end;\n x = x;\nx = decimate(x,20);", "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/11122-frequency-modulation-and-demodulation/FMdemod.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4962180291499471}} {"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\u2013430. \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": "function sudoku_test02 ( )\n\n%*****************************************************************************80\n%\n%% SUDOKU_TEST02 demonstrates SUDOKU_DIGIT_PERMUTE.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 February 2006\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SUDOKU_TEST02:\\n' );\n fprintf ( 1, ' SUDOKU_DIGIT_PERMUTE permutes the digits\\n' );\n fprintf ( 1, ' of a Sudoku puzzle.\\n' );\n\n s = [ ...\n 0,0,1,9,0,0,0,0,8; ...\n 6,0,0,0,8,5,0,3,0; ...\n 0,0,7,0,6,0,1,0,0; ...\n 0,3,4,0,9,0,0,0,0; ...\n 0,0,0,5,0,4,0,0,0; ...\n 0,0,0,0,1,0,4,2,0; ...\n 0,0,5,0,7,0,9,0,0; ...\n 0,1,0,8,4,0,0,0,7; ...\n 7,0,0,0,0,9,2,0,0];\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Here is the initial Sudoku puzzle:\\n' );\n fprintf ( 1, '\\n' );\n\n sudoku_print ( s );\n \n permutation = [ 2, 3, 4, 5, 6, 7, 8, 9, 1 ];\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Here is the permutation:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Original Permuted\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : 9\n fprintf ( 1, ' %8d %8d\\n', i, permutation(i) );\n end\n\n s = sudoku_digit_permute ( permutation, s );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Here is the permuted Sudoku:\\n' );\n fprintf ( 1, '\\n' );\n\n sudoku_print ( 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/sudoku/sudoku_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646140788306, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.49609200271439724}} {"text": "function [edgeResponse, commonSize] = calculateEdgeCost(edgeImg, labels,labelIndices, labOne, labTwo)\nedgeResponse = 0;\ncommonSize = 0;\n% Find common border..\n\n\n[rC,cC] = size(labels);\ntemp = labelIndices{1,labOne};\nrowArr = temp(:,1);\ncolArr = temp(:,2);\n[realSize,~] = size(rowArr);\n\ntotalResp = 0;\ncommonSize = 0;\nfor i=1:realSize\n xCor = rowArr(i,1);\n yCor = colArr(i,1);\n \n if xCor + 1 <= rC\n if labels(xCor+1,yCor) == labTwo % Common border!\n commonSize = commonSize + 1;\n if edgeImg(xCor,yCor) ~= edgeImg(xCor+1,yCor)\n totalResp = totalResp + 1;\n end\n end\n end\n \n if xCor - 1 > 0\n if labels(xCor-1,yCor) == labTwo % Common border!\n commonSize = commonSize + 1;\n if edgeImg(xCor,yCor) ~= edgeImg(xCor-1,yCor)\n totalResp = totalResp + 1;\n end\n end\n end\n \n if yCor + 1 <= cC\n if labels(xCor,yCor+1) == labTwo % Common border!\n commonSize = commonSize + 1;\n if edgeImg(xCor,yCor) ~= edgeImg(xCor,yCor+1)\n totalResp = totalResp + 1;\n end\n end\n end\n \n if yCor - 1 > 0\n if labels(xCor,yCor-1) == labTwo % Common border!\n commonSize = commonSize + 1;\n if edgeImg(xCor,yCor) ~= edgeImg(xCor,yCor-1)\n totalResp = totalResp + 1;\n end\n end\n end\nend\n\nif commonSize ~=0\n edgeResponse = totalResp / commonSize;\nend\n\nend\n\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u8bc6\u522b\u7b97\u6cd5/Object Recognition based on super pixel/calculateEdgeCost.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.496091998783436}} {"text": "function test_suite = test_clusterize()\n% tests for cosmo_clusterize\n%\n% # For CoSMoMVPA's copyright information and license terms, #\n% # see the COPYING file distributed with CoSMoMVPA. #\n try % assignment of 'localfunctions' is necessary in Matlab >= 2016\n test_functions=localfunctions();\n catch % no problem; early Matlab versions can use initTestSuite fine\n end\n initTestSuite\n\nfunction test_clusterize_basics\n ds=cosmo_synthetic_dataset('size','normal','ntargets',1,'nchunks',1);\n sample=ds.samples;\n\n nh_struct=cosmo_cluster_neighborhood(ds,'progress',false);\n nh=cosmo_convert_neighborhood(nh_struct,'matrix');\n\n x=sample;\n sample=x>2;\n cl1=cosmo_clusterize(sample,nh);\n assertEqual(cl1,{21,25});\n nb=cosmo_convert_neighborhood(nh,'cell');\n\n sample=round(x/2);\n cl2=cosmo_clusterize(sample,nh);\n assertEqual(cl2,{[1 11 9 14 17 21 22 23 26 30 25]',...\n [3 6]',28});\n\n % test exceptions\n aet=@(varargin)assertExceptionThrown(@()...\n cosmo_clusterize(varargin{:}),'');\n aet('foo',[]);\n aet(sample,[]);\n aet(sample,-1);\n aet('foo',nh);\n aet(zeros([2 2 2 ]),nh);\n aet([sample;sample],nh);\n aet(sample,zeros([1 1 6]));\n aet(sample,ones(1,7));\n aet(sample,[true;false;true;true;true;false]);\n\n", "meta": {"author": "CoSMoMVPA", "repo": "CoSMoMVPA", "sha": "5de75a1b4bef89b082d39d69e2b99d7f894ad717", "save_path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA", "path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA/CoSMoMVPA-5de75a1b4bef89b082d39d69e2b99d7f894ad717/tests/test_clusterize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.4960919970579166}} {"text": "function [x,state] = struct_sum(z,task,dim)\n%STRUCT_SUM Sum of elements.\n% [x,state] = struct_sum(z,[],dim) computes x as sum(z,dim), or as\n% sum(z(:)) if dim is the empty matrix [] or not supplied. The structure\n% state stores information which is reused in computing the right and\n% left Jacobian-vector products.\n%\n% struct_sum(z,task,dim) computes the right or left Jacobian-vector\n% product of this transformation, depending on the structure task. Use\n% the structure state and add the field 'r' of the same shape as z or the\n% field 'l' of the same shape as x to obtain the structure task for\n% computing the right and left Jacobian-vector products\n% \n% (dF(:)/dz(:).')*task.r(:) and\n% (dF(:)/dz(:).')'*task.l(:) + conj((dF(:)/dconj(z(:)).')'*task.l(:)),\n% \n% respectively. Here, F(z) represents this transormation, (:) signifies\n% vectorization and the derivative w.r.t. z (conj(z)) is a partial\n% derivative which treats conj(z) (z) as constant. The output has the\n% same shape as x or z for the right and left Jacobian-vector products,\n% respectively.\n% \n% See also struct_prod.\n\n% Authors: Laurent Sorber (Laurent.Sorber@cs.kuleuven.be)\n% Marc Van Barel (Marc.VanBarel@cs.kuleuven.be)\n% Lieven De Lathauwer (Lieven.DeLathauwer@kuleuven-kulak.be)\n%\n% References:\n% [1] L. Sorber, M. Van Barel, L. De Lathauwer, \"Structured data fusion,\"\n% ESAT-SISTA Internal Report 13-177, KU Leuven, 2013.\n\nif nargin < 2, task = []; end\nif nargin < 3, dim = []; end\nstate = [];\n\nif isempty(task)\n if isempty(dim), x = sum(z(:));\n else x = sum(z,dim);\n end\nelseif ~isempty(task.r)\n if isempty(dim), x = sum(task.r(:));\n else x = sum(task.r,dim);\n end\nelseif ~isempty(task.l)\n if isempty(dim), siz = size(z);\n else siz = ones(1,ndims(z)); siz(dim) = size(z,dim);\n end\n x = repmat(task.l,siz);\nend\n\nend\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/libs/+tensorlab/struct_sum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.49609199398971515}} {"text": "% add activation of all previous layers, which are required to have the\n% same size. \n% \nclassdef AddNode < GraphNode\n \n methods\n function obj = AddNode(dimOut)\n obj = obj@GraphNode('Add',dimOut);\n end\n \n function obj = forward(obj,prev_layers)\n obj = obj.preprocessingForward(prev_layers);\n obj.a = prev_layers{1}.a;\n for i=2:length(prev_layers)\n obj.a = obj.a + prev_layers{i}.a;\n end\n obj = forward@GraphNode(obj, prev_layers);\n end\n \n function obj = backward(obj,prev_layers, future_layers)\n if obj.skipGrad || obj.skipBP\n return;\n end\n \n future_grad = obj.GetFutureGrad(future_layers);\n for i=1:length(prev_layers)\n obj.grad{i} = future_grad;\n end\n\n obj = backward@GraphNode(obj, prev_layers, future_layers);\n end\n \n end\n \nend", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/graph_obj/nodes/AddNode.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.4960919861277924}} {"text": "function scalar2d = slice_scalar3d(scalar3d, normal_axis, intercept)\n\nchkarg(istypesizeof(scalar3d, 'Scalar3d'), '\"scalar3d\" should be instance of Scalar3d.');\nchkarg(istypesizeof(normal_axis, 'Axis'), '\"normal_axis\" should be instance of Axis.');\nchkarg(istypesizeof(intercept, 'real'), '\"intercept\" should be real.');\n\ngrid3d = scalar3d.grid3d;\n[h, v, n] = cycle(normal_axis);\nchkarg(grid3d.comp(n).contains(intercept), ...\n\t'\"intercept\" should be contained in %s-axis range.', char(n));\n\nlall = grid3d.lall(Axis.elems + Axis.count*subsindex(scalar3d.gt_array));\nnall = lall{n};\n\nind = {':', ':', ':'};\nindn = ismembc2(intercept, nall);\nif indn ~= 0\n\tind{n} = indn;\n\tarray = scalar3d.array(ind{:});\nelse\n% \twarning('Maxwell:interp', 'slice at %s = %s is not grid plane where %s is defined; fields are interpolated.', ...\n% \t\tchar(n), num2str(intercept), scalar3d.name);\n\n\tindn = find(nall < intercept, 1, 'last');\n\tind{n} = [indn indn+1];\n\n\tV = scalar3d.array(ind{:});\n\tl = lall;\n\tl{n} = nall(ind{n});\n\t[Xh, Yv, Zn] = ndgrid(l{:});\n\n\tli = lall;\n\tli{n} = intercept;\n\t[XIh, YIv, ZIn] = ndgrid(li{:});\n\n\tarray = interpn(Xh, Yv, Zn, V, XIh, YIv, ZIn);\nend\n\narray = permute(array, int([h v n]));\nassert(ndims(array) == Dir.count);\n\ngrid2d = Grid2d(grid3d, n);\nscalar2d = Scalar2d(array, grid2d, scalar3d.gt_array([h v]), scalar3d.osc, scalar3d.physQcell, scalar3d.name, intercept);\n", "meta": {"author": "wsshin", "repo": "maxwellfdfd", "sha": "f7d583813781694c8a6f0533a91f56c2a78a9ee5", "save_path": "github-repos/MATLAB/wsshin-maxwellfdfd", "path": "github-repos/MATLAB/wsshin-maxwellfdfd/maxwellfdfd-f7d583813781694c8a6f0533a91f56c2a78a9ee5/io/slice_scalar3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.4958379747787031}} {"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": "function ncV=grComp(E,n)\n% Function ncV=grComp(E,n) find all components of the graph.\n% Input parameter: \n% E(m,2) - the edges of graph;\n% 1st and 2nd elements of each row is numbers of vertexes;\n% m - number of edges.\n% n - number of vertexes ( optional, by default n=max(max(E)) ).\n% This input parameter is needed, if last vertexes is isolated.\n% Output parameter:\n% ncV(n,1) - the the vector-column with the number of component \n% for each vertex;\n% Author: Sergiy Iglin\n% e-mail: siglin@yandex.ru\n% personal page: http://iglin.exponenta.ru\n\nif nargin<1,\n error('There are no input data!')\nend\n[m,n1,E1] = grValidation(E); % data validation\nE2=[E1(:,1:2);E1(:,[2 1])]; % all arrows and vice versa\n[Dec,Ord]=grDecOrd(E2); % the components\nncV=sum(Dec*diag([1:size(Dec,2)]),2); % the numbers of components\nif (nargin>1)&(n>n1), % last isolated vertexes\n ncV=[ncV;[1:n-n1]'+max(ncV)];\nend\nreturn", "meta": {"author": "HuangCongQing", "repo": "Algorithms_MathModels", "sha": "e15b0e9053b11f08b5ce1e3492c4acb444409c8b", "save_path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels", "path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels/Algorithms_MathModels-e15b0e9053b11f08b5ce1e3492c4acb444409c8b/GraphTheory(\u56fe\u8bba)/basic/grComp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.4958379573715508}} {"text": "function x = p22_start ( n )\n\n%*****************************************************************************80\n%\n%% P22_START returns a starting point for optimization for problem 22.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 December 2000\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of variables X.\n%\n% Output, real X(N), a starting point for the optimization.\n%\n x = ( linspace ( - 5.12, + 5.12, 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/test_opt/p22_start.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.661922862511608, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.4958379486679744}} {"text": "function y = reshape1d(x)\n% y = reshape1d(x)\n% Reshapes matrix x into 1-D column vector y.\n%\n% $Id: reshape1d.m,v 1.1 2004/03/12 07:31:58 sayres Exp $\n\n\ny = reshape(x, [prod(size(x)) 1]);\n\nreturn;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/EventRelated/reshape1d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.4958379486679744}} {"text": "function [hPlot] = plot_CDF(vDistribution, hAxes, sColor)\n % Plots the cumulative density function of a given distribution.\n %\n % [hPlot] = plot_CDF(vDistribution, hAxes, sColor)\n % ---------------------------------------------------------\n % NaN values are removed from the distribution.\n %\n % plot_CDF(vDistribution) opens a figure and plots the cumulative density function\n % with default parameters.\n %\n % Input parameters:\n % vDistribution Distribution of values to be plotted\n % hAxes Handle of axes to plot the cumulative density function\n % sColor Color of plot (refer to Matlab 'plot')\n %\n % Output parameters:\n % hPlot Handle of the plot\n %\n % Danijel Schorlemmer\n % July 9, 2003\n \n report_this_filefun();\n \n % Define missing input parameters\n if ~exist('hAxes', 'var')\n figure;\n hAxes = newplot;\n end\n if ~exist('sColor', 'var')\n sColor = 'k';\n end\n \n % Remove NaN-values\n vSel = ~isnan(vDistribution);\n vPlotDist = vDistribution(vSel,:);\n \n % Activate given axes\n axes(hAxes);\n \n % Plot the cumulative density function\n nLen = length(vPlotDist);\n vIndices = [1:nLen]/nLen;\n vDist = sort(vPlotDist);\n hPlot = plot(vDist, vIndices, sColor);\nend", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/danijel/plot/plot_CDF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.4958352048102651}} {"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 varargout = ihashsum(varargin)\n% VL_IHASHSUM Accumulate integer labels into a hash table\n% [H,ID,NEXT] = VL_IHASHSUM(H,ID,NEXT,K,X) counts the number of\n% occurences of the columns of X, accumulating these to the hash\n% table represented by the tripled H,ID,NEXT.\n%\n% X is a D x N array of class UINT8 each row of which defines an D\n% dimensional label. Labels cannot be all zeros.\n%\n% H and NEXT are 1 x C arrays of class UINT32 and ID is a D x C\n% array of class UINT8. H is a vector of counts, ID stores, for each\n% element of H, the corresponding label, and NEXT is a vector of\n% indexes.\n%\n% Once constructed, the hash table can be searched by means of the\n% VL_IHASHFIND() function.\n%\n% The hash table uses double hashing [1] with an initial size equal\n% to K (so that C >= K). Given a label X, this is first hashed by\n% using the FNV algorithm [2] to one of K bucket. If this bucket is\n% free, it is assigned to label X and the count is incremented. If\n% the bucket is already assigned to the same label X, the count is\n% incremented. If the bucket is already assigned to a different\n% label, a second hash is used to scan (probe) the table for a free\n% bucket.\n%\n% If no free/matching bucket is found (because the hash table is\n% full) an overflow area containing extra buckets is used. This is\n% visited by reading off indexe from the NEXT vector, until a\n% matching bucket is found or the overflow area is enlarged.\n%\n% Example::\n% The following example counts integer bi-dimensional label\n% occurences:\n%\n% K = 5 ;\n% h = zeros(1,K,'uint32') ;\n% id = zeros(2,K,'uint8');\n% next = zeros(1,K,'uint32') ;\n% X = uint8([1 1 ; 1 2 ; 2 1 ; 1 1]') ;\n% [h,id,next] = vl_ihashsum(h,id,next,K,X) ;\n%\n% resulting in\n%\n% h = [1 0 1 2 0]\n% id = [1 0 2 1 0\n% 2 0 1 1 0]\n% next = [0 0 0 0 0]\n%\n% For example, [1;2] has a count of 1 and [1;1] has a count of\n% 2. NEXT is zero because there have been no collisions.\n%\n% REFERENCES::\n% [1] http://en.wikipedia.org/wiki/Double_hashing\n% [2] http://www.isthe.com/chongo/tech/comp/fnv\n%\n% See also: VL_IHASHFIND().\n[varargout{1:nargout}] = vl_ihashsum(varargin{:});\n", "meta": {"author": "yihui-he", "repo": "panorama", "sha": "0c993d4ba6780dcb175b2c1fc7d25b513b7bb39b", "save_path": "github-repos/MATLAB/yihui-he-panorama", "path": "github-repos/MATLAB/yihui-he-panorama/panorama-0c993d4ba6780dcb175b2c1fc7d25b513b7bb39b/lib/vlfeat-0.9.20/toolbox/noprefix/ihashsum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.4958351873235613}} {"text": "function sphere_llt_grid_display_test ( )\n\n%*****************************************************************************80\n%\n%% SPHERE_LLT_GRID_DISPLAY_TEST tests SPHERE_LLT_GRID_DISPLAY.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 April 2015\n%\n% Author:\n%\n% John Burkardt\n%\n lat_num = 10;\n long_num = 12;\n pc(1,1:3) = [ 0.0, 0.0, 0.0 ];\n r = 10.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPHERE_LLT_GRID_DISPLAY_TEST\\n' );\n fprintf ( 1, ' SPHERE_LLT_GRID_DISPLAY displays an LLT grid on a sphere.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of latitudes is %d\\n', lat_num );\n fprintf ( 1, ' Number of longitudes is %d\\n', long_num );\n%\n% Get points.\n%\n node_num = sphere_llt_grid_point_count ( lat_num, long_num );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The number of grid points is %d\\n', node_num );\n\n node_xyz = sphere_llt_grid_points ( r, pc, lat_num, long_num, node_num );\n%\n% Get lines.\n%\n line_num = sphere_llt_grid_line_count ( lat_num, long_num );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of line segments is %d\\n', line_num );\n\n line_data = sphere_llt_grid_lines ( lat_num, long_num, line_num );\n\n filename = 'sphere_llt_grid.png';\n\n sphere_llt_grid_display ( r, pc, lat_num, long_num, node_num, node_xyz, line_num, ...\n line_data, filename );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sphere_llt_grid/sphere_llt_grid_display_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.49578475502712266}} {"text": "function [w,winit_pix]=init_w(method,peval,image)\n% [w,winit_pix]=init_w(method,peval,image)\n% method: 'rand' %random initialization\n% 'image' %specified initialization for example image=double(array2im(dpixc_ind)) \n% 'image_repmat' %for example image = mean(image,3); \n% 'res' %image is res.w -> initialisation from the nmf results\n% addbackgroundcomponent: 1 adds one component flat component as a background (peval.ncomp th)\n% 0 no background component\nif ~isfield(peval, 'bgcomp')\n peval.bgcomp = 1;\nend\n\nswitch method\n case 'rand'\n winit_pix = normalize(rand(peval.nx,peval.ny,peval.ncomp)); \n msg='W initialzied as uniform random.';\n case 'image'\n winit_pix = normalize(image);\n msg='W initialized with specified 3D image.';\n case 'image_repmat'\n winit_pix(:,:,1:peval.ncomp) = normalize(repmat(image,[1,1,peval.ncomp]));\n msg='W initialized as repmat(image,[1,1,peval.ncomp].)';\n case 'res'\n s2=size(image,2); %it is only 2D (#pixX#comp)\n winit_pix(:,:,1:s2) = reshape(image, peval.nx, peval.ny, s2);\n msg='W initialized from the results res.w.';\nend\nwinit_pix=max(winit_pix, eps); % To avoid zeros...\nsw=size(winit_pix);\nw=reshape(winit_pix,sw(1)*sw(2), size(winit_pix,3)); % it must be specifically set to size(winit_pix,3) for the case tehre is only one compoenent (ncomp=1)\n\nif isfield (peval,'fid')\n mfprintf(peval.fid, [msg '\\n'])\nelse\n fprintf([msg '\\n']);\nend\n\nif peval.bgcomp\n w(:,peval.ncomp)=normalize(ones(sw(1)*sw(2),1));\n mfprintf(peval.fid, 'Last component [%g] of w initialised as a flat background. (background=%g)\\n',peval.ncomp,peval.bg); \nend", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/initialization/init_w.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.49574645258047384}} {"text": "function z = power( x, y, op )\n\n%POWER Internal cvx version.\n\npersistent BP\nif isempty( BP ),\n BP.map = cvx_remap( ...\n ... % Invalid combinations: zero ^ negative, posynomial ^ negative\n { { 'zero', 'g_posynomial', 'gg_monomial' }, { 'negative' } }, ...\n ... % Constant\n { { 'constant' } }, ...\n ... % constant ^ convex/concave\n { { 'positive' }, { 'convex', 'concave' } }, ...\n ... % geometric ^ real\n { { 'l_valid_' }, { 'real' } }, ...\n ... % other non-constant ^ real\n { { 'valid' }, { 'real' } }, [0,1,2,3,4] );\n BP.funcs = { @power_c, @power_e, @power_g, @power_p };\n BP.constant = 1;\nend\nif isnumeric( y ) && numel( y ) == 1,\n switch y,\n case 1, z = x; return\n case 2, z = square( x ); return\n case 0.5, z = sqrt( x ); return \n case -1, z = recip( x ); return\n end\nend\nif nargin < 3, op = '.^'; end\nBP.name = op;\nz = cvx_binary_op( BP, x, y );\n\nfunction z = power_c( x, y )\nz = builtin( 'power', x, y );\n\nfunction z = power_e( x, y )\nz = exp( log( cvx_constant( x ) ) .* y );\n\nfunction z = power_g( x, y )\nz = exp( log( x ) .* y );\n\nfunction z = power_p( x, y )\nnx = numel( x );\nny = numel( y );\ny = cvx_constant( y );\nvx = cvx_classify( x );\nnz = max( nx, ny );\nif ny == 1\n pu = y;\n multp = false;\nelse\n pu = sort( y' ); %#ok'\n pu = pu( [ true, diff(pu) ~= 0 ] );\n multp = length( pu ) ~= 1;\nend\nif multp,\n zp = cvx( nz, [] );\n vp = vx;\n xp = x;\n yp = y;\nend\nerrs = {};\nfor pk = pu,\n if multp,\n tp = yp == pk;\n if nx > 1, \n x = cvx_fastref( xp, tp );\n x = cvx( [size(x,2),1], x );\n vx = vp( tp ); \n end\n if ny > 1, \n y = yp( tp ); \n end\n end\n y1 = y(1);\n if y == 2,\n z = square( x );\n elseif y1 > 1,\n z = power_cvx( x, vx, y1 );\n elseif y1 == 1,\n z = x;\n elseif y1 > 0,\n z = power_ccv( x, vx, y1 );\n elseif y1 == 0,\n z = cvx( ones(size(x)) );\n else\n z = power_neg( x, vx, y1 );\n end\n if islogical( z ),\n errs(end+1,:) = { cvx_subsref( x, z ), y }; %#ok\n continue\n end\n if nx ~= nz,\n z = repmat( z, [nz,1] );\n end\n if multp,\n zp = cvx_fastasgn( zp, tp, z );\n end\nend\nif multp\n z = zp;\nend\nif ~isempty( errs ),\n cvx_dcp_error( errs, op );\nelseif multp\n z = zm;\nend\n\n%\n% P > 1, integer: X affine, p-convex, n-concave\n% P > 1, non-integer: X affine, p-convex\n%\n\nfunction y = power_cvx_fast( x, p ) %#ok\nne = 0;\nnx = numel( x );\nwhile rem(p,2) == 0,\n ne = ne + 1;\n p = p * 0.5;\nend\ncvx_begin\n epigraph variable y(nx) nonnegative_\n if ne > 0,\n variables z2(nx,ne-1)\n if p == 1,\n w = y;\n else\n variable w(nx)\n end\n { [x,z2], 0.5, [z2,w] } == rotated_lorentz( [ nx, ne ], 3 ); %#ok\n else\n w = x;\n end\n if p > 1,\n { [y,ones(nx,1)], w } == geo_mean_cone( [ nx, 2 ], 2, [1/p,1-1/p], 'func' ); %#ok\n end\ncvx_end\n\nfunction y = power_cvx( x, v, p )\npersistent remap remap_i remap_e\nif isempty( remap_e ),\n remap = cvx_remap( 'affine', 'p_convex' );\n remap_i = cvx_remap( 'p_convex' ) - cvx_remap( 'n_concave' );\n remap_e = remap_i | remap;\nend\nif ~isempty( v ),\n isint = rem( p, 1 ) == 0;\n if isint,\n isevn = rem( p, 2 ) == 0;\n if isevn,\n v = remap_e( v );\n else\n v = remap_i( v );\n end\n else\n v = remap( v );\n end\n if ~all( v ),\n y = v == 0;\n return\n end\n v = 1 - 2 * ( v(:) == 3 );\n x = linearize( v .* x );\nelse\n isint = false;\nend\ny = power_cvx_fast( x, p );\nif isint,\n y = v .* y; \nend\n\n%\n% 0 < P < 1: X concave\n%\n\nfunction y = power_ccv( x, v, p )\npersistent remap\nif isempty( remap ),\n remap = ~cvx_remap( 'concave' );\nend\nv = remap( v );\nif any( v ),\n y = v;\n return\nend\ncvx_begin\n hypograph variable y(numel(x)) nonnegative_\n power_cvx_fast( y, 1.0 / p ) <= x; %#ok\ncvx_end\n\n%\n% P < 0, integer: p-concave, n-convex\n% P < 0, non-integer: p-concave\n%\n\nfunction y = power_neg( x, v, p )\npersistent remap remap_i\nif isempty( remap_i ),\n remap = cvx_remap( 'p_concave' );\n remap_i = remap - cvx_remap( 'n_convex' );\nend\nif rem( p, 1 ) == 0,\n % Integer: positive and negative lobes\n v = remap_i( v );\nelse\n % Non-integer: positive lobe only\n v = remap( v );\nend\nif ~all( v ),\n y = v == 0;\n return\nend\nnx = numel(x);\nz = linearize( v .* x );\ncvx_begin\n epigraph variable y(nx)\n if p == 1,\n { 2, z, y } == rotated_lorentz( [nx,1], 2, 0 ); %#ok\n else\n { [z,y], 1 } == geo_mean_cone( [nx,2], 2, [-p,1], 'func' ); %#ok\n end\n cvx_setnneg(y);\ncvx_end\ny = v .* y;\n\n% Copyright 2005-2014 CVX Research, Inc.\n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/cvx-w64/cvx/builtins/@cvx/power.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.63341024983754, "lm_q1q2_score": 0.4957464363320486}} {"text": "function sucra() \n % This script evaluates the percentage of space time coevered by\n %alarms\n %\n % turned into function by Celso G Reyes 2017\n \n ZG=ZmapGlobal.Data; % used by get_zmap_globals\n global iala\n re = [];\n % Stefan Wiemer 4/95\n \n report_this_filefun();\n \n abo = abo2;\n \n for tre2 = min(abo(:,4)):0.1:max(abo(:,4)-0.1)\n abo = abo2;\n abo(:,5) = abo(:,5)* days(ZG.bin_dur) + ZG.primeCatalog.Date(1);\n l = abo(:,4) >= tre2;\n abo = abo(l,:);\n l = abo(:,3) < ZG.tresh_km;\n abo = abo(l,:);\n set(gca,'NextPlot','add')\n \n % space time volume covered by alarms\n if isempty(abo)\n Va = 0;\n else\n Va = sum(pi*abo(:,3).^2)*iala;\n end\n \n % All space time\n [len, ncu] = size(cumuall);\n \n r = loc(3,:);\n %r = reshape(cumuall(len,:),length(gy),length(gx));\n %r=reshape(normlap2,length(yvect),length(xvect));\n l = r < ZG.tresh_km;\n V = sum(pi*r(l).^2*(teb-t0b));\n disp([' Zalarm = ' num2str(tre2)])\n disp([' =============================================='])\n disp([' Total space-time volume (R 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 s = char(ker)\n\n% CHAR\n%\n% Return a textual representation of a polynomial kernel object.\n%\n% str = char(ker);\n\n%\n% File : @polynomial/char.m\n%\n% Date : Tuesday 12th Spetember 2000\n%\n% Author : Dr Gavin C. Cawley\n%\n% Description : Cast a polynomial kernel object to a character string.\n% 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, September 2000.\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n%\n\ns = ['polynomial (d = ' num2str(ker.d) ')'];\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/@polynomial/char.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.4956839312118448}} {"text": "function hb_io_test11 ( )\n\n%*****************************************************************************80\n%\n%% HB_IO_TEST11 tests HB_MATVEC_A_MEM;\n%\n% Modified:\n%\n% 04 February 2005\n%\n ncol = 32;\n neltvl = 0;\n nnzero = 126;\n nrhs = 2;\n nrhsix = 0;\n nrow = 32;\n\n colptr = [ ...\n 1, 7, 12, 18, 22, 26, 29, 34, 39, 46, ...\n 53, 58, 61, 63, 65, 68, 71, 74, 79, 82, ...\n 85, 88, 90, 94, 97, 102, 106, 110, 112, 117, ...\n 121, 124, 127 ]';\n exact = [ ...\n 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, ...\n 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ...\n 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ...\n 0.0, 0.0;\n 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, ...\n 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, ...\n 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, ...\n 1.0, 1.0 ]';\n guess = [ ...\n 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, ...\n 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, ...\n 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, ...\n 1.0, 1.0;\n 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, ...\n 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, ...\n 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, ...\n 1.0, 1.0 ]';\n indcrd = 8;\n indfmt = '(16I5)';\n key = 'RUA_32';\n mxtype = 'RUA';\n output_file = 'rua_32_ax.txt';\n ptrcrd = 3;\n ptrfmt = '(16I5)';\n rhscrd = 12;\n rhsfmt = '(10F7.1)';\n rhsind = 0;\n rhsptr = 0;\n rhstyp = 'FGX';\n rhsvec = 0;\n rowind = [ ...\n 1, 2, 3, 4, 7, 26, 1, 2, 9, 21, ...\n 28, 2, 3, 6, 8, 9, 29, 3, 4, 5, ...\n 12, 3, 5, 23, 27, 1, 6, 16, 3, 7, ...\n 14, 21, 31, 1, 8, 12, 17, 27, 7, 9, ...\n 10, 13, 19, 23, 27, 1, 10, 11, 21, 23, ...\n 25, 27, 2, 11, 15, 18, 29, 6, 12, 24, ...\n 11, 13, 3, 14, 2, 15, 20, 4, 16, 22, ...\n 4, 16, 17, 6, 10, 18, 20, 30, 1, 19, ...\n 26, 8, 16, 20, 3, 21, 32, 11, 22, 2, ...\n 17, 21, 23, 12, 24, 26, 6, 15, 18, 24, ...\n 25, 13, 18, 22, 26, 5, 24, 26, 27, 9, ...\n 28, 3, 5, 27, 29, 32, 12, 17, 23, 30, ...\n 13, 14, 31, 24, 28, 32 ]';\n title = '1Real unsymmetric assembled matrix based on IBM32';\n totcrd = 36;\n valcrd = 13;\n valfmt = '(10F7.1)';\n values = [ ...\n 101.0, 102.0, 103.0, 104.0, 107.0, ...\n 126.0, 201.0, 202.0, 209.0, 221.0, ...\n 228.0, 302.0, 303.0, 306.0, 308.0, ...\n 309.0, 329.0, 403.0, 404.0, 405.0, ...\n 412.0, 503.0, 505.0, 523.0, 527.0, ...\n 601.0, 606.0, 616.0, 703.0, 707.0, ...\n 714.0, 721.0, 731.0, 801.0, 808.0, ...\n 812.0, 817.0, 827.0, 907.0, 909.0, ...\n 910.0, 913.0, 919.0, 923.0, 927.0, ...\n 1001.0, 1010.0, 1011.0, 1021.0, 1023.0, ...\n 1025.0, 1027.0, 1102.0, 1111.0, 1115.0, ...\n 1118.0, 1129.0, 1206.0, 1212.0, 1224.0, ...\n 1311.0, 1313.0, 1403.0, 1414.0, 1502.0, ...\n 1515.0, 1520.0, 1604.0, 1616.0, 1622.0, ...\n 1704.0, 1716.0, 1717.0, 1806.0, 1810.0, ...\n 1818.0, 1820.0, 1830.0, 1901.0, 1919.0, ...\n 1926.0, 2008.0, 2016.0, 2020.0, 2103.0, ...\n 2121.0, 2132.0, 2211.0, 2222.0, 2302.0, ...\n 2317.0, 2321.0, 2323.0, 2412.0, 2424.0, ...\n 2426.0, 2506.0, 2515.0, 2518.0, 2524.0, ...\n 2525.0, 2613.0, 2618.0, 2622.0, 2626.0, ...\n 2705.0, 2724.0, 2726.0, 2727.0, 2809.0, ...\n 2828.0, 2903.0, 2905.0, 2927.0, 2929.0, ...\n 2932.0, 3012.0, 3017.0, 3023.0, 3030.0, ...\n 3113.0, 3114.0, 3131.0, 3224.0, 3228.0, ...\n 3232.0 ]';\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HB_IO_TEST11\\n' );\n fprintf ( 1, ' HB_MATVEC_A_MEM multiplies a matrix times a vector.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' This particular version assumes:\\n' );\n fprintf ( 1, ' * the matrix is in \"A\" format (assembled),\\n' );\n fprintf ( 1, ' * the matrix and vectors can fit in memory,\\n' );\n fprintf ( 1, ' * the matrix and multiplicand have been read into\\n' );\n fprintf ( 1, ' memory before the routine is called.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' For this example, the first vector X is zero except\\n' );\n fprintf ( 1, ' for a 1 in row 10. This means A*X should return\\n' );\n fprintf ( 1, ' column 10 of A.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The second vector X is all 1''s. A*X should be\\n' );\n fprintf ( 1, ' the sum of the entries of each row.\\n' );\n\n rhsval = hb_matvec_a_mem ( nrow, ncol, nnzero, nrhs, colptr, rowind, ...\n values, exact );\n\n r8mat_print ( nrow, nrhs, rhsval, ' The product vectors A*X' );\n\n output_unit = fopen ( output_file, 'wt' );\n\n if ( output_unit < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST11 - Fatal error!\\n' );\n fprintf ( 1, ' Error opening the file.\\n' );\n return;\n end\n\n hb_file_write ( output_unit, title, key, totcrd, ptrcrd, indcrd, ...\n valcrd, rhscrd, mxtype, nrow, ncol, nnzero, neltvl, ptrfmt, indfmt, ...\n valfmt, rhsfmt, rhstyp, nrhs, nrhsix, colptr, rowind, values, ...\n rhsval, rhsptr, rhsind, rhsvec, guess, exact );\n\n fclose ( output_unit );\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/hb_io/hb_io_test11.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.4956839269607855}} {"text": "function varargout = imChainPixels(img, varargin)\n%IMCHAINPIXELS Chain neighbor pixels in an image to form a contour\n%\n% POINTS = imChainPixels(IMG)\n% [PX, PY] = imChainPixels(IMG)\n% returns a list of points, chaining points visible in the image.\n% IMG shoud be a binary image, containing a single 8-connected loop.\n%\n% Example\n% img = imread('circles.png');\n% img = imFillHoles(img);\n% bnd = imSkeleton(imBoundary(img));\n% figure; subplot(1, 3, 1); imshow(img);\n% subplot(1, 3, 2); imshow(imOverlay(img, bnd));\n% pts = imChainPixels(bnd);\n% subplot(1, 3, 3); imshow(img); hold on; \n% drawPolygon(pts, 'g', 'linewidth', 2);\n%\n% See Also\n% imFillHoles, imSkeleton, bwboundaries\n%\n% -----\n% author: David Legland \n% INRA - TPV URPOI - BIA IMASTE\n% created the 01/11/2003.\n%\n\n% HISTORY\n% 2004-04-06 add to graph lib, correct x-y ordering, and add doc.\n% 2012-05-16 rename from findContour to imChainPixels\n\n\n% set to logical\nimg = img ~= 0;\n\n% find points in the image\n[pty, ptx] = find(img);\n\n\n% Initialize iteration: first set the initial point\npoints = zeros(length(ptx), 2);\nx0 = ptx(1);\ny0 = pty(1);\npoints(1, 1) = x0;\npoints(1, 2) = y0;\n\n% Then set the second point, in the neighbourhood of the first point\nvois = findNeighbors(img, [x0 y0]);\nx = vois(1, 1);\ny = vois(1, 2);\npoints(2, 1) = x;\npoints(2, 2) = y;\n\n% For each point, find all neighbours (should be only 2)\n% Compare with point previously processed, and choose the other one.\n% then shift points references, and loop until all points are processed.\nfor p=3:length(points)\n vois = findNeighbors(img, [x y]);\n if vois(1,1)==x0 && vois(1,2)==y0\n x0 = x;\n y0 = y;\n x = vois(2, 1);\n y = vois(2, 2);\n else\n x0 = x;\n y0 = y;\n x = vois(1, 1);\n y = vois(1, 2);\n end\n points(p, 1) = x;\n points(p, 2) = y;\nend\n\n\n% format results to match output\nif nargout==1\n varargout{1} = points;\nelseif nargout==2\n varargout{1} = points(:, 1);\n varargout{2} = points(:, 2);\nend\n\n\nreturn\n\n\n\nfunction neighList = findNeighbors(img, coord)\n\nxp = coord(1);\nyp = coord(2);\nneighList = [];\nnv = 0;\n\nfor x = xp-1:xp+1\n if img(yp-1, x)\n nv = nv+1;\n neighList(nv, 1) = x; %#ok\n neighList(nv, 2) = yp-1; %#ok\n end\n if img(yp+1, x)\n nv = nv+1;\n neighList(nv, 1) = x; %#ok\n neighList(nv, 2) = yp+1; %#ok\n end\nend\n\nif img(yp, xp-1)\n nv = nv+1;\n neighList(nv, 1) = xp-1;\n neighList(nv, 2) = yp;\nend\nif img(yp, xp+1)\n nv = nv+1;\n neighList(nv, 1) = xp+1;\n neighList(nv, 2) = yp;\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/imFilters/imChainPixels.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.4956839264799733}} {"text": "function [matrix xmin xmax ymin ymax]=grd_read_v2(namefile)\n% Function to read a GRD file\n% (from Golden Software Surfer, ASCII format)\n%\n% [matrix xmin xmax ymin ymax]=grd_read_v2(name of file)\n%\n% Input:\n% nomarch = name of the file to be read, including \".grd\" extension\n% Output:\n% matrix = matrix of the read data\n% xmin xmax ymin ymax = grid limits\n%\n% Coded by Alberto Avila Armella.\n% UPDATED & IMPROVED BY Jose Maria Garcia-Valdecasas\n\ngrdfile=fopen(namefile,'r'); % Open file\ncode=fgetl(grdfile); % Reads surfer code 'DSAA'\n% Grid dimensions (number of nodes)\naux=str2num(fgetl(grdfile)); nx=aux(1); ny=aux(2);\n% X limits\naux=str2num(fgetl(grdfile)); xmin=aux(1); xmax=aux(2);\n% Y limits\naux=str2num(fgetl(grdfile)); ymin=aux(1); ymax=aux(2);\n% Z limits\naux=str2num(fgetl(grdfile)); zmin=aux(1); aux(2);\n% Read matrix\n[matrix,count] = fscanf(grdfile, '%f', [nx,ny]);\nmatrix=matrix'; % Trasposes matrix\n\nfclose(grdfile);\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/20880-surfer-grid-importexport/grd_read_v2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.49568392246932025}} {"text": "function laith()\n% LAITH Graphical Simulation of an elevator system\n% laith() creates a GUI with the number of floors as input. Granting this number\n% creates a building with this number of floors and an elevator that moves up\n% and down in it according to the will of animated people (modeled as balls).\n%\n% To run, type laith in the command window or press F5 from this editor window.\n% \n% Laith Alkurdi is the name of a friend who worked with me on the code.\n%\n% Husam Aldahiyat\n% Feb. 2009\n% numandina@gmail.com\n%\n%\n%% Creating Figure and Uicontrols\n% create figure\nfigure('units','normalized','position',[.1 .1 .8 .8],'color',[1 1 1],...\n\t'menubar','none','numbertitle','off','name','Elevator')\n\n% create axes\naxes('position',[.35 .1 .65 .9])\n\n% create pushbutton (Start)\npb=uicontrol('style','pushbutton','units','normalized','position',...\n\t[.1 .5 .04 .025],'backgroundcolor',[1 1 1],'string','Start',....\n\t'fontweight','bold','callback',@dogo);\n\n% create edit box\ned2=uicontrol('style','edit','units','normalized','position',[.1 .525 .04 .025],...\n\t'backgroundcolor',[1 1 1],'fontweight','bold');\n\n% create text (Floors)\nuicontrol('style','text','units','normalized','position',[.1 .55 .04 .025],...\n\t'backgroundcolor',[1 1 1],'string','Floors','fontweight','bold')\n\n% creates debug text \ntee=uicontrol('style','text','foregroundcolor',[1 0 0],'units','normalized',...\n\t'position',[.025 .6 .25 .35],'backgroundcolor',[0 0 0],'max',2,'fonts',15,...\n\t'fontname','courier');\n\n% this is so the the floor numbers on the z-axis will have dotted lines\n% showing their connection to the elevator\ngrid on\n\n% initially, we can't see the axes\naxis off\n\n% this is just so we can move the camera around during play\nrotate3d\n\n%% Drawing the Elevator\n% when we press the pushbutton we go here\n\tfunction dogo(varargin)\n\t\t\n\t\t% if we press the 'Start' button, change its string to 'Stop'\n\t\tif strcmp(get(pb,'string'),'Start')\n\t\t\tset(pb,'string','Stop')\n\t\telse\n\t\t\t\n\t\t\t% if we press the 'Stop' button, change its string to 'Start' and\n\t\t\tset(pb,'string','Start')\n\t\t\t\n\t\t\t% clear the axes\n\t\t\tcla\n\t\t\t\n\t\t\t% and halt operation\n\t\t\treturn\n\t\tend\n\t\t\n\t\t% make axes appear\n\t\taxis on\n\t\t\n\t\t% clear debugging text\n\t\tset(tee,'string','')\n\t\t\n\t\t% get number of floors and turn it from string to number\n\t\tflrz=str2double(get(ed2,'string'));\n\t\t\n\t\t% check input\n\t\tif flrz < 2\n\t\t\terrordlg('Number of floors needs to be at least 2','Stupid!')\n\t\t\tset(pb,'string','Start')\n\t\t\treturn\n\t\tend\n\t\t\n\t\t% this is compensated later by adding 1 to flrz\n\t\t% it's stupid but I like to do things like this\n\t\tflrz=flrz-1;\n\t\t\n\t\t% the following (a) and (b) matrices are very important. they create our\n\t\t% 'cube' shape.\n\t\t% the first column of (a) determines the min and max values for the (x),\n\t\t% the second for (y) and third for (z). So initially we have a unit cube\n\t\t% because the min and max for (x),(y) and (z) are (0) and (1).\n\t\ta= [0 0 0;\n\t\t\t1 0 0;\n\t\t\t1 1 0;\n\t\t\t0 1 0;\n\t\t\t0 0 1;\n\t\t\t1 0 1;\n\t\t\t1 1 1;\n\t\t\t0 1 1];\n\t\t\n\t\t% this (b) matrix specifies the faces of said cube. The cube has six faces\n\t\t% and eight vertices (points). the first row of (b) specifies which points\n\t\t% of (a) lie on the [b] face. \n\t\t% For example, the first face is (1,2,6,5), which are the rows of (a).\n\t\t% This mean the points [0,0,0],[1,0,0],[1,0,1] and [0,0,1] lie on the\n\t\t% first face, and so on.\n\t\tb= [1 2 6 5;\n\t\t\t2 3 7 6;\n\t\t\t3 4 8 7;\n\t\t\t4 1 5 8;\n\t\t\t1 2 3 4;\n\t\t\t5 6 7 8];\n\t\t\n\t\t% we want to make the elevator shaft first.\n\t\tac=a;\n\t\t\n\t\t% take the max for (z) and multiply it by the number of floors. I have\n\t\t% decided that each floor is (0.2) high.\n\t\tac(5:8,3)=.2*(flrz+1);\n\t\t\n\t\t% make the 3D patch that has height of the number of floors. this will act\n\t\t% as the elevator shaft, or building which our elevator will move\n\t\t% through in.\n\t\t% the facealpha makes the shaft kind of transparent so you would see the\n\t\t% people inside\n\t\tpatch('vertices',ac,'faces',b,'edgecolor','k','facecolor',[.3 .3 .3],...\n\t\t\t'facevertexalphadata',0.5,'facealpha','flat');\n\t\t\n\t\t% next we make the elevator itself\n\t\tc=a;\n\t\t\n\t\t% for this, just make the (z) column of (a) from (0) to (0.2),\n\t\t% this means our elevator is placed initially between (0) and (0.2)\n\t\t% in the (z) axis\n\t\tc(:,3)=c(:,3).*.2;\n\t\t\n\t\t% create our elevator!\n\t\telv=patch('vertices',c,'faces',b,'edgecolor','w','facecolor',[0 0 1],...\n\t\t\t'facevertexalphadata',0.3,'facealpha','flat');\n\t\t\n\t\t% next we will make the two elevator doors\t\t\n\t\tc1=a;\n\t\t\n\t\t% the (x) of these doors is zero (flat!)\n\t\tc1(:,1)=c1(:,1).*0;\n\t\t\n\t\t% the (z) is the same as the elevator\n\t\tc1(:,3)=[0;0;0;0;.2;.2;.2;.2];\n\t\t\n\t\t% for the first door, the (y) goes from (0) to (0.5)\n\t\tc1(:,2)=c1(:,2).*.5;\n\t\t\n\t\t% create door number one!\n\t\tdoor1 = patch('vertices',c1,'faces',b,'edgecolor','k','facecolor',...\n\t\t\t[0 0 .8],'facevertexalphadata',1,'facealpha','flat','linewidth',2);\n\t\t\n\t\t% same thing for our second door\n\t\tc2=a;\n\t\t\n\t\t% flat (x)\n\t\tc2(:,1)=c2(:,1).*0;\n\t\t\n\t\t% (z) from (0) to (0.2)\n\t\tc2(:,3)=[0;0;0;0;.2;.2;.2;.2];\n\t\t\n\t\t% (y) from (0.5) to (1)\n\t\tc2(:,2)=c2(:,2).*.5+.5;\n\t\t\n\t\t% create second door!\n\t\tdoor2 = patch('vertices',c2,'faces',b,'edgecolor','k','facecolor',[0 0 1],'facevertexalphadata',1,'facealpha','flat',...\n\t\t\t'linewidth',2);\n\t\t\n\t\t% next we want to make flat surfaces for each ground as a reference\n\t\t\n\t\t% for each floor go through the loop\n\t\tfor jk=1:flrz+1\n\t\t\t\n\t\t\tpk=a;\n\t\t\t\n\t\t\t% make the (z) equal a number multiple of (0.2)\n\t\t\t% since the min and max of (z) are the same, the resulting surface\n\t\t\t% is flat\n\t\t\tpk(:,3)=repmat(.2*(jk-1),8,1);\n\t\t\t\n\t\t\t% create this floor\n\t\t\tpatch('vertices',pk,'faces',b,'edgecolor','k','facecolor','k','facevertexalphadata',0.9,'facealpha','flat');\n\t\t\t\n\t\tend\n\t\t\n\t\t% by now we'll have a transparent elevator shaft with floors and an\n\t\t% elevator inside. we'll next want to cover one of the shaft sides with\n\t\t% a kind of curtain patch right above and below the elevator.\n\t\t% to do this, we will create two patches, one right above the elevator\n\t\t% and extends to the roof, while the other will have a min of the ground\n\t\t% and a max of the lower limits of our elevators.\n\t\t% these two patches will have the cyan face colour\n\t\t\n\t\t% flat (x)\n\t\tar=[0 0 0;\n\t\t\t0 0 0;\n\t\t\t0 1 0;\n\t\t\t0 1 0;\n\t\t\t0 0 1;\n\t\t\t0 0 1;\n\t\t\t0 1 1;\n\t\t\t0 1 1];\n\t\t\n\t\t% max (z) depends on number of floors\n\t\tar(5:8,3)=.2*(flrz+1);\n\t\t\n\t\t% for our first patch, min (z) stays at (0), while max (z) changes with\n\t\t% the min height of the elevator, so initially, max (z) is (0)\n\t\t\n\t\taf1=ar;\n\t\taf1(5:8,3)=repmat(0,4,1);\n\t\tfp1=patch('vertices',af1,'faces',b,'edgecolor','k','facecolor','c',...\n\t\t\t'facevertexalphadata',1,'facealpha','flat');\n\t\t\n\t\t% for our second patch, max (z) stays at the roof, while min (z) changes\n\t\t% with elevator max height. initially, min (z) is (0.2)\n\t\taf2=ar;\n\t\taf2(1:4,3)=repmat(0.2,4,1);\n\t\tfp2=patch('vertices',af2,'faces',b,'edgecolor','k','facecolor','c',...\n\t\t\t'facevertexalphadata',1,'facealpha','flat');\n\t\t\n\t\t% next we'll mark the (z) axis with labels indicating the floor names\n\t\tFN=cell(flrz+1,1);\n\t\tfor kkp=1:flrz+1\n\t\t\tFN{kkp}=['Floor ',num2str(kkp)];\n\t\tend\n\t\t\n\t\t% by now we have a cell (FN) containing strings for the floors numbers,\n\t\t% so we then set the (z) tick label as this string, and the (z) ticks\n\t\t% as multiples of (0.2)\n\t\tset(gca,'zticklabel',FN,'ztick',.1:.2:(flrz+1)*.2)\n\t\t\n\t\t% hide (x) and (y) ticks\n\t\tset(gca,'xtick',[]);\n\t\tset(gca,'ytick',[]);\n\t\t\n\t\t% the following are saved points that will be used later (kind of like\n\t\t% lookup table)\n\t\t\n\t\t% first are the co-ordinates for the points -inside- the elevator\n\t\tin={[.25 .1];[.35 .1];[.5 .1];[.65 .1];[.8 .1];[.925 .1]};\n\t\t\n\t\t% these are the co-ordinates for the points outside the elevator after\n\t\t% getting out from it\n\t\tout={[-.2 .925];[-.2 .75];[-.2 .575];[-.2 .425];[-.2 .275];[-.2 .125]};\n\t\t\n\t\t% points outside the elevator waiting to get inside it\n\t\ttoin={[-.2 .1];[-.2 .25];[-.2 .4];[-.2 .55];[-.2 .7];[-.2 .85]};\n\t\t\n\t\t% run function (do1)\n\t\tdo1\n\t\t\n\t\tfunction do1()\n\t\t\t\n\t\t\t% create the ground (lobby)\n\t\t\t\n\t\t\t% the groud axis limits\n\t\t\tv(1)=-.25;\n\t\t\tv(2)=1;\n\t\t\tv(3)=0;\n\t\t\tv(4)=1;\n\t\t\t\n\t\t\t% (z) is (0) and flat, (y) is same as elevator shaft, while (x) min\n\t\t\t% is slightly lower (so the ground would appear sticking out)\n\t\t\taaa=[v(1) v(3) 0;\n\t\t\t\tv(2) v(3) 0;\n\t\t\t\tv(2) v(4) 0;\n\t\t\t\tv(1) v(4) 0;\n\t\t\t\tv(1) v(3) 0;\n\t\t\t\tv(2) v(3) 0;\n\t\t\t\tv(2) v(4) 0;\n\t\t\t\tv(1) v(4) 0];\n\t\t\tb=[1 2 6 5;2 3 7 6;3 4 8 7;4 1 5 8;1 2 3 4;5 6 7 8];\n\t\t\t\n\t\t\t% create the ground!\n\t\t\tpatch('vertices',aaa,'faces',b,'edgecolor',[1 1 1],'facecolor',...\n\t\t\t\t[.3 .3 .3],'facevertexalphadata',0.5,'facealpha','flat');\n\t\t\t\n\t\t\t% set proper view (3D)\n\t\t\tview(3)\n\t\t\t\n\t\t\t% current floor is (0)\n\t\t\tcf=0;\n\t\t\t\n\t\t\t% dummy variable, means nothing\n\t\t\tdumnop=4;\n\n\t\t\t% choose number of balls randomly from (1) to (6)\n\t\t\tnum=floor(6*rand)+1;\n\t\t\t\n\t\t\t% create these balls (people)\n\t\t\tcreateballs(num)\n\t\t\t\n\t\t\t% counter to be used later\n\t\t\tcountz=0;\n\t\t\t\n\t\t\t% choose heading floor randomly between (2) and max number of floors\n\t\t\ttofloor=floor(rand*(flrz))+1;\n% \t\t\t\n% [pa1,pa2,aa,aa1,aa2,aa3,ha]=pigeon(.05);\n% \t\t\tfunction movp(varargin)\n% \t\t\t\t\n% \t\t\t\tfor kkl=1:length(ha)\n% \t\t\t\t\tset(ha(kkl),'zdata',get(ha(kkl),'zdata')+.5)\n% \t\t\t\t\tset(ha(kkl),'ydata',get(ha(kkl),'ydata')+.5)\n% \t\t\t\t\tset(ha(kkl),'xdata',get(ha(kkl),'xdata')-.5)\n% \t\t\t\tend\n% \t\t\t\tppI=get(pa1,'vertices');\n% \t\t\t\tppII=get(pa2,'vertices');\n% \t\t\t\tppI(:,3)=ppI(:,3)+.5;\n% \t\t\t\tppI(:,2)=ppI(:,2)+.5;\n% \t\t\t\tppI(:,1)=ppI(:,1)-.5;\n% \t\t\t\tppII(:,3)=ppII(:,3)+.5;\n% \t\t\t\tppII(:,2)=ppII(:,2)+.5;\n% \t\t\t\tppII(:,1)=ppII(:,1)-.5;\n% \t\t\t\t\n% \t\t\t\taa2(:,1)=aa2(:,1)-.5;\n% \t\t\t\taa2(:,2)=aa2(:,2)+.5;\n% \t\t\t\taa2(:,3)=aa2(:,3)+.5;\n% \t\t\t\taa1(:,1)=aa1(:,1)-.5;\n% \t\t\t\taa1(:,2)=aa1(:,2)+.5;\n% \t\t\t\taa1(:,3)=aa1(:,3)+.5;\n% \t\t\t\taa3(:,1)=aa3(:,1)-.5;\n% \t\t\t\taa3(:,2)=aa3(:,2)+.5;\n% \t\t\t\taa3(:,3)=aa3(:,3)+.5;\n% \t\t\t\taa(:,1)=aa(:,1)-.5;\n% \t\t\t\taa(:,2)=aa(:,2)+.5;\n% \t\t\t\taa(:,3)=aa(:,3)+.5;\n% \t\t\t\t\n% \t\t\t\taa\n% \t\t\t\taa1\n% \t\t\t\taa2\n% \t\t\t\taa3\n% \t\t\t\t\n% \t\t\t\tget(pa1,'faces')\n% \t\t\t\tfor kk=1:2\n% \t\t\t\t\tset(pa1,'vertices',aa2)\n% \t\t\t\t\tset(pa2,'vertices',aa3)\n% \t\t\t\t\tpause(.1)\n% \t\t\t\t\tset(pa1,'vertices',aa)\n% \t\t\t\t\tset(pa2,'vertices',aa1)\n% \t\t\t\t\tpause(.1)\n% \t\t\t\tend\n% \t\t\t\t\n% \n% \t\t\tend\n%% Main Loop\n\t\t\t% while 'Stop' pushbutton has not yet been pressed\n\t\t\twhile strcmp(get(pb,'string'),'Stop')\n\t\t\t\t\n\t\t\t\t% increment counter\n\t\t\t\tcountz=countz+1;\n\t\t\t\t\n\t\t\t\t% choose speed for opening the door\n\t\t\t\tdspeed=.1;\n\t\t\t\t\n\t\t\t\t% open door\n\t\t\t\topend(dspeed)\n\t\t\t\t\n\t\t\t\t% move balls inside\n\t\t\t\tfor j=1:num\n\t\t\t\t\t\n\t\t\t\t\t% move each ball from its location (toin) to its heading\n\t\t\t\t\t% point (in)\n\t\t\t\t\ths(j)=movb(rz(j),toin{j},in{j},rand*10+15,j,hs(j)); %#ok\n\t\t\t\tend\n\t\t\n\t\t\t\t% choose speed for closing the door\n\t\t\t\tdspeed=.1;\n\t\t\t\t\n\t\t\t\t% close door\n\t\t\t\tclosed(dspeed)\n\t\t\t\t\n\t\t\t\t% choose speed of going up\n\t\t\t\tupspeed=.035;\n\t\t\t\t\n\t\t\t\t% update debugging text\n\t\t\t\tset(tee,'string',{['Number of Stops: ',num2str(countz)];...\n\t\t\t\t\tsprintf('Current Stop: Floor %d',tofloor+1);...\n\t\t\t\t\t['Number of Dudes: ',num2str(num)]})\n% \t\t\t\tmovp\n\t\t\t\t% have elevator go up from (cf) to (tofloor) with speed\n\t\t\t\t% (upspeed) and ball handles (hs)\n\t\t\t\tcf=goup(upspeed,tofloor,cf,hs);\n\t\t\t\t\n\t\t\t\t% choose speed of door opening again\n\t\t\t\tdspeed=.075;\n\t\t\t\t\n\t\t\t\t% open door\n\t\t\t\topend(dspeed)\n\t\t\t\t\n\t\t\t\t% next we'll want to move each ball outside the elevator\n\t\t\t\t% also, we want to get their handles\n\t\t\t\t\n\t\t\t\t% preallocation\n\t\t\t\ttodel=zeros(1,num*2);\t\t\t\t\n\t\t\t\t\n\t\t\t\t% for each ball go once around the loop\n\t\t\t\tfor kmpf=1:num\n\t\t\t\t\t\n\t\t\t\t\t% move ball outside its location to (out) and draw virtual\n\t\t\t\t\t% ground (patch) and get the patche's handle\n\t\t\t\t\t[hs2,pn]=movb(rz(num),dumnop,out{kmpf},20,kmpf,hs(kmpf));\n\t\t\t\t\t\n\t\t\t\t\t% store handles for each ball and ground here\n\t\t\t\t\ttodel(kmpf*2-1:kmpf*2)=[hs2,pn];\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\t% now it's time to make the balls and patches gradually\n\t\t\t\t% disappear\n\t\t\t\t\n\t\t\t\t% initial transperancy is (0.5)\n\t\t\t\tfor k=.5:-.075:0\n\t\t\t\t\t\n\t\t\t\t\t% gradually lower the transperancy of everything (every\n\t\t\t\t\t% handle) in (todel)\n\t\t\t\t\tset(todel,'facealpha',k,'edgealpha',k)\t\t\t\t\t\n\t\t\t\t\tpause(.05)\n\t\t\t\t\t\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\t% finally after everything is completely transparent, delete it\n\t\t\t\tdelete(todel)\n\t\t\t\t\n\t\t\t\t% choose speed for closing the door\n\t\t\t\tspeedc=.075;\n\t\t\t\t\n\t\t\t\t% close doors\n\t\t\t\tclosed(speedc)\n\t\t\t\t\n\t\t\t\t% choose a new number of dudes from (1) to (6)\n\t\t\t\tnum=floor(6*rand)+1;\n\t\t\t\t\n\t\t\t\t% choose a new floor number from (2) to number of floors\n\t\t\t\ttofloor=floor(rand*(flrz))+1;\n\t\t\t\t\n\t\t\t\t% update debugger text\n\t\t\t\tset(tee,'string',{['Number of Stops: ',num2str(countz)];...\n\t\t\t\t\tsprintf('Current Stop: Floor %d',tofloor+1);...\n\t\t\t\t\t['Number of Dudes: ',num2str(num)]})\n\t\t\t\t\n\t\t\t\t% create the balls (people)\n\t\t\t\tcreateballs(num)\n\t\t\t\t\n\t\t\t\t% choose speed to returning the elevator to the ground\n\t\t\t\tspeedret=.035;\n\t\t\t\t\n\t\t\t\t% return elevator to the ground\n\t\t\t\tcf=retn(speedret,cf);\n\t\t\t\t\n\t\t\tend\n\t\t\t\n%% Create Balls\n\t\t\tfunction createballs(num)\n\t\t\t\t\n\t\t\t\t% choose random radii for each ball (fat, tall, young, etc...)\n\t\t\t\t% from (0.02) to (0.05)\n\t\t\t\trz=rand(num,1).*.03+.02;\n\t\t\t\t\n\t\t\t\t% next we create the balls by moving them from (toin) to (toin)\n\t\t\t\ths=zeros(num,1);\n\t\t\t\tfor n2=1:num\n\t\t\t\t\ths(n2)=movb(rz(n2),toin{n2},toin{n2},10,n2);\n\t\t\t\tend\n\t\t\tend\n\t\t\t\n\t\tend\n\t\t\n%% Raising the Elevator\n\t\tfunction cf=goup(inc_speed,floor,cf,hs)\n\t\t\t\n\t\t\t% counter for use later\n\t\t\tcc=1;\n\t\t\twhile true\n\t\t\t\t\n\t\t\t\t% condition for stopping the elevator: next elevtor position\n\t\t\t\t% (indicated by current position + speed) is higher than\n\t\t\t\t% required floor, in which case, set the position of the\n\t\t\t\t% elevator as the next floor minimum coordinate\n\t\t\t\tif min(c(:,3))+inc_speed>floor*.2\n\t\t\t\t\t\n\t\t\t\t\t% min (z) of elevator is same as floor height\n\t\t\t\t\tc(1:4,3)=repmat(floor*.2,4,1);\n\t\t\t\t\t\n\t\t\t\t\t% max (z) of elevator is same as floor ceiling (next floor)\n\t\t\t\t\tc(5:8,3)=repmat(floor*.2+.2,4,1);\n\t\t\t\t\t\n\t\t\t\t\t% move elevator to this position\n\t\t\t\t\tset(elv,'vertices',c)\n\t\t\t\t\t\n\t\t\t\t\t% do the same thing for the elevator doors\n\t\t\t\t\tc1(1:4,3)=repmat(floor*.2,4,1);\n\t\t\t\t\tc1(5:8,3)=repmat(floor*.2+.2,4,1);\n\t\t\t\t\tc2(1:4,3)=repmat(floor*.2,4,1);\n\t\t\t\t\tc2(5:8,3)=repmat(floor*.2+.2,4,1);\n\t\t\t\t\tset(door1,'vertices',c1)\n\t\t\t\t\tset(door2,'vertices',c2)\n\t\t\t\t\t\n\t\t\t\t\t% also move the curtains in the same way\n\t\t\t\t\taf1=get(fp1,'vertices');\n\t\t\t\t\taf1(5:8,3)=repmat(floor*.2,4,1);\n\t\t\t\t\taf2=get(fp2,'vertices');\n\t\t\t\t\taf2(1:4,3)=repmat(.2+floor*.2,4,1);\n\t\t\t\t\tset(fp1,'vertices',af1)\n\t\t\t\t\tset(fp2,'vertices',af2)\n\t\t\t\t\t\n\t\t\t\t\t% and move the balls as well\n\t\t\t\t\tfor k=1:length(hs)\n\t\t\t\t\t\tppv=get(hs(k),'zdata');\n\t\t\t\t\t\tset(hs(k),'zdata',ppv+floor*.2-min(min(ppv)))\n\t\t\t\t\tend\n\t\t\t\t\t\n\t\t\t\t\t% update plot\n\t\t\t\t\tdrawnow()\n\t\t\t\t\t\n\t\t\t\t\t% leave loop\n\t\t\t\t\tbreak\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\t% increment counter\n\t\t\t\tcc=cc+1;\n\t\t\t\t\n\t\t\t\t% increase height of elevator (z) by its speed\n\t\t\t\tc(:,3)=c(:,3) + inc_speed;\n\t\t\t\tset(elv,'vertices',c)\n\t\t\t\t\n\t\t\t\t% same with doorsw\n\t\t\t\tc1(:,3)=c1(:,3) + inc_speed;\n\t\t\t\tc2(:,3)=c2(:,3) + inc_speed;\n\t\t\t\tset(door1,'vertices',c1)\n\t\t\t\tset(door2,'vertices',c2)\n\t\t\t\t\n\t\t\t\t% change the height of curtains in the same way\n\t\t\t\taf1=get(fp1,'vertices');\n\t\t\t\taf1(5:8,3)=repmat(0+cc*inc_speed+cf*.2,4,1);\n\t\t\t\taf2=get(fp2,'vertices');\n\t\t\t\taf2(1:4,3)=repmat(0.2+cc*inc_speed+cf*.2,4,1);\n\t\t\t\tset(fp1,'vertices',af1)\n\t\t\t\tset(fp2,'vertices',af2)\n\t\t\t\t\n\t\t\t\t% increase the height of the balls as well\n\t\t\t\tfor k=1:length(hs)\n\t\t\t\t\tset(hs(k),'zdata',get(hs(k),'zdata')+inc_speed)\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\t% update plot\n\t\t\t\tdrawnow()\n\t\t\t\t\t\t\t\t\n\t\t\tend\n\t\t\t\n\t\t\t% update floor number (output)\n\t\t\tcf=floor;\n\t\tend\n\n%% Returning the Elevator\n\t\tfunction cf=retn(inc_speed,cf)\n\t\t\t\n\t\t\t% counter\n\t\t\tcc=1;\n\t\t\t\n\t\t\t% destination floor\n\t\t\tfloor=0;\n\t\t\t\n\t\t\t% the following is the same as raising the elevator, with the\n\t\t\t% replacement of a few addition with subtractions\n\t\t\twhile true\n\t\t\t\t\n\t\t\t\tif min(c(:,3))-inc_speed0;\n\t\t\t\t\n\t\t\t\t% move both doors relative to the speed, in opposite directions\n\t\t\t\tvar1([3,4,7,8],2)=var1([3,4,7,8],2)-dspeed;\n\t\t\t\tvar2([1,2,5,6],2)=var2([1,2,5,6],2)+dspeed;\n\t\t\t\tset(door1,'vertices',var1)\n\t\t\t\tset(door2,'vertices',var2)\n\t\t\t\t\n\t\t\t\t% for the loop condition\n\t\t\t\ty1=var1(:,2);\t\t\t\n\t\t\t\t\n\t\t\t\t% update plot\n\t\t\t\tdrawnow()\n\t\t\tend\n\t\t\t\n\t\t\t% set both doors to fully open status\n\t\t\tvar1(:,2)=zeros(8,1);\n\t\t\tvar2(:,2)=ones(8,1);\n\t\t\tset(door1,'vertices',var1)\n\t\t\tset(door2,'vertices',var2)\n\t\t\t\n\t\t\t% update plot\n\t\t\tdrawnow()\n\t\t\t\n\t\tend\n\t\t\n%% Closing Elevator Doors\n\t\tfunction closed(dspeed)\n\t\t\t\n\t\t\t% very similar to opening the elevator doors, with subtraction\n\t\t\t% operation replacing the addition, as well as having the fully\n\t\t\t% closed conditions being one door having a maximum (y) of (0.5)\n\t\t\t% while the other has a minimum (y) of (0.5).\n\t\t\tvar1=get(door1,'vertices');\n\t\t\ty1=var1(:,2);\n\t\t\tvar2=get(door2,'vertices');\n\t\t\twhile max(y1)+dspeed<0.5;\n\t\t\t\tvar1([3,4,7,8],2)=var1([3,4,7,8],2)+dspeed;\n\t\t\t\tvar2([1,2,5,6],2)=var2([1,2,5,6],2)-dspeed;\n\t\t\t\ty1=var1(:,2);\n\t\t\t\tset(door1,'vertices',var1)\n\t\t\t\tset(door2,'vertices',var2)\n\t\t\t\tdrawnow()\n\t\t\tend\n\t\t\tvar1([3,4,7,8],2)=repmat(.5,4,1);\n\t\t\tvar2([1,2,5,6],2)=repmat(.5,4,1);\n\t\t\tset(door1,'vertices',var1)\n\t\t\tset(door2,'vertices',var2)\n\t\t\tdrawnow()\n\t\t\t\n\t\tend\n\n%% Moving the Balls\n\t\tfunction [h,pn]=movb(r,A,B,V,nm,varargin)\n\t\t\t\n\t\t\t% r: Radius of ball\n\t\t\t%\n\t\t\t% A: Starting position of centre of ball\n\t\t\t%\n\t\t\t% B: Ending position of centre of ball\n\t\t\t%\n\t\t\t% V: Speed of rotation\n\t\t\t%\n\t\t\t% nm: Number denoting the colour\n\t\t\t%\n\t\t\t% varargin: Could contain handle of previously created ball\n\t\t\t\n\t\t\t% so previous plots would not disappear\n\t\t\thold on\n\t\t\t\n\t\t\t% if no previous ball is created (i.e. we want to create instead\n\t\t\t% of move)\n\t\t\tif ~numel(varargin)\n\t\t\t\t% create unit ball\n\t\t\t\t[a,b,cC2]=sphere(25);\n\t\t\t\t\n\t\t\t\t% adjust size of ball by multiplying by the radius\n\t\t\t\t% also, move ball to starting position by adding\n\t\t\t\t% and put ball on the ground (0z) by adding r to z\n\t\t\t\th=surf(a.*r+A(1),b.*r+A(2),cC2.*r+r);\n\t\t\t\t\n\t\t\t\t% make colors cooler\n\t\t\t\tset(h,'facecolor','interp','edgecolor','interp')\n\t\t\t\t\n\t\t\t\t% get ball colour data\n\t\t\t\ts2=get(h,'cdata');\n\t\t\t\t\n\t\t\t\t% take the ball top and change its colour to something\n\t\t\t\t% now each ball has a cute little colourful hat!\n\t\t\t\ts2(end-3:end,:)=repmat(.15*nm,4,size(s2,2));\t\t\t\t\n\t\t\t\tset(h,'cdata',s2)\n\t\t\t\t\n\t\t\t\t% adjust axis for better viewing\n \t\t\t\taxis equal\n\n\t\t\tend\n\t\t\t\n\t\t\t% for future reference\n\t\t\tv=axis;\n\t\t\t\n\t\t\t% for while loop initial status\n\t\t\tctr=[1e9 1e9];\n\t\t\t\n\t\t\t% move ball\n\t\t\tif numel(varargin)\n\n\t\t\t\t% get handle of ball\n\t\t\t\th=varargin{1};\n\t\t\t\t\n\t\t\t\t% create a patch that spans the axis edges (acts as ground)\n\t\t\t\t% (z) is flat, and depends on the ball's min (z)\t\t\t\t\n\t\t\t\tpft=min(min(get(h,'zdata')));\n\t\t\t\taaa=[v(1) v(3) pft;\n\t\t\t\t\tv(2) v(3) pft;\n\t\t\t\t\tv(2) v(4) pft;\n\t\t\t\t\tv(1) v(4) pft;\n\t\t\t\t\tv(1) v(3) pft;\n\t\t\t\t\tv(2) v(3) pft;\n\t\t\t\t\tv(2) v(4) pft;\n\t\t\t\t\tv(1) v(4) pft];\n\t\t\t\tb=[1 2 6 5;2 3 7 6;3 4 8 7;4 1 5 8;1 2 3 4;5 6 7 8];\n\t\t\t\t\n\t\t\t\t% plot ground!\n\t\t\t\tpn=patch('vertices',aaa,'faces',b,'edgecolor',[1 1 1],'facecolor',[.3 .3 .3],...\n\t\t\t\t\t'facevertexalphadata',0.5,'facealpha','flat');\n\t\t\tend\n\t\t\t\n\t\t\t% get min (z) of ball (i.e. get the current floor)\n\t\t\tllpp=get(h,'zdata');\n\t\t\tcf=min(min(llpp));\n\t\t\t\n\t\t\t% while centre of the ball is at least .1 away from\n\t\t\t% the destination points, keep moving it. notice here that the\n\t\t\t% condition for stopping the ball movement doesn't depend on the\n\t\t\t% next location, but rather on the current location. this leads to\n\t\t\t% the balls to end up in slightly different locations that their\n\t\t\t% destinations, due to the randomization of the ball radius coupled\n\t\t\t% with their relatively high speeds\n\t\t\twhile mean(abs(ctr-B))>1e-1\n\t\t\t\t\n\t\t\t\t% get centre of ball\n\t\t\t\tctr=[(max(max(get(h,'xdata')))+min(min(get(h,'xdata'))))/2,...\n\t\t\t\t\t(max(max(get(h,'ydata')))+min(min(get(h,'ydata'))))/2];\n\t\t\t\t\n\t\t\t\t% vector from current point to destination\n\t\t\t\trot=B-ctr;\n\t\t\t\t\n\t\t\t\t% get orthogonal vector (which the ball will spin around)\n\t\t\t\tyu=rot(2);\n\t\t\t\trot(2)=rot(1);\n\t\t\t\trot(1)=-yu;\n\t\t\t\t\n\t\t\t\t% rotate around ball about said vector\n\t\t\t\t% origin is centre of ball\n\t\t\t\trotate(h,[rot,0],V,[ctr,r+cf])\n\t\t\t\t\n\t\t\t\t% move ball according to its speed\n\t\t\t\t% the sign commands are for the direction of movement\n\t\t\t\t% the sphere moves in X and Y the same distance as the one it has rolled\n\t\t\t\t% in other words it moves V/360\n\t\t\t\t% but it doesn't move the entirety of this roll since it is divided between\n\t\t\t\t% X and Y rolling, we find out how much is shared between X and Y using atan\n\t\t\t\tset(h,'xdata',get(h,'xdata')...\n\t\t\t\t\t-(sign(rot(1))-~sign(rot(1)))...\n\t\t\t\t\t*V/360*...\n\t\t\t\t\tatan(rot(2)/-rot(1)))\n\t\t\t\tset(h,'ydata',get(h,'ydata')+(sign(rot(2))+sign(rot(2)))*V/360*atan(rot(1)/-rot(2)))\n\t\t\t\t\n\t\t\t\t% so that axis wouldn't change while animating\n\t\t\t\taxis(v)\n\t\t\t\t\n\t\t\t\t% update plot\n\t\t\t\tdrawnow()\n\t\t\tend\n\t\tend\n\tend\n% EOF\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/23156-graphical-simulation-of-an-elevator/laith.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.4956839184586668}} {"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": "%WARPPERSPECTIVE Applies a perspective transformation to an image\n%\n% dst = cv.warpPerspective(src, M)\n% dst = cv.warpPerspective(src, M, 'OptionName',optionValue, ...)\n%\n% ## Input\n% * __src__ Input image.\n% * __M__ 3x3 transformation matrix, floating-point.\n%\n% ## Output\n% * __dst__ Output image that has the size `DSize` (with\n% `size(dst,3) == size(src,3)`) and the same type as `src`.\n%\n% ## Options\n% * __DSize__ Size of the output image `[w,h]`. Default `[0,0]` means using\n% the same size as the input `[size(src,2) size(src,1)]`.\n% * __Interpolation__ interpolation method, default 'Linear'. One of:\n% * __Nearest__ nearest neighbor interpolation\n% * __Linear__ bilinear interpolation\n% * __Cubic__ bicubic interpolation\n% * __Lanczos4__ Lanczos interpolation over 8x8 neighborhood\n% * __WarpInverse__ Logical flag to apply inverse perspective transform,\n% meaning that `M` is the inverse transformation (`dst -> src`).\n% default false\n% * __BorderType__ Pixel extrapolation method. When 'Transparent', it means\n% that the pixels in the destination image corresponding to the \"outliers\"\n% in the source image are not modified by the function. default 'Constant'\n% * __Constant__ `iiiiii|abcdefgh|iiiiiii` with some specified `i`\n% * __Replicate__ `aaaaaa|abcdefgh|hhhhhhh`\n% * __Reflect__ `fedcba|abcdefgh|hgfedcb`\n% * __Reflect101__ `gfedcb|abcdefgh|gfedcba`\n% * __Wrap__ `cdefgh|abcdefgh|abcdefg`\n% * __Transparent__ `uvwxyz|abcdefgh|ijklmno`\n% * __Default__ same as 'Reflect101'\n% * __BorderValue__ Value used in case of a constant border. default 0\n% * __Dst__ Optional initial image for the output. If not set, it is\n% automatically created by the function. Note that it must match the\n% expected size `DSize` and the type of `src`, otherwise it is ignored and\n% recreated by the function. This option is only useful when\n% `BorderType=Transparent`, in which case the transformed image is drawn\n% onto the existing `Dst` without extrapolating pixels. Not set by default.\n%\n% The function cv.warpPerspective transforms the source image using the\n% specified matrix:\n%\n% dst(x,y) = src((M_11*x + M_12*y + M_13) / (M_31*x + M_32*y + M_33),\n% (M_21*x + M_22*y + M_23) / (M_31*x + M_32*y + M_33))\n%\n% when the `WarpInverse` option is true. Otherwise, the transformation is first\n% inverted with cv.invert and then put in the formula above instead of `M`.\n%\n% See also: cv.warpAffine, cv.remap, cv.resize, cv.getRectSubPix,\n% cv.perspectiveTransform, imtransform, imwarp\n%\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/+cv/warpPerspective.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.49568390049280564}} {"text": "%MDL_OFFSET3 A minimalistic 3DOF robot arm with shoulder offset\n%\n% MDL_OFFSET3 is a script that creates the workspace variable off3 which\n% describes the kinematic characteristics of a simple arm manipulator with\n% a shoulder offset, using standard DH conventions.\n%\n% Somewhat like a Puma arm without the wrist.\n%\n% Also define the workspace vectors:\n% qz zero joint angle configuration\n%\n% Notes::\n% - Unlike most other mdl_xxx scripts this one is actually a function that\n% behaves like a script and writes to the global workspace.\n%\n% See also SerialLink, mdl_offset6, mdl_simple6, mdl_puma560.\n\n% MODEL: generic, 3DOF, standard_DH\n\n% Copyright (C) 1993-2015, by Peter I. Corke\n%\n% This file is part of The Robotics Toolbox for MATLAB (RTB).\n% \n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with RTB. If not, see .\n%\n% http://www.petercorke.com\n\nfunction r = mdl_offset3()\n \n % robot length values (metres)\n L1 = 1;\n L2 = 1;\n O1 = 0;\n O2 = 0.2;\n O3 = 0;\n \n % and build a serial link manipulator\n \n robot = SerialLink([\n Revolute('alpha', -pi/2, 'a', O1, 'd', 0)\n Revolute('alpha', 0, 'a', L1, 'd', O2)\n Revolute('alpha', pi/2, 'a', L2, 'd', O3)\n ], ...\n 'name', 'Offset3');\n \n % place the variables into the global workspace\n if nargout == 1\n r = robot;\n elseif nargout == 0\n assignin('base', 'off3', robot);\n assignin('base', 'qz', [0 0 0 ]); % zero angles, arm up\n end\nend\n", "meta": {"author": "Allopart", "repo": "rbpf-gmapping", "sha": "affe0adc25fa446fc7af4902d699d92864bdba1b", "save_path": "github-repos/MATLAB/Allopart-rbpf-gmapping", "path": "github-repos/MATLAB/Allopart-rbpf-gmapping/rbpf-gmapping-affe0adc25fa446fc7af4902d699d92864bdba1b/rvctools/robot/mdl_offset3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.495614809723654}} {"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": "\n\n% ========================================================================\n% Fast Multi-Scale Structural Patch Decomposition for Multi-Exposure Image Fusion, TIP,2020\n% algorithm Version 1.0\n% Copyright(c) 2020, Hui Li, Kede Ma, Yongwei Yong and Lei Zhang\n% All Rights Reserved.\n% ----------------------------------------------------------------------\n% Permission to use, copy, or modify this software and its documentation\n% for educational and research purposes only and without fee is hereby\n% granted, provided that this copyright notice and the original authors'\n% names appear on all copies and supporting documentation. This program\n% shall not be used, rewritten, or adapted as the basis of a commercial\n% software or hardware product without first obtaining permission of the\n% authors. The authors make no representations about the suitability of\n% this software for any purpose. It is provided \"as is\" without express\n% or implied warranty.\n%----------------------------------------------------------------------\n% This is a dynamic scene implementation of \"Fast Multi-Scale Structural Patch Decomposition for Multi-Exposure Image Fusion\"\n% Please refer to the following paper:\n% H. Li et al., \"Fast Multi-Scale Structural Patch Decomposition for Multi-Exposure Image Fusion, 2020\" In press\n% IEEE Transactions on Image Processing\n% Please kindly report any suggestions or corrections to xiaohui102788@126.com\n%----------------------------------------------------------------------\n\nclear ;\nclose all;\naddpath(genpath(pwd));\n\n\n imgSeqColor= loadImg('ArchSequence'); % [0,1]\n imgSeqColor = downSample(imgSeqColor, 1024);\n \ntic\n%% motion detection \nr=10;\n imgSeqColor = detection_color(imgSeqColor,r);\n \n%% fusion as static\nr1=4;\n[ D1,i_mean1,aa1,N1] = scale_fine(imgSeqColor,r1);\n\n%% the intermediate scale\n[w,h,~,~]=size(imgSeqColor);\nnlev = floor(log(min(w,h)) / log(2))-5;\n\nD2 = cell(nlev,1);\naa2= cell(nlev,1);\nN2= cell(nlev,1);\n\nr2=4;\nfor ii=1:nlev\n [ D2{ii},i_mean2,aa2{ii},N2{ii}] = scale_interm(i_mean1,r2);\n i_mean1=i_mean2;\nend\n\n\n%% the coarsest scale\nr3=4;\n[fI3,i_mean3,aa3,N3] = scale_coarse(i_mean2,r3);\n\n%% reconstruct\n%% Intermediate layers\nfor ii=nlev:-1:1\n temp=aa2{ii};\n fI=zeros(size(temp));\n fI(1:2:size(temp,1),1:2:size(temp,2))=fI3;\n B2=boxfilter(fI, r2)./ N2{ii}+D2{ii};\n \n fI3=B2;\nend\n%% finest layers\nfI=zeros(size(aa1));\nfI(1:2:size(aa1,1),1:2:size(aa1,2))=B2;\nB1=boxfilter(fI, r1)./ N1;\nC_out=repmat(B1,[1 1 3])+D1;\ntoc\n\nfigure,imshow(C_out)\n \n", "meta": {"author": "thfylsty", "repo": "Classic-and-state-of-the-art-image-fusion-methods", "sha": "5d9457df396f1ea6921e1b9b3703995205940862", "save_path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods", "path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods/Classic-and-state-of-the-art-image-fusion-methods-5d9457df396f1ea6921e1b9b3703995205940862/fmmef-TIP-2020-master/demo_multi_dy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49553458119607385}} {"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": "%%*******************************************************************\n%% detect_ublk: search for implied free variables in linear\n%% block.\n%% [blk2,At2,C2,ublkinfo] = detect_ublk(blk,At,C);\n%%\n%% i1,i2: indices corresponding to splitting of unrestricted varaibles\n%% i3 : remaining indices in the linear block\n%%\n%% SDPT3: version 3.1\n%% Copyright (c) 1997 by\n%% K.C. Toh, M.J. Todd, R.H. Tutuncu\n%% Last Modified: 16 Sep 2004\n%%*******************************************************************\n\nfunction [blk2,At2,C2,ublkinfo,parbarrier2,X2,Z2] = ...\n detect_ublk(blk,At,C,parbarrier,X,Z,printlevel)\n\nif (nargin < 7); printlevel = 1; end\n\nblk2 = blk; At2 = At; C2 = C;\nif (nargin >= 6)\n parbarrier2 = parbarrier;\n X2 = X; Z2 = Z;\nelse\n X2 = []; Z2 = [];\nend\nnumblk = size(blk,1);\nublkinfo = cell(size(blk,1),3);\ntol = 1e-14;\n%%\nnumblknew = numblk;\n%%\nfor p = 1:numblk\n pblk = blk(p,:);\n m = size(At{p},2);\n if strcmp(pblk{1},'l')\n r = randmat(1,m,0,'n');\n % stime = cputime;\n Ap = At{p}'; Cp = C{p};\n ApTr = (r*Ap)';\n [sApTr,perm] = sort(abs(ApTr));\n idx0 = find(abs(diff(sApTr)) < tol);\n if ~isempty(idx0)\n n = pblk{2};\n i1 = perm(idx0); i2 = perm(idx0+1);\n Api1 = Ap(:,i1);\n Api2 = Ap(:,i2);\n Cpi1 = Cp(i1)';\n Cpi2 = Cp(i2)';\n idxzr = abs(Cpi1+Cpi2) < tol & sum(abs(Api1+Api2),1) < tol;\n if any(idxzr)\n i1 = i1(idxzr');\n i2 = i2(idxzr');\n blk2{p,1} = 'u';\n blk2{p,2} = length(i1);\n At2{p} = Ap(:,i1)';\n C2{p} = Cp(i1);\n if (printlevel)\n fprintf('\\n %1.0d linear variables from unrestricted variable.\\n',...\n 2*length(i1));\n end\n if (nargin >= 6)\n parbarrier2{p} = parbarrier{p}(i1);\n X2{p} = X{p}(i1)-X{p}(i2);\n Z2{p} = zeros(length(i1),1);\n end\n i3 = setdiff(1:n,union(i1,i2));\n if ~isempty(i3)\n numblknew = numblknew + 1;\n blk2{numblknew,1} = 'l';\n blk2{numblknew,2} = length(i3);\n At2{numblknew,1} = Ap(:,i3)';\n C2{numblknew,1} = Cp(i3);\n if (nargin >= 6)\n parbarrier2{numblknew,1} = parbarrier{p}(i3);\n X2{numblknew,1} = X{p}(i3); Z2{numblknew,1} = Z{p}(i3);\n end\n end\n ublkinfo{p,1} = i1; ublkinfo{p,2} = i2; ublkinfo{p,3} = i3;\n end\n end\n end\nend\n%%*******************************************************************\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/sdpt3/Solver/detect_ublk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4955345697143154}} {"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 calpak_test24 ( )\n\n%*****************************************************************************80\n%\n%% CALPAK_TEST24 tests JED_TO_YMDF_PERSIAN and YMDF_TO_JED_PERSIAN.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 14 March 2013\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CALPAK_TEST24\\n' );\n fprintf ( 1, ' For the Persian calendar:\\n' );\n fprintf ( 1, ' JED_TO_YMDF_PERSIAN: JED -> YMDF.\\n' );\n fprintf ( 1, ' YMDF_TO_JED_PERSIAN: YMDF -> JED.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' JED (in) YMDF JED (out)\\n' );\n fprintf ( 1, '\\n' );\n\n jed_epoch = epoch_to_jed_persian ( );\n\n i = 0;\n\n while ( 1 )\n\n i = i + 1;\n jed1 = jed_test ( i );\n\n if ( jed1 < 0.0 )\n break\n end\n\n if ( jed_epoch <= jed1 )\n\n [ y2, m2, d2, f2 ] = jed_to_ymdf_persian ( jed1 );\n\n s2 = ymdf_to_s_numeric ( y2, m2, d2, f2 );\n\n jed3 = ymdf_to_jed_persian ( y2, m2, d2, f2 );\n\n fprintf ( 1, ' %11.2f %20s %11.2f\\n', jed1, s2, jed3 );\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/calpak/calpak_test24.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.4955326994242676}} {"text": "function [edges,idx,edgemap]=uniqedges(elem)\n%\n% [edges,idx,edgemap]=uniqedges(elem)\n%\n% return the unique edge list from a surface or tetrahedral mesh\n%\n% author: Qianqian Fang, \n%\n% input:\n% elem: a list of elements, each row is a list of nodes for an element.\n% elem can have 2, 3 or 4 columns\n%\n% output:\n% edge: unique edges in the mesh, denoted by a pair of node indices\n% idx: index of the output in the raw edge list (returned by meshedge)\n% edgemap: index of the raw edges in the output list (for triangular mesh)\n%\n% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)\n%\n\nif(size(elem)==2)\n edges=elem;\nelseif(size(elem)>=3)\n edges=meshedge(elem);\nelse\n error('invalid input');\nend\n\n[uedges,idx,jdx]=unique(sort(edges,2),'rows');\nedges=edges(idx,:);\nif(nargout>2)\n edgemap=reshape(jdx,[size(elem,1) nchoosek(size(elem,2),2)]);\nend\n", "meta": {"author": "fangq", "repo": "iso2mesh", "sha": "556f4c321467a3ee042d4c559b4edc11e01dc574", "save_path": "github-repos/MATLAB/fangq-iso2mesh", "path": "github-repos/MATLAB/fangq-iso2mesh/iso2mesh-556f4c321467a3ee042d4c559b4edc11e01dc574/uniqedges.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.495532695221642}} {"text": "function S = statistics(V,F,varargin)\n % STATISTICS Determine a number of statistics about a mesh\n %\n % Inputs:\n % V #V by 3 list of mesh vertices\n % F #F by 3 list of triangle indices\n % Optional:\n % 'Fast' followed by bool. Whether to skip certain expensive statistics\n % 'MinArea' Followed by factor of bounding_box_diagonal^2 area value for\n % determining small triangles {1e-7}*bounding_box_diagonal^2\n % 'MinDist' Followed by factor of bounding box diagonal dist value for\n % determining close vertices {1e-7}*bounding_box_diagonal\n % 'MinAngle' Followed by dist value for determining small angles\n % {0.01 radians}\n % Outputs:\n % S Struct containing:\n % num_faces Number of triangles in F\n % num_vertices Number of vertices in V\n % num_edges Number of unique undirected edges\n % num_small_triangles Number of triangles with area < min_area\n % num_small_angles Number of corners with internal angles < min_angle\n % num_close_vertices Number of vertices minus number of unique vertices\n % upto rounding coordinates by min_dist (~L1 distance)\n % num_connected_components Number of connected compenents of mesh as\n % graph (includes each unreferenced vertex as a singlton component)\n % num_handles Genus of surface, (2-X)/2, where X is Euler characteristic\n % euler_characteristic Euler characteristic\n % num_boundary_loops Number of connected components in undirected graph\n % of boundary edges\n % num_boundary_edges Number of boundary edges\n % num_ears Number of topological ears (triangles with single internal\n % edge)\n % num_nonmanifold_edges Number of non-manifold edges (edges with valence\n % >2)\n % num_conflictingly_oriented_edges Number of edges with and even number\n % of incident faces having conflicting orientation\n % num_duplicate_vertices Number vertices minus number of geometrically\n % unique vertices\n % num_nonmanifold_vertices Number of non-manifold vertices (vertices\n % whose incident faces do not form exaclty one connected component)\n % num_unreferenced_vertices Number of vertices not appearing in F\n % num_combinatorially_duplicate_faces Number of faces minus number of\n % combinatorially unique faces\n % num_geometrically_degenerate_faces Number of faces with area == 0.\n % Note that combinatorially degenerate faces will be included.\n % num_combinatorially_degenerate_faces Number of faces with 2 or more of\n % the same vertices as corners\n % Not 'Fast'\n % num_selfintersecting_pairs Number of self intersecting pairs of\n % triangles\n % num_intracomponent_selfintersecting_pairs Number of self intersecting\n % pairs of triangles _in the same connected component_\n %\n % Examples:\n % S = statistics(V,F,'Fast',true)\n % subplot(3,1,1);\n % hist(doublearea(V,F)/2,100);\n % title('areas');\n % subplot(3,1,2);\n % hist(reshape(internalangles(V,F),[],1),100);\n % title('internal angles');\n % subplot(3,1,3);\n % bar( ...\n % sort(sparse( ...\n % connected_components(F),1,diag(massmatrix(V,F,'barycentric'))), ...\n % 'descend'));\n % title('CC areas');\n\n fast = false;\n min_area = 1e-7;\n min_dist = 1e-7;\n min_angle = 0.01;\n\n ii = 1;\n while ii<=numel(varargin)\n switch varargin{ii}\n case 'MinArea'\n assert(ii+1<=numel(varargin));\n ii = ii+1;\n min_area = varargin{ii};\n case 'MinDist'\n assert(ii+1<=numel(varargin));\n ii = ii+1;\n min_dist= varargin{ii};\n case 'MinAngle'\n assert(ii+1<=numel(varargin));\n ii = ii+1;\n min_angle = varargin{ii};\n case 'Fast'\n assert(ii+1<=numel(varargin));\n ii = ii+1;\n fast = varargin{ii};\n otherwise\n error(['Unsupported parameter `' varargin{ii} '`']);\n end\n ii = ii + 1;\n end\n\n bbd = sqrt(sum((max(V)-min(V)).^2,2));\n \n % To achieve this ordering (or almost this order?):\n % Basic counts\n S.num_faces = 0;\n S.num_vertices = 0;\n S.num_edges = 0;\n % Small things\n S.num_small_triangles = 0;\n S.num_small_angles = 0;\n S.num_kahan_length_violations = 0;\n S.num_close_vertices = 0;\n % Topology related\n S.num_connected_components = 0;\n S.num_handles = 0;\n S.euler_characteristic = 0;\n S.num_boundary_loops = 0;\n S.num_boundary_edges = 0;\n S.num_ears = 0;\n S.num_nonmanifold_edges = 0;\n S.num_conflictingly_oriented_edges = 0;\n S.num_duplicate_vertices = 0;\n S.num_nonmanifold_vertices = 0;\n S.num_unreferenced_vertices = 0;\n % Degeneracy related\n S.num_combinatorially_duplicate_faces = 0;\n S.num_geometrically_degenerate_faces = 0;\n S.num_combinatorially_degenerate_faces = 0;\n if ~fast\n S.num_intracomponent_selfintersecting_pairs = 0;\n S.num_selfintersecting_pairs = 0;\n end\n\n % easy\n S.num_faces = size(F,1);\n S.num_vertices = size(V,1);\n S.num_edges = size(edges(F),1);\n S.num_combinatorially_duplicate_faces = ...\n S.num_faces - size(unique(sort(F,2),'rows'),1);\n S.num_duplicate_vertices = ...\n S.num_vertices - size(remove_duplicate_vertices(V,0),1);\n\n C = zeros(size(V,1),1);\n C(1:max(F(:)),:) = connected_components(F);\n C(C==0) = max(C)+(1:sum(C==0));\n is_unreferenced = sparse(F,1,1,size(V,1),1)==0;\n %S.num_unreferenced_vertices = sum(sparse(C,1,1)==1)\n S.num_unreferenced_vertices = sum(is_unreferenced);\n S.num_connected_components = max(C);\n\n E = [F(:,[2 3]); F(:,[3 1]); F(:,[1 2])];\n % Direct all edges so sortE(:,1) < sortE(:,2)\n sortE = sort(E,2);\n % Adjacency matrix for these \"redirected\" edges\n DA = sparse(sortE(:,1),sortE(:,2),1,size(V,1),size(V,1));\n % If edge occurs more than once it's non-manifold\n S.num_nonmanifold_edges = nnz(DA>2);\n % If edge only occurs once then it's a boundary\n S.num_boundary_edges = nnz(DA==1);\n if S.num_nonmanifold_edges == 0\n S.num_ears = size(find_ears(F),1);\n else\n rmfield(S,'num_ears');\n end\n % Same adjacency matrix but count -1 if E(:,1)1);\n\n S.euler_characteristic = S.num_vertices - S.num_edges + S.num_faces;\n b = S.num_boundary_loops;\n % http://en.wikipedia.org/wiki/Genus_(mathematics)#Orientable_surface\n % X = 2 - 2g - b\n % X + b - 2 = - 2g\n % 2-b-X = 2g\n % g = (2-b-X)/2\n % http://sketchesoftopology.wordpress.com/2008/02/04/genus-euler-characteristic-boundary-components/\n S.num_handles = ...\n (2* ...\n (S.num_connected_components-S.num_unreferenced_vertices) - ...\n S.num_boundary_loops - ...\n (S.euler_characteristic-S.num_unreferenced_vertices))/2 ;\n\n dblA = doublearea(V,F);\n S.num_geometrically_degenerate_faces = sum(dblA==0);\n S.num_combinatorially_degenerate_faces = ...\n sum((F(:,1)==F(:,2)) | (F(:,2)==F(:,3)) | (F(:,3)==F(:,1)));\n\n S.num_small_triangles = sum(dblA<2*min_area*bbd*bbd);\n S.num_small_angles = sum(sum(internalangles(V,F)0;\n Fnd = F(nd,:);\n [~,~,IF] = selfintersect(V3,Fnd,'DetectOnly',true);\n S.num_selfintersecting_pairs = size(IF,1);\n CF = C(F(:,1));\n CFnd = CF(nd)';\n S.num_intracomponent_selfintersecting_pairs = ...\n sum(CFnd(IF(:,1))== CFnd(IF(:,2)));\n end\n\n\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/statistics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.7154240079185318, "lm_q1q2_score": 0.495532694548751}} {"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 varargout = grDilate(varargin)\n%GRDILATE Morphological dilation on graph.\n%\n% LBL2 = grDilate(EDGES, LBL1)\n% Each label of the graph is assigned the highest label of its\n% neighbours, or it keeps the same label this one is bigger.\n%\n% Example\n% grDilate\n%\n% See also \n% grErode, grOpen, grClose\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@grignon.inra.fr\n% Created: 2006-01-20\n% Copyright 2006-2022 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas)\n\nif length(varargin) == 2\n edges = varargin{1};\n lbl = varargin{2};\nelseif length(varargin) == 3\n edges = varargin{2};\n lbl = varargin{3};\nelse\n error('Wrong number of arguments in \"grDilate\"');\nend\n \n\nlbl2 = zeros(size(lbl));\n\nuni = unique(edges(:));\nfor n = 1:length(uni)\n neigh = grAdjacentNodes(edges, uni(n));\n lbl2(uni(n)) = max(lbl([uni(n); neigh])); \nend\n\nvarargout{1} = lbl2;\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/graphs/grDilate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7154239836484144, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.49553268227731995}} {"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 \u00a0\u00a0\u00a0\u00a0 |\n%| |\n%| Please acknowledge the gypsilab toolbox in programs or publications in |\n%| which you use it. |\n%|________________________________________________________________________|\n%| '&` | |\n%| # | FILE : 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\u00b0C (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 [ M, N ] = getPsiMat( data, image )\n%GETPSIMAT gets \\Psi matrix (LBP features) for all components\n% Detailed explanation goes here\n% \n% Synopsis:\n% [ M ] = getPsiMat(data, image)\n% \n% INPUT:\n% data ... struct, containes filed lbp (cell array - holds\n% neccessary parameters for lbppyr_features_sparse\n% function), imSize (size of image), Images (matrix\n% [imSize(1)*imSize(2) x nImages]), nImages (count of\n% images), structure options (with field M - count of\n% components)\n% image ... idx of image on which LBP features are computed\n% \n% OUTPUT:\n% M ... cell array [1 x data.options.M] - \\Psi matrices with\n% LBP features\n% N ... cell array [1 x data.options.M] - \\Psi matrices with\n% indices of nonzero elements of LBP features\n% \n% 05-08-10 Michal Uricar\n% 11-07-11 Michal Uricar, corners dataset (checked-only)\n\n M = cell(1, data.options.M);\n N = cell(1, data.options.M);\n\n for j = 1 : data.options.M;\n [M{j} N{j}] = lbp2sparse(data.Images(:, image), data.imSize, data.lbp{j}.wins, data.lbp{j}.winSize, data.lbp{j}.hop, 0);\n end;\n \nend\n\n", "meta": {"author": "uricamic", "repo": "flandmark", "sha": "ecf122f93f73504fe7d8faccca525c6b1e98fdcd", "save_path": "github-repos/MATLAB/uricamic-flandmark", "path": "github-repos/MATLAB/uricamic-flandmark/flandmark-ecf122f93f73504fe7d8faccca525c6b1e98fdcd/learning/code/Functions/getPsiMat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4955122000936246}} {"text": "function kernel = calibSPIRiT(kCalib, kSize, nCoils, CalibTyk)\n\n% kernel = calibSPIRiT(kCalib, kSize, nCoils, CalibTyk)\n%\n% Function calibrates a SPIRiT kernel from a calibration area in k-space\n%\n%\n% (c) Michael Lustig 2013\n%\n\n[AtA] = dat2AtA(kCalib,kSize);\nfor n=1:nCoils\n\tkernel(:,:,:,n) = calibrate(AtA,kSize,nCoils,n,CalibTyk);\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/utils/utils_SPIRiT/calibSPIRiT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.49551220009362457}} {"text": "function simOutput = mpcSim(nx, ny, nu, Nsim, e0, umin, umax, H, G, Lineq, Mineq, Leq, Meq, phi, gamma, lambda, chkInputBoundFlag, sivdMode, Xref)\n% mpcSim Simulate the system with MPC Controller\n% \n% Author : Ajinkya Khade, askhade@ncsu.edu\n\n[J, sivd,exitflag] = deal(zeros(1, Nsim));\n\n% Initializing matrices to log simulation data\nempc = zeros(nx, Nsim); % stores error vectors at all time steps\nympc = zeros(ny, Nsim); % stores output vectors at all time steps\numpc = zeros(nu, Nsim); % stores calculated input vectors \nuact = umpc; % stores applied input vectors \n\n% Assigning values at the beginning of simulation\nempc(:,1) = e0;\numpc(:,1) = 0;\nsivd(1) = Xref(2);\n\n% Options structure for the QP Solver\noptions = optimoptions('quadprog','Algorithm','active-set','Display','off','TolFun',0.001);\n\n% Simulating over N time steps\nfor k = 1:Nsim\n \n F = (2*G(empc(:,k)))';\n \n % Solving the QP at current time step\n [U, J(k),exitflag(k)] = quadprog(H, F, Lineq, Mineq(empc(:,k),sivd(k),Xref(2,k)), ...\n Leq, Meq(empc(:,k)), ...\n [], [], [], options);\n \n\t% Extracting and storing calculated input at current time step\n umpc(:,k) = U(1:nu);\n % Checking for saturation and storing applied input at current time step\n uact(:,k) = getActualU(umpc(:,k), umin, umax, chkInputBoundFlag);\n\t% Calculating and storing error vector at current time step\n empc(:,k+1) = phi*empc(:,k) + gamma*uact(:,k);\n\t% Calculating and storing ouput at current time step\n ympc(:,k) = lambda*empc(:,k);\n \n % Calculating SIVD\n if sivdMode == 0\n % SIVD varies linearly with reference trajectory\n sivd(k+1) = Xref(2,k);\n elseif sivdMode == 1\n % SIVD varies dynamically with range rate\n sivd(k+1) = getsivd(empc(2,k), umin);\n end\n \n % Update range and range rate to make it relative to SIVD\n empc(1,k+1) = empc(1,k+1) + (sivd(k+1) - sivd(k));\n empc(2,k+1) = empc(2,k+1) - (Xref(2,k+1) - Xref(2,k));\nend\n\nempc = empc(:,1:end-1);\nsivd = sivd(:,1:end-1);\n\n% Storing all simulation information in a structure for returning\nsimOutput.empc = empc;\nsimOutput.ympc = ympc;\nsimOutput.umpc = umpc;\nsimOutput.uact = uact;\nsimOutput.sivd = sivd;\nsimOutput.exitflag = exitflag;\nsimOutput.J = J;\n\nend\n\nfunction uact = getActualU(umpc, umin, umax, uConstraintFlag)\n%getActualU Calculate actual input applied.\n% This function checks if input violates bounds and calculates the actual \n% input to be applied.\n\nuact = umpc;\n\nif uConstraintFlag\n if umpc > umax\n uact = umax;\n elseif umpc < umin\n uact = umin;\n end\nend\n\nend", "meta": {"author": "ajinkya-khade", "repo": "ACC_Vehicle_MPC", "sha": "4c5f643977ac417e8186f347bdde4bfff2a33d84", "save_path": "github-repos/MATLAB/ajinkya-khade-ACC_Vehicle_MPC", "path": "github-repos/MATLAB/ajinkya-khade-ACC_Vehicle_MPC/ACC_Vehicle_MPC-4c5f643977ac417e8186f347bdde4bfff2a33d84/mpcSim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.49551219449615175}} {"text": "function F = OCP_F(u,x,p,discretizationMethod,isMEnabled,parIdx) %#codegen\n\n if isMEnabled\n fdt = OCP_GEN_fdt(u,x,p,parIdx);\n % forced to 'Euler'\n M = OCP_GEN_M(u,x,p);\n invM = inv(M);\n invMf = invM*fdt;\n % F\n F = invMf - x;\n else % M disabled\n switch discretizationMethod\n case 'RK2'\n fdt = OCP_GEN_fdt(u,x,p,parIdx); \n f12dt = OCP_GEN_fdt(u,x-fdt/2,p,parIdx); \n\n F = f12dt - x;\n case 'RK4'\n fdt = OCP_GEN_fdt(u,x,p,parIdx); % k1\n f12dt = OCP_GEN_fdt(u,x-fdt/2,p,parIdx); % k2\n f22dt = OCP_GEN_fdt(u,x-f12dt/2,p,parIdx); % k3\n f3dt = OCP_GEN_fdt(u,x-f22dt,p,parIdx); % k4\n\n F = (fdt+2*f12dt+2*f22dt+f3dt)/6 - x;\n\n otherwise % 'Euler'\n fdt = OCP_GEN_fdt(u,x,p,parIdx);\n F = fdt - x;\n end\n end\nend", "meta": {"author": "deng-haoyang", "repo": "ParNMPC", "sha": "ddbe418e630b49897e8bc17e5c2f9e1ef1ab453b", "save_path": "github-repos/MATLAB/deng-haoyang-ParNMPC", "path": "github-repos/MATLAB/deng-haoyang-ParNMPC/ParNMPC-ddbe418e630b49897e8bc17e5c2f9e1ef1ab453b/ParNMPC/OCP_F.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4955121888986788}} {"text": "function varargout = imregrotate(varargin)\n%ROIROTATE Rotate & crop region of interest avoiding 'black corners'.\n% \tB = ROIROTATE(A,ROI,ANGLE,METHOD) rotates the region of intererest ROI\n% \tfound in the image A by ANGLE degrees in a counter-clockwise direction, \n% \tusing the specified interpolation method and gives the rotated \n% \tregion as output in B cropped out of the original image.\n% \t\n% \tUsefulness\n% \t----------\n% \tROIROTATE was designed to avoid the 'black corners' typical of\n% MATLAB's imrotate function, which are apearing from its behaviour\n% of padding by zeros the space outside the image borders prior to \n% the rotation. This is possible if the image to be rotated is \n% part of a bigger image - which is the definition of a 'region \n% of interest' -, because there is enough information to fill \n% the corners.\n% \t\n% \tDescription\n% \t-----------\n% \tApart of the first entry which is based on the IMCROP syntax, \n% \tall other are identical to the IMROTATE function.\n% \t\n% ROI is a four-element vector with the form [xmin ymin width height];\n% these values are specified in spatial coordinates.\n% \t\n% \txmin - starting pixel to be cut, x-th of the original image\n% \tymin - same on y-axis\n% \twidth - number of pixels to be cut minus one (width)\n% \theight - same on height\n% \t\n% \tIf you want to point the 5 pixel wide & 7 pixel heigh NW corner \n% \tof an image, replace R with [1,1,4,6].\n% \t\n% Because ROI is specified in terms of spatial coordinates,\n% the WIDTH and HEIGHT of ROI do not always correspond exactly\n% with the size of the output image. For example, suppose ROI\n% is [20 20 40 30], using the default spatial coordinate\n% system. The upper left corner of the specified rectangle is\n% the center of the pixel (20,20) and the lower right corner is\n% the center of the pixel (50,60). The resulting output image\n% is 31-by-41, not 30-by-40, because the output image includes\n% all pixels in the input that are completely or partially\n% enclosed by the rectangle.\n% \t\n% Note for IMCROP:\n% To cut the NW pixel only:\n% NWcornerPixel = imcrop(I, [1,1,0,0]);\n% \n% To cut the first top stripe of pixels:\n% topStripe = imcrop(I, [1,1,size(I,2)-1,0]);\n% \t\n% \tMETHOD is a string that can have one of these values:\n% \t\n% 'nearest' (default) nearest neighbor interpolation\n% 'bilinear' bilinear interpolation\n% 'bicubic' bicubic interpolation\n% \t\n% \tIf you omit the METHOD argument, ROIROTATE uses the default\n% \tmethod of 'nearest'.\n%\n% To rotate the image clockwise, specify a negative angle.\n% \t\n% \tClass Support\n% \t-------------\n% \tThe input image can be of class uint8, uint16, or double.\n% The output image is of the same class as the input image.\n% \t\n% \tExample\n% \t-------\n% I = imread('circuit.tif');\n% J = imrotate(imcrop(I,[60 80 100 90]),-21,'bilinear','crop');\n% [K x y w h] = roirotate(I,[60 80 100 90],-21,'bilinear');\n% figure, subplot(1,3,1), imshow(I), title('roi')\n% rectangle('Position',[60 80 100 90],'EdgeColor','red');\n% rectangle('Position',[x y w h],'EdgeColor','green');\n% subplot(1,3,2), imshow(J), title('imrotate')\n% subplot(1,3,3), imshow(K), title('roirotate')\n%\n% \tSee also IMROTATE, IMCROP, IMRESIZE, IMTRANSFORM, TFORMARRAY.\n\n% Vlad Atanasiu - 06/05/2002\n% Revisions: 3 > 01/11/2008\n\n\n\n% check image input data\n[A,dim,x,y,width,height,ang,method] = parseInputs(varargin{:});\n\n% calculate padding borders\npadX = abs(ceil(height*sin(ang*pi/180)/2));\npadY = abs(ceil(width*sin(ang*pi/180)/2));\n\n% padding zeros if extended region of interest coordinates outside image\nif x-padX < 1 % left\n A = [zeros(size(A,1),padX-x+1,dim) A];\nend\nif y-padY < 1 % top\n A = [zeros(padY-y+1,size(A,2),dim);...\n A];\nend\nif x+width+padX > size(A,2) % right\n A = [A zeros(size(A,1),x+width+padX-size(A,2),dim)];\nend\nif y+height+padY > size(A,1) % bottom\n A = [A;...\n zeros(y+height+padY-size(A,1),size(A,2),dim)];\nend\n\n% cut extended region\nROI = imcrop(A,[x-padX y-padY width+padX*2 height+padY*2]);\n\n% rotate extended region\nROI = imrotate(ROI,ang,method,'crop');\n\n% cut region\nvarargout{1} = imcrop(ROI,[padX padY width height]);\n\n% gives extended region coordinates\nif nargout == 5\n varargout{2} = x-padX;\n varargout{3} = y-padY;\n varargout{4} = width+padX*2;\n varargout{5} = height+padY*2;\nend\n\n\n% ------------------------------------------------\n\nfunction [A,dim,x,y,width,height,ang,method] = parseInputs(varargin)\n% Input checkings\n\n% Defaults\nmethod = 'n';\n\n% Check number of input parameters\nerror(nargchk(3,4,nargin));\nswitch nargin\ncase 3, % regrotate(A,reg,ang,)\n A = varargin{1};\n\tx = varargin{2}(1);\n\ty = varargin{2}(2);\n\twidth = varargin{2}(3);\n\theight = varargin{2}(4);\n ang = varargin{3};\ncase 4, % regrotate(A,reg,ang,method) \n A = varargin{1};\n\tx = varargin{2}(1);\n\ty = varargin{2}(2);\n\twidth = varargin{2}(3);\n\theight = varargin{2}(4);\n ang = varargin{3};\n method = varargin{4};\notherwise,\n error('Invalid number of input arguments.');\nend\n\n% Check validity of the input parameters \nif ischar(method),\n strings = {'nearest','bilinear','bicubic'};\n idx = strmatch(lower(method),strings);\n if isempty(idx),\n error(sprintf('Unknown interpolation method: %s',method));\n elseif length(idx)>1,\n error(sprintf('Ambiguous interpolation method: %s',method));\n else\n method = strings{idx};\n end \nelse\n error('Interpolation method have to be a string.'); \nend\n\nif size(varargin{2},2) ~= 4\n error('Region of interest should be defined by 4 arguments.'); \nend\n\n% transforms the format of A into an image if it is a filename\nif (isstr(A))\n A = imread(A);\nend\n\n% gets the dimensions of A\ndim = ndims(A);\nif dim == 2, dim=1; end\n\n% modifies if needed the region of interest coordinates if outside image\nif x < 1, x = 1; end\nif y < 1, y = 1; end\nif x > size(A,2)-1, x = size(A,2)-1; end\nif y > size(A,1)-1, y = size(A,1)-1; end\nif x+width > size(A,2)-1, width = size(A,2)-x-1; end\nif y+height > size(A,1)-1, height = size(A,1)-y-1; end\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/1825-fill-corners-of-rotated-image/roirotate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.49546079762345235}} {"text": "function [varsigma] = ppcaPosteriorVar(model, X);\n\n% PPCAPOSTERIORVAR Mean and variances of the posterior at points given by X.\n% FORMAT\n% DESC returns the posterior mean and variance for a given set of\n% points.\n% ARG model : the model for which the posterior will be computed.\n% ARG x : the input positions for which the posterior will be\n% computed.\n% RETURN sigma : the variances of the posterior distributions.\n%\n% SEEALSO : ppcaCreate, ppcaPosteriorMeanVar\n%\n% COPYRIGHT : Neil D. Lawrence, 2008\n\n% MLTOOLS\n\nvarsigma = repmat(1/model.beta, size(X, 1), 1);\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/mltools/ppcaPosteriorVar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.49546079762345224}} {"text": "function varargout = det(varargin)\n%DET (overloaded)\n%\n% t = DET(X)\n\nswitch class(varargin{1})\n \n case 'sdpvar' % Overloaded operator for SDPVAR objects. Pass on args and save them.\n \n X = varargin{1};\n [n,m] = size(X);\n if n~=m\n error('Matrix must be square.')\n end\n if nargin == 2\n if strcmp(varargin{2},'polynomial')\n varargout{1} = polynomialform(X);\n return\n else\n error('If you use two arguments in @sdpvar/det, the second should be ''polynomial''');\n end\n end\n if n==1\n varargout{1} = X;\n return\n else\n y = yalmip('define','det_internal',reshape(X,[],1));\n end\n varargout{1} = y;\n\n otherwise\nend\n\n\nfunction d = polynomialform(X)\n\nn = X.dim(1);\nm = X.dim(2);\n\nif n~=m\n error('Matrix must be square.');\nelse\n switch n\n case 1\n d = X;\n case 2\n % Freakin overloading on multiplication doesn't work. Probalby\n % stupid code...\n Y1.type = '()';\n Y2.type = '()';\n Y3.type = '()';\n Y4.type = '()';\n Y1.subs = {1,1};\n Y2.subs = {2,2};\n Y3.subs = {1,2};\n Y4.subs = {2,1};\n d = subsref(X,Y1)*subsref(X,Y2)-subsref(X,Y3)*subsref(X,Y4);\n otherwise\n d = 0;\n Y.type = '()';\n for i = 1:n\n Y.subs = {i,1};\n xi = subsref(X,Y);\n if ~isequal(xi,0)\n Y.subs = {[1:1:i-1 i+1:1:n],2:n};\n subX = subsref(X,Y);\n if isa(subX,'sdpvar')\n d = d + (-1)^(i+1)*xi*polynomialform(subX);\n else\n d = d + (-1)^(i+1)*xi*det(subX);\n end\n end\n end\n end\nend\n% Reset info about conic terms\nif isa(d,'sdpvar')\n d.conicinfo = [0 0];\nend", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/@sdpvar/det.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.49546079762345224}} {"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 y = tifs2cv(f,m,d,q)\n%TIFS2CV Compresses a multi-frame TIFF image sequence.\n% Y = TIFS2CV(F,M,D,Q) compresses multiframe TIFF F using motion\n% compensated frames, 8 x 8 DCT transforms, and Huffman coding. If\n% parameter Q is omitted or is 0, only Huffman encoding is used and\n% the compression is lossless; for Q > 0, lossy JPEG encoding is\n% performed. The inputs are:\n%\n% F A multi-frame TIFF file (e.g., 'file.tif') \n% M Macroblock size (e.g., 8)\n% D Search displacement (e.g., [16 8])\n% Q JPEG quality for IM2JPEG (e.g., 1)\n%\n% Output Y is an encoding structure with fields: \n%\n% Y.blksz Size of motion compensation blocks\n% Y.frames The number of frames in the image sequence\n% Y.quality The reconstruction quality\n% Y.motion Huffman encoded motion vectors\n% Y.video An array of MAT2HUFF or IM2JPEG coding structures\n%\n% See also CV2TIFS.\n%\n% Copyright 2002-2020 Gatesmark\n%\n% This function, and other functions in the DIPUM Toolbox, are based \n% on the theoretical and practical foundations established in the \n% book Digital Image Processing Using MATLAB, 3rd ed., Gatesmark \n% Press, 2020.\n%\n% Book website: http://www.imageprocessingplace.com\n% License: https://github.com/dipum/dipum-toolbox/blob/master/LICENSE.txt\n\n% The default reconstruction quality is lossless.\nif nargin < 4\n q = 0;\nend\n\n% Compress frame 1 and reconstruct for the initial reference frame.\nif q == 0\n cv(1) = mat2huff(imread(f,1));\n r = double(huff2mat(cv(1)));\nelse\n cv(1) = im2jpeg(imread(f,1),q);\n r = double(jpeg2im(cv(1)));\nend\nfsz = size(r);\n\n% Verify that image dimensions are multiples of the macroblock size.\nif ((mod(fsz(1),m) ~= 0) || (mod(fsz(2),m) ~= 0))\n error('Image dimensions must be multiples of the block size.');\nend\n\n% Get the number of frames and preallocate a motion vector array.\nfcnt = size(imfinfo(f),1);\nmvsz = [fsz/m 2 fcnt];\nmv = zeros(mvsz);\n\n% For all frames except the first, compute motion conpensated\n% prediction residuals and compress with motion vectors.\nfor i = 2:fcnt\n frm = double(imread(f,i));\n frmC = im2col(frm,[m m],'distinct');\n eC = zeros(size(frmC));\n \n for col = 1:size(frmC,2)\n lookfor = col2im(frmC(:,col),[m m],[m m],'distinct');\n \n x = 1 + mod(m * (col - 1),fsz(1));\n y = 1 + m * floor((col - 1) * m / fsz(1));\n x1 = max(1,x - d(1));\n x2 = min(fsz(1),x + m + d(1) - 1);\n y1 = max(1,y - d(2));\n y2 = min(fsz(2),y + m + d(2) - 1);\n \n here = r(x1:x2,y1:y2);\n hereC = im2col(here,[m m],'sliding');\n for j = 1:size(hereC,2)\n hereC(:,j) = hereC(:,j) - lookfor(:);\n end\n sC = sum(abs(hereC));\n s = col2im(sC,[m m],size(here),'sliding');\n mins = min(min(s));\n [sx,sy] = find(s == mins);\n \n ns = abs(sx) + abs(sy); % Get the closest vector\n si = find(ns == min(ns));\n n = si(1);\n \n mv(1 + floor((x - 1)/m), 1 + floor((y - 1)/m), 1:2, i) = ...\n [x - (x1 + sx(n) - 1) y - (y1 + sy(n) - 1)];\n eC(:,col) = hereC(:, sx(n) + (1 + size(here,1) - m) ...\n * (sy(n) - 1));\n end\n\n % Code the prediction residual and reconstruct it for use in\n % forming the next reference frame.\n e = col2im(eC,[m m],fsz,'distinct');\n if q == 0\n cv(i) = mat2huff(int16(e));\n e = double(huff2mat(cv(i)));\n else\n cv(i) = im2jpeg(uint16(e + 255),q,9);\n e = double(jpeg2im(cv(i)) - 255);\n end\n \n % Decode the next reference frame. Use the motion vectors to get\n % the subimages needed to subtract from the prediction residual.\n rC = im2col(e,[m m],'distinct');\n for col = 1:size(rC,2)\n u = 1 + mod(m * (col - 1),fsz(1));\n v = 1 + m * floor((col - 1) * m / fsz(1));\n rx = u - mv(1 + floor((u - 1)/m), 1 + floor((v - 1)/m), 1, i);\n ry = v - mv(1 + floor((u - 1)/m), 1 + floor((v - 1)/m), 2, i);\n temp = r(rx:rx + m - 1,ry:ry + m - 1);\n rC(:,col) = temp(:) - rC(:,col);\n end\n r = col2im(double(uint16(rC)),[m m],fsz,'distinct');\nend\n\ny = struct;\ny.blksz = uint16(m);\ny.frames = uint16(fcnt);\ny.quality = uint16(q);\ny.motion = mat2huff(mv(:));\ny.video = cv;\n", "meta": {"author": "dipum", "repo": "dipum-toolbox", "sha": "9ce653c4c0c4b7c56e46194c24bf152db4ab6832", "save_path": "github-repos/MATLAB/dipum-dipum-toolbox", "path": "github-repos/MATLAB/dipum-dipum-toolbox/dipum-toolbox-9ce653c4c0c4b7c56e46194c24bf152db4ab6832/dipum/tifs2cv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.495460792370122}} {"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": "%FEATSELI Trainable mapping for individual feature selection\n% \n% [W,R] = FEATSELI(A,CRIT,K,T)\n% [W,R] = A*FEATSELI([],CRIT,K,T)\n% [W,R] = A*FEATSELI(CRIT,K,T)\n% [W,R] = FEATSELI(A,CRIT,K,N)\n% [W,R] = A*FEATSELI([],CRIT,K,N)\n% [W,R] = A*FEATSELI(CRIT,K,N)\n% \n% INPUT\t\n% A Training dataset\n% CRIT Name of the criterion or untrained mapping\n% (default: 'NN', i.e. the LOO 1-Nearest Neighbor error)\n% K Number of features to select (default: sort all features)\n% T Tuning dataset (optional)\n% N Number of cross-validations (optional)\n%\n% OUTPUT\n% W Feature selection mapping\n% R Matrix with criterion values\n%\n% DESCRIPTION\n% Individual selection of K features using the dataset A. CRIT sets the\n% criterion used by the feature evaluation routine FEATEVAL. If the dataset\n% T is given, it is used as test set for FEATEVAL. For K = 0 all features are\n% selected, but reordered according to the criterion. The result W can be\n% used for selecting features using B*W. \n% The selected features are stored in W.DATA and can be found by +W.\n% In R, the search is reported step by step as:\n% \n% \tR(:,1) : number of features\n% \tR(:,2) : criterion value\n% \tR(:,3) : added / deleted feature\n% \n% SEE ALSO (PRTools Guide)\n% MAPPINGS, DATASETS, FEATEVAL, FEATSELO, FEATSELB, FEATSELF,\n% FEATSEL, FEATSELP,FEATSELM\n\n% Copyright: R.P.W. Duin, duin@ph.tn.tudelft.nl\n% Faculty of Applied Sciences, Delft University of Technology\n% P.O. Box 5046, 2600 GA Delft, The Netherlands\n\n% $Id: featseli.m,v 1.5 2009/07/01 07:48:05 davidt Exp $\n\nfunction [w,r] = featseli(varargin)\n\n varargin = shiftargin(varargin,{'char','prmapping'});\n argin = setdefaults(varargin,[],'NN',0,[]);\n if mapping_task(argin,'definition')\n w = define_mapping(argin,'untrained','Individual FeatSel');\n return\n end\n \n [a,crit,ksel,t] = deal(argin{:});\n\n\t[m,k,c] = getsize(a); featlist = getfeatlab(a);\n\n\t% If KSEL is not given, return all features.\n\n\tif (ksel == 0), ksel = k; end\n\t\n\tisvaldfile(a,1,2); % at least 1 object per class, 2 classes\n\ta = testdatasize(a);\n\tif isdataset(t), iscomdset(a,t); end\n\t\n\tcritval = zeros(k,1);\n\t\n\t% Evaluate each feature in turn.\n\n\ts = sprintf('Evaluation of %i features: ',k);\n\tprwaitbar(k,s);\n a = setprior(a,getprior(a));\n\tif (isempty(t))\n\t\tfor j = 1:k\n\t\t\tprwaitbar(k,j,[s int2str(j)]);\n\t\t\tcritval(j) = feateval(a(:,j),crit);\n\t\tend\n elseif isdataset(t)\n\t\tfor j = 1:k\n\t\t\tprwaitbar(k,j,[s int2str(j)]);\n\t\t\tcritval(j) = feateval(a(:,j),crit,t(:,j));\n end\n else\n\t\tfor j = 1:k\n\t\t\tprwaitbar(k,j,[s int2str(j)]);\n\t\t\tcritval(j) = feateval(a(:,j),crit,t);\n end\n\tend\n\tprwaitbar(0);\n\n\t% Sort the features by criterion value (maximum first).\n\t[critval_sorted,J] = sort(-critval);\n\tr = [[1:k]', -critval_sorted, J];\n\tJ = J(1:ksel)'; \n\n\t% Return the mapping found.\n\tw = featsel(k,J);\n w = setmapping_type(w,'trained');\n w = setsize(w,[k length(J)]);\n\tif ~isempty(featlist)\n\t\tw = setlabels(w,featlist(J,:));\n\tend\n\tw = setname(w,'Individual FeatSel');\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/featseli.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6513548782017746, "lm_q1q2_score": 0.49545352029702017}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Max manipulability index ALONG A LINE.\n% Use stomp like to optimize along a surface/line\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction experiment1B\nclose all;\nglobal robot\nglobal parameters\nglobal hfigures\n\n%STOMP PARAMETERS\n%conversion from cost to Prob factor\nparameters.lambda = .4;\nparameters.lambda_obstacles = .2;\n%height of the obstacle\nparameters.yo = 2.5;\n%cost function starts at this distance\n%must be below 0.3 for the 4 DOF robot\nparameters.epsilon = 0.2;\n%multiply noise by this facto\n%parameters.noise_k = 5;\n%parameters.noise_sigma_null_space = 0.01;\nparameters.alpha=0.02;\nparameters.time_step=0.01;\n\n%number of waypoints\nparameters.N = 12;\n%number of particles\nparameters.K = 10;\nparameters.n_repeat = 30;\nparameters.experiment_name = 'experiment1B_K10_N30.mat';\n\nparameters.animate = 0;\n\nparameters.obstacles = [];\n\n\n%LINE 1\nx1 = -1.5;\ny1 = .5; %m\nx2 = 0;\ny2 = 2; %m\nphi = 3*pi/4; \np0 = [x1 y1 0]';\npf = [x2 y2 0]';\nT0 = build_T_4dof(p0, phi);\nparameters.obstacles{1}.line = [p0 pf];\nparameters.obstacles{1}.T0 = T0;\n\n%repeat the experiment E times\nrandom_manips=[];\nGout = [];\nfor i=1:parameters.n_repeat\n close all\n [pk, final_manip] = stomp_null_space(robot);\n Gout{i}=pk;\n random_manips = [random_manips; final_manip];\n save(parameters.experiment_name)\nend\n\n\n\nfunction T = build_T_4dof(p, phi)\nT = [cos(phi) -sin(phi) 0 p(1);\n sin(phi) cos(phi) 0 p(2);\n 0 0 1 p(3);\n 0 0 0 1];\n \n function T = build_T_sawyer(p, phi)\nT = [1 -sin(phi) 0 p(1);\n 0 cos(phi) 0 p(2);\n 0 0 1 p(3);\n 0 0 0 1];\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/lib/SCO_v0.5/backup/experiment1/experiment1B_K10_N30.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.495453502932761}} {"text": "classdef LIRCMOP14 < PROBLEM\n% \n% Constrained benchmark MOP with large infeasible regions\n\n%------------------------------- Reference --------------------------------\n% Z. Fan, W. Li, X. Cai, H. Huang, Y. Fang, Y. You, J. Mo, C. Wei, and E.\n% Goodman, An improved epsilon constraint-handling method in MOEA/D for\n% CMOPs with large infeasible regions, Soft Computing, 2019, 23:\n% 12491-12510.\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 Wenji Li\n \n methods\n %% Default settings of the problem\n function Setting(obj)\n obj.M = 3;\n if isempty(obj.D); obj.D = 30; end\n obj.lower = zeros(1,obj.D);\n obj.upper = ones(1,obj.D);\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 [popsize,variable_length] = size(X);\n sum1 = zeros(popsize,1);\n for j = 3 : variable_length\n sum1 = sum1+10*(X(:,j)-0.5).^2;\n end\n PopObj(:,1) = (1.7057+sum1).*cos(0.5*pi*X(:,1)).*cos(0.5*pi*X(:,2));\n PopObj(:,2) = (1.7057+sum1).*cos(0.5*pi*X(:,1)).*sin(0.5*pi*X(:,2));\n PopObj(:,3) = (1.7057+sum1).*sin(0.5*pi*X(:,1));\n gx = PopObj(:,1).^2+PopObj(:,2).^2+PopObj(:,3).^2;\n PopCon(:,1) = (gx-9).*(4-gx);\n PopCon(:,2) = (gx-3.61).*(3.24-gx);\n PopCon(:,3) = (gx-3.0625).*(2.56-gx);\n Population = SOLUTION(X,PopObj,PopCon,varargin{2:end});\n obj.FE = obj.FE + length(Population);\n end\n %% Generate points on the Pareto front\n function R = GetOptimum(obj,N)\n R = UniformPoint(N,3);\n R = sqrt(3.0625)*R./repmat(sqrt(sum(R.^2,2)),1,3);\n end\n %% Generate the image of Pareto front\n function R = GetPF(obj)\n a = linspace(0,pi/2,10)';\n R = {sin(a)*cos(a')*sqrt(3.0625),sin(a)*sin(a')*sqrt(3.0625),cos(a)*ones(size(a'))*sqrt(3.0625)};\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/LIR-CMOP/LIRCMOP14.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6513548578981939, "lm_q1q2_score": 0.49545349778478365}} {"text": "function i4vec_indexed_heap_d_insert_test ( )\n\n%*****************************************************************************80\n%\n%% I4VEC_INDEXED_HEAP_D_INSERT_TEST tests I4VEC_INDEXED_HEAP_D_INSERT.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 September 2014\n%\n% Author:\n%\n% John Burkardt\n%\n m = 20;\n n_max = 20;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4VEC_INDEXED_HEAP_D_INSERT_TEST\\n' );\n fprintf ( 1, ' For an indexed I4VEC,\\n' );\n fprintf ( 1, ' I4VEC_INDEXED_HEAP_D_INSERT inserts a value into the heap.\\n' );\n%\n% Set the data array. To keep things easy, we will use the indicator vector.\n%\n a = i4vec_indicator1 ( m );\n%\n% The index array will initially be a random subset of the numbers 1 to M,\n% in random order.\n%\n n = 5;\n indx(1:11,1) = [ 9, 2, 8, 14, 5, 7, 15, 1, 19, 20, 3 ]';\n\n i4vec_print ( m, a, ' The data vector:' );\n i4vec_print ( n, indx, ' The index vector:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' A(INDX):\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n\n fprintf ( 1, ' %4d %4d\\n', i, a(indx(i)) );\n end\n%\n% Create a descending heap from the indexed array.\n%\n indx = i4vec_indexed_heap_d ( n, a, indx );\n\n i4vec_print ( n, indx, ' The index vector after heaping:' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' A(INDX) after heaping:\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n\n fprintf ( 1, ' %4d %4d\\n', i, a(indx(i)) );\n end\n%\n% Insert five entries, and monitor the maximum.\n%\n for i = 1 : 5\n\n indx_insert = indx(n+1);\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Inserting value %d\\n', a(indx_insert) );\n\n [ n, indx ] = i4vec_indexed_heap_d_insert ( n, a, indx, indx_insert );\n\n indx_max = i4vec_indexed_heap_d_max ( n, a, indx );\n\n fprintf ( 1, ' Current maximum is %d\\n', a(indx_max) );\n\n end\n i4vec_print ( m, a, ' The data vector after insertions:' )\n i4vec_print ( n, indx, ' The index vector after insertions:' )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' A(INDX) after insertions:\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n\n fprintf ( 1, ' %4d %4d\\n', i, a(indx(i)) );\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_indexed_heap_d_insert_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.4954534961709585}} {"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 [R2,R2_states] = tudaR2(X,Y,T,tuda,Gamma)\n% Training explained variance per time point per each state\n%\n% R2_states is per state, R2 is for the entire model\n% X and Y must be in matrix format (2D)\n% All trials must have equal size, ie all elements of T must be equal\n%\n% Diego Vidaurre\n\nif any(T(1)~=T)\n error(['tudaR2 requires that all trials have the same length, ' ...\n 'i.e. that all elements in T are equal']);\nend\n\n[X,Y,T] = preproc4hmm(X,Y,T,tuda.train);\n\nintercept = all(X(:,1)==1); \n\nN = length(T); ttrial = T(1); p = size(X,2);\nK = length(tuda.state); q = size(Y,2);\n\nif intercept\n mY = repmat(mean(Y),size(Y,1),1); % one single mean value for the entire data\n mY = reshape(mY,[ttrial N q]);\nelse\n mY = zeros(ttrial,N,q);\nend\n\nmat1 = ones(ttrial,q);\nY = reshape(Y,[ttrial N q]);\nYhat = zeros(ttrial,N,q);\n\nR2_states = zeros(ttrial,q,K);\nbeta = tudabeta(tuda);\nfor k = 1:K\n Yhatk = X * beta(:,:,k); %tuda.state(k).W.Mu_W(1:p,p+1:end);\n Yhatk = reshape(Yhatk,[ttrial N q]);\n if k > size(Gamma,2) % NESS model baseline state\n break%\n noGamma = prod(1-Gamma,2);\n Yhat = Yhat + Yhatk .* reshape(repmat(noGamma,1,q),[ttrial,N,q]);\n else\n Yhat = Yhat + Yhatk .* reshape(repmat(Gamma(:,k),1,q),[ttrial,N,q]);\n end\n if intercept\n mYk = mean(reshape(Y,[ttrial*N q]) .* repmat(Gamma(:,k),1,q));\n mYk = reshape(repmat(mYk,size(Y,1),1),[ttrial N q]);\n else\n mYk = zeros(ttrial,N,q);\n end\n ek = permute(sum((Yhatk - Y).^2,2),[1 3 2]); % ttrial x q\n e0k = permute(sum((mYk - Y).^2,2),[1 3 2]); % ttrial x q\n R2_states(:,:,k) = mat1 - ek ./ e0k ; % we do not compute the \nend\n\ne = permute(sum((Yhat - Y).^2,2),[1 3 2]); % ttrial x q\ne0 = permute(sum((mY - Y).^2,2),[1 3 2]); % ttrial x q\nR2 = mat1 - e ./ e0 ;\n\nend", "meta": {"author": "OHBA-analysis", "repo": "HMM-MAR", "sha": "bb0433b75482e473980791a2b30afe2012cf6578", "save_path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR", "path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR/HMM-MAR-bb0433b75482e473980791a2b30afe2012cf6578/task/tudaR2.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 [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\u00b0)\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=Tsallis_entro(x,q)\n [M,N]=size(x);\n y=zeros(1,N);\n for l=1:N\n sum1=sum(x(:,l)-(x(:,l)).^q);\n sum2=sum1/(q-1);\n y(1,l)=sum2;\n end", "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/18133-shannon-and-non-extensive-entropy/entropy/Tsallis_entro.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6187804267137441, "lm_q1q2_score": 0.4954525328373978}} {"text": "function [P,E,logw,acc,traj] = spm_mci_ais_single (mcmc,M,U,Y)\n% Produce a single independent sample using AIS\n% FORMAT [P,E,logw,acc,traj] = spm_mci_ais_single (mcmc,M,U,Y)\n%\n% mcmc Sampling settings\n% M Model structure\n% U Input structure\n% Y Data\n%\n% P [Np x 1] sample\n% E Negative log joint\n% logw Contribution to model evidence\n% acc acc(j) is acceptance rate at temperature j\n% traj traj(p,j) is value of parameter p at temperature j\n% (only set if mcmc.rec_traj=1)\n%__________________________________________________________________________\n% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny\n% $Id: spm_mci_ais_single.m 6548 2015-09-11 12:39:47Z will $\n\nbeta=mcmc.beta;\nnprop=mcmc.nprop;\nprop=mcmc.prop;\nscale=mcmc.scale;\n\nJ=length(beta);\n\nif isstruct(M.pC)\n pC = full(diag(spm_vec(M.pC)));\nelse\n pC = M.pC;\nend\n% prior cov in subspace\npC=M.V'*pC*M.V;\n\nNp=size(pC,1);\n\n% Sample from prior (in subspace)\nx(:,1) = spm_normrnd(zeros(Np,1),pC,1);\n[L(1),L2] = spm_mci_joint (x(:,1),M,U,Y);\nLsum = (beta(2)-beta(1))*L2;\nacc(1) = 1;\nfor j=2:J,\n xs=x(:,j-1); Ls=L(:,j-1);acc(j)=0;\n switch prop,\n case 'mh',\n % Generate sample at next temperature by composing\n % Metropolis moves at different scales\n for s=1:nprop,\n dx=spm_normrnd(zeros(Np,1),scale(s)^2*pC,1);\n xcand=xs+dx;\n [Lcand,L2cand] = spm_mci_joint (xcand,M,U,Y,beta(j));\n dL = Lcand-Ls;\n r = exp(dL);\n alpha = min(1,r);\n test_prob = rand(1);\n if alpha > test_prob\n % Accept\n xs = xcand;\n Ls = Lcand;\n L2 = L2cand;\n acc (j) = 1;\n end\n end\n \n case 'lmc',\n % Generate sample at next temperature using\n % Langevin Monte Carlo\n M.beta=beta(j);\n lgv_mcmc.init=xs;\n lgv_mcmc.maxits=nprop;\n lgv_mcmc.update_obs_noise=0;\n \n [tmp,stats] = spm_mci_lgv (lgv_mcmc,M,U,Y);\n \n xs = stats.P(:,end);\n Ls = -stats.E(:,end);\n L2 = stats.L2(end);\n acc (j) = any(stats.acc(2:end));\n \n otherwise\n disp('Unknown proposal type in spm_mci_ais_single.m');\n end\n x(:,j)=xs;\n L(j)=Ls;\n if j < J\n Lsum = Lsum + (beta(j+1)-beta(j))*L2;\n end\nend\nlogw=Lsum;\nP=x(:,J);\nE=-L(J);\n\nif mcmc.rec_traj\n nj=size(x,2);\n traj=spm_vec(M.pE)*ones(1,nj)+M.V*x;\nelse\n traj=[];\nend\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/mci/inference/spm_mci_ais_single.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.49538675863039544}} {"text": "function [fdMc, bH, fPval, fKsstat] = calc_KStest_dMc(mCat1, mCat2)\n% ----------------------------------------------------------------------------------------------\n%\n% Incoming variable\n% mCat1 : EQ catalog period 1 (Catalog to be modified)\n% mCat2 : EQ catalog period 2 (Observed catalog)\n%\n% Outgoing variable\n%\n% Author: J. Woessner, woessner@seismo.ifg,.ethz.ch\n% last update: 21.01.04\n\nfBinning = 0.1;\nnSample = 100;\nnMethod = 6;\n\n% Determine exact time period\nfPeriod1 = max(mCat1(:,3)) - min(mCat1(:,3));\nfPeriod2 = max(mCat2(:,3)) - min(mCat2(:,3));\n\n\n% Initialize values\nfMinMag = min([min(mCat1(:,6)) min(mCat2(:,6))]);\nfMaxMag = max([max(mCat1(:,6)) max(mCat2(:,6))]);\n\n%% Calculate model for best fitting Mc, both periods\n[mResult1, fMls1, fMc1, fMu1, fSigma1, mDataPredBest1, vPredBest1, fBValue1, fAvalue1] = calc_McCdfnormal(mCat1, fBinning);\n[mResult, fMls, fMc2, fMu, fSigma, mDataPredBest, vPredBest, fBValue2, fAvalue2] = calc_McCdfnormal(mCat2, fBinning);\n\n% Using bootstrap approach\n% [fMc1, fStd_Mc1, fBvalue1, fStd_B1, fAvalue1, fStd_A1, vMc1, mBvalue1] = calc_McBboot(mCat1, fBinning, nSample, nMethod)\n% [fMc2, fStd_Mc2, fBvalue2, fStd_B2, fAvalue2, fStd_A2, vMc2, mBvalue2] = calc_McBboot(mCat2, fBinning, nSample, nMethod)\n\n% Mc difference\nfdMc = fMc2-fMc1;\n\ntry\n % Select part of catalog\n vSel = mCat1(:,6) >= fMc2-fBinning/2;\n mCat1tmp=mCat1(vSel,:);\n\n % Create Model distribution\n vMagnitudes = [fMc2:0.1:floor(max(mCat2(:,6)))+0.1];\n % Productuvity for fMc2\n nNumberEvents = length(mCat1tmp(:,1));\n %vNumbers = 10.^(log10(nNumberEvents) - fBValue1*(vMagnitudes-fMc2));\n vNumbers = 10.^(fAvalue1- fBValue1*(vMagnitudes));%-fMc2\n vNumbers = round(vNumbers);\n vNCumFMD = round(-diff(vNumbers));\n % Calculate synthetic data below Mc\n fMinMag = min(mCat2(:,6));\n vMagstep = fMinMag:0.1:fMc2-0.1;\n vProb = normcdf(vMagstep,fMu1, fSigma1);\n vProb = vProb';\n vMagstep = vMagstep';\n\n % Calculate number of EQs in bins\n fN_Mc = vNCumFMD(1,1);\n vN = round(vProb(:,1)*fN_Mc);\n mNonCumModel = [vN vMagstep; vNCumFMD' vMagnitudes(:,1:end-1)'];\n\n % vMags = mDataPredBest(:,2)';\n % FMD to be modeled (second period)\n [vObsFMD,vBin2] = hist(mCat2(:,6),roundn(min(mCat2(:,6)),-1):0.1:floor(max(mCat2(:,6))));\n\n % Select bins to calculate loglikelihood\n vSel = (mNonCumModel(:,2) < min(vBin2) | mNonCumModel(:,2) > max(vBin2));\n vPredFMD = mNonCumModel(~vSel,:);\n % Normalize\n vObsFMD = ceil(vObsFMD./fPeriod2);\n vPredFMD(:,1) = vPredFMD(:,1)./fPeriod1;\n\n if length(vObsFMD') ~= length(vPredFMD(:,1))\n disp('warning')\n end\n % Calculate the likelihood\n vProb_ = calc_log10poisspdf2(vObsFMD', vPredFMD(:,1));\n % Sum the probabilities\n fProbability = (-1) * sum(vProb_);\n\n nDegFree = 1; % degree of freedom\n n_samples = length(mCat2(:,6))+length(mCat1(:,6));\n %% Corrected Akaike Information Criterion (AICc)\n fAICc = -2*(-fProbability)+2*nDegFree+2*nDegFree*(nDegFree+1)/(n_samples-nDegFree-1);\n\ncatch\n fdMc = nan;\n fProbability = nan;\n fAICc = nan;\nend\n\n% % Create model\n% fMinMag = min(mCat2(:,6));\n% vMagstep = fMinMag:0.1:fMc2-0.1;\n% vProb = normcdf(vMagstep,fMu1, fSigma1);\n% vProb = vProb';\n% vMagstep = vMagstep';\n% mDataPredBest1(:,1) = mDataPredBest1(:,1)./fPeriod1;\n%\n% % Calculate number of EQs in bins\n% vSel = (roundn(mDataPredBest1(:,2),-1) == roundn(fMc2,-1));\n% fN_Mc = mDataPredBest1(vSel,1);\n% vN = round(vProb(:,1)*fN_Mc);\n%\n% vSel = mDataPredBest1(:,2) >= fMc2;\n% mModelFMD = [vN vMagstep; mDataPredBest1(vSel,1) mDataPredBest1(vSel,2)];\n\n% Reconstruct vector of magnitudes from model for Period 1\nvMag = [];\n% % Normalize to time period\n% mModelFMD(:,1) = round(mModelFMD(:,1));\nmNonCumModel(:,1) = round(mNonCumModel(:,1)./fPeriod1);\nvSel = (mNonCumModel(:,1) ~= 0); % Remove bins with zero frequency of zero events\nmData = mNonCumModel(vSel,:);\n% mModelFMD = [round(mDataPredBest1(:,1)./fPeriod1) mDataPredBest1(:,2)];\n% vSel = (mModelFMD(:,1) ~= 0); % Remove bins with zero frequency of zero events\n% mData = mModelFMD(vSel,:);\nfor nCnt=1:length(mData(:,1))\n fM = repmat(mData(nCnt,2),mData(nCnt,1),1);\n vMag = [vMag; fM];\nend\n\n% Reconstruct vector of magnitudes from model for Period 2\n% from normalized FMD\nvMag2 = [];\n%mObsFMD = [vObsFMD' vBin2'];\nmObsFMD = [round(mDataPredBest(:,1)./fPeriod2) mDataPredBest(:,2)];\nvSel = (mObsFMD(:,1) ~= 0); % Remove bins with zero frequency of zero events\nmData2 = mObsFMD(vSel,:);\nfor nCnt=1:length(mData2(:,1))\n fM = repmat(mData2(nCnt,2),mData2(nCnt,1),1);\n vMag2 = [vMag2; fM];\nend\n\n[bH,fPval,fKsstat] = kstest2(roundn(vMag2,-1),roundn(vMag,-1),0.05,0);\n\nfigure\nh1=cdfplot(vMag2)\nset(h1,'Color',[1 0 0]);\nhold on\nh2=cdfplot(vMag)\nset(h2,'Color',[0 0 0]);\n\nh3=cdfplot(mCat2(:,6))\nset(h2,'Color',[0 1 0]);\nh4=cdfplot(mCat1(:,6))\nset(h4,'Color',[0 0 1]);\n\n\nfigure\nhistogram(vMag2,min(vMag2):0.1:max(vMag2))\nfigure\nhistogram(vMag,min(vMag):0.1:max(vMag))\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/jochen/seisvar/calc/calc_KStest_dMc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.49538675317469993}} {"text": "function metaboliteMassBalancePlot(model, metAbbr, solution, N)\n% Plots the top N reactions producing and consuming a metabolite in a flux solution\n%\n% USAGE:\n%\n% metaboliteMassBalancePlot(model, metAbbr, solution, N)\n%\n% INPUTS:\n% model: COBRA model structure\n% metAbbr: metabolite abbreviation\n% solution: `solveCobraLP` output of a solution to FBA problem\n% N: Number of reactions to include for production/consumption\n%\n% .. Author: - Ronan M.T. Fleming\n\n[nMet,nRxn]=size(model.S);\n\nmetInd=find(strcmp(metAbbr,model.mets));\nif isempty(metInd)\n error('metabolite abbreviation not found')\nend\n\ntol = 1e-6;\n\nnegS=(model.S(metInd,:)<0)';\nposS=(model.S(metInd,:)>0)';\n\nv=solution.full;\n\nconsumeBool=( negS & v>tol ) | ( posS & v<-tol );\nproduceBool=( posS & v>tol ) | ( negS & v<-tol );\n\nvConsume=zeros(nRxn,1);\nvProduce=zeros(nRxn,1);\n\nvConsume(consumeBool)=v(consumeBool);\nvProduce(produceBool)=v(produceBool);\n\n[sortedConsume,XIMax]=sort(abs(vConsume),'descend');\nNConsume=nnz(sortedConsume~=0);\n\n[sortedProduce,XIMin]=sort(abs(vProduce),'descend');\nNProduce=nnz(sortedProduce~=0);\n\nfigure\nh1=subplot(2,1,1);\nNConsume=min([NConsume,N]);\nYI=(1:NConsume)';\nbarh(YI,v(XIMax(1:NConsume)));\n% title(['Consumers (top) and Producers of ' metAbbr],'FontSize',16)\n\nif NConsume==0\n set(h1,'YTickLabel','NONE','FontSize',8);\nelse\n for n=1:NConsume\n if strcmp(model.rxn(XIMax(n)).directionality,'forward')\n YTickLabelMax{n}=['*' model.rxns{XIMax(n)}];\n else\n YTickLabelMax{n}=model.rxns{XIMax(n)};\n end\n end\n set(h1,'Ytick', 1:NConsume)\n set(h1,'YTickLabel',YTickLabelMax,'FontSize',8);\n ylim([0.5 NConsume+0.5])\nend\nxlabel(['Consumer of ' metAbbr],'FontSize',12)\n\nh2=subplot(2,1,2);\nNProduce=min([NProduce,N]);\nYI=(1:NProduce)';\nbarh(YI,v(XIMin(1:NProduce)));\nif NProduce==0\n set(h1,'YTickLabel','NONE','FontSize',8);\nelse\n for n=1:NProduce\n if strcmp(model.rxn(XIMin(n)).directionality,'forward')\n YTickLabelMin{n}=['*' model.rxns{XIMin(n)}];\n else\n YTickLabelMin{n}=model.rxns{XIMin(n)};\n end\n end\n set(h2,'Ytick', 1:NProduce)\n set(h2,'YTickLabel',YTickLabelMin,'FontSize',8);\n ylim([0.5 NProduce+0.5])\nend\nxlabel(['Producer of ' metAbbr],'FontSize',12)\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/thermo/thermoFBA/metaboliteMassBalancePlot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.4953311555760932}} {"text": "function tests = test_intersectEdgePolygon3d\n% Test suite for the file intersectEdgePolygon3d.\n%\n% Test suite for the file intersectEdgePolygon3d\n%\n% Example\n% test_intersectEdgePolygon3d\n%\n% See also\n% intersectEdgePolygon3d\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inrae.fr\n% Created: 2021-02-24, using Matlab 9.9.0.1570001 (R2020b) Update 4\n% Copyright 2021 INRAE - BIA-BIBS.\n\ntests = functiontests(localfunctions);\n\nfunction test_Simple(testCase) %#ok<*DEFNU>\n% Test computation for one edge and one polygon\n\n% Compute intersection between a 3D edge and a 3D triangle\npts3d = [3 0 0; 0 6 0;0 0 9];\nedge1 = [0 0 0 3 6 9];\n\ninter = intersectEdgePolygon3d(edge1, pts3d);\n\nassertEqual(testCase, size(inter), [1 3]);\nassertEqual(testCase, inter, [1 2 3]);\n\n\nfunction test_TwoEdges(testCase) %#ok<*DEFNU>\n% Test computation for two edges\n\npts3d = [3 0 0; 0 6 0;0 0 9];\nedges = [0 0 0 3 6 9;10 0 0 10 2 3];\n\n[inter, inside] = intersectEdgePolygon3d(edges, pts3d);\n\nassertEqual(testCase, size(inter), [2 3]);\nassertEqual(testCase, size(inside), [2 1]);\nassertEqual(testCase, inside, [true ; false]);\nassertEqual(testCase, inter(inside, :), [1 2 3]);\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/tests/geom3d/test_intersectEdgePolygon3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7185944046238982, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.4953311547113701}} {"text": "function a = softMaxSelection(Q, state, actions, T)\n\n n_actions = length(actions);\n P = zeros(1, n_actions);\n \n random = rand();\n \n % Boltzmann distribution\n P = exp(Q(state,:)./T)./sum(exp(Q(state,:)./T));\n \n if( find(isnan(P),1) ~= 0 )\n \n a = getBestAction(Q, state, actions); \n else \n \n if(random < P(1))\n\n a = 1;\n elseif(random >= P(1) && random < sum(P(1:2)) )\n\n a = 2;\n elseif(random >= sum(P(1:2)))\n\n a = 3;\n end\n end\n \nend", "meta": {"author": "kennydl", "repo": "Reinforcment-Learning-With-Q-Learning", "sha": "d9aff50bfaa57bedd59134e3eeab029ba4e42c8c", "save_path": "github-repos/MATLAB/kennydl-Reinforcment-Learning-With-Q-Learning", "path": "github-repos/MATLAB/kennydl-Reinforcment-Learning-With-Q-Learning/Reinforcment-Learning-With-Q-Learning-d9aff50bfaa57bedd59134e3eeab029ba4e42c8c/Matlab/softMaxSelection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4953091318837202}} {"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 [V,E,F,C] = voronoi_tetgen(P,varargin)\n % VORONOI_TETGEN Compute a voronoi diagram using tetgen\n %\n % \n % [V,E,F,C] = voronoi_tetgen(P,varargin)\n % \n % Inputs:\n % P #P by 3 list of points\n % Outputs:\n % V #V by 3 list of orthocenters (?)\n % E #E by 2 list of edge indices into V\n % F #F by 3 list of face indices into ?\n % C #C list of cells (not supported)\n %\n % I don't trust the tetgen output...\n % \n\n % default values\n flags = '';\n % Map of parameter names to variable names\n params_to_variables = containers.Map( ...\n {'Flags'}, {'flags'});\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 % get a temporary file name prefix\n prefix = tempname;\n prefix = tempname;\n node_filename = [prefix '.node'];\n writeNODE(node_filename,P);\n\n % call tetgen\n voronoi_flags = '-vNEF';\n command = [path_to_tetgen ' ' voronoi_flags ' ' flags ' ' node_filename];\n [status, result] = system(command);\n if status~=0\n error(result)\n end\n\n edge_filename = [prefix '.1.v.edge'];\n face_filename = [prefix '.1.v.face'];\n node_filename = [prefix '.1.v.node'];\n cell_filename = [prefix '.1.v.cell'];\n\n F = readFACE(face_filename,'ForceNoBoundary',true);\n E = readEDGE(edge_filename);\n V = readNODE(node_filename);\n C = [];\n if nargout>3\n error('Cell output not handled yet.');\n end\n\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/voronoi_tetgen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4952648088306493}} {"text": "function [k, innerProd, arg, denom, numer, vec] = polyardKernCompute(kern, x, x2)\n\n\n% POLYARDKERNCOMPUTE Compute the POLYARD kernel given the parameters and X.\n% FORMAT\n% DESC computes the kernel parameters for the automatic relevance determination polynomial\n% kernel given inputs associated with rows and columns.\n% ARG kern : the kernel structure for which the matrix is computed.\n% ARG x : the input matrix associated with the rows of the kernel.\n% ARG x2 : the input matrix associated with the columns of the kernel.\n% RETURN k : the kernel matrix computed at the given points.\n%\n% FORMAT\n% DESC computes the kernel matrix for the automatic relevance determination polynomial\n% kernel given a design matrix of inputs.\n% ARG kern : the kernel structure for which the matrix is computed.\n% ARG x : input data matrix in the form of a design matrix.\n% RETURN k : the kernel matrix computed at the given points.\n%\n% SEEALSO : polyardKernParamInit, kernCompute, kernCreate, polyardKernDiagCompute\n%\n% COPYRIGHT : Neil D. Lawrence, 2005, 2006\n\n% KERN\n\n\nscales = sparse(diag(sqrt(kern.inputScales)));\nx = x*scales;\n\nif nargin < 3\n innerProd = x*x';\n arg = innerProd*kern.weightVariance + kern.biasVariance;\n k = kern.variance*arg.^kern.degree;\nelse\n x2 = x2*scales;\n innerProd = x*x2'; \n arg = innerProd*kern.weightVariance + kern.biasVariance;\n k = kern.variance*arg.^kern.degree;\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/polyardKernCompute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.49526480883064916}} {"text": "function model = SRModel\n%SRMODEL Super-resolution model parameter structure.\n\n % Magnification factor used for super-resolution (default: 2)\n model.magFactor = 2.0; \n \n % Width of isotropic Gaussian PSF (default: 0.4)\n model.psfWidth = 0.4; \n \n % Motion parameters used for super-resolution. This can be either a\n % 2-D homography to model parametric motion or displacement vector\n % fields in case of local motion estimation (optical flow).\n % - 2-D homography:\n % Motion is given by a cell array of 2-D homographies where the\n % k-th element models the motion for the k-th low-resolution\n % frame:\n % motionParams{1} = [h11 h12 h13; h21 h22 h23; h31 h32 h33]\n % motionParams{2} = ...\n % - Displacement fields:\n % Motion is given by cell array of displacement fields where the\n % k-th element models the motion for the k-th low-resolution.\n % A displacement field is given by a structure with matrices to\n % model displacements in x- and y-direction:\n % v.vx = [...] Displacements in x-direction (pixel-wise)\n % v.vy = [...] Displacements in y-direction (pixel-wise)\n % motionParams{1} = v;\n % motionParams{2} = ...\n model.motionParams = []; \n \n % Photometric parameters used for super-resolution (optional).\n % see also SRPhotometricParams\n model.photometricParams = [];\n \n % Error (noise) model assumed for the low-resolution observations\n % (optional). Can be either 'l2NormErrorModel' (least square, default) \n % in case of Gaussian noise or 'l1NormErrorModel' (least absolute \n % deviation) in case of Laplacian noise. Additionally, user-defined\n % error models can be specified, e.g. a Lorentzian M-estimator:\n % sigma = 0.05;\n % lorentzian = @(r) deal(log(1 + 0.5*(r/sigma).^2), ... Function\n % (2*r) ./ (r.^2 + 2*sigma^2)); Gradient\n % model.errorModel = lorentzian;\n model.errorModel = 'l2NormErrorModel';\n \n % Image prior used for regularization of super-resolved images. \n % see also SRPrior\n model.imagePrior = [];\n \n % Confidence map for the low-resolution observations (optional). A 3-D\n % array of size M x N x K can be used to weight K low-resolution frames\n % of size M x N pixel-wise.\n model.confidence = [];\n \n % Initial guess for the super-resolved image (optional). This can be\n % used as starting point for numerical optimization algorithms for\n % image reconstruction.\n model.SR = [];", "meta": {"author": "thomas-koehler", "repo": "SupER", "sha": "d8c6f2e4b26db002ff55bc2beba18639f1d0bb49", "save_path": "github-repos/MATLAB/thomas-koehler-SupER", "path": "github-repos/MATLAB/thomas-koehler-SupER/SupER-d8c6f2e4b26db002ff55bc2beba18639f1d0bb49/matlab/algorithms/SRAlgorithms/SRToolbox/common/SRModel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.49526480883064916}} {"text": "function d=dcirc(p,xc,yc,r)\n\n% Copyright (C) 2004-2006 Per-Olof Persson. See COPYRIGHT.TXT for details.\n\nd=sqrt((p(:,1)-xc).^2+(p(:,2)-yc).^2)-r;\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/mesh/distmeshModified/dcircle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.6224593382055109, "lm_q1q2_score": 0.49526480837097514}} {"text": "function ins=ins_init(opt,avp0)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% INS initilization\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Copyright (C) 2020-2025, by Kai Chen, All rights reserved.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% sample date\nins.nt = 1/opt.sample_rate;\nins.old_imud = zeros(1,6);\n\n% initialize position,attitude and velocity\nins.att = avp0(1:3);\nins.vel = avp0(4:6);\nins.pos = avp0(7:9);\nins.acc = zeros(3,1);\nins.Cnb = att2Cnb(ins.att);\n\n% initialize imu error\nins.bg = zeros(3,1);\nins.ba = zeros(3,1);\nins.Kg = eye(3);\nins.Ka = eye(3);\nins.tauG = [inf;inf;inf];\nins.tauA = [inf;inf;inf];\n\n% initialize earth related parameters\nins.eth = earth_update(ins.pos,ins.vel);\nins.Mpv = [0, ins.eth.Mpv4, 0; ins.eth.Mpv2, 0, 0; 0, 0, 1];\nins.wib = zeros(3,1);\nins.fb = zeros(3,1);\nins.fn = -ins.eth.gn;\nins.web = zeros(3,1);\n\n% initialize state, state covariance matrix, system noise matrix\n% state transition matrix, lever arm\ninit_att_unc = opt.init_att_unc;\ninit_vel_unc = opt.init_vel_unc;\ninit_pos_unc = opt.init_pos_unc;\ninit_bg_unc = repmat(opt.init_bg_unc,1,3);\ninit_ba_unc = repmat(opt.init_ba_unc,1,3);\npsd_gyro = repmat(opt.psd_gyro,1,3);\npsd_acce = repmat(opt.psd_acce,1,3);\npsd_bg = repmat(opt.psd_bg,1,3);\npsd_ba = repmat(opt.psd_ba,1,3);\n\nins.x = [ins.att;ins.vel;ins.pos;ins.bg;ins.ba];\nins.P = diag([init_att_unc,init_vel_unc,init_pos_unc,init_bg_unc,init_ba_unc].^2);\nins.Q = diag([psd_gyro, psd_acce, zeros(1,3), psd_bg, psd_ba])*ins.nt;\nins.Phi= update_trans_mat(ins);\nins.lever = opt.lever';\n\nins.xa = zeros(15,1);\nins.Pa = zeros(15,15);\n\nreturn\n\n", "meta": {"author": "kaichen686", "repo": "GINav", "sha": "bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666", "save_path": "github-repos/MATLAB/kaichen686-GINav", "path": "github-repos/MATLAB/kaichen686-GINav/GINav-bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666/src/ins/ins_init.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.4952648032581332}} {"text": "clear; close all; clc;\n\n%%\n% Plot settings\n\nmarkerSize=10;\nmarkerSize2=10;\nfontSize=15;\nfaceAlpha1=0.3;\nfaceAlpha2=0.5;\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=[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_sed=[febioFebFileNamePart,'_stress_out.txt']; %Log file name for exporting strain energy density\n\ntireWidth = 120;\ntireRadius = 150;\ntireThickness = 8;\nthreadHeight = 8;\ntireBulge=tireWidth/8;\npointSpacing = 8;\ntireCircumference = 2*pi.*tireRadius;\n\nnumFeatures = 20;\ngroveWidth = 8;\n\ndistKeep=75; %Distance after which model is cropped, empty = full model\ndisplacementVert=0.8*tireThickness;\ndisplacementHor=-tireRadius/20;\ncontactInitialOffset=0.1;\n\n%Material parameter set\nc1=1e-3; %Shear-modulus-like parameter\nm1=2; %Material parameter setting degree of non-linearity\nk_factor=100; %Bulk modulus factor \nk=c1*k_factor; %Bulk modulus\n\n% FEA control settings\nnumTimeSteps=20; %Number of time steps desired\nmax_refs=40; %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\nrunMode='external';%'internal';\nmin_residual=1e-20;\n\n%Contact parameters\ncontactPenalty=5;\nlaugon=0;\nminaug=1;\nmaxaug=10;\nfric_coeff=0.5;\n\n%%\n\ntireHalfWidth=tireWidth/2;\nfeatureHeight = (tireCircumference-(numFeatures*groveWidth))./numFeatures;\nfeatureWidth = tireHalfWidth-2*groveWidth;\n\n% Coordinates of 1x1 square\nv=[-1 -1 0;...\n 1 -1 0;...\n 1 1 0;...\n -1 1 0]/2;\n\n% Deformation gradient tensor for shear\nf=eye(3,3);\nf(1,2)=1;\n\n%Create boundary coordinates\nV1=v; %Copy square\nV1(:,1)=V1(:,1).*tireCircumference+tireCircumference/2; %Stretch to create circumference\nV1(:,2)=V1(:,2).*tireHalfWidth+tireHalfWidth/2; %Stretch to get desired width\nV1=evenlySpaceCurve(V1,pointSpacing,'linear',1,1:1:size(v,1)); %Evenly sample\nV1=(f*V1')'; %Shear\n\n%Create thread feature\nVf=v; %Copy square\nVf(:,1)=Vf(:,1).*featureHeight; %Stretch to create circumference\nVf(:,2)=Vf(:,2).*(featureWidth+groveWidth/2)+tireHalfWidth/2-groveWidth/4; %Stretch to get desired width\nVf=evenlySpaceCurve(Vf,pointSpacing,'linear',1,1:1:size(v,1)); %Evenly sample\nVf(:,1)=Vf(:,1)+featureHeight/2+groveWidth/2;\n\nVF=cell(1,numFeatures);\nfor q=1:1:numFeatures\n Vff=Vf;\n Vff(:,1)=Vf(:,1)+(q-1).*(featureHeight+groveWidth); %Shift\n VF{q}=(f*Vff')'; %Shear and store\nend\n\n%%\n\n\n%Defining 4 regions\nregionSpec{1}={V1(:,[1 2])};\nfor q=1:1:numFeatures\n regionSpec{1}{q+1}=VF{q}(:,[1 2]);\nend\n\nfor q=1:1:numFeatures\n regionSpec{q+1}{1}=VF{q}(:,[1 2]);\nend\n\n[Ft,Vt,Ct]=multiRegionTriMesh2D(regionSpec,pointSpacing,0,0);\nVt(:,3)=0;\n\nFb=fliplr(Ft);\nVb=Vt;\nVb(:,2)=-Vb(:,2);\n\nCb=Ct;\nCb(Cb>1)=Cb(Cb>1)-1+max(Ct);\n\n[F,V,C]=joinElementSets({Ft,Fb},{Vt,Vb},{Ct,Cb});\n[F,V]=mergeVertices(F,V);\n\n%%\n\ncFigure; hold on;\nplotV(V1,'r.-','MarkerSize',markerSize);\nplotV(VF,'b.-','MarkerSize',markerSize);\ngpatch(F,V,C);\n\naxisGeom(gca,fontSize); view(2);\ncolormap spectral; icolorbar;\ngdrawnow;\n\n%%\n\ncMax=max(C);\nnumVert=size(V,1);\nF2=F(C>1,:);\nC2=C(C>1,:)+cMax;\nEb1=patchBoundary(F2);\n\nEb2=Eb1+numVert;\nF=[F(C==1,:);F2+numVert];\nV=[V;V];\nC=[C(C==1,:);C2+max(C(:))];\n\n%%\n%\n\nif tireBulge>eps(0)\n w=tireWidth;\n h=tireBulge;\n r=h/2+(w^2/(8*h));\n a=atan((w/2)./(r-h));\n\n TH = (V(:,2)./tireHalfWidth)*a;\n R = r.*ones(size(V,1),1);\n R(numVert+1:end)=R(numVert+1:end)+threadHeight;\n Z = V(:,1);\n [V(:,1),V(:,2),V(:,3)] = pol2cart(TH,R,Z);\n V=V(:,[3 2 1]);\n\n V(:,3)=V(:,3)-r+h;\nelse\n V(numVert+1:end,3)=V(numVert+1:end,3)+threadHeight;\nend\n\n%%\ncFigure; hold on;\nplotV(V1,'r.-','MarkerSize',markerSize);\nplotV(VF,'b.-','MarkerSize',markerSize);\ngpatch(F,V,C);\n\naxisGeom(gca,fontSize); view(2);\ncolormap spectral; icolorbar;\ngdrawnow;\n\n%%\n\nTH = V(:,1)./tireRadius;\nR = tireRadius+V(:,3);\n\nZ = V(:,2);\n[V(:,1),V(:,2),V(:,3)] = pol2cart(TH,R,Z);\nV=V(:,[1 3 2]); F=fliplr(F);\n\n[Eb1,V1]=patchCleanUnused(Eb1,V);\n[Eb2,V2]=patchCleanUnused(Eb2,V);\n\n[F,V,~,indFix]=mergeVertices(F,V);\n\nnumSteps=ceil(threadHeight./pointSpacing)+1;\n\n\n%Create quadrilateral faces\nX=linspacen(V1(:,1),V2(:,1),numSteps);\nY=linspacen(V1(:,2),V2(:,2),numSteps);\nZ=linspacen(V1(:,3),V2(:,3),numSteps);\n\nVn=[X(:) Y(:) Z(:)]; %Vertex set\nFn=repmat([fliplr(Eb1) Eb2],numSteps-1,1);\nq=repmat(0:(numSteps-2),size(Eb1,1),1);\nq=q(:);\nQ=[q q q+1 q+1]*size(V1,1);\nFn=Fn+Q;\n\n[Fn,Vn]=quad2tri(Fn,Vn,'a');\n\n%%\n\n[F,V]=patchCleanUnused(F,V);\nC(C>1)=2; %Switch to use 2 for all thread profile parts\n[F_out,V_out,C_out]=joinElementSets({F,Fn},{V,Vn},{C,max(C(:))+1*ones(size(Fn,1),1)});\n[F_out,V_out]=patchCleanUnused(F_out,V_out);\n[F_out,V_out]=mergeVertices(F_out,V_out);\nEb_out=patchBoundary(F_out);\n%%\n\ncFigure; hold on;\ngpatch(F_out,V_out,C_out);\n% patchNormPlot(Fq,Vq);\naxisGeom(gca,fontSize); camlight headlight;\ncolormap spectral; icolorbar;\ngdrawnow;\n\n%%\n% Create inner cylinder\ninputStructCyl.cylRadius=tireRadius-tireThickness;\ninputStructCyl.numRadial=ceil((2*pi*inputStructCyl.cylRadius)/pointSpacing);\ninputStructCyl.cylHeight=tireWidth;\nnumheight=ceil(tireWidth./pointSpacing);\nnumheight=numheight+iseven(numheight); %Force uneven\ninputStructCyl.numHeight=numheight;\ninputStructCyl.meshType='tri';\n\n%%\n% Derive patch data for a cylinder\n[F_in,V_in]=patchcylinder(inputStructCyl);\nV_in=V_in(:,[1 3 2]);\nEb_in=patchBoundary(F_in);\nC_in=(max(C_out)+1)*ones(size(F_in,1),1);\n\n%%\ninputStructGroup.outputType='label';\nG_out=tesgroup(Eb_out,inputStructGroup);\nG_in=tesgroup(Eb_in,inputStructGroup);\n\nyMean_out=nan(2,1);\nyMean_in=nan(2,1);\nfor q=1:1:2\n ind_out=Eb_out(G_out==q,:);\n yMean_out(q)=mean(V_out(ind_out(:),2));\n\n ind_in=Eb_in(G_in==q,:);\n yMean_in(q)=mean(V_in(ind_in(:),2));\nend\n\n[~,ind1_out]=min(yMean_out);\n[~,ind2_out]=max(yMean_out);\nindCurve1_out=edgeListToCurve(Eb_out(G_out==ind1_out,:));\nindCurve1_out=indCurve1_out(1:end-1);\nindCurve2_out=edgeListToCurve(Eb_out(G_out==ind2_out,:));\nindCurve2_out=indCurve2_out(1:end-1);\n\n[~,ind1_in]=min(yMean_in);\n[~,ind2_in]=max(yMean_in);\nindCurve1_in=edgeListToCurve(Eb_in(G_in==ind1_in,:));\nindCurve1_in=indCurve1_in(1:end-1);\nindCurve2_in=edgeListToCurve(Eb_in(G_in==ind2_in,:));\nindCurve2_in=indCurve2_in(1:end-1);\n\n[Fs1,Vs1]=regionTriMesh2D({V_out(indCurve1_out,[1 3]),V_in(indCurve1_in,[1 3])},pointSpacing,0);\nVs1(:,3)=-tireWidth/2;\nVs1=Vs1(:,[1 3 2]);\nCs1=(max(C_in)+1)*ones(size(Fs1,1),1);\n\n[Fs2,Vs2]=regionTriMesh2D({V_out(indCurve2_out,[1 3]),V_in(indCurve2_in,[1 3])},pointSpacing,0);\nVs2(:,3)=tireWidth/2;\nVs2=Vs2(:,[1 3 2]);\nFs2=fliplr(Fs2);\nCs2=(max(Cs1)+1)*ones(size(Fs2,1),1);\n\n%%\n\n[FT,VT,CT]=joinElementSets({F_out,F_in,Fs1,Fs2},{V_out,V_in,Vs1,Vs2},{C_out,C_in,Cs1,Cs2});\n[FT,VT]=patchCleanUnused(FT,VT);\n[FT,VT]=mergeVertices(FT,VT);\n\n%%\n\ncFigure; hold on;\n\ngpatch(FT,VT,CT,'none');\npatchNormPlot(FT,VT);\n\naxisGeom(gca,fontSize); camlight headlight;\ncolormap spectral; icolorbar;\ngdrawnow;\n\n%%\n\nV_regions=getInnerPoint(FT,VT); %Define region points\nV_holes=[]; %Define hole points\n[regionTetVolumes]=tetVolMeanEst(FT,VT); %Volume estimate for regular tets\nstringOpt='-pq1.2AaY'; %Options for tetgen\n\n%%\n% Mesh using TetGen\n\n%Create tetgen input structure\ninputStruct.stringOpt=stringOpt; %Tetgen options\ninputStruct.Faces=FT; %Boundary faces\ninputStruct.Nodes=VT; %Nodes of boundary\ninputStruct.faceBoundaryMarker=CT;\ninputStruct.regionPoints=V_regions; %Interior points for regions\ninputStruct.holePoints=V_holes; %Interior points for holes\ninputStruct.regionA=regionTetVolumes; %Desired tetrahedral volume for each region\n\n% Mesh model using tetrahedral elements using tetGen\n[meshOutput]=runTetGen(inputStruct); %Run tetGen\n\n%%\n% Access mesh output structure\n\nE=meshOutput.elements; %The elements\nV=meshOutput.nodes; %The vertices or nodes\nFb=meshOutput.facesBoundary; %The boundary faces\nCb=meshOutput.boundaryMarker; %The boundary markers\n\n%%\n% Visualization\n\nhf=cFigure;\nsubplot(1,2,1); hold on;\ntitle('Input boundaries','FontSize',fontSize);\nhp(1)=gpatch(Fb,V,Cb,'k',faceAlpha1);\nhp(2)=plotV(V_regions,'r.','MarkerSize',markerSize);\nlegend(hp,{'Input mesh','Interior point(s)'},'Location','NorthWestOutside');\naxisGeom(gca,fontSize); camlight headlight;\ncolormap(cMap); icolorbar;\n\nhs=subplot(1,2,2); hold on;\ntitle('Tetrahedral mesh','FontSize',fontSize);\n\n% Visualizing using |meshView|\noptionStruct.hFig=[hf,hs];\nmeshView(meshOutput,optionStruct);\n\naxisGeom(gca,fontSize);\ngdrawnow;\n\n\n%%\n\nif ~isempty(distKeep)\n Fb_full=Fb;\n V_full=V;\n [Fb_full,V_full]=patchCleanUnused(Fb_full,V_full);\n\n VE=patchCentre(E,V);\n logicKeepElements = VE(:,3) <= (min(VE(:,3))+distKeep);\n E=E(logicKeepElements,:);\n indKeepNodes=unique(E);\n logicKeep_Fb=all(ismember(Fb,indKeepNodes),2);\n Fb=Fb(logicKeep_Fb,:);\n Cb=Cb(logicKeep_Fb,:);\n\n logicKeep_F=all(ismember(F,indKeepNodes),2);\n F=F(logicKeep_F,:);\n\n [E,V,indFix]=patchCleanUnused(E,V);\n Fb=indFix(Fb);\n F=indFix(F);\n meshOutput.nodes=V;\n meshOutput.facesBoundary=Fb;\n meshOutput.boundaryMarker=Cb;\n meshOutput.faces=F;\n meshOutput.elements=E;\n meshOutput.elementMaterialID=ones(size(E,1),1); \nelse\n Fb_full=Fb;\n V_full=V;\nend\n\n%%\n\nhf=cFigure;\nsubplot(1,2,1); hold on;\ntitle('Input boundaries','FontSize',fontSize);\nhp(1)=gpatch(Fb,V,Cb,'k',faceAlpha1);\nhp(2)=plotV(V_regions,'r.','MarkerSize',markerSize);\nlegend(hp,{'Input mesh','Interior point(s)'},'Location','NorthWestOutside');\naxisGeom(gca,fontSize); camlight headlight;\ncolormap(cMap); icolorbar;\n\nhs=subplot(1,2,2); hold on;\ntitle('Tetrahedral mesh','FontSize',fontSize);\n\n% Visualizing using |meshView|\noptionStruct.hFig=[hf,hs];\nmeshView(meshOutput,optionStruct);\n\naxisGeom(gca,fontSize);\ngdrawnow;\n\n%%\n\nplateDim=[2*tireRadius tireWidth];\nplateEl=ceil(plateDim./pointSpacing);\n[Eg,Vg]=quadPlate(plateDim,plateEl);\nVg(:,3)=Vg(:,3)+min(VT(:,3))-contactInitialOffset;\ncenter_of_mass=mean(Vg,1);\n\n%% Joining node sets\nEg=Eg+size(V,1); %Fixed element indices\nV=[V;Vg;]; %Combined node sets\n\n%%\n\ncFigure; hold on;\nhp(1)=gpatch(Fb,V,Cb,'k',faceAlpha1);\nhp(2)=gpatch(Eg,V,'kw','k',faceAlpha1);\n% legend(hp,{'Input mesh','Interior point(s)'},'Location','NorthWestOutside');\naxisGeom(gca,fontSize); camlight headlight;\ncolormap(cMap); icolorbar;\ngdrawnow;\n\n%% Define contact surfaces\n\n% The rigid master surface of the sphere\nF_contact_secondary=Eg;\n\n% The deformable slave surface of the slab\nlogicContactSurf1=Cb==2;\nF_contact_primary=fliplr(Fb(logicContactSurf1,:));\n\n% Plotting surface models\ncFigure; hold on;\ntitle('Contact sets and normal directions','FontSize',fontSize);\n\ngpatch(Fb,V,'kw','none',faceAlpha2); \nhl(1)=gpatch(F_contact_secondary,V,'g','k',1); \npatchNormPlot(F_contact_secondary,V);\nhl(2)=gpatch(F_contact_primary,V,'b','k',1);\npatchNormPlot(F_contact_primary,V);\n\nlegend(hl,{'Secondary','Primary'});\n\naxisGeom(gca,fontSize);\ncamlight headlight;\ndrawnow;\n\n%% Define boundary conditions\n\n%Supported nodes\nbcSupportList=unique(Fb(Cb==4,:));\n\n%%\n% Visualize BC's\nhf=cFigure;\ntitle('Boundary conditions model','FontSize',fontSize);\nxlabel('X','FontSize',fontSize); ylabel('Y','FontSize',fontSize); zlabel('Z','FontSize',fontSize);\nhold on;\n\ngpatch(Fb,V,'w','none',faceAlpha2); \n\nhl2(1)=gpatch(Eg,V,'gw','k',1); \nhl2(2)=plotV(V(bcSupportList,:),'k.','MarkerSize',markerSize);\n\nlegend(hl2,{'Rigid body plate','BC support'});\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\nfebio_spec.Control.analysis='STATIC';\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.solver.symmetric_stiffness=0;\nfebio_spec.Control.solver.min_residual=min_residual;\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;\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\nmaterialName2='Material2';\nfebio_spec.Material.material{2}.ATTR.name=materialName2;\nfebio_spec.Material.material{2}.ATTR.type='rigid body';\nfebio_spec.Material.material{2}.ATTR.id=2;\nfebio_spec.Material.material{2}.density=1;\nfebio_spec.Material.material{2}.center_of_mass=center_of_mass;\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(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='tet4'; %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\npartName2='Part2';\nfebio_spec.Mesh.Elements{2}.ATTR.name=partName2; %Name of this part\nfebio_spec.Mesh.Elements{2}.ATTR.type='quad4'; %Element type \nfebio_spec.Mesh.Elements{2}.elem.ATTR.id=size(E,1)+(1:1:size(Eg,1))'; %Element id's\nfebio_spec.Mesh.Elements{2}.elem.VAL=Eg; %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\n%MeshDomains section\nfebio_spec.MeshDomains.SolidDomain.ATTR.name=partName1;\nfebio_spec.MeshDomains.SolidDomain.ATTR.mat=materialName1;\n\nfebio_spec.MeshDomains.ShellDomain.ATTR.name=partName2;\nfebio_spec.MeshDomains.ShellDomain.ATTR.mat=materialName2;\n\n% -> Surfaces\nsurfaceName1='contactSurface1';\nfebio_spec.Mesh.Surface{1}.ATTR.name=surfaceName1;\nfebio_spec.Mesh.Surface{1}.quad4.ATTR.id=(1:1:size(F_contact_secondary,1))';\nfebio_spec.Mesh.Surface{1}.quad4.VAL=F_contact_secondary;\n\nsurfaceName2='contactSurface2';\nfebio_spec.Mesh.Surface{2}.ATTR.name=surfaceName2;\nfebio_spec.Mesh.Surface{2}.tri3.ATTR.id=(1:1:size(F_contact_primary,1))';\nfebio_spec.Mesh.Surface{2}.tri3.VAL=F_contact_primary;\n\n% -> Surface pairs\nfebio_spec.Mesh.SurfacePair{1}.ATTR.name='Contact1';\nfebio_spec.Mesh.SurfacePair{1}.primary=surfaceName2;\nfebio_spec.Mesh.SurfacePair{1}.secondary=surfaceName1;\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%Rigid section \n% -> Prescribed rigid body boundary conditions\nfebio_spec.Step.step{1}.Rigid.rigid_constraint{1}.ATTR.name='RigidFix_1';\nfebio_spec.Step.step{1}.Rigid.rigid_constraint{1}.ATTR.type='fix';\nfebio_spec.Step.step{1}.Rigid.rigid_constraint{1}.rb=2;\nfebio_spec.Step.step{1}.Rigid.rigid_constraint{1}.dofs='Rx,Ry';\n\nfebio_spec.Step.step{1}.Rigid.rigid_constraint{2}.ATTR.name='RigidPrescribe';\nfebio_spec.Step.step{1}.Rigid.rigid_constraint{2}.ATTR.type='prescribe';\nfebio_spec.Step.step{1}.Rigid.rigid_constraint{2}.rb=2;\nfebio_spec.Step.step{1}.Rigid.rigid_constraint{2}.dof='Rz';\nfebio_spec.Step.step{1}.Rigid.rigid_constraint{2}.value.ATTR.lc=1;\nfebio_spec.Step.step{1}.Rigid.rigid_constraint{2}.value.VAL=(displacementVert+contactInitialOffset);\nfebio_spec.Step.step{1}.Rigid.rigid_constraint{2}.relative=0;\n\nfebio_spec.Step.step{2}.Rigid.rigid_constraint{1}.ATTR.name='RigidFix_1';\nfebio_spec.Step.step{2}.Rigid.rigid_constraint{1}.ATTR.type='fix';\nfebio_spec.Step.step{2}.Rigid.rigid_constraint{1}.rb=2;\nfebio_spec.Step.step{2}.Rigid.rigid_constraint{1}.dofs='Ry,Rz,Ru,Rv,Rw';\n\nfebio_spec.Step.step{2}.Rigid.rigid_constraint{2}.ATTR.name='RigidPrescribe';\nfebio_spec.Step.step{2}.Rigid.rigid_constraint{2}.ATTR.type='prescribe';\nfebio_spec.Step.step{2}.Rigid.rigid_constraint{2}.rb=2;\nfebio_spec.Step.step{2}.Rigid.rigid_constraint{2}.dof='Rx';\nfebio_spec.Step.step{2}.Rigid.rigid_constraint{2}.value.ATTR.lc=2;\nfebio_spec.Step.step{2}.Rigid.rigid_constraint{2}.value.VAL=displacementHor;\n% febio_spec.Step.step{2}.Rigid.rigid_constraint{2}.relative=1;\n\n%Contact section\nfebio_spec.Contact.contact{1}.ATTR.type='sliding-elastic';\nfebio_spec.Contact.contact{1}.ATTR.surface_pair=febio_spec.Mesh.SurfacePair{1}.ATTR.name;\nfebio_spec.Contact.contact{1}.two_pass=0;\nfebio_spec.Contact.contact{1}.laugon=laugon;\nfebio_spec.Contact.contact{1}.tolerance=0.2;\nfebio_spec.Contact.contact{1}.gaptol=0;\nfebio_spec.Contact.contact{1}.minaug=minaug;\nfebio_spec.Contact.contact{1}.maxaug=maxaug;\nfebio_spec.Contact.contact{1}.search_tol=0.01;\nfebio_spec.Contact.contact{1}.search_radius=0.1*sqrt(sum((max(V,[],1)-min(V,[],1)).^2,2));\nfebio_spec.Contact.contact{1}.symmetric_stiffness=0;\nfebio_spec.Contact.contact{1}.auto_penalty=1;\nfebio_spec.Contact.contact{1}.penalty=contactPenalty;\nfebio_spec.Contact.contact{1}.fric_coeff=fric_coeff;\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; 2 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=[0 0; 1 0; 2 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.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_sed;\nfebio_spec.Output.logfile.element_data{1}.ATTR.data='sed';\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=runMode;\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_sed),1,1); \n \n %Access data\n E_sed_mat=dataStruct.data;\n E_sed_mat(isnan(E_sed_mat))=0;\n \n %% \n % Plotting the simulated results using |anim8| to visualize and animate\n % deformations \n \n [CV]=faceToVertexMeasure(E,V,E_sed_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('Strain energy density','Interpreter','Latex')\n gpatch(Fb_full,V_full,'w','none',0.25);\n hp=gpatch(Fb,V_DEF(:,:,end),CV,'none',1); %Add graphics object to animate\n% hp.Marker='.';\n% hp.MarkerSize=markerSize2;\n hp.FaceColor='interp';\n \n hp2=gpatch(Eg,V_DEF(:,:,end),'w','none',0.5); %Add graphics object to animate\n Ebb=patchBoundaryLabelEdges(Fb,V,Cb);\n hp3=gpatch(Ebb,V_DEF(:,:,end),'none','k',1,3); \n hp4=gpatch(patchBoundary(Eg),V_DEF(:,:,end),'none','kw',1,3); \n \n axisGeom(gca,fontSize); \n colormap(spectral(250)); colorbar;\n caxis([0 0.25*max(E_sed_mat(:))]); \n axis(axisLim(V_DEF,V_full)); %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_sed_mat(:,:,qt));\n \n %Set entries in animation structure\n animStruct.Handles{qt}=[hp hp hp2 hp3 hp4]; %Handles of objects to animate\n animStruct.Props{qt}={'Vertices','CData','Vertices','Vertices','Vertices'}; %Properties of objects to animate\n animStruct.Set{qt}={V_DEF(:,:,qt),CV,V_DEF(:,:,qt),V_DEF(:,:,qt),V_DEF(:,:,qt)}; %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_0079_tire_load_01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6224593171945417, "lm_q1q2_score": 0.49526479768561726}} {"text": "function [model,b] = robustlssvm(model,ab,X,Y)\n% Robust training in the case of non-Gaussian noise or outliers\n%(only possible with the object oriented interface)\n%\n% >> model = robustlssvm(model)\n%\n% Robustness towards outliers can be achieved by reducing the\n% influence of support values corresponding to large errors.\n%\n%\n% Full syntax\n%\n% 1. Using the object oriented interface:\n%\n% >> model = robustlssvm(model)\n%\n% Outputs\n% model : Robustly trained object oriented representation of the LS-SVM model\n% Inputs\n% model : Object oriented representation of the LS-SVM model\n%\n% See also:\n% trainlssvm, tunelssvm, crossvalidate\n\n\n% Copyright (c) 2011, KULeuven-ESAT-SCD, License & help @ http://www.esat.kuleuven.be/sista/lssvmlab\n\n\n\nif iscell(model),\n func = 1;\n model = initlssvm(model{:});\nelse\n func = 0;\nend\n\n\nif model.type(1)~='f',\n error('Robustly weighted least squares only implemented for regression case...');\nend\n\n\n\nif nargin>1,\n if iscell(ab) && ~isempty(ab),\n model.alpha = ab{1};\n model.b = ab{2};\n model.status = 'trained';\n if nargin>=4,\n model = trainlssvm(model,X,Y);\n end\n else\n model = trainlssvm(model,ab,X);\n end\nelse\n model = trainlssvm(model);\nend\n\n\n% model errors\nek = model.alpha./model.gam';\ng = model.gam;\n%\n% robust estimation of the variance\n%\neval('delta=model.delta;','delta=[];')\nfor j=1:500\n vare = 1.483*median(abs((ek)-median(ek)));\n alphaold = model.alpha;\n %\n % robust re-estimation of the alpha's and the b\n %\n cases = reshape((ek./vare),1,model.nb_data);\n W = weightingscheme(cases,model.weights,delta);\n W = g*W;\n \n model = changelssvm(model,'gam',W);\n % model = changelssvm(model,'implementation','MATLAB');\n model = trainlssvm(model);\n ek = model.alpha./model.gam';\n \n if norm(abs(alphaold-model.alpha),'fro')<=1e-4,\n fprintf('Converged after %.0f iteration(s)', j);\n if func && nargout~=1,\n b = model.b;\n model = model.alpha;\n end\n return\n end\n model.status = 'changed';\nend\n\n", "meta": {"author": "peterhcharlton", "repo": "RRest", "sha": "f5022e7029c5b6d6b8159b665dccc2c8f267976e", "save_path": "github-repos/MATLAB/peterhcharlton-RRest", "path": "github-repos/MATLAB/peterhcharlton-RRest/RRest-f5022e7029c5b6d6b8159b665dccc2c8f267976e/RRest_v3.0/Algorithms/extract_resp_sig/feat_based_extraction/LSSVMlabv1_8_R2009b_R2011a/robustlssvm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.49516396539909174}} {"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 aa = fitnesstra2(pop,para)\n[pops,numvar]=size(pop);\nfor i=1:pops\n time=pop(i,5)+pop(i,6);\n kk=trajt(para,pop(i,:));\n tt=torque(kk);\n ft=ftorque(tt);\n poo=kk(1:2,:);\n fq=sum(sum(abs(diff(poo'))));\n pos=forkin(poo);xx=pos(1,:);yy=pos(2,:);\n x=diff(xx);\n y=diff(yy);\n dis=sqrt(x.^2+y.^2);\n fdis=sum(dis);\n a1=2;\n a2=1.8;\n a3=2;\n a4=1;\n f=a1*ft+a2*fq+a3*fdis+a4*time;\n aa(i)=1/f;\nend\n \n ", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/23289-motion-planning-for-a-robot-arm-by-using-genetic-algorithm/robot motion planning/matlab code/fitnesstra2f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.4951639427572556}} {"text": "% BARH Horizontal bar graph.\n% BARH(X,Y) draws the columns of the M-by-N matrix Y as M groups of\n% N horizontal bars. The vector X must not have duplicate values.\n% \n% BARH(Y) uses the default value of X=1:M. For vector inputs,\n% BARH(X,Y) or BARH(Y) draws LENGTH(Y) bars. The colors are set by\n% the colormap.\n% \n% BARH(X,Y,WIDTH) or BARH(Y,WIDTH) specifies the width of the\n% bars. Values of WIDTH > 1, produce overlapped bars. The\n% default value is WIDTH=0.8.\n% \n% BARH(...,'grouped') produces the default horizontal grouped bar chart.\n% BARH(...,'stacked') produces a horizontal stacked bar chart.\n% BARH(...,LINESPEC) uses the line color specified (one of 'rgbymckw').\n% \n% BARH(AX,...) plots into AX instead of GCA.\n% \n% H = BARH(...) returns a vector of handles to barseries objects.\n% \n% Use SHADING FACETED to put edges on the bars. Use SHADING FLAT to\n% turn them off.\n% \n% Examples: subplot(3,1,1), barh(rand(10,5),'stacked'), colormap(cool)\n% subplot(3,1,2), barh(0:.25:1,rand(5),1)\n% subplot(3,1,3), barh(rand(2,3),.75,'grouped')\n% \n% See also PLOT, BAR, BAR3, BAR3H, HISTOGRAM.\n% \n% Copyright 1984-2017 The MathWorks, Inc.\n%\n% Reference page in Doc Center\n% doc barh\n%\n% Other functions named barh\n%\n% fints/barh ts/barh\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/time_series/@ts/barh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307806984445, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.4951639374009061}} {"text": "function varargout = mtimes(varargin)\n%* Pointwise multiplication for DISKFUN objects.\n% c*F or F*c multiplies a DISKFUN F by a scalar c.\n%\n% F*G computes the integral of F(s,t)G(l,s) over s, and this is the \n% continuous analogue of matrix-matrix multiplication.\n%\n% See also DISKFUN/TIMES.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n[varargout{1:nargout}] = mtimes@separableApprox(varargin{:});\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@diskfun/mtimes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.49516393740090603}} {"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": "% evaluate simulated data - ICA and NMF\nfunction separ(sep0, offset0, path_data, path_res, prename, niter, savethis, hint, sep_how)\n% sep_how: string i - ica, n - nmf -> method for separation\nif ~exist('hint', 'var')\n hint = 0;\nend\n\nif ~exist('sep_how', 'var')\n sep_how = 'in';\nend\n\nfprintf('Separation of components... \\n')\nfor rr = 1: length(offset0)\n fprintf('\\n%g: ',rr)\n for ll=1 : length(sep0)\n fprintf('.')\n p.namedir = [prename num2str(100*sep0(ll)) 'offset_' num2str(offset0(rr))];\n cd ([path_data p.namedir])\n for mm=1:niter\n \n namefile = [p.namedir '-iter_' num2str(mm)];\n load ([namefile '.mat'])\n % ims(psf);\n % SaveImageFULL('psf', 'pf');\n \n if sum(sep_how == 'i')>0 %ICA\n [icasig{mm}, A{mm}, W{mm}] = fastica (dveccr, 'numOfIC', 2, 'g', 'tanh');\n icapixICA{mm} = reshape(A{mm},32, 32, 2);\n end\n if sum(sep_how == 'n')>0 %NMF\n ncomp = 2; %number of components to be separated\n if hint\n dvec_ind = squeeze(reshape(double(array2im(dpixc_ind)), p.nx*p.ny, 1, 2)); % vectors of resized images\n% [out, bg(mm), bg_im]=backgroundoffset(dpixc);\n [out, bg(mm), bg_im]=backgroundoffset(dpixc, 'no', 5, 20, 8); %empirical values...\n dvec_bg = bg(mm)*ones(1, p.nx*p.ny);\n% dvec_bg = p.offset*ones(1, p.nx*p.ny); %changed for offset 10...\n \n blinkmatrand = rand(p.Nt, ncomp);\n winit = [blinkmatrand,ones(p.Nt,1)]; %random weights will be assigned to firts two and bg fixed\n \n hinit = [dvec_ind'; dvec_bg]; %original 'true' points + background\n% hinit = [rand(ncomp, p.nx*p.ny); dvec_bg];\n ncomp = ncomp+1; %background added\n [w{mm},h{mm}, wtrace{mm},htrace{mm}]=nmf_test(double(dveccr'),ncomp+1,1,winit,hinit, [3], [3]);\n \n else\n [w{mm},h{mm}]=nmf(double(dveccr'),ncomp,1);\n end\n icapixNMF{mm} = reshape(h{mm}',32,32,ncomp);\n end\n % imstiled(icapixICA{mm});\n % SaveImageFULL([p.namedir 'ICA_' num2str(mm)], 'p');\n % imstiled(icapixNMF{mm});\n % SaveImageFULL([p.namedir 'NMF_' num2str(mm)], 'p');\n close all\n \n end\n \n p.path_data = path_data;\n p.path = path_res;\n\n if savethis == 1\n fprintf('saving data \\n');\n if ~(strcmp('p.path', 'p.path_data')) %not identical\n mkdir ([p.path p.namedir]);\n cd ([p.path p.namedir]);\n end\n save ([p.namedir '_separ'])\n writedata([],[],p,[p.namedir '_param'])\n end\n end\nend\n\nfprintf('\\n')", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/separ/separ18.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.49516318239715057}} {"text": "classdef BiGE < ALGORITHM\n% \n% Bi-goal evolution\n\n%------------------------------- Reference --------------------------------\n% M. Li, S. Yang, and X. Liu, Bi-goal evolution for many-objective\n% optimization problems, Artificial Intelligence, 2015, 228: 45-65.\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 %% Generate random population\n Population = Problem.Initialization();\n\n %% Optimization\n while Algorithm.NotTerminated(Population)\n MatingPool = MatingSelection(Estimation(Population.objs,1/Problem.N^(1/Problem.M)));\n Offspring = OperatorGA(Problem,Population(MatingPool));\n Population = EnvironmentalSelection([Population,Offspring],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/BiGE/BiGE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4951596964492249}} {"text": "function [xhat,e,k,theta0,P,b] = celp9600(x,N,L,M,c,cb,Pidx)\n% celp --> 9600 bps CELP analyzer and synthesizer.\n%\n% [xhat,e,k,theta0,P,b] = celp9600(x,N,L,M,c,cb,Pidx)\n%\n% The function implements a 9600 bps CELP analyzer and synthesizer,\n% if the speech signal is sampled at 8 kHz, the frame size N is 20 ms\n% (160 samples), and the block duration L for the excitation sequence\n% selection is 5 ms (40 samples). Furthermore, assume that the\n% codebook has 1024 sequences which require 10 bit to send the index k,\n% and that the lag of the pitch filter, P, is searched in the range 16\n% to 160 which require 8 bit to represent exactly. Thus, the quantization\n% procedure only affects the M = 10 LPC parameters (inverse sine) coded\n% by 6 bits, the gain Theta0 coded by 7 bit, and the pitch filter coeff.\n% b coded by 8 bit.\n\nNx = length(x); % Signal length.\nF = fix(Nx/N); % No. of frames.\nJ = N/L; % No. blocks per frame.\n\n% Initialize output signals.\nxhat = zeros(Nx,1); % Synthesized signal.\ne = zeros(Nx,1); % Excitation signal.\nk = zeros(J,F); % Columns are excitation\ntheta0 = zeros(J,F); % parameters per frame.\nP = zeros(J,F);\nb = zeros(J,F);\n\nebuf = zeros(Pidx(2),1); % Vectors with previous excitation\nebuf2 = ebuf; bbuf = 0; % samples.\nZf = []; Zw = []; Zi = []; % Memory hangover in filters.\n\nfor (f=1:F)\n %fprintf(1,'... Frame no. %g out of %g.\\n',f,F);\n n = (f-1)*N+1:f*N; % Time index of current speech frame.\n\n [kappa,kf,theta0f,Pf,bf,ebuf,Zf,Zw] = celpana(x(n),L,M,c,cb,Pidx,bbuf,...\n ebuf,Zf,Zw);\n\n sigma = 2/pi*asin(kappa);\n sigma = udecode(uencode(sigma,6),6);\n kappa = sin(pi/2*sigma);\n theta0 = udecode(uencode(theta0,7,0.2),7,0.2);\n b = udecode(uencode(b,8,1.4),8,1.4);\n\n [xhat(n),ebuf2,Zi] = celpsyn(cb,kappa,kf,theta0f,Pf,bf,ebuf2,Zi);\n\n % Output excitation signal and parameters for current frame.\n e(n) = ebuf(Pidx(2)-N+1:Pidx(2));\n k(:,f) = kf;\n theta0(:,f) = theta0f;\n P(:,f) = Pf;\n b(:,f) = bf; bbuf = bf(J); % Last estimated b used in next frame.\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/39038-celp-codec/CELP_done/celp9600.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.49515968581795483}} {"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 [cl] = qt2cl(qt)\n% Convert volume from US liquid quarts to centiliters. \n% Chad Greene 2012\ncl = qt*94.6352946;", "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/qt2cl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.4951382442463673}} {"text": "function Edges = detectAreaBorders(images)\n\nimages(isnan(images))=0;\n% Edges=double(edge(images, 'canny'));\nimages = images+1;\nEdges = zeros(size(images));\nfor area=3:max(images(:))-1\n images_tmp = double(images==area);\n Edges=Edges | double(edge(images_tmp, 'canny'));\nend\n% figure;imagesc(Edges)\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Analysis/Atlas/detectAreaBorders.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125626441471, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4951382318871454}} {"text": "function plotData(x, y)\n%PLOTDATA Plots the data points x and y into a new figure \n% PLOTDATA(x,y) plots the data points and gives the figure axes labels of\n% population and profit.\n\nfigure; % open a new figure window\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Plot the training data into a figure using the \n% \"figure\" and \"plot\" commands. Set the axes labels using\n% the \"xlabel\" and \"ylabel\" commands. Assume the \n% population and revenue data have been passed in\n% as the x and y arguments of this function.\n%\n% Hint: You can use the 'rx' option with plot to have the markers\n% appear as red crosses. Furthermore, you can make the\n% markers larger by using plot(..., 'rx', 'MarkerSize', 10);\n\n\nplot(x, y, 'rx', 'MarkerSize', 10); % Plot the data\nylabel('Profit in $10,000s'); % Set the y\udbc0\udc00axis label\nxlabel('Population of City in 10,000s'); % Set the x\udbc0\udc00axis label\n\n\n% ============================================================\n\nend\n", "meta": {"author": "vkosuri", "repo": "CourseraMachineLearning", "sha": "b11d4152c323a084fa3bc942e108ed456b77cbd3", "save_path": "github-repos/MATLAB/vkosuri-CourseraMachineLearning", "path": "github-repos/MATLAB/vkosuri-CourseraMachineLearning/CourseraMachineLearning-b11d4152c323a084fa3bc942e108ed456b77cbd3/home/week-2/exercises/machine-learning-ex1/ex1/plotData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.8688267796346599, "lm_q1q2_score": 0.4951032439944346}} {"text": "%==============================================================================\n% This code is part of the Matlab-based toolbox\n% FAIR - Flexible Algorithms for Image Registration. \n% For details see \n% - https://github.com/C4IR and\n% - http://www.siam.org/books/fa06/\n%==============================================================================\n%\n% Tutorial for FAIR: SSD versus rotations, linearInter, HNSP level=4\n% \n%==============================================================================\n\nclear, close all, help(mfilename);\n\nsetup2DHNSPData; \nimgModel('set','imgModel','linearInter'); \nlevel = 4; omega = ML{level}.omega; m = ML{level}.m; \n[T,R] = imgModel('coefficients',ML{level}.T,ML{level}.R,omega);\nxc = getCellCenteredGrid(omega,m); \nRc = imgModel(R,omega,xc);\n\ncenter = (omega(2:2:end)-omega(1:2:end))'/2;\ntrafo('set','trafo','rotation2D','c',center);\n\nwc = pi/2*linspace(-1,1,101); dc = zeros(size(wc));\nfigure(1); clf;\nfor j=1:length(wc),\n yc = trafo(wc(j),xc);\n Tc = imgModel(T,omega,yc);\n dc(j) = SSD(Tc,Rc,omega,m);\n viewImage(128+(Tc-Rc)/2,omega,m); drawnow; \n FAIRpause(1/6)\nend;\nfigure; clf; p1 = plot(wc,dc); \n%==============================================================================\n", "meta": {"author": "C4IR", "repo": "FAIR.m", "sha": "975edebd37b833ae76696792870de5c05efcb9cb", "save_path": "github-repos/MATLAB/C4IR-FAIR.m", "path": "github-repos/MATLAB/C4IR-FAIR.m/FAIR.m-975edebd37b833ae76696792870de5c05efcb9cb/kernel/examples/E6_HNSP_SSD_rotation2D_level4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487572, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4951032362524718}} {"text": "% Author: Ricardo Baptista and Matthias Poloczek\n% Date: June 2018\n%\n% See LICENSE.md for copyright information\n%\n\nfunction output = local_search(objective, inputs)\n% LOCAL_SEARCH: Function runs binary optimization by searching over the neighborhood\n% of single model flips at each iteration\n\n% Extract inputs\nnVars = inputs.n_vars;\nnEval = inputs.evalBudget;\n\n% Generate initial condition and evaluate objective\nmodel \t = sample_models(1,nVars);\nmodel_val = objective(model);\n\n% determine the total number of iterations\nnIter = ceil(nEval/nVars);\n\n% Setup cells to store model, objective, and runtime\nmodel_iter = zeros(nIter, nVars);\nobj_iter = zeros(nIter,1);\ntime_iter = zeros(nIter,1);\n\n% Declare counter\ncounter = 0;\n\nfor i=1:nIter\n\n\t% Update counter\n\tcounter = counter + 1;\n\n\tls_iter = tic;\n\n\t% Setup vector to store new objective values and difference\n\tnew_obj = zeros(nVars,1);\n\tdiff_obj = zeros(nVars,1);\n\n\tfor j=1:nVars\n\t\t\n\t\t% Setup new_model with one flipped variable\n\t\tnew_model = model;\n\t\tnew_model(j) = 1-new_model(j);\n\n\t\t% Evaluate objective\n\t\tnew_obj(j) = objective(new_model);\n\t\tdiff_obj(j) = model_val - new_obj(j);\n\n\tend\n\n\t% Check if diff_obj is positive - improvement can be made\n\tif any(diff_obj > 0)\n\n\t\t% Choose optimal index to flip\n \t[~, opt_idx] = max(diff_obj);\n \tmodel(opt_idx) = 1 - model(opt_idx);\n \tmodel_val = new_obj(opt_idx);\n\n end\n\n\t% Save models, model_obj, and runtime\n\tmodel_iter(counter,:) = model;\n\tobj_iter(counter) = model_val;\n\ttime_iter(counter) = toc(ls_iter);\n\t\nend\n\n% extend results\nmodel_iter_new = zeros(nVars*nIter, nVars);\ntime_iter_new = zeros(nVars*nIter, 1);\nfor i=1:nIter\n\tidx = nVars*(i-1)+1:nVars*i;\n\tmodel_iter_new(idx,:) = repmat(model_iter(i,:), nVars, 1);\n\ttime_iter_new(idx) = interp1([0,1],[0,time_iter(i)],linspace(1/nVars,1,nVars));\nend\nobj_iter = reshape(repmat(obj_iter, 1, nVars)', nVars*nIter, 1);\n\n% save outputs\noutput = struct;\noutput.objVals = obj_iter; \noutput.optModel = model_iter_new;\noutput.runTime = time_iter_new;\n\nend", "meta": {"author": "baptistar", "repo": "BOCS", "sha": "fef0d4e34e376e8bb0dae9955d70c2155530b9eb", "save_path": "github-repos/MATLAB/baptistar-BOCS", "path": "github-repos/MATLAB/baptistar-BOCS/BOCS-fef0d4e34e376e8bb0dae9955d70c2155530b9eb/algorithms/local_search.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.4950880248861989}} {"text": "function dz = dynamics(z,u)\n% dz = dynamics(z,u)\n%\n% Computes the dynamics of a quadruple chain integrator\n%\n% INPUTS: \n% z = [4*nx,nt] = [position;velocity;acceleration;jerk]\n% u = [nx,nt] = snap\n%\n% OUTPUTS:\n% dz = dz/dt\n%\n\nnx = size(u,1); % dimension of the position space\nidx = (nx+1):(4*nx); % index of velocity, acceleration, and jerk\ndz = [z(idx,:);u]; % derivatives\n\nend", "meta": {"author": "MatthewPeterKelly", "repo": "OptimTraj", "sha": "c97b57fda511dacc6a6187f683428f0f3a1965f2", "save_path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj", "path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj/OptimTraj-c97b57fda511dacc6a6187f683428f0f3a1965f2/demo/minimumSnap/chainIntegrator/dynamics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.4950880172188622}} {"text": "function [node,elem,face]=volmap2mesh(img,ix,iy,iz,elemnum,maxvol,thickness,Amat,Bvec)\n%\n% [node,elem,face]=volmap2mesh(img,ix,iy,iz,thickness,elemnum,maxvol,A,B)\n%\n% convert a binary volume to tetrahedral mesh followed by an Affine transform\n%\n% author: Qianqian Fang (q.fang at neu.edu)\n% date: 2008/01/12\n%\n% input: \n% img, ix,iy,iz, elemnum and maxvol: see vol2mesh.m\n% thickness: scale z-dimension of the mesh to specified thickness, \n% if thickness==0, scaling is bypassed\n% Amat: a 3x3 transformation matrix\n% Bvec: a 3x1 vector\n% Amat and Bvec maps the image index space to real world coordnate system by\n% [x,y,z]_new=Amat*[x,y,z]_old+Bvec\n%\n% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)\n%\n\n[node,elem,face]=vol2mesh(img,ix,iy,iz,elemnum,maxvol);\n\nnode(:,1:3)=(Amat*node(:,1:3)'+repmat(Bvec(:),1,size(node,1)))';\n\nif(thickness)\n\tzmin=min(node(:,3));\n\tzmax=max(node(:,3));\n\tnode(:,3)=(node(:,3)-zmin)/(zmax-zmin)*thickness;\nend\n", "meta": {"author": "fangq", "repo": "iso2mesh", "sha": "556f4c321467a3ee042d4c559b4edc11e01dc574", "save_path": "github-repos/MATLAB/fangq-iso2mesh", "path": "github-repos/MATLAB/fangq-iso2mesh/iso2mesh-556f4c321467a3ee042d4c559b4edc11e01dc574/volmap2mesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303285397348, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4949701515309618}} {"text": "function title = p07_title ( )\n\n%*****************************************************************************80\n%\n%% P07_TITLE returns a title for problem 7.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 February 2002\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, string TITLE, a title for the problem.\n%\n title = 'The dying snake, ( x + sin(x) ) * e^(-x^2).';\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_min/p07_title.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.49497014998599104}} {"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": "%TIME_INTOVERSAMP\n%\n% The purpose of this test is to determine whether special code for\n% handling the integer oversampling case in the factorization routines\n% pays off in any way.\n\n\nLr=[1048576*2,2400];\nar=[ 512, 2];\nMr=[ 1024, 800];\n\nfor ii=1:length(Lr)\n\n L=Lr(ii);\n \n M=Mr(ii);\n a=ar(ii); \n \n [L, a, M]\n \n N=L/a;\n c=gcd(a,M);\n p=a/c;\n q=M/c;\n d=N/q;\n\n f=rand(L,1);\n gf=rand(p*q,c*d); \n c1=mex_dgt_fac_1(f,gf,a,M);\n\n f=rand(L,1);\n gf=rand(p*q,c*d);\n c2=mex_dgt_fac_2(f,gf,a,M);\n\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/timing/time_intoversamp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.49496190100371684}} {"text": "function [inplane_pix_size] = mrGetIPPixSize()\n%function [inplane_pix_size] = mrGetIPPixSize()\n%\n% PURPOSE: Prompt the user for the inplane anatomy pixel size\n% AUTHOR: Poirson \n% DATE: 07.16.97\n% HISTORY: Based on routine by Geoff Boynton \n% NOTES: The default values [256/260,256/260,1/4] mean that\n% 26 cm of brain image are interpolated on the 256 pixels\n% in the x and y dimensions (units are pixels/mm).\n% And that 1 pixel in the inplane direction equals 4mm thickness.\n%\n\n% 04/13/00 huk and nestares -- gets defPixSize from mrSESSION now\n% 07/27/00 wandell, brewer -- added extra check for reconParams field\n\nglobal mrSESSION\n\nqt=''''; %single quote character\n\nif isfield(mrSESSION,'fullInplaneSize') & ...\n isfield(mrSESSION,'reconParams') & ...\n isfield(mrSESSION.reconParams(1),'FOV') & ...\n isfield(mrSESSION.reconParams(1),'sliceThickness')\n defPixSize = [mrSESSION.fullInplaneSize(1)/ mrSESSION.reconParams(1).FOV, ...\n mrSESSION.fullInplaneSize(2)/mrSESSION.reconParams(1).FOV, ...\n 1/mrSESSION.reconParams(1).sliceThickness];\n disp('Calculating inplane anatomy voxel size from fullInplaneSize, FOV, and sliceThickness.');\nelse\n defPixSize = [256/260,256/260,1/4];\n disp('mrSESSION inplane voxel size info does not exist. Default values set; check your protocol parameters.');\nend\n\ndisp('Enter size of inplane anatomy pixels/mm in x,y and z directions');\n%inplane_pix_size=input('Default is [256/260,256/260,1/4]: ');\ndefStr = mat2str(defPixSize);\ninplane_pix_size=input(['Default is: ' defStr ': ']);\n%Or go the default\nif isempty(inplane_pix_size)\n\tinplane_pix_size= defPixSize;\nend\n\nreturn\n\n\n\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAlign/pixel/mrGetIPPixSize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.49496190100371684}} {"text": "function crfw = crfPairwiseTrain(vlab, hlab, pvSP, phSP, adjlist, pE, params, edgelen)\n\n% get f1(y1, y2) = log(P(y1|x)) + log(P(y2|x))\n% and f2(y1, y2) = I(y1=y2)*log(P(y1=y2|x)) + I(y1~=y2)*log(P(y1~=y2|x))\n\nnpair = 0;\nfor f = 1:numel(adjlist)\n npair = npair + size(adjlist{f}, 1);\nend\n\n\nf1 = zeros(npair, 49);\nf2 = zeros(npair, 49);\nf3 = zeros(npair, 49);\nlab = zeros(npair, 1);\n%nbpair = zeros(npair, 2);\n\nc = 0;\nfor f = 1:numel(adjlist)\n npairf = size(adjlist{f}, 1);\n pg = [pvSP{f}(:, 1) repmat(pvSP{f}(:, 2), 1, 5).*phSP{f} pvSP{f}(:, 3)]; \n labf = (vlab{f}==1)*1 + (vlab{f}==2).*(hlab{f}>0).*(hlab{f}+1) + (vlab{f}==3)*7;\n \n s1 = adjlist{f}(:, 1);\n s2 = adjlist{f}(:, 2);\n\n edgeperc = zeros(numel(s1), 2);\n nb = zeros(size(pg, 1), 1);\n for k = 1:numel(s1)\n nb(s1(k)) = nb(s1(k))+1;\n nb(s2(k)) = nb(s2(k))+1;\n edgeperc(k, 1) = edgelen{f}(s1(k), s2(k)) / (sum(edgelen{f}(s1(k), :))+sum(edgelen{f}(:, s1(k))));\n edgeperc(k, 2) = edgelen{f}(s1(k), s2(k)) / (sum(edgelen{f}(s2(k), :))+sum(edgelen{f}(:, s2(k))));\n end\n %nbpair(c+1:c+npairf, :) = [nb(s1) nb(s2)];\n% min(1./edgeperc(:, 1) + 1./edgeperc(:, 2))\n% max(1./edgeperc(:, 1) + 1./edgeperc(:, 2))\n % unaries normalize for number of edges, and pairwise normalize for\n % edge length\n for k1 = 1:7\n for k2 = 1:7\n f1(c+1:c+npairf, (k1-1)*7+k2) = log(pg(s1, k1))./nb(s1) + log(pg(s2, k2))./nb(s2);\n kp = params(k1 + (k2-1)*7, :);\n if k1==k2\n f2(c+1:c+npairf, (k1-1)*7+k2) = ...\n log(kp(3)./(1+exp(-kp(1)-kp(2)*(log(pE{f})-log(1-pE{f}))))).*...\n (edgeperc(:, 1) + edgeperc(:, 2));\n else\n f3(c+1:c+npairf, (k1-1)*7+k2) = ...\n log(kp(3)./(1+exp(-kp(1)-kp(2)*(log(pE{f})-log(1-pE{f}))))).*...\n (edgeperc(:, 1) + edgeperc(:, 2));\n end\n end\n end\n \n lab(c+1:c+npairf) = (labf(s1)>0 & labf(s2)>0).*((labf(s1)-1)*7 + labf(s2)); \n \n c = c + npairf;\nend\n\n\nind = find(lab==0);\nlab(ind) = [];\nf1(ind, :) = [];\nf2(ind, :) = [];\nf3(ind, :) = [];\n%nbpair(ind, :) = [];\n\nf2 = f2 - repmat(log(sum(exp(f2), 2)), [1 size(f2, 2)]);\nf3 = f3 - repmat(log(sum(exp(f3), 2)), [1 size(f3, 2)]);\n\nfnc{1} = f1;\nfnc{2} = f2;\nfnc{3} = f3;\n%disp(numel(lab))\n\n[p, err] = avep([1 0 0], fnc, lab);\ndisp(num2str([p err]))\n\n\ncrfw = fminsearch(@(x) objective(x, fnc, lab), [1 1 1]); \n\n[p, err] = avep(crfw, fnc, lab);\ndisp(num2str([p err]))\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction lpw = objective(w, f, lab)\n\ncorrectind = [1:numel(lab)]' + (lab-1)*numel(lab);\n\nlpw = 0;\ntmpz = 0;\nfor k = 1:numel(f)\n %if k==1\n lpw = lpw + w(k)*f{k}(correctind);\n tmpz = tmpz + w(k)*f{k};\n% else\n% lpw = lpw + w(k)*f{k}(correctind)./nb(:, 1).^w(end) + w(k)*f{k}(correctind)./nb(:, 2).^w(end);\n% tmpz = tmpz + w(k)*f{k}./repmat(nb(:, 1).^w(end), [1 size(f{k},2)]) + w(k)*f{k}./repmat(nb(:, 2).^w(end), [1 size(f{k},2)]);\n %end\nend\nz = log(sum(exp(tmpz), 2));\n\nlpw = -(sum(lpw - z));\n\n%disp(num2str([lpw w]))\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [p err] = avep(w, f, lab)\n\ncorrectind = [1:numel(lab)]' + (lab-1)*numel(lab);\n\nlpw = 0;\ntmpz = 0;\nfor k = 1:numel(f)\n %if k==1\n lpw = lpw + w(k)*f{k}(correctind);\n tmpz = tmpz + w(k)*f{k};\n% else\n% lpw = lpw + w(k)*f{k}(correctind)./nb(:, 1).^w(end) + w(k)*f{k}(correctind)./nb(:, 2).^w(end);\n% tmpz = tmpz + w(k)*f{k}./repmat(nb(:, 1).^w(end), [1 size(f{k},2)]) + w(k)*f{k}./repmat(nb(:, 2).^w(end), [1 size(f{k},2)]);\n %end\nend\nz = log(sum(exp(tmpz), 2));\n\np = mean(exp(lpw-z));\n\n[tmp, guess] = max(tmpz, [], 2);\nerr = mean(guess~=lab);\n \n\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/src/GeometricContext/crf/crfPairwiseTrain2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4949618964587064}} {"text": "vm.f=@(A,B).5*norm(A(:)+B(:)-Z(:))^2;\nvm.g=@(A,B)A+B-Z;\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/model_formation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4948324560418365}} {"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": "function [reduced_pot,successful] = reduce_pot(pot,tailnodes)\n% Executes the reduce operation defined in\n% Stable Local Computation with Conditional Gaussian Distributions\n% Steffen L. Lauritzen\n% Frank Jensen\n% September 1999\n% The potential pot is reduced if B contains any zero columns\n% The test are restricted to the positions in tailnodes.\n% Any columns successfully deleted are entered in the array successful\nif nargin < 2\n tailnodes = pot.ctaildom;\nend\n\nsuccessful = [];\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Keep track of remaining tailnodes %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nrem_tailnodes = pot.ctaildom;\nfor i = tailnodes\n pos = find(i==rem_tailnodes);\n successful_red = [pos];\n red_scgcpot = cell(1,pot.dsize);\n j = 1;\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Test whether all components of pot.scgpotc can be reduced %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n while ((j <= pot.dsize) & ~isempty(successful_red))\n [cpot,successful_red] = reduce_pot(pot.scgpotc{j},pos);\n red_scgcpot{j} = cpot;\n j = j + 1;\n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % If i is a reducible tailnode, then reduce the potential %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n if ~isempty(successful_red)\n successful = [successful i];\n pot.scgpotc = red_scgcpot;\n rem_tailnodes = mysetdiff(rem_tailnodes,i);\n end;\nend\n\npot.ctaildom = rem_tailnodes;\npositions = find_equiv_posns(rem_tailnodes,pot.ctaildom);\npot.ctailsizes = pot.ctailsizes(positions);\npot.ctailsize = sum(pot.ctailsizes);\npot.domain = mysetdiff(pot.domain,successful);\nreduced_pot = pot;\n\n\n\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/potentials/@scgpot/reduce_pot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639792, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.49477742416898157}} {"text": "function [state,options] = psoplotbestf(options,state,flag)\n% Plots the best, mean, and worst scores of particle swarm.\n\nnotinf = isfinite(state.Score) ;\n\nif strcmp(flag,'init')\n set(gca,'NextPlot','add',...\n 'XLabel',xlabel('Generation'),...\n 'YLabel',ylabel('Score'))\n% line(state.Generation,max(state.Score),...\n% 'Color','red',...\n% 'Tag','Worst Scores',...\n% 'Marker','.',...\n% 'LineStyle','none')\n line(state.Generation,mean(state.Score(notinf)),...\n 'Color','blue',...\n 'Tag','Mean Scores',...\n 'Marker','.',...\n 'LineStyle','none')\n line(state.Generation,min(state.Score),...\n 'Color','black',...\n 'Tag','Best Scores',...\n 'Marker','.',...\n 'LineStyle','none')\nelseif strcmp(flag,'done')\n legend({'Mean Score','Best Score'})\nelse\n% hworst = findobj(gca,'Tag','Worst Scores','Type','line') ;\n hmean = findobj(gca,'Tag','Mean Scores','Type','line') ;\n hbest = findobj(gca,'Tag','Best Scores','Type','line') ;\n x = [get(hmean,'XData'), state.Generation] ;\n% yworst = [get(hworst,'YData'), max(state.Score)] ;\n ymean = [get(hmean,'YData'), mean(state.Score(notinf))] ;\n ybest = [get(hbest,'YData'), min(state.Score)] ;\n% set(hworst,...\n% 'XData',x,...\n% 'YData',yworst)\n set(hmean,...\n 'XData',x,...\n 'YData',ymean)\n set(hbest,...\n 'XData',x,...\n 'YData',ybest)\n titletxt = sprintf('Best: %g Mean: %g',ybest(end),ymean(end)) ;\n title(titletxt)\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/psopt/psoplotbestf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.4947774160551222}} {"text": "%% DEMO 16: TIGRE 2D tomography \n%\n%\n% In demo we show how to do 2D tomography in TIGRE. It is exactly the same\n% as 3D.\n%\n% \n%\n%--------------------------------------------------------------------------\n%--------------------------------------------------------------------------\n% This file is part of the TIGRE Toolbox\n% \n% Copyright (c) 2015, University of Bath and \n% CERN-European Organization for Nuclear Research\n% All rights reserved.\n%\n% License: Open Source under BSD. \n% See the full license at\n% https://github.com/CERN/TIGRE/blob/master/LICENSE\n%\n% Contact: tigre.toolbox@gmail.com\n% Codes: https://github.com/CERN/TIGRE/\n% Coded by: Ander Biguri \n%--------------------------------------------------------------------------\n%% Initialize\nclear;\nclose all;\n%% PARALLEL BEAM 2D\n\n% VARIABLE DESCRIPTION UNITS\n%-------------------------------------------------------------------------------------\ngeo.DSD = 1536; % Distance Source Detector (mm)\ngeo.DSO = 1000; % Distance Source Origin (mm)\n% Detector parameters\n\n%\n% 1- Make the detector Nx1 \n% 2- Make the image NxMx1 \n\n\n% Image parameters\ngeo.nVoxel=[256;256;1]; % number of voxels (vx)\ngeo.sVoxel=[256;256;1]; % total size of the image (mm)\ngeo.dVoxel=geo.sVoxel./geo.nVoxel; % size of each voxel (mm)\n\ngeo.nDetector=[512; 1];\t\t\t\t\t% number of pixels (px)\ngeo.dDetector=[0.8; geo.dVoxel(3)]; \t\t\t\t\t% size of each pixel (mm)\ngeo.sDetector=geo.nDetector.*geo.dDetector; % total size of the detector (mm)\n\n% MAKE SURE THAT THE DETECTOR PIXELS SIZE IN V IS THE SAME AS THE IMAGE!\n\n% Offsets\ngeo.offOrigin =[0;0;0]; % Offset of image from origin (mm) \ngeo.offDetector=[0; 0]; \n\n\n% Auxiliary \ngeo.accuracy=0.5; % Accuracy of FWD proj (vx/sample)\ngeo.mode='parallel';\n%% Define angles of projection and load phatom image\n\nangles=linspace(0,2*pi,100);\nphatom=single(phantom('Modified Shepp-Logan',geo.nVoxel(1)));\nprojections=Ax(phatom,geo,angles);\n%% recosntruct\n\nimgOSSART=OS_SART(projections,geo,angles,40);\nimgASDPOCS=ASD_POCS(projections,geo,angles,40);\n\n%% Plot\nplotImg([imgOSSART;imgASDPOCS ],'Dim',3,'Slice',1); %top is ASD_POCS, bottom OSSART\n\n\n%%\n%%\n%% And now Fan Beam\n%% \n% The same thing!\n\n%% FAN BEAM 2D\n\n% VARIABLE DESCRIPTION UNITS\n%-------------------------------------------------------------------------------------\ngeo.DSD = 1536; % Distance Source Detector (mm)\ngeo.DSO = 1000; % Distance Source Origin (mm)\n% Detector parameters\n\n% Image parameters\ngeo.nVoxel=[256;256;1]; % number of voxels (vx)\ngeo.sVoxel=[256;256;1]; % total size of the image (mm)\ngeo.dVoxel=geo.sVoxel./geo.nVoxel; % size of each voxel (mm)\n\ngeo.nDetector=[512; 1];\t\t\t\t\t% number of pixels (px)\ngeo.dDetector=[0.8; 1]; \t\t\t\t\t% size of each pixel (mm)\ngeo.sDetector=geo.nDetector.*geo.dDetector; % total size of the detector (mm)\n\n% Offsets\ngeo.offOrigin =[0;0;0]; % Offset of image from origin (mm) ; \ngeo.offDetector=[0; 0]; \n\n% Auxiliary \ngeo.accuracy=0.5; % Accuracy of FWD proj (vx/sample)\ngeo.mode='cone';\n%% Define angles of projection and load phatom image\n\nangles=linspace(0,2*pi,100);\nphatom=single(phantom('Modified Shepp-Logan',geo.nVoxel(1)));\n% phatom=cat(3,phatom,phatom);\nprojections=Ax(phatom,geo,angles,'interpolated');\n%% recosntruct\n\nimgOSSART=OS_SART(projections,geo,angles,40);\n% in 2D, the TV norm minimization happens in CPU, this causes the\n% algorithms to be slower\nimgASDPOCS=ASD_POCS(projections,geo,angles,40);\n\n%% Plot\nplotImg([imgOSSART;imgASDPOCS ],'Dim',3,'Slice',1); %top is ASD_POCS, nottom OSSART\n\n\n", "meta": {"author": "CERN", "repo": "TIGRE", "sha": "8df632662228d1b1c52afd95c90d0f7a9f8dc4b3", "save_path": "github-repos/MATLAB/CERN-TIGRE", "path": "github-repos/MATLAB/CERN-TIGRE/TIGRE-8df632662228d1b1c52afd95c90d0f7a9f8dc4b3/MATLAB/Demos/d16_2Dtomography.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.4947774126218764}} {"text": "function out = vscale(F)\n%VSCALE Vertical scale of a CHEBFUN3V.\n% VSCL = VSCALE(F) returns the maximal vertical scale of the components of a\n% CHEBFUN3V object F as determined by evaluating F on a coarse tensor-product\n% grid.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nfor jj = 1:F.nComponents\n vscl(jj,1) = vscale(F.components{jj});\nend\nout = max(vscl);\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/@chebfun3v/vscale.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.49477740326064856}} {"text": "classdef S2AxisFieldTri < S2AxisField\n% a class represeneting a function on the sphere\n \n properties\n tri % S2Triangulation\n values = vector3d % function values\n end\n \n properties (Dependent = true)\n vertices\n antipodal\n end\n \n methods\n \n function sVF = S2AxisFieldTri(nodes,values)\n % initialize a spherical vector field\n \n if nargin == 0, return; end\n\n if isa(nodes,'function_handle')\n n = equispacedS2Grid('resolution',1.5*degree);\n values = nodes(n);\n nodes = n;\n end\n \n if isa(nodes,'S2Triangulation')\n sVF.tri = nodes;\n else\n sVF.tri = S2Triangulation(nodes);\n end\n\n sVF.values = values;\n \n end\n \n function v = get.vertices(S2F)\n v = S2F.tri.vertices;\n end\n \n function v = get.antipodal(S2F)\n v = S2F.tri.antipodal;\n end\n \n function S2F = set.vertices(S2F,v)\n if ~isempty(S2F.values), S2F.values = S2F.eval(v); end\n S2F.tri.vertices = v;\n S2F.tri.update;\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/S2Fun/@S2AxisFieldTri/S2AxisFieldTri.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.72487026428967, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.4947773938994204}} {"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 [c, ceq] = rendezvousNonlconFunc(x, iniOrbit, finOrbit, gmuXfr, minPe, maxAp, onlyOptBurn1)\n%rendezvousNonlconFunc Summary of this function goes here\n% Detailed explanation goes here\n [~, ~, ~, ~, ~, ~, xfrOrbit, ~, ~] = rendezvousObjFunc(x, iniOrbit, finOrbit, gmuXfr, [1,1], onlyOptBurn1);\n \n\t[rAp, rPe] = computeApogeePerigee(xfrOrbit(1), xfrOrbit(2));\n c(1) = rAp - maxAp;\n c(2) = minPe - rPe;\n ceq = [];\nend\n\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/astrodynamics/rendezvous/rendezvousNonlconFunc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837743174789, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.49458342843821407}} {"text": "function [cs,h]=m_contourf(long,lat,data,varargin)\n% M_CONTOURF Adds filled contours to a map\n% M_CONTOURF(LONG,LAT,DATA,...) is the same as M_CONTOUR except\n% that contours are filled. Areas of data above a given level are\n% filled, areas below are left blank or are filled by a lower level.\n% NaN's in the data leave holes in the filled plot/\n%\n% [CS,H] = M_CONTOURF(...) returns contour matrix C as described in\n% CONTOURC and a vector H of handles to PATCH objects (for use by\n% CLABEL).\n%\n% See also M_CONTOUR, CONTOURF\n\n% Rich Pawlowicz (rich@ocgy.ubc.ca) 17/Jan/1998\n%\n% This software is provided \"as is\" without warranty of any kind. But\n% it's mine, so you can't sell it.\n\n% 19/02/98 - type - should have been 'clip','patch', rather than 'off'.\n% 9/12/98 - handle all-NaN plots without letting contour crash.\n% 6/Nov/00 - eliminate returned stuff if ';' neglected (thx to D Byrne)\n\n\nglobal MAP_PROJECTION\n\n% Have to have initialized a map first\n\nif isempty(MAP_PROJECTION)\n disp('No Map Projection initialized - call M_PROJ first!');\n return;\nend\n\nif min(size(long))==1 && min(size(lat))==1\n [long,lat]=meshgrid(long,lat);\nend\n\n[X,Y]=m_ll2xy(long,lat,'clip','on'); %First find the points outside\n\ni=isnan(X); % For these we set the *data* to NaN...\ndata(i)=NaN;\n\n % And then recompute positions without clipping. THis\n % is necessary otherwise contouring fails (X/Y with NaN\n % is a no-no. Note that this only clips properly down\n % columns of long/lat - not across rows. In general this\n % means patches may nto line up properly a right/left edges.\nif any(i(:)), [X,Y]=m_ll2xy(long,lat,'clip','patch'); end\n\nif any(~i(:))\n [cs,h]=contourf(X,Y,data,varargin{:});\n set(h,'tag','m_contourf');\nelse\n cs=[];h=[];\nend\n\nif nargout==0\n clear cs h\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/m_map/m_contourf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.4945834248761891}} {"text": "function c = times(a,b)\n% TIMES implements a.*b, where either a or b is an adiff object.\n\nswitch [class(a),class(b)]\n \ncase 'adiffdouble'\n c = adiff(b.*a.x, rowmult(b, a.dx), a.root);\n \ncase 'doubleadiff'\n c = adiff(a.*b.x, rowmult(a, b.dx), b.root);\n \ncase 'adiffadiff'\n checkroot(a,b);\n c = adiff( a.x.*b.x, rowmult(b.x, a.dx)+rowmult(a.x, b.dx), a.root);\n \notherwise\n error(['Can''t multiply (.*) ',class(a),' and ',class(b)]);\n \nend\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/OptiToolbox/Utilities/Differentiation/Automatic/@adiff/times.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.49458342146584094}} {"text": "% The COBRAToolbox: testGeometricFBA.m\n%\n% Purpose:\n% - Tests whether geometricFBA works as intended.\n%\n% Authors:\n% - Thomas Pfau, Oct 2018\n\n\n% save the current path\ncurrentDir = pwd;\n\n% The testmodel used is structured as follows:\n%\n% <-> A -> B ---> C --> E <->\n% \\ ^\n% \\ /\n% -> F --> G\n%\n% Thus the flux can be split between A -> B -> C -> E and A -> F -> G -> E\n\n% load the test models\nmodel = createToyModelForGeoFBA();\n% model with Constraints\nmodelWConst = addCOBRAConstraints(model,{'R1'},400); % R1 restricted to a maximum flux of 400\n\n%When detectDeadEnds is changed according to Ronans suggestion, we need to test\n%multiple solvers.\nsolverPkgs = prepareTest('needsLP', true, 'minimalMatlabSolverVersion',8.0, 'excludeSolvers',{'pdco','ddqMinos','quadMinos','matlab'});\ntol = 1e-4;\nfor k = 1:length(solverPkgs.LP)\n % set the solver\n changeCobraSolver(solverPkgs.LP{k}, 'LP', 0);\n fprintf('Testing geometricFBA with solver %s ...\\n',solverPkgs.LP{k}); \n sol = geometricFBA(model);\n assert(all(abs(sol(1:6) - 500) < tol))\n sol = geometricFBA(modelWConst);\n % flux is now centered between 0 and 400 for R11.. R3 and between 600\n % and 1000 for R4..6\n assert(all(abs(sol(1:3) - 200) < tol))\n assert(all(abs(sol(4:6) - 800) < tol)) \nend\n\nfprintf('Done...\\n');\ncd(currentDir)\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/test/verifiedTests/analysis/testGeometricFBA/testGeometricFBA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.4945834180554922}} {"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 polygonal_surface_display ( node_file_name, face_file_name )\n\n%*****************************************************************************80\n%\n%% POLYGONAL_SURFACE_DISPLAY displays a polygonal surface file.\n%\n% Discussion:\n%\n% This program reads two files defining the nodes and the faces\n% of a polygonal surface in 3D.\n%\n% It displays the surface using MATLAB's graphics system.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 January 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string NODE_FILE_NAME, the name of the node file.\n%\n% Input, string FACE_FILE_NAME, the name of the face file.\n%\n timestamp ( );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'POLYGONAL_SURFACE_DISPLAY\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Read the nodes and faces defining\\n' );\n fprintf ( 1, ' a polygonal surface and display the object\\n' );\n fprintf ( 1, ' as a MATLAB shape.\\n' );\n%\n% If at least one command line argument, it's the node file name.\n%\n if ( nargin < 1 )\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'POLYGONAL_SURFACE_DISPLAY:\\n' );\n node_file_name = input ( 'Enter the name of the node file:' );\n\n end\n%\n% If at least two command line arguments, it's the face file name.\n%\n if ( nargin < 2 )\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'POLYGONAL_SURFACE_DISPLAY:\\n' );\n face_file_name = input ( 'Enter the name of the face file:' );\n\n end\n%\n% Read the data.\n%\n [ node_num, node_xyz ] = polygonal_surface_node_file_read ( node_file_name );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of nodes = %d\\n', node_num );\n\n r8mat_transpose_print_some ( 3, node_num, node_xyz, 1, 1, 3, 5, ...\n ' First five nodes:' );\n\n [ face_order, face_num, face_node ] = ...\n polygonal_surface_face_file_read ( face_file_name );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Face order = %d\\n', face_order );\n fprintf ( 1, ' Number of faces = %d\\n', face_num );\n\n i4mat_transpose_print_some ( face_order, face_num, face_node, ...\n 1, 1, face_order, 5, ' First five faces:' );\n%\n% Display the image as a collection of polygons.\n%\n handle = patch ( 'Vertices', node_xyz', 'Faces', face_node' );\n \n set ( handle, 'FaceColor', [0.5, 0.6, 0.8], 'EdgeColor', 'Black' );\n\n axis equal; \n grid on;\n\n xlabel ( '--X axis--' )\n ylabel ( '--Y axis--' )\n zlabel ( '--Z axis--' )\n%\n% The TITLE function will interpret underscores in the title.\n% We need to unescape such escape sequences!\n%\n title_string = s_escape_tex ( face_file_name );\n title ( title_string )\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'POLYGONAL_SURFACE_DISPLAY:\\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 table = i4mat_data_read ( input_filename, m, n )\n\n%*****************************************************************************80\n%\n%% I4MAT_DATA_READ reads data from an I4MAT file.\n%\n% Discussion:\n%\n% An I4MAT is an array of I4'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 in the data.\n%\n% Output, integer 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, ' %d' );\n end\n\n input_unit = fopen ( input_filename );\n\n if ( input_unit < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4MAT_DATA_READ - Error!\\n' );\n fprintf ( 1, ' Could not open the input file.\\n' );\n error ( 'I4MAT_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 fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4MAT_DATA_READ - Error!\\n' );\n fprintf ( 1, ' End of input while reading data.\\n' );\n error ( 'I4MAT_DATA_READ - Error!' );\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 ] = i4mat_header_read ( input_filename )\n\n%*****************************************************************************80\n%\n%% I4MAT_HEADER_READ reads the header from an I4MAT file.\n%\n% Discussion:\n%\n% An I4MAT is an array of I4'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, 'I4MAT_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, 'I4MAT_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 i4mat_transpose_print_some ( m, n, a, ilo, jlo, ihi, jhi, title )\n\n%*****************************************************************************80\n%\n%% I4MAT_TRANSPOSE_PRINT_SOME prints some of an I4MAT, transposed.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 June 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns.\n%\n% Input, integer A(M,N), an M by N matrix to be printed.\n%\n% Input, integer ILO, JLO, the first row and column to print.\n%\n% Input, integer IHI, JHI, the last row and column to print.\n%\n% Input, string TITLE, an optional title.\n%\n incx = 10;\n\n if ( 0 < s_len_trim ( title ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, '%s\\n', title );\n end\n\n for i2lo = max ( ilo, 1 ) : incx : min ( ihi, m )\n\n i2hi = i2lo + incx - 1;\n i2hi = min ( i2hi, m );\n i2hi = min ( i2hi, ihi );\n\n inc = i2hi + 1 - i2lo;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Row: ' );\n for i = i2lo : i2hi\n fprintf ( 1, '%7d ', i );\n end\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Col\\n' );\n fprintf ( 1, '\\n' );\n\n j2lo = max ( jlo, 1 );\n j2hi = min ( jhi, n );\n\n for j = j2lo : j2hi\n\n fprintf ( 1, '%5d ', j );\n for i2 = 1 : inc\n i = i2lo - 1 + i2;\n fprintf ( 1, '%7d ', a(i,j) );\n end\n fprintf ( 1, '\\n' );\n\n end\n\n end\n\n return\nend\nfunction [ face_order, face_num, face_node ] = ...\n polygonal_surface_face_file_read ( face_file_name )\n\n%*****************************************************************************80\n%\n%% POLYGONAL_SURFACE_FACE_FILE_READ reads faces defining a surface.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 January 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Edward Angel,\n% Interactive Computer Graphics, \n% a Top-Down Approach with OpenGL,\n% Addison-Wesley, 2000.\n%\n% Parameters:\n%\n% Input, string FACE_FILE_NAME, the name of the face file.\n%\n% Output, integer FACE_ORDER, the order of the face.\n%\n% Output, integer FACE_NUM, the number of face defined.\n%\n% Output, real FACE_NODE(FACE_ORDER,FACE_NUM), \n% the nodes making up each face.\n%\n [ face_order, face_num ] = i4mat_header_read ( face_file_name );\n\n face_node = i4mat_data_read ( face_file_name, face_order, face_num );\n\n return\nend\nfunction [ node_num, node_xyz ] = polygonal_surface_node_file_read ( ...\n node_file_name )\n\n%*****************************************************************************80\n%\n%% POLYGONAL_SURFACE_NODE_FILE_READ reads node information from a polygonal surface node file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 June 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Edward Angel,\n% Interactive Computer Graphics, \n% a Top-Down Approach with OpenGL,\n% Addison-Wesley, 2000.\n%\n% Parameters:\n%\n% Input, string NODE_FILE_NAME, the name of the node file.\n%\n% Output, integer NODE_NUM, the number of nodes defined.\n%\n% Output, real NODE_XYZ(3,NODE_NUM), the coordinates of nodes.\n%\n [ dim_num, node_num ] = r8mat_header_read ( node_file_name );\n\n node_xyz = r8mat_data_read ( node_file_name, dim_num, node_num );\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_transpose_print_some ( m, n, a, ilo, jlo, ihi, jhi, title )\n\n%*****************************************************************************80\n%\n%% R8MAT_TRANSPOSE_PRINT_SOME prints some of an R8MAT, transposed.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 May 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns.\n%\n% Input, real A(M,N), an M by N matrix to be printed.\n%\n% Input, integer ILO, JLO, the first row and column to print.\n%\n% Input, integer IHI, JHI, the last row and column to print.\n%\n% Input, string TITLE, an optional title.\n%\n incx = 5;\n\n if ( 0 < s_len_trim ( title ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, '%s\\n', title );\n end\n\n for i2lo = max ( ilo, 1 ) : incx : min ( ihi, m )\n\n i2hi = i2lo + incx - 1;\n i2hi = min ( i2hi, m );\n i2hi = min ( i2hi, ihi );\n\n inc = i2hi + 1 - i2lo;\n \n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Row: ' );\n for i = i2lo : i2hi\n fprintf ( 1, '%7d ', i );\n end\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Col\\n' );\n\n j2lo = max ( jlo, 1 );\n j2hi = min ( jhi, n );\n\n for j = j2lo : j2hi\n\n fprintf ( 1, '%5d ', j );\n for i2 = 1 : inc\n i = i2lo - 1 + i2;\n fprintf ( 1, '%12f', a(i,j) );\n end\n fprintf ( 1, '\\n' );\n\n end\n\n end\n\n return\nend\nfunction s2 = s_escape_tex ( s1 )\n\n%*****************************************************************************80\n%\n%% S_ESCAPE_TEX de-escapes TeX escape sequences.\n%\n% Discussion:\n%\n% In particular, every occurrence of the characters '\\', '_',\n% '^', '{' and '}' will be replaced by '\\\\', '\\_', '\\^',\n% '\\{' and '\\}'. A TeX interpreter, on seeing these character\n% strings, is then likely to return the original characters.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 January 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string S1, the string to be de-escaped.\n%\n% Output, string S2, a copy of the string, modified to avoid TeX escapes.\n%\n s1_length = length ( s1 );\n\n s1_pos = 0;\n s2_pos = 0;\n s2 = [];\n\n while ( s1_pos < s1_length )\n\n s1_pos = s1_pos + 1;\n\n if ( s1(s1_pos) == '\\' || ...\n s1(s1_pos) == '_' || ...\n s1(s1_pos) == '^' || ...\n s1(s1_pos) == '{' || ...\n s1(s1_pos) == '}' )\n s2_pos = s2_pos + 1;\n s2 = strcat ( s2, '\\' );\n end\n\n s2_pos = s2_pos + 1;\n s2 = strcat ( s2, s1(s1_pos) );\n\n end\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/polygonal_surface_display/polygonal_surface_display.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.49456740638429686}} {"text": "function [errors, perrors] = ...\n mcmcTestSuperpixelClassifier(spfeatures, imsegs, vclassifier, hclassifier)\n\nspvlabels = {imsegs(:).vert_labels};\nsphlabels = {imsegs(:).horz_labels};\n\n% test vertical\n[vdata, vlab, imind] = formatData(spfeatures, spvlabels);\nvconf = test_boosted_dt_mc(vclassifier, vdata);\nvconf = 1 ./ (1+exp(-vconf));\nvconf = vconf ./ repmat(sum(vconf, 2), 1, size(vconf, 2));\n[tmp, vmax] = max(vconf, [], 2);\nverror = mean(vmax~=vlab)\n\nvconferr = 0;\nfor k = 1:numel(vlab)\n vconferr = vconferr + 1 - vconf(k, vlab(k));\nend\nvconferr = vconferr / numel(vlab)\n\n% test subclass\n[hdata, hlab] = formatData(spfeatures, sphlabels);\nhconf = test_boosted_dt_mc(hclassifier, hdata);\nhconf = 1 ./ (1+exp(-hconf));\nhconf = hconf ./ repmat(sum(hconf, 2), 1, size(hconf, 2));\n[tmp, hmax] = max(hconf, [], 2);\nherror = mean(hmax~=hlab)\n\nhconferr = 0;\nfor k = 1:numel(hlab)\n hconferr = hconferr + 1 - hconf(k, hlab(k));\nend\nhconferr = hconferr / numel(hlab)\n\n% get same_label error\n%[serror, sconferr] = sameLabelError(spfeatures, spvlabels, sphlabels, ...\n% {imsegs(:).adjmat}, vclassifier, hclassifier)\n\nerrors.verr = verror;\nerrors.vcerr = vconferr;\nerrors.herr = herror;\nerrors.hcerr = hconferr;\n%errors.serr = serror;\n%errors.scerr = sconferr;\n\n[hdata2, hlab2, imind] = formatData(spfeatures, spvlabels);\nhconf2 = test_boosted_dt_mc(hclassifier, hdata2);\nhconf2 = 1 ./ (1+exp(-hconf2));\nhconf2 = hconf2 ./ repmat(sum(hconf2, 2), 1, size(hconf2, 2));\n\nlab = (vlab==1)*1 + (vlab==2).*(hlab2+1) + (vlab==3)*7;\n\npEst = [vconf(:, 1) repmat(vconf(:, 2), 1, 5).*hconf2 vconf(:, 3)];\npTrue = (repmat((1:7), numel(lab), 1)==repmat(lab, 1, 7));\n\n[pMean, pVal, estBias] = evaluateProbabilityEstimate(pEst(:), pTrue(:), 0.05);\nperrors.pMean = pMean; \nperrors.pVal = pVal;\nperrors.estBias = estBias;\n\nperrors.pMean2 = 0;\nperrors.estBias2 = 0;\nsnv = 0;\nfor k = 1:5\n testind = find((imind > (1-k)*50) & (imind < k*50));\n trainind = setdiff((1:numel(imind)),testind)'; \n \n [pMean, pVal, estBias] = evaluateProbabilityEstimate(pEst(trainind), pTrue(trainind), 0.05);\n perrors.pMeanTr{k} = pMean;\n \n pEstTest = pEst(testind);\n for i = 1:numel(pEstTest)\n [val, maxind] = min(abs(pVal-pEstTest(i)));\n pEstTest(i) = pMean(maxind);\n end\n% disp(num2str(numel(pEstTest)))\n [pMean, pVal, estBias, nv] = evaluateProbabilityEstimate(pEstTest, pTrue(testind), 0.05);\n snv = snv + nv; \n perrors.pMean2 = perrors.pMean2 + pMean.*nv;\n perrors.estBias2 = perrors.estBias2 + estBias/5;\nend\nperrors.pMean2 = perrors.pMean2 ./ max(snv, 1E-5);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [data, lab, imind] = formatData(features, labels, labels2)\n% concatenate data and labels, and give adjacency information\n\nnimages = numel(features);\n[tmp, nvars] = size(features{1});\n% count superpixels\nnsp = 0;\nfor f = 1:nimages\n nsp = nsp + sum(labels{f}~=0);\nend\ndata = zeros(nsp, nvars);\nlab = zeros(nsp, 1);\nimind = zeros(nsp, 1);\n\n% concatenate data\nvc = 0;\nfor f = 1:nimages\n ind = find(labels{f}~=0);\n data(vc+1:vc+numel(ind), :) = features{f}(ind, :); \n lab(vc+1:vc+numel(ind)) = labels{f}(ind);\n imind(vc+1:vc+numel(ind)) = f;\n vc = vc + numel(ind); \nend\n\n\n\nfunction [serror, sconferr] = sameLabelError(features, vlabels, hlabels, adjmat, vclassifier, hclassifier)\n\nnimages = numel(features);\n[tmp, nvars] = size(features{1});\n% count superpixels\nnsp = 0;\nfor f = 1:nimages\n nsp = nsp + sum((vlabels{f}~=0) & ((hlabels{f}~=0) | (vlabels{f}~=2)));\nend\ndata = zeros(nsp, nvars);\nlab = zeros(nsp, 1);\nadj = cell(nsp, 1);\nissame = cell(nsp, 1);\n\n% concatenate data\nvc = 0;\nnadj = 0;\nfor f = 1:nimages\n ind = find((vlabels{f}~=0) & ((hlabels{f}~=0) | (vlabels{f}~=2)));\n data(vc+1:vc+numel(ind), :) = features{f}(ind, :); \n for k = 1:numel(ind)\n restind = ind(k+1:end);\n adj{vc+k} = restind(find(adjmat{f}(ind(k), restind)));\n issame{vc+k} = zeros(numel(adj{vc+k}), 1);\n for k2 = 1:numel(adj{vc+k})\n issame{vc+k}(k2) = (vlabels{f}(ind(k))==vlabels{f}(adj{vc+k}(k2))) && ...\n (hlabels{f}(ind(k))==hlabels{f}(adj{vc+k}(k2)));\n end\n nadj = nadj +numel(adj{vc+k});\n end\n vc = vc + numel(ind);\nend\n \nvconf = test_boosted_dt_mc(vclassifier, data); \nvconf = 1 ./ (1+exp(-vconf));\nvconf = vconf ./ repmat(sum(vconf, 2), 1, size(vconf, 2));\nhconf = test_boosted_dt_mc(hclassifier, data);\nhconf = 1 ./ (1+exp(-hconf));\nhconf = hconf ./ repmat(sum(hconf, 2), 1, size(hconf, 2));\n\nsconf = zeros(nadj, 1);\nslab = zeros(nadj, 1);\nsc = 0;\nfor k = 1:numel(adj)\n for k2 = 1:numel(adj{k})\n sc = sc + 1;\n slab(sc) = issame{k}(k2);\n sconf(sc) = sum(vconf(k, [1 3]).*vconf(k2, [1 3])) + ...\n sum((vconf(k, 2)*hconf(k, :)) .* (vconf(k2, 2)*hconf(k2, :)));\n end\nend\n\nind1 = find(slab==1);\nind2 = find(slab==0);\ndisp(num2str([mean(sconf(ind1)) mean(sconf(ind2))]))\n[sorted] = sort(sconf);\ntval = sorted(floor(numel(sconf)*(1-mean(slab))));\nserror = mean(slab~=(sconf>tval));\nsconferr = mean(abs(slab-sconf));\n\n", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/panoContext_code/Toolbox/SpatialLayout_shrink/spatiallayoutcode/GeometricContext/geomContext_src_07_02_08/src/mcmc/mcmcTestSuperpixelClassifier.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4945674032199049}} {"text": "classdef CellsClassifier < handle\n \n methods (Access = public, Static)\n \n function [full,empty,cut] = classifyCells(levelSet,connec)\n nodes = connec;\n indexes = (1:size(connec,1))';\n lsNodes = levelSet(nodes);\n phiCase = sum((sign(lsNodes)<0),2);\n \n full = phiCase == size(nodes,2);\n empty = phiCase == 0;\n cut = indexes(~(full | empty));\n end\n \n end\n \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/FEM/Mesh/Unfitted/Strategies/CellsClassifier.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.49456740321990483}} {"text": "function [ z, stats ] = solve_cosamp( Phi, K, y, x)\n%SOLVEBPIC Solves the CoSaMP problem\n [M, N] = size(Phi);\n epsilon = 1e-6;\n %We now setup our recovery program.\n solver = spx.pursuit.single.CoSaMP(Phi, K);\n result = solver.solve(y);\n % recovered representation. N length vector\n z = result.z;\n stats.recoveredRepresentationVector = z;\n % recovery error vector. N length vector\n h = x - z;\n stats.recoveryErrorVector = h;\n % l_2 norm of reconstruction error\n stats.recoveryErrorL2Norm = norm(h);\n % The K non-zero coefficients in x (set of indices)\n stats.T0 = find (x ~= 0);\n % The portion of recovery error over T0 K length vector\n stats.recoveryErrorVectorT0 = h(stats.T0); \n % Positions of other places (set of indices)\n stats.T0C = setdiff(1:N , stats.T0);\n % Recovery error at T0C places [N - K] length vector\n hT0C = h(stats.T0C);\n stats.recoveryErrorVectorT0C = hT0C;\n % The K largest indices after T0 in recovery error (set of indices)\n stats.T1 = spx.commons.signals.largest_indices(hT0C, K);\n % The recovery error component over T1. [K] length vector.\n hT1 = h(stats.T1);\n stats.recoveryErrorVectorT1 = hT1;\n % Remaining indices [N - 2K] set of indices\n stats.TRest = setdiff(stats.T0C , stats.T1);\n % Recovery error over remaining indices [N - 2K] length vector\n hTRest = h(stats.TRest);\n stats.recoveryErrorVectorTRest = hTRest;\n % largest indices of the recovered vector\n stats.TT0 = spx.commons.signals.largest_indices(z, K);\n % Support Overlap\n stats.supportOverlap = intersect(stats.T0, stats.TT0);\n % Support recovery ratio\n stats.supportRecoveryRatio = numel(stats.supportOverlap) / K;\n % measurement error vector [M] length vector\n e = y - Phi * z;\n stats.measurementError = e;\n % Norm of measurement error. This must be less than epsilon\n stats.measurementErrorL2Norm = norm(e);\n % Ratio between the norm of recovery error and measurement error\n stats.recoveryToMeasurementErrorNormRatio = ...\n stats.recoveryErrorL2Norm / stats.measurementErrorL2Norm;\n % whether we consider the process to be success or not.\n % We consider success only if the support has been recovered\n % completely.\n stats.success = numel(stats.supportOverlap) == K;\nend\n\n", "meta": {"author": "indigits", "repo": "sparse-plex", "sha": "43cae2978f62938d001baaa03308a2a717ee6c9b", "save_path": "github-repos/MATLAB/indigits-sparse-plex", "path": "github-repos/MATLAB/indigits-sparse-plex/sparse-plex-43cae2978f62938d001baaa03308a2a717ee6c9b/examples/pursuit/single_recovery/cosamp/solve_cosamp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.4945673977630576}} {"text": "%%***************************************************************************\n%% blkeig: compute eigenvalue decomposition of a cell array\n%% whose contents are square matrices or the diagonal\n%% of a diagonal matrix. \n%% \n%% [d,V] = blkeig(blk,X);\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 [d,V] = blkeig(blk,X);\n\n spdensity = 0.5; \n\n if ~iscell(X); \n if strcmp(blk{1},'s'); \n blktmp = blk{2}; \n if (length(blktmp) == 1);\n if (nargout == 1); \n d = eig(full(X)); \n elseif (nargout == 2);\n [V,d] = eig(full(X));\n d = diag(d); \n end\n else\n if (nargout == 2); \n V = sparse(length(X),length(X)); \n end\n\t d = zeros(sum(blktmp),1); \n xx = mexsvec(blk,X,0); \n blktmp2 = blktmp.*(blktmp+1)/2;\n s2 = [0, cumsum(blktmp2)];\n blksub{1,1} = 's'; blksub{1,2} = 0; \n s = [0, cumsum(blktmp)]; \n for i = 1:length(blktmp)\n pos = [s(i)+1 : s(i+1)];\n blksub{2} = blktmp(i); \n Xsub = mexsmat(blksub,xx(s2(i)+1:s2(i+1)),0); \n if (nargout == 1); \n lam = eig(Xsub); \n elseif (nargout == 2); \n [evec,lam] = eig(Xsub); \n lam = diag(lam);\n V(pos,pos) = sparse(evec); \n end \n d(pos,1) = lam;\n end\n end\n n2 = sum(blktmp.*blktmp); \n if (nargout == 2); \n if (nnz(V) <= spdensity*n2);\n V = sparse(V); \n else\n V = full(V); \n end \n end \n elseif strcmp(blk{1},'l');\n if (nargout == 2); \n V = ones(size(X)); d = X; \n elseif (nargout == 1); \n d = X; \n end\n end\n else\n if (nargout == 2); \n V = cell(size(X)); d = cell(size(X)); \n for p = 1:size(blk,1); \n\t [d{p},V{p}] = blkeig(blk(p,:),X{p}); \n end\n elseif (nargout == 1); \n d = cell(size(X)); \n for p = 1:size(blk,1); \n\t d{p} = blkeig(blk(p,:),X{p}); \n end\n end\n end\n%%***************************************************************************\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/cvx-1.21.b795/sdpt3/Solver/blkeig.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.49451184478463395}} {"text": "% Group (split) position data by time or in specified number of partitions\n%\n% This function divides position data into groups based on pair of values (groupType, groupingValue).\n% You can use it to split position data into predefined number of groups (2, 4, e.t.c.), or into\n% groups of equal time.\n%\n% USAGE\n% [groupIndices, edges] = general.groupPositions(pos, groupType, groupingValue)\n% pos Position samples. Matrix of size at least Nx1.\n% groupType String that defines type of grouping. Affects how groupingValue\n% argument is used. 'time' defines group by time interval.\n% 'num' groups positions in specified number of groups.\n% groupingValue Integer that specify value for grouping. If groupType == 'time'\n% this argument should be a value of seconds.\n% If groupType == 'num' this argument is the number of groups.\n%\n% groupIndices Vector of length equal to number of position samples. Each value\n% indicates group belongingness. If groupIndices(3) == 1, means that\n% position sample number 3 belongs to group number 1.\n% edges Vector of edges that define groups. For example, if data is split \n% in halves, then edges = [0 Inf].\n%\n% EXAMPLE\n%\n% pos = data.getPositions();\n% groupIndices = general.groupPositions(pos, 'num', 2); % divide data into halves\n% positionsOfFirstGroup = pos(groupIndices == 1, :);\n%\n% general.groupPositions(pos, 'time', 1); % divide data into groups each duration of 1 second\n%\nfunction [groupIndices, edges] = groupPositions(pos, groupType, groupingValue)\n if nargin < 3\n error('BNT:numArgs', 'Incorrect number of parameters (type ''help general.groupPositions'' for details).');\n end\n\n if size(pos, 1) == 1 && size(pos, 2) > 2\n % this is probably a row vector, transpose it\n pos = pos';\n end\n \n if size(pos, 2) < 1\n error('Incorrect value for argument ''pos'' (type ''help general.groupPositions'' for details).');\n end\n\n if ~helpers.isstring(groupType, 'time', 'num')\n error('Incorrect value for argument ''groupType'' (type ''help general.groupPositions'' for details).');\n end\n\n if ~helpers.isdscalar(groupingValue, '>0')\n error('Incorrect value for argument ''groupingValue'', it should be >= 1 (type ''help general.groupPositions'' for details).');\n end\n\n post = pos(:, 1);\n duration = max(post) - min(post);\n\n if strcmpi(groupType, 'num')\n interval = duration / groupingValue;\n edges = 0:interval:duration;\n edges = min(post) + edges; % shift if for case min(post) ~= 0\n edges(end) = Inf;\n else\n interval = groupingValue;\n edges = 0:interval:duration;\n edges = min(post) + edges; % shift if for case min(post) ~= 0\n edges(end+1) = Inf;\n end\n\n [~, groupIndices] = histc(post, edges);\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/+general/groupPositions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.4945118424927172}} {"text": "function varargout = drawGraph(varargin)\n%DRAWGRAPH Draw a graph, given as a set of vertices and edges\n%\n% drawGraph(NODES, EDGES) \n% Draws a graph specified by a set of nodes (array N-by-2 or N-by-3,\n% corresponding to coordinate of each node), and a set of edges (an array\n% NE-by-2, containing for each edge the first and the second node).\n% Default drawing is a red circle for nodes and a blue line for edges.\n%\n% drawGraph(NODES, EDGES, FACES)\n% Also draws faces of the graph as patches.\n%\n% drawGraph(GRAPH)\n% Passes argument in a srtucture with at least 2 fields named 'nodes' and\n% 'edges', and possibly one field 'faces', corresponding to previously\n% described parameters.\n% GRAPH can also be a cell array, whose first element is node array,\n% second element is edges array, and third element, if present, is faces\n% array.\n%\n%\n% drawGraph(..., SNODES)\n% drawGraph(..., SNODES, SEDGES)\n% drawGraph(..., SNODES, SEDGES, SFACES)\n% Specifies the draw mode for each element, as in the classical 'plot'\n% function. To not display some elements, uses 'none'.\n%\n%\n% H = drawGraph(...) \n% Returns handle to the set of edges.\n% \n% [HN, HE] = drawGraph(...) \n% Returns handle to the set of nodes and to the set of edges.\n%\n% [HN, HE, HF] = drawGraph(...) \n% Also returns handle to the set of faces.\n% \n% See Also\n% graphs, drawGraphEdges, fillGraphFaces, clipGraph, clipGraphPolygon\n%\n\n% -----\n% author : David Legland \n% INRA - TPV URPOI - BIA IMASTE\n% created the 17/07/2003.\n%\n\n% HISTORY\n% 10/02/2004 : documentation\n% 06/04/2004 : change name\n% 09/07/2004 : add faces\n% 05/08/2004 : correct bug when drawing 2D graph\n% 06/08/2004 : small bug for drawing poins (length instead of size(.,1))\n% 09/08/2004 : rewrite code (separate 2D and 3D, use of plot instead of\n% line, manage faces if present in 2D and 3D, ...), add style\n% management, various input types, and documentation\n% 22/09/2004 : correct bug in drawing faces\n% 11/11/2005 : forgot a loop index for faces stored as cells\n% 22/05/2009 add more drawing options\n\n\n%% initialisations\n\n% uses empty arrays by default for edges and faces\ne = [];\nf = [];\n\n% default styles for nodes, edges, and faces\n\n% nodes are drawn as red circles\nsn = {'linestyle', 'none', 'color', 'r', 'marker', 'o'};\n\n% edges are drawn as blue lines\nse = {'linestyle', '-', 'color', 'b'};\n\n% faces are cyan, their edges are not drawn\nsf = {'EdgeColor', 'none', 'Facecolor', 'c'};\n\n\n%% Process input arguments\n\n% case of a call without arguments\nif nargin == 0\n help drawGraph;\n return;\nend\n\n% ---------------------------------------------------------------\n% First extract the graph structure\n\nvar = varargin{1};\nif iscell(var)\n % graph is stored as a cell array: first cell is nodes, second one is\n % edges, and third is faces\n n = var{1};\n if length(var)>1\n e = var{2};\n end\n if length(var)>2\n f = var{3};\n end\n varargin(1) = [];\nelseif isstruct(var)\n % graph is stored as a structure, with fields 'nodes', 'edges', and\n % eventually 'faces'.\n n = var.nodes;\n e = var.edges;\n if isfield(var, 'faces')\n f = var.faces;\n end\n varargin(1) = [];\nelse\n % graph is stored as set of variables: nodes, edges, and eventually\n % faces\n n = varargin{1};\n e = varargin{2};\n varargin(1:2) = [];\n \n if ~isempty(varargin)\n var = varargin{1};\n if isnumeric(var)\n % faces are stored in a numeric array of indices\n f = var;\n varargin(1) = [];\n elseif iscell(var)\n if ~ischar(var{1})\n % faces are stored in a cell array, each cell containing a\n % row vector of indices\n f = var;\n varargin(1) = [];\n end\n end\n end\nend\n\n% extract drawing style \n\nif ~isempty(varargin)\n sn = concatArguments(sn, varargin{1});\nend\n\nif length(varargin)>1\n se = concatArguments(se, varargin{2});\nend\n\nif length(varargin)>2\n sf = concatArguments(sf, varargin{3});\nend\n\n\n\n%% Main drawing processing\n\nhold on;\n\nif size(n, 2) == 2\n % Draw a 2 dimensional graph ----------------------\n\n % Draw faces of the graph ------------\n if ~strcmp(sf{1}, 'none') && ~isempty(f)\n if iscell(f)\n % each face is contained in a cell.\n hf = zeros(size(f));\n for fi = 1:length(f)\n hf(fi) = patch('Faces', f{fi}, 'Vertices', n, sf{:}); \n end\n else\n % process faces as an Nf*N array. Nf is the number of faces,\n % and all faces have the same number of vertices (nodes).\n hf = patch('Faces', f, 'Vertices', n, sf{:}); \n end\n end\n \n % Draw 2D Edges ----------------------\n if ~strcmp(se{1}, 'none') && size(e, 1) > 0\n he = plot([n(e(:,1),1) n(e(:,2),1)]', [n(e(:,1),2) n(e(:,2),2)]', se{:});\n end\n\n % Draw 2D nodes ----------------------\n if ~strcmp(sn{1}, 'none')\n hn = plot(n(:,1), n(:,2), sn{:});\n end\n \n \nelseif size(n, 2)==3\n % Draw a 3 dimensional graph ----------------------\n\n % use a zbuffer to avoid display pbms.\n set(gcf, 'renderer', 'zbuffer');\n\n % Draw 3D Faces ----------------------\n if ~strcmp(sf{1}, 'none')\n if iscell(f)\n % each face is contained in a cell.\n hf = zeros(size(f));\n for fi = 1:length(f)\n hf(fi) = patch('Faces', f{fi}, 'Vertices', n, sf{:}); \n end\n else\n % process faces as an Nf*N array. Nf i the number of faces,\n % and all faces have the same number of vertices (nodes).\n hf = patch('Faces', f, 'Vertices', n, sf{:}); \n end\n end\n \n % Draw 3D edges ----------------------\n if ~strcmp(se{1}, 'none') && size(e, 1) > 0\n he = line(...\n [n(e(:,1),1) n(e(:,2),1)]', ...\n [n(e(:,1),2) n(e(:,2),2)]', ...\n [n(e(:,1),3) n(e(:,2),3)]', ...\n se{:});\n end\n \n % Draw 3D nodes ----------------------\n if ~strcmp(sn{1}, 'none')\n hn = plot3(n(:,1), n(:,2), n(:,3), sn{:});\n end\n \nend\n\n\n%% Format output arguments\n\n% return handle to edges\nif nargout==1\n varargout{1} = he;\nend\n\n% return handle to nodes and edges\nif nargout==2\n varargout{1} = hn;\n varargout{2} = he;\nend\n\n% return handle to nodes, edges and faces\nif nargout==3\n varargout{1} = hn;\n varargout{2} = he;\n varargout{3} = hf;\nend\n\n\n\nend\n\nfunction res = concatArguments(in1, in2)\n% in1 is a cell array already initialized\n% in2 is an argument that can be:\n% - empty\n% - the string 'none'\n% - another cell array\n\nif isempty(in2)\n res = in1;\n return;\nend\n\nif ischar(in2)\n if strcmp('none', in2)\n res = {'none'};\n return;\n end\nend\n\nif iscell(in1)\n res = [in1(:)' in2(:)'];\nelse\n res = [{in1} in2(:)];\nend\n\nend", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/matGeom/graphs/drawGraph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105587468141, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.49451183985358826}} {"text": "function F = conj(F)\n%CONJ Complex conjugate of a CHEBFUN.\n% CONJ(F) is the complex conjugate of F.\n%\n% See also REAL, IMAG.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Loop over the columns of F:\nfor j = 1:numel(F)\n \n % Conjugate the point values:\n F(j).pointValues = conj(F(j).pointValues);\n \n % Conjugate the FUNs:\n for k = 1:numel(F(j).funs)\n F(j).funs{k} = conj(F(j).funs{k});\n end \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/conj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.4945118398535881}} {"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": "%% Load data\nclear all; close all; clc;\n\nnst_on = load('msckf_NST_on.mat');\nnst_off = load('msckf_NST_off.mat');\n\nkStart = 500; kEnd = 1000;\n\n%% Compute RMSE\nnst_off_trans_rmse = sqrt(mean(nst_off.msckf_trans_err.^2,1));\nnst_off_rot_rmse = sqrt(mean(nst_off.msckf_rot_err.^2,1));\n\nnst_on_trans_rmse = sqrt(mean(nst_on.msckf_trans_err.^2,1));\nnst_on_rot_rmse = sqrt(mean(nst_on.msckf_rot_err.^2,1));\n\n%% Plot stuff\nfigure(1); clf;\nfontSize = 14;\nlineWidth = 2;\npos = [200,200,640,400];\nxLim = [kStart, kEnd];\nk = kStart:kEnd;\nxticks = linspace(kStart,kEnd,11);\n\ntransLim = [0 0.6];\nrotLim = [0 0.25];\n\nset(gcf,'Position',pos);\n\n% Translational RMSE\nsubplot(2,1,1);\nplot(k,nst_off_trans_rmse, '-r','LineWidth',lineWidth); hold on;\nplot(k,nst_on_trans_rmse, '-b','LineWidth',lineWidth);\nxlim(xLim);\nset(gca,'XTick',xticks);\n% ylim(transLim)\nlegend('Noise Correlated to State', 'Noise De-correlated from State', ...\n 'Location','northwest');\nylabel('Trans. RMSE (m)')\ntitle('Effect of Nullspace Projection');\nset(gca,'FontSize',fontSize);\ngrid minor;\nbox on;\n\n% Rotational RMSE\nsubplot(2,1,2);\nplot(k,nst_off_rot_rmse,'-r','LineWidth',lineWidth); hold on;\nplot(k,nst_on_rot_rmse,'-b','LineWidth',lineWidth);\nxlim(xLim);\nset(gca,'XTick',xticks);\n% ylim(rotLim)\nlegend('Noise Correlated to State', 'Noise De-correlated from State', ...\n 'Location','northwest');\nylabel('Rot. RMSE (Axis-Angle)')\nxlabel('Timestep')\nset(gca,'FontSize',fontSize)\ngrid minor;\nbox on;\n\n%% Export figure\nexport_fig(gcf, 'NST_RMSE.pdf', '-transparent');", "meta": {"author": "yuzhou42", "repo": "MSCKF", "sha": "d95d90c85b24f27001bd0ecdce8739b6e602b6df", "save_path": "github-repos/MATLAB/yuzhou42-MSCKF", "path": "github-repos/MATLAB/yuzhou42-MSCKF/MSCKF-d95d90c85b24f27001bd0ecdce8739b6e602b6df/plotting/nullspace_RMSE_plots.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914997895581, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.49438986316620326}} {"text": "% Fast convolution, replacement for both conv2 and convn.\n%\n% See conv2 or convn for more information on convolution in general.\n%\n% This works as a replacement for both conv2 and convn. Basically,\n% performs convolution in either the frequency or spatial domain, depending\n% on which it thinks will be faster (see below). In general, if A is much\n% bigger then B then spatial convolution will be faster, but if B is of\n% similar size to A and both are fairly big (such as in the case of\n% correlation), convolution as multiplication in the frequency domain will\n% tend to be faster.\n%\n% The shape flag can take on 1 additional value which is 'smooth'. This\n% flag is intended for use with smoothing kernels. The returned matrix C\n% is the same size as A with boundary effects handled in a special manner.\n% That is instead of A being zero padded before being convolved with B;\n% near the boundaries a cropped version of the matrix B is used, and the\n% results is scaled by the fraction of the weight found in the cropped\n% version of B. In this case each dimension of B must be odd, and all\n% elements of B must be positive. There are other restrictions on when\n% this flag can be used, and in general it is only useful for smoothing\n% kernels. For 2D filtering it does not have much overhead, for 3D it has\n% more and for higher dimensions much much more.\n%\n% For optimal performance some timing constants must be set to choose\n% between doing convolution in the spatial and frequency domains, for more\n% info see timeConv below.\n%\n% USAGE\n% C = convnFast( A, B, [shape] )\n%\n% INPUTS\n% A - d dimensional input matrix\n% B - d dimensional matrix to convolve with A\n% shape - ['full'] 'valid', 'full', 'same', or 'smooth'\n%\n% OUTPUTS\n% C - result of convolution\n%\n% EXAMPLE\n%\n% See also CONV2, CONVN\n\n% Piotr's Image&Video Toolbox Version 2.0\n% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu\n% Please email me if you find bugs, or have suggestions or questions!\n\nfunction C = convnFast( A, B, shape )\n\nif( nargin<3 || isempty(shape)); shape='full'; end\nif(isempty(strmatch(shape, char({'same', 'valid', 'full', 'smooth'}))))\n error( 'convnFast: unknown shape flag' ); end\n\nshapeorig = shape;\nsmoothFlag = (strcmp(shape,'smooth'));\nif( smoothFlag ); shape = 'same'; end;\n\n% get dimensions of A and B\nndA = ndims(A); ndB = ndims(B); nd = max(ndA,ndB);\nsizA = size(A); sizB = size(B);\nif (ndA>ndB); sizB = [sizB ones(1,ndA-ndB)]; end\nif (ndA0 ) )\n error('If flag==''smooth'' then mask must have >0 values.');\n end;\n if( any( (sizB-1)/2>sizA ) )\n error('B is more then twice as big as A, cannot use flag==''smooth''');\n end;\nend\n\n% OPTIMIZATION for 3D conv when B is actually 2D - calls (spatial) conv2\n% repeatedly on 2D slices of A. Note that may need to rearange A and B\n% first and use recursion. The benefits carry over to convnBound\n% (which is faster for 2D arrays).\nif( ndA==3 && ndB==3 && (sizB(1)==1 || sizB(2)==1) )\n if (sizB(1)==1)\n A = permute( A, [2 3 1]); B = permute( B, [2 3 1]);\n C = convnFast( A, B, shapeorig );\n C = permute( C, [3 1 2] );\n elseif (sizB(2)==1)\n A = permute( A, [3 1 2]); B = permute( B, [3 1 2]);\n C = convnFast( A, B, shapeorig );\n C = permute( C, [2 3 1] );\n end\n return;\nelseif( ndA==3 && ndB==2 )\n C1 = conv2( A(:,:,1), B, shape );\n C = zeros( [size(C1), sizA(3)] ); C(:,:,1) = C1;\n for i=2:sizA(3); C(:,:,i) = conv2( A(:,:,i), B, shape ); end\n if (smoothFlag)\n for i=1:sizA(3)\n C(:,:,i) = convnBound(A(:,:,i),B,C(:,:,i),sizA(1:2),sizB(1:2));\n end\n end\n return;\nend\n\n% get predicted time of convolution in frequency and spatial domain\n% constants taken from timeConv\nsizfft = 2.^ceil(real(log2(sizA+sizB-1))); psizfft=prod(sizfft);\nfrequenPt = 3 * 1e-7 * psizfft * log(psizfft);\nif (nd==2)\n spatialPt = 5e-9 * sizA(1) * sizA(2) * sizB(1) * sizB(2);\nelse\n spatialPt = 5e-8 * prod(sizA) * prod(sizB);\nend\n\n% perform convolution\nif ( spatialPt < frequenPt )\n if (nd==2)\n C = conv2( A, B, shape );\n else\n C = convn( A, B, shape );\n end\nelse\n C = convnFreq( A, B, sizA, sizB, shape );\nend;\n\n\n% now correct boundary effects (if shape=='smooth')\nif( ~smoothFlag ); return; end;\nC = convnBound( A, B, C, sizA, sizB );\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% calculate boundary values for C in spatial domain\nfunction C = convnBound( A, B, C, sizA, sizB )\nnd = length(sizA);\nradii = (sizB-1)/2;\n\n% flip B appropriately (conv flips B)\nfor d=1:nd; B = flipdim(B,d); end\n\n% get location that need to be updated\n% this is the LEAST efficient part (fixing is annoying though)\ninds = {':'}; inds = inds(:,ones(1,nd));\nDind = zeros( sizA );\nfor d=1:nd\n inds1 = inds; inds1{ d } = 1:radii(d);\n inds2 = inds; inds2{ d } = sizA(d)-radii(d)+1:sizA(d);\n Dind(inds1{:}) = 1; Dind(inds2{:}) = 1;\nend\nDind = find( Dind );\nDndx = ind2sub2( sizA, Dind );\nnlocs = length(Dind);\n\n% get cuboid dimensions for all the boundary regions\nsizeArep = repmat( sizA, [nlocs,1] );\nradiiRep = repmat( radii, [nlocs,1] );\nAstarts = max(1,Dndx-radiiRep);\nAends = min( sizeArep, Dndx+radiiRep);\nBstarts = Astarts + (1-Dndx+radiiRep);\nBends = Bstarts + (Aends-Astarts);\n\n% now update these locations\nvs = zeros( 1, nlocs );\nif( nd==2 )\n for i=1:nlocs % accelerated for 2D arrays [fast]\n Apart = A( Astarts(i,1):Aends(i,1), Astarts(i,2):Aends(i,2) );\n Bpart = B( Bstarts(i,1):Bends(i,1), Bstarts(i,2):Bends(i,2) );\n v = (Apart.*Bpart); vs(i) = sum(v(:)) ./ sum(Bpart(:));\n end\nelseif( nd==3 ) % accelerated for 3D arrays\n for i=1:nlocs\n Apart = A( Astarts(i,1):Aends(i,1), Astarts(i,2):Aends(i,2), ...\n Astarts(i,3):Aends(i,3) );\n Bpart = B( Bstarts(i,1):Bends(i,1), Bstarts(i,2):Bends(i,2), ...\n Bstarts(i,3):Bends(i,3) );\n za = sum(sum(sum(Apart.*Bpart))); zb=sum(sum(sum(Bpart)));\n vs(1,i) = za./zb;\n end\nelse % general case [slow]\n extract=cell(1,nd);\n for i=1:nlocs\n for d=1:nd; extract{d} = Astarts(i,d):Aends(i,d); end\n Apart = A( extract{:} );\n for d=1:nd; extract{d} = Bstarts(i,d):Bends(i,d); end\n Bpart = B( extract{:} );\n v = (Apart.*Bpart); vs(i) = sum(v(:)) ./ sum(Bpart(:));\n end\nend\nC( Dind ) = vs * sum(B(:));\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Convolution as multiplication in the frequency domain\nfunction C = convnFreq( A, B, sizA, sizB, shape )\nsiz = sizA + sizB - 1;\n\n% calculate correlation in frequency domain\nFa = fftn(A,siz);\nFb = fftn(B,siz);\nC = ifftn(Fa .* Fb);\n\n% make sure output is real if inputs were both real\nif(isreal(A) && isreal(B)); C = real(C); end\n\n% crop to size\nif(strcmp(shape,'valid'))\n C = arrayToDims( C, max(0,sizA-sizB+1 ) );\nelseif(strcmp(shape,'same'))\n C = arrayToDims( C, sizA );\nelseif(~strcmp(shape,'full'))\n error('unknown shape');\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Function used to calculate constants for prediction of convolution in the\n% frequency and spatial domains. Method taken from normxcorr2.m\n% May need to reset K's if placing this on a new machine, however, their\n% ratio should be about the same..\nfunction K = timeConv() %#ok\nmintime = 4;\n\nswitch 3\n case 1 % conv2 [[empirically K = 5e-9]]\n % convolution time = K*prod(size(a))*prod(size(b))\n siza = 30; sizb = 200;\n a = ones(siza); b = ones(sizb);\n t1 = cputime; t2 = t1; k = 0;\n while (t2-t1)\n end\n K = (t2-t1)/k/siza^2/sizb^2;\n\n case 2 % convn [[empirically K = 5e-8]]\n % convolution time = K*prod(size(a))*prod(size(b))\n siza = [10 10 10]; sizb = [30 30 10];\n a = ones(siza); b = ones(sizb);\n t1 = cputime; t2 = t1; k = 0;\n while (t2-t1)\n end\n K = (t2-t1)/k/prod(siza)/prod(sizb);\n\n case 3 % fft (one dimensional) [[empirically K = 1e-7]]\n % fft time = K * n log(n) [if n is power of 2]\n % Works fastest for powers of 2. (so always zero pad until have\n % size of power of 2?). 2 dimensional fft has to apply single\n % dimensional fft to each column, and then signle dimensional fft\n % to each resulting row. time = K * (mn)log(mn). Likewise for\n % highter dimensions. convnFreq requires 3 such ffts.\n n = 2^nextpow2(2^15);\n vec = complex(rand(n,1),rand(n,1));\n t1 = cputime; t2 = t1; k = 0;\n while (t2-t1) < mintime;\n disc = fft(vec); k = k + 1; t2 = cputime; %#ok\n end\n K = (t2-t1) / k / n / log(n);\nend\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/spaceTime/adamMice/pdollarOF/convnFast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.494389855944055}} {"text": "function hbg = bgCircleGraph(bg,NodeSizes,varargin)\n% (optional) NodeSizes should be an array specifying the radius of each node\n% as a fraction (0 to 1) of the radius of the circlegraph\n\nif nargin<2 \n NodeSizes = [];\nelseif numel(NodeSizes)==1\n NodeSizes = NodeSizes*ones(1,length(bg.Nodes));\nend\n\n% I create a random graph with 28 nodes:\n% bg = biograph(28);\n\n% Display it in the GUI and get a handle \n% back to work with it (this will use by default \n% the hierarchical layout):\nhbg = view(bg);\n% Get an idea of what are the actual extents of \n% the page in the GUI by looking at all the current \n% node positions:\npage_Size = max(cell2mat(arrayfun(@(x) get(x,'Position'),...\n get(hbg,'Nodes'),'Uniform',false)));\n% Place the nodes in a circular layout, in my graph \n% page_size was around [1000,1000], so I will select a \n% center at [500 500] and a radius of 300, this will keep \n% the layout approximately in the same scale and I will \n% not have to manually change the size of the nodes or \n% the fonts:\nradius = 0.6*(min(page_Size)/2);\ncenter = [page_Size(1)/2 page_Size(2)/2];\nnumNodes = length(hbg.Nodes);\nfor i = 1:numNodes\nset(hbg.Nodes(i),'Position',...\n [center(1)+radius.*sin((i*2*pi/numNodes)),...\n center(2)+radius.*cos((i*2*pi/numNodes))],'shape','circle')\n\n if ~isempty(NodeSizes)\n sz = 2*radius*NodeSizes(i);\n set(hbg.Nodes(i),'Size',[sz sz]);\n end\nend\n\n% Now I can use dolayout:\nset(bg,'NodeAutoSize','off','EdgeType','curved',varargin{:});\ndolayout(hbg,'pathsOnly',true)", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/utils/bgCircleGraph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.49438984577451667}} {"text": "function test_suite = test_medianLine\n%TESTMEDIANLINE One-line description here, please.\n% output = testMedianLine(input)\n%\n% Example\n% testMedianLine\n%\n% See also\n%\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2009-04-22, using Matlab 7.7.0.471 (R2008b)\n% Copyright 2009 INRA - Cepia Software Platform.\n% Licensed under the terms of the LGPL, see the file \"license.txt\"\n\ntest_suite = functiontests(localfunctions); \n\nfunction testTwoPoints(testCase) %#ok<*DEFNU>\n% test with 2 points\n\np1 = [0 0];\np2 = [10 0];\nexp = [5 0 0 10];\nline = medianLine(p1, p2);\ntestCase.assertEqual(exp, line, 'AbsTol', .01);\n\nfunction testEdge(testCase) \n% test with an edge as input\n\np1 = [0 0];\np2 = [10 0];\nexp = [5 0 0 10];\nline = medianLine([p1 p2]);\ntestCase.assertEqual(exp, line, 'AbsTol', .01);\n\nfunction testTwoPointArrays(testCase) %#ok<*DEFNU>\n% test with 2 points\n\np1 = [0 0; 10 10];\np2 = [10 0;10 20];\n\nexp = [5 0 0 10; 10 15 -10 0];\n\nline = medianLine(p1, p2);\ntestCase.assertEqual(exp, line, 'AbsTol', .01);\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/tests/geom2d/test_medianLine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.4943898421634425}} {"text": "function sR=icassoCluster(sR,varargin)\n%function sR=icassoCluster(sR,['identifier1',value1,'identifier2',value2,...])\n%\n%PURPOSE \n%\n%To cluster the ICA estimates and to compute a relative clustering validity\n%index (R-index)\n%\n%EXAMPLE OF BASIC USAGE\n%\n% sR=icassoCluster(sR); \n% \n%where sR is an Icasso result structure. This applies hierarchical\n%clustering using group-average linkage agglomeration strategy and\n%stores the results back into workspace variable sR.\n%\n%INPUT \n%\n% sR (struct) Icasso result data structure\n%\n%Optional input arguments are given as argument identifier - value\n%pairs: 'identifier1', value1, 'identifier2', value2,... \n%(case insensitive)\n%\n% 'simfcn' (string) 'abscorr' (default) | (matrix) \n% Indicates how to compute similarities S between estimates i,j\n% 'abscorr' S(i,j) is the absolute value of the linear\n% correlation coefficient \n% (matrix) explicitly given similarity matrix S\n% (elements should be 0...1) \n% 'strategy' (string) 'AL' (default) | 'SL' | 'CL' \n% Sets the clustering strategy: \n% 'AL' hierarchical group average linkage\n% 'SL' hierarchical single linkage (nearest neighbor)\n% 'CL' hierarchical complete linkage (furthest neighbor)\n% 'L' (integer) | (string) 'rdim' (default) \n% computes a relative clustering validity index for 2...L\n% clusters. Default string 'rdim' sets L same as the (reduced)\n% data dimension \n%'s2d' (string) (default is 'sim2dis') \n% the name of function that is used to make the transformation\n% from similarities between IC components to dissimilarities\n% D. Default 'sim2dis' makes simply D=1-S; \n%\n%OUTPUT\n%\n% sR (struct) updated Icasso result data structure \n%\n%The function updates the fields sR.cluster.* only.\n%\n%DETAILS\n%1. The function computes similarities between the\n%estimates. See Note 1 \n%2. stores the similarity matrix S into field sR.cluster.similarity\n%and the method into field sR.cluster.simfcn\n%2. transforms the similarities into dissimilarities (distances)\n%D. See Note 2. \n%3. applies the selected clustering strategy on dissimilarities. D\n%The results is a partition matrix P (of size MxM). See explanation\n%in function hcluster The function stores P in field\n%sR.cluster.partition (Stores also other outputs of function\n%hcluster into sR.cluster.dendrogram). \n%4. computes a relative clustering validity index (see function\n%rindex) for dissimilarities D and partitions P from 2 to L\n%clusters. If not explicitly given (or string 'rdim' is given, L\n%will be the (reduced data) dimension. Stores the result in field\n%sR.cluster.index.R. \n%\n%NOTE 1\n%\n%By default, the similarities between estimates are computed as\n%linear correlation coefficients (using the demixing matrix rows and\n%dewhitening matrix; see function corrw). You can also explicitly\n%give any MxM similarity matrix as input. The similarities\n%should be between 0...1. (M is the total number of estimates.)\n%\n%NOTE 2\n%The clustering and clustering validity indices are computed for\n%dissimilarities. Therefore, the similarities must be transformed\n%into dissimilarities. By default, icassoCluster uses subfunction\n%sim2dis to do this; sim2dis performs simply D=1-S. If you wish to\n%make the transformation otherwise, you can set a different\n%function by using input identifier - valuepair\n%'s2d','myfunctionname'. icassoCluster then computes\n%dissimilarities by calling \n% D=feval('myfunctionname',sR.cluster.similarity); \n%A possible function is sqrtsim2dis \n%\n%SEE ALSO\n% hcluster\n% som_linkage\n% sqrtsim2dis\n% rindex\n% icassoDendrogram\n\n%COPYRIGHT NOTICE\n%This function is a part of Icasso software library\n%Copyright (C) 2003-2005 Johan Himberg\n%\n%This program is free software; you can redistribute it and/or\n%modify it under the terms of the GNU General Public License\n%as published by the Free Software Foundation; either version 2\n%of the License, or 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% ver 1.21 070305 johan\n\n% Init some variables\n\n% total number of estimates\nM=icassoGet(sR,'M');\n\n%reduced data dimension\nrdim=icassoGet(sR,'rdim');\n\n% Set default parameters\ndefault={'simfcn','abscorr','s2d','sim2dis','strategy','AL','L','rdim'};\n\n%% Check optional arguments and add defaults\nclusterparameters=processvarargin(varargin,default);\nnum_of_args=length(clusterparameters);\n\n%% check arguments\nfor i=1:2:num_of_args;\n switch lower(clusterparameters{i})\n \n case 'simfcn'\n simfcn=clusterparameters{i+1};\n \n % Explicit similarity matrix?\n if isnumeric(simfcn),\n if size(simfcn,1)==M & size(simfcn,2)==M,\n sR.cluster.similarity=simfcn;\n sR.cluster.simfcn='';\n else \n error('Explicitly given similarity matrix has wrong size!');\n end\n else\n % should be a string\n switch lower(simfcn)\n case 'abscorr'\n % ok\n sR.cluster.simfcn=lower(simfcn);\n otherwise\n error('''simfcn'' must be string ''abscorr'' or an MxM similarity matrix');\n end\n end\n case 's2d'\n s2dfcn=lower(clusterparameters{i+1});\n if ~ischar(s2dfcn),\n error('''s2d'' must be a string (name of a function)');\n end\n sR.cluster.s2d=s2dfcn;\n case 'l'\n L=clusterparameters{i+1};\n if isnumeric(L),\n % The user has specified max number for clusters\n \n % Check L \n if fix(L)~=L,\n error('''L'' must be an integer.');\n elseif L<2,\n error('''L'' must be at least 2.');\n elseif L>M,\n error('''L'' cannot be more than the number of estimates.');\n end\n else\n if ~strcmp(lower(L),'rdim'),\n error('''L'' expects an integer value or ''rdim''.');\n end\n % set (reduced) data dimension\n L=icassoGet(sR,'rdim');\n end\n \n if L>100,\n warning(['R-index requested for more that 100 clusters: this can' ...\n ' be heavy...']);\n end\n \n case 'strategy'\n strategy=clusterparameters{i+1};\n if ~ischar(strategy),\n error('''strategy'' must be a string');\n end\n \n % we are case insensitive\n strategy=upper(strategy);\n sR.cluster.strategy=strategy;\n \n switch sR.cluster.strategy\n case {'AL','CL','SL'}\n ; % hierarchical clustering\n otherwise\n error(['Strategy ' strategy ' not implemented.']);\n end\n otherwise\n error(['Indentifier ' clusterparameters{i} ' not recognized.']);\n end\nend\n\n%%%% Compute similarities %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nswitch lower(sR.cluster.simfcn)\n case ''\n % already handled\n case 'abscorr'\n sR.cluster.similarity=abs(corrw(icassoGet(sR,'W'),icassoGet(sR,'dewhitemat')));\n %just to make sure \n sR.cluster.similarity(sR.cluster.similarity>1)=1; \n sR.cluster.similarity(sR.cluster.similarity<0)=0;\nend\n\n%%%%% Convert to dissimilarities using .s2d\n\nD=feval(sR.cluster.s2d, sR.cluster.similarity);\n\n%%%% Make partition %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[sR.cluster.partition,sR.cluster.dendrogram.Z,sR.cluster.dendrogram.order]=...\n hcluster(D,sR.cluster.strategy);\n\n%%%%% Compute cluster validity %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% init R\nsR.cluster.index.R=ones(M,1)*NaN;\n% compute\n\nsR.cluster.index.R(1:L,1)=rindex(D,sR.cluster.partition(1:L,:)); \n\n\n \n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/icasso/icassoCluster.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.49438982838282997}} {"text": "% ------------------------------------------------------------------------\nfunction stats = vid_image_stats(imdb_video, perc_training, base_path)\n%VID_IMAGE_STATS\n%\tCompute basic colour stats for a random PERC_TRAINING of the dataset\n%\tUsed for data augmentation during training.\n% \te.g. vid_image_stats(imdb_video, 0.1, /path/to/curated/ILSVRC15/')\n% ------------------------------------------------------------------------\n % collect different stats for z and x crops (x contains more padding)\n z_sz = 127;\n x_sz = 255;\n samples_per_video = 16;\n imout_z = zeros(z_sz, z_sz, 3, samples_per_video, 'single');\n imout_x = zeros(x_sz, x_sz, 3, samples_per_video, 'single');\n crops_z_string = cell(1, samples_per_video);\n crops_x_string = cell(1, samples_per_video);\n n_video = numel(imdb_video.id);\n n_video_train = round(perc_training * n_video);\n avg_z = cell(1,n_video_train);\n rgbm1_z = cell(1,n_video_train);\n rgbm2_z = cell(1,n_video_train);\n n_z = samples_per_video*z_sz*z_sz;\n avg_x = cell(1,n_video_train);\n rgbm1_x = cell(1,n_video_train);\n rgbm2_x = cell(1,n_video_train);\n n_x = samples_per_video*x_sz*x_sz;\n for v=1:n_video_train\n n_obj = numel(imdb_video.objects{v});\n rand_objs = datasample(1:n_obj, samples_per_video);\n for o=1:samples_per_video\n crops_z_string{o} = [base_path strrep(imdb_video.objects{v}{rand_objs(o)}.frame_path, '.JPEG','') '.' num2str(imdb_video.objects{v}{rand_objs(o)}.track_id, '%02d') '.crop.z.jpg'];\n crops_x_string{o} = [base_path strrep(imdb_video.objects{v}{rand_objs(o)}.frame_path, '.JPEG','') '.' num2str(imdb_video.objects{v}{rand_objs(o)}.track_id, '%02d') '.crop.x.jpg'];\n end\n files = [crops_z_string crops_x_string];\n imgs = vl_imreadjpeg(files, 'numThreads', 12);\n crops_z = imgs(1:samples_per_video);\n crops_x = imgs(samples_per_video+1 : end);\n for o=1:samples_per_video\n imout_z(:,:,:,o) = crops_z{o};\n imout_x(:,:,:,o) = crops_x{o};\n end\n\n Z = reshape(permute(imout_z,[3 1 2 4]),3,[]);\n avg_z{end+1} = mean(imout_z, 4);\n rgbm1_z{end+1} = sum(Z,2)/n_z;\n rgbm2_z{end+1} = Z*Z'/n_z;\n\n X = reshape(permute(imout_x,[3 1 2 4]),3,[]);\n avg_x{end+1} = mean(imout_x, 4);\n rgbm1_x{end+1} = sum(X,2)/n_x;\n rgbm2_x{end+1} = X*X'/n_x;\n fprintf('Processed video %d/%d\\n', v, n_video_train);\n end\n\n stats = struct();\n stats.z = struct();\n stats.x = struct();\n\n stats.z.averageImage = mean(cat(4,avg_z{:}),4);\n rgbm1_z = mean(cat(2,rgbm1_z{:}),2);\n stats.z.rgbm1 = rgbm1_z;\n rgbm2_z = mean(cat(3,rgbm2_z{:}),3);\n stats.z.rgbm2 = rgbm2_z;\n stats.z.rgbMean = rgbm1_z;\n stats.z.rgbCovariance = rgbm2_z - rgbm1_z*rgbm1_z';\n\n stats.x.averageImage = mean(cat(4,avg_x{:}),4);\n rgbm1_x = mean(cat(2,rgbm1_x{:}),2);\n stats.x.rgbm1 = rgbm1_x;\n rgbm2_x = mean(cat(3,rgbm2_x{:}),3);\n stats.z.rgbm2 = rgbm2_z;\n stats.x.rgbMean = rgbm1_x;\n stats.x.rgbCovariance = rgbm2_x - rgbm1_x*rgbm1_x';\nend\n", "meta": {"author": "bertinetto", "repo": "siamese-fc", "sha": "e86eb64d6f146b51135232c1d46a29f64c63678a", "save_path": "github-repos/MATLAB/bertinetto-siamese-fc", "path": "github-repos/MATLAB/bertinetto-siamese-fc/siamese-fc-e86eb64d6f146b51135232c1d46a29f64c63678a/ILSVRC15-curation/vid_image_stats.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 [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 [Wout,Phiout,Phioutbis]=dualwavelets(W,Phi,LP)\n\t%for jr=1:Jres\n\t%filters.psi=W;\n\t%filters.phi=Phi;\n\t%LP=littlewood_paley_ISCV(filters);\n\tJ=size(W,2);\n\tL=size(W{end},2);\n\teps=1e-12;\n\ttight=0;\n\n\tWout = W;\n\tPhiout = Phi;\n\n\tfor j=1:J\n\t\tif ~isempty(W{j})\n\t\t\tfor l=1:L\n\t\t\t\tif tight\n\t\t\t\t\t% if frame is tight, LP = 1 for all omega, so we only need to conjugate\n\t\t\t\t\tWout{j}{l}=conj(W{j}{l});\n\t\t\t\telse\n\t\t\t\t\t% if frame is not tight, we need to divide by LP so that\n\t\t\t\t\t% sum W_j*Wd_j = sum W_j*conj(W_j)/LP = LP/LP = 1\n\t\t\t\t\t% but this can be dangerous is LP becomes very small, so only\n\t\t\t\t\t% do this on the support of W_j\n\t\t\t\t\tsupp=(abs(W{j}{l})>eps);\n\t\t\t\t\tWout{j}{l} = supp.*(conj(W{j}{l})./(LP));\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\n\teps = 2e-2;\n\tsupp=(abs(Phi)>eps);\n\tPhiout=supp.*((Phi)./(LP));\n\tif tight\n\t\tPhiout=Phi;\n\t\tPhioutbis=supp.*min(8,1./Phi);\n\t\tIc=find(supp==0);\n\t\tPhioutbis(Ic)=0;\n\tend\nend\n\n\n", "meta": {"author": "scatnet", "repo": "scatnet", "sha": "59d935afa20359845282a3518134e24244862c1f", "save_path": "github-repos/MATLAB/scatnet-scatnet", "path": "github-repos/MATLAB/scatnet-scatnet/scatnet-59d935afa20359845282a3518134e24244862c1f/papers/ISCV/dualwavelets.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.6334102705979902, "lm_q1q2_score": 0.49405552049323465}} {"text": "function linplus_test445 ( )\n\n%*****************************************************************************80\n%\n%% TEST445 tests R8PBL_INDICATOR.\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 n = 9;\n mu = 3;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST445\\n' );\n fprintf ( 1, ' R8PBL_INDICATOR sets up a R8PBL indicator matrix.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Matrix order N = %d\\n', n );\n fprintf ( 1, ' Bandwidth MU = %d\\n', mu );\n\n a = r8pbl_indicator ( n, mu );\n\n r8pbl_print ( n, mu, a, ' The R8PBL indicator matrix:' );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linplus/linplus_test445.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.49403773901980746}} {"text": "function H = mrdivide(F, G)\n%/ SPHEREFUNV right divide.\n% F/G divides each component of the SPHEREFUNV F by the DOUBLE or \n% SPHEREFUN G.\n% \n% Only allowed to divide by a DOUBLE or a SPHEREFUN.\n% \n% See also SPHEREFUNV/MLDIVIDE.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nif ( isempty(F) || isempty(G) )\n H = spherefunv;\n return \nend\n\nif ( ~isa(G,'double') && ~isa(G,'chebfun2') )\n error('SPHEREFUN:SPHEREFUNV:mrdivide:nonScalar', ...\n 'Division must be scalar valued.');\nend\n\n\n% componentwise divide. \nif ( isa(G,'double') )\n H = F; \n for j = 1:3\n H.components{j} = mrdivide(F.components{j}, G);\n end\nelse\n H = F;\n for j = 1:3\n H.components{j} = rdivide(F.components{j}, G);\n end\nend\n \nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@spherefunv/mrdivide.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672320414786, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.49403773887986185}} {"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": "% plots prior and, if information is available, posterior densities\n% \n% ::\n% \n% [h,legend_]=prior_posterior(ss,varargin)\n% \n% Args:\n% \n% - **ss** [struct]: structure containing the relevant information to plot\n% and more specifically\n% \n% - **x_kdens** [vector]: x-axis values for the posterior density\n% - **f_kdens** [vector]: y-axis values for the posterior density\n% - **x_prior** [vector]: x-axis values for the prior density\n% - **f_prior** [vector]: y-axis values for the prior density\n% - **mean_sim** [scalar]: mean of the posterior simulation\n% - **post_mode** [scalar]: value at the posterior maximization mode\n% - **post_mode_sim** [scalar]: value at the posterior simulation mode\n% - **tex_name** [char]: name of the parameter\n% \n% - **varargin** [pairwise arguments]: standard plotting arguments for\n% matlab\n% \n% Returns:\n% :\n% \n% - **h** [handle]: handle for the plot\n% - **legend_** [cellstr]: names of the lines in the plot\n% - **tex_name** [char]: name of the parameter\n% \n% Note:\n% \n% - Only the prior density is plotted if no posterior information is\n% available.\n% \n%", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/m/+utils/+plot/prior_posterior.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.49402351348319057}} {"text": "function [yhat prdt_per_tree] = classRFPredict( x, rf )\n [nsample ndim] = size(x);\n ntree = rf.ntree;\n prdt_per_tree = zeros(nsample, ntree);\n \n ntree = rf.ntree;\n \n for ix = 1 : nsample\n for n = 1 : ntree\n k = 1;\n while rf.nodestatus{n}(k) ~= -1\n if x(ix, rf.bestvar{n}(k)) <= rf.bestsplit{n}(k)\n k = rf.treemap{n}(k, 1);\n else\n k = rf.treemap{n}(k, 2);\n end\n end\n prdt_per_tree(ix, n) = rf.nodeclass{n}(k);\n % fprintf( 'ix: %d, n: %d\\n', ix, n );\n end\n end\n \n yhat = zeros(nsample, 1);\n for ix = 1 : nsample\n % for n = 1 : ntree\n % when there are equal votes for the classes, it favors the\n % first class\n yhat(ix) = mode( prdt_per_tree(ix, :) );\n % end\n end\n \n for ix = 1 : length(rf.new_labels)\n yhat( yhat == rf.new_labels(ix) ) = rf.orig_labels(ix);\n end\nend", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u68c0\u6d4b\u7b97\u6cd5/drfi_matlab-master/randomforest-matlab/RF_Class_C/MATLAB/classRFPredict.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.49402351033764863}} {"text": "%% DEMO_additional_colormaps\n% Below is a demonstration for:\n%\n% * Additional colormaps available in GIBBON\n\n%%\nclear; close all; clc;\n\n%%\n%Plot settings\nfontSize=15;\n\n% Create example data for visualizations\nn=250;\ns=1;\n[X,Y]=ndgrid(linspace(-3*s,3*s,n));\nZ=exp( -0.5.*((X./s).^2+(Y./s).^2));\nZ=Z./max(Z(:));\nZ(X<0)=-Z(X<0);\ncolorLim=[-1 1];\ncolormapset={'gjet','wjet','graygjet','grayjet',...\n 'fire','ice','fireice','warmcold','iwarmcold','blood','bloodbone',...\n 'che','wcbp','viridis','magma','inferno','turbo',...\n 'plasma','gviridis','igviridis','kvw','cividis','spectral','ukr','flare'};\n\n%% The gibbon color maps\n\n%%\n% Visualizing all additional color maps\n\nn1=floor(sqrt(numel(colormapset)));\nn2=ceil(numel(colormapset)/n1);\n\ncFigure;\n\nfor q=1:1:numel(colormapset)\n \n h=subplot(n1,n2,q); hold on;\n title(colormapset{q},'FontSize',fontSize);\n imagesc(Z);\n colormap(h,colormapset{q}); colorbar;\n axis tight; axis equal; axis xy; box on;\n axis off;\n set(h,'FontSize',fontSize);\n clim(colorLim);\nend\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/DEMO_additional_colormaps.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.49402351033764863}} {"text": "function pcircles(fhdl, center, radius, varargin)\n%\n% PCIRCLE(fhdl, center, radius, varargin)\n% A simple function for drawing a circle on the selected figure using\n% polylines.\n%\n% INPUT:\n% fhdl: figure handler\n% center: center of the circle in [x0 y0] format\n% radius: radius of the circle (in pixels)\n% varargin: colors, plot symbols and line types\n\nformat = '-w'; % default\nif nargin == 4\n format = varargin{1};\nend\n\nx0 = center(1);\ny0 = center(2);\nnseg = ceil(2*pi*radius);\ntheta = 0 : (2 * pi / nseg) : (2 * pi);\nx = radius * cos(theta) + x0;\ny = radius * sin(theta) + y0;\n\nfigure(fhdl), hold;\nplot(x0, y0, '.r', 'LineWidth',5);\nplot(x, y, format);\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/28974-generalized-fuzzy-hough-transform/fuzzy Hough transform/common/pcircles.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.49402350870945727}} {"text": "function Z = or(X,Y)\n%OR Logical OR (|) for tensors.\n%\n% See also TENSOR.\n%\n%MATLAB Tensor Toolbox.\n%Copyright 2012, Sandia Corporation.\n\n% This is the MATLAB Tensor Toolbox by T. Kolda, B. Bader, and others.\n% http://www.sandia.gov/~tgkolda/TensorToolbox.\n% Copyright (2012) Sandia Corporation. Under the terms of Contract\n% DE-AC04-94AL85000, there is a non-exclusive license for use of this\n% work by or on behalf of the U.S. Government. Export of this data may\n% require a license from the United States Government.\n% The full license terms can be found in the file LICENSE.txt\n\n\nZ = tenfun(@or,X,Y);\n", "meta": {"author": "andrewssobral", "repo": "mtt", "sha": "0152a77df09f24af4c294f46845931e4e0e63b55", "save_path": "github-repos/MATLAB/andrewssobral-mtt", "path": "github-repos/MATLAB/andrewssobral-mtt/mtt-0152a77df09f24af4c294f46845931e4e0e63b55/libs/tensor_toolbox_2.5/@tensor/or.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.49402350870945727}} {"text": "function y = linearize( x )\n\n% LINEARIZE Linearize.\n% For real affine X, Y = X. \n% For convex X, Y is linear, and satisfies Y >= X.\n% For concave X, Y is linear, and satisfies Y <= X.\n% This is used primarily within CVX functions to efficiently implement\n% certain monotonic functions.\n\npersistent P\nif isempty( P ),\n P.map = cvx_remap( { 'r_affine' }, ...\n { 'convex' }, { 'concave' }, [2,3,4] );\n P.funcs = { [], @lin_affn, @lin_cnvx, @lin_cncv };\nend\ny = cvx_unary_op( P, x );\n\nfunction y = lin_affn( x )\ny = x;\n\nfunction y = lin_cnvx( x ) %#ok\ncvx_begin set\n variable y(size(x))\n x <= y; %#ok\ncvx_end\n\nfunction y = lin_cncv( x ) %#ok\ncvx_begin set\n variable y(size(x))\n x >= y; %#ok\ncvx_end\n\n% Copyright 2005-2014 CVX Research, Inc.\n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/cvx-w64/cvx/functions/linearize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031738152021788, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49402245959936564}} {"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 i4vec_sorted_unique_test ( )\n\n%*****************************************************************************80\n%\n%% I4VEC_SORTED_UNIQUE_TEST tests I4VEC_SORTED_UNIQUE.\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 n = 20;\n b = 0;\n c = n;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4VEC_SORTED_UNIQUE_TEST\\n' );\n fprintf ( 1, ' I4VEC_SORTED_UNIQUE finds unique entries in a sorted array.\\n' );\n\n seed = 123456789;\n\n [ a, seed ] = i4vec_uniform_ab ( n, b, c, seed );\n\n a = i4vec_sort_heap_a ( n, a );\n\n i4vec_print ( n, a, ' Input vector:' );\n\n [ unique_num, a_unique ] = i4vec_sorted_unique ( n, a );\n\n i4vec_print ( unique_num, a_unique, ' Unique entries:' );\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_sorted_unique_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.49402245380361515}} {"text": "function ap_multi = compute_AP_multiCam(good_image, junk_image, index, queryCam, testCam)\ngood_cam = testCam(good_image);\ngood_cam_uni = unique(good_cam); \nap_multi = zeros(1, 6);\n\n% on the same camera\ngood_cam_now = queryCam;\nngood = length(junk_image);\njunk_image_now = good_image;\ngood_image_now = junk_image;\nold_recall = 0; \nold_precision = 1.0; \nap = 0; \nintersect_size = 0; \nj = 0; \ngood_now = 0; \nfor n = 1:length(index) \n flag = 0;\n if ~isempty(find(good_image_now == index(n), 1)) \n flag = 1; % good image \n good_now = good_now+1; \n end\n if ~isempty(find(junk_image_now == index(n), 1))\n continue; % junk image \n end\n\n if flag == 1%good\n intersect_size = intersect_size + 1; \n end \n if ngood == 0\n ap_multi(good_cam_now) = 0;\n break;\n end\n recall = intersect_size/ngood; \n precision = intersect_size/(j + 1); \n ap = ap + (recall - old_recall)*((old_precision+precision)/2); \n old_recall = recall; \n old_precision = precision; \n j = j+1; \n\n if good_now == ngood \n ap_multi(good_cam_now) = ap;\n break; \n end \nend \n\nfor k = 1:length(good_cam_uni)\n good_cam_now = good_cam_uni(k);\n ngood = length(find(good_cam == good_cam_now));\n pos_junk = find(good_cam ~= good_cam_now);\n junk_image_now = [junk_image good_image(pos_junk)];\n pos_good = find(good_cam == good_cam_now);\n good_image_now = good_image(pos_good);\n old_recall = 0; \n old_precision = 1.0; \n ap = 0; \n intersect_size = 0; \n j = 0; \n good_now = 0; \n for n = 1:length(index) \n flag = 0;\n if ~isempty(find(good_image_now == index(n), 1)) \n flag = 1; % good image \n good_now = good_now+1; \n end\n if ~isempty(find(junk_image_now == index(n), 1))\n continue; % junk image \n end\n\n if flag == 1%good\n intersect_size = intersect_size + 1; \n end \n recall = intersect_size/ngood; \n precision = intersect_size/(j + 1); \n ap = ap + (recall - old_recall)*((old_precision+precision)/2); \n old_recall = recall; \n old_precision = precision; \n j = j+1; \n\n if good_now == ngood \n ap_multi(good_cam_now) = ap;\n break; \n end \n end \nend\n\nend\n\n\n", "meta": {"author": "naiq", "repo": "PN_GAN", "sha": "276dda6772709a527f99e0351342f1023e1bb423", "save_path": "github-repos/MATLAB/naiq-PN_GAN", "path": "github-repos/MATLAB/naiq-PN_GAN/PN_GAN-276dda6772709a527f99e0351342f1023e1bb423/script/Market-1501_baseline/compute_AP_multiCam.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4940224538036151}} {"text": "function [ ave_recall, recall, thresholds] = compute_ave_recall_of_bbox( bbox_pred, bbox_gt, thresholds )\n\nif ~exist('thresholds','var') || isempty(thresholds)\n thresholds = 0.5:0.05:0.95;\nend\n\nif iscell(bbox_pred)\n assert(iscell(bbox_gt));\n assert(length(bbox_pred) == length(bbox_gt));\n num_imgs = length(bbox_pred);\n overlap = cell(num_imgs,1);\n for i = 1:num_imgs\n bbox_pred_this = bbox_pred{i};\n bbox_gt_this = bbox_gt{i};\n num_bbox_gt = size(bbox_gt_this,1);\n num_bbox_pred = size(bbox_pred_this,1);\n overlap{i} = zeros(num_bbox_gt,1,'single');\n \n \n if num_bbox_gt && num_bbox_pred\n [overlap{i}, ~] = closest_candidates(bbox_gt_this(:,1:4), bbox_pred_this(:,1:4));\n overlap{i} = single(overlap{i});\n% overlap{i} = max(boxoverlap(bbox_pred_this(:,1:4), bbox_gt_this(:,1:4)),[],1)';\n end\n end\n overlap = cell2mat(overlap);\nelse\n assert(size(bbox_pred,1) == size(bbox_gt,1));\n assert(size(bbox_pred,2) == size(bbox_gt,2));\n assert(size(bbox_pred,2) == 4);\n overlap = boxoverlap(bbox_pred, bbox_gt, true);\n assert(size(bbox_pred,1) == size(overlap,1));\n assert(size(overlap,2)==1);\nend\n\n[thresholds, recall, ave_recall] = compute_average_recall(overlap);\n\nend\n\nfunction [overlap, recall, AR] = compute_average_recall(unsorted_overlaps)\nall_overlaps = sort(unsorted_overlaps(:)', 'ascend');\nnum_pos = numel(all_overlaps);\ndx = 0.001;\n\noverlap = 0:dx:1;\noverlap(end) = 1;\nrecall = zeros(length(overlap), 1);\nfor i = 1:length(overlap)\nrecall(i) = sum(all_overlaps >= overlap(i)) / (num_pos+eps);\nend\n\ngood_recall = recall(overlap >= 0.5);\nAR = 2 * dx * trapz(good_recall);\n\nif num_pos == 0\n AR = 0;\nend\nend\n\nfunction [best_overlap,best_boxes] = closest_candidates(gt_boxes, candidates)\n% do a matching between gt_boxes and candidates\n\n num_gt_boxes = size(gt_boxes, 1);\n num_candidates = size(candidates, 1);\n \n% iou_matrix = zeros(num_gt_boxes, num_candidates);\n iou_matrix = boxoverlap(candidates, gt_boxes)';\n% for i = 1:num_gt_boxes\n% iou = boxoverlap(gt_boxes(i,:), candidates);\n% iou_matrix(i,:) = iou';\n% end\n \n best_overlap = zeros(num_gt_boxes, 1);\n best_boxes = -ones(num_gt_boxes, 4);\n\n [best_overlap,best_boxes] = greedy_matching(iou_matrix, gt_boxes, candidates);\nend\n\nfunction [best_overlap,best_boxes] = greedy_matching(iou_matrix, gt_boxes, candidates)\n [n, m] = size(iou_matrix);\n assert(n == size(gt_boxes, 1));\n assert(m == size(candidates, 1));\n if n > m\n gt_matching = greedy_matching_rowwise(iou_matrix');\n candidate_matching = (1:m)';\n else\n gt_matching = (1:n)';\n candidate_matching = greedy_matching_rowwise(iou_matrix);\n end\n \n best_overlap = zeros(n, 1);\n best_boxes = zeros(n, 4);\n for pair_idx = 1:numel(gt_matching)\n gt_idx = gt_matching(pair_idx);\n candidate_idx = candidate_matching(pair_idx);\n \n best_overlap(gt_idx) = iou_matrix(gt_idx, candidate_idx);\n best_boxes(gt_idx,:) = candidates(candidate_idx, :);\n end\nend\n\nfunction [matching, objective] = greedy_matching_rowwise(iou_matrix)\n assert(size(iou_matrix, 1) <= size(iou_matrix, 2));\n n = size(iou_matrix, 1);\n matching = zeros(n, 1);\n objective = 0;\n for i = 1:n\n % find max element int matrix\n [max_per_row, max_col_per_row] = max(iou_matrix, [], 2);\n [max_iou,row] = max(max_per_row);\n if max_iou == -inf\n break\n end\n \n objective = objective + max_iou;\n col = max_col_per_row(row);\n matching(row) = col;\n iou_matrix(row,:) = -inf;\n iou_matrix(:,col) = -inf;\n end\nend\n", "meta": {"author": "gidariss", "repo": "mrcnn-object-detection", "sha": "2f355c0539961aa22f57d31971aa163a35f3152c", "save_path": "github-repos/MATLAB/gidariss-mrcnn-object-detection", "path": "github-repos/MATLAB/gidariss-mrcnn-object-detection/mrcnn-object-detection-2f355c0539961aa22f57d31971aa163a35f3152c/code/utils/compute_ave_recall_of_bbox.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4940224480078644}} {"text": "%% Demo for semi-supervised learning\n% Copyright: Andreas Damianou 2015\n\n\n\n\n\n%% id of differerent random trials\nallTrials = 1:2;\nsaveDir = './results/semiSupervised_master/';\n\n%%\nfor trial = allTrials\n % For each trial, try different number of observed outputs\n for NtrObs = [10:10:160]\n keep('saveDir','allTrials','trial','NtrObs','res');\n % Different trials should have different seeds\n curSeed = trial + 1000;\n randn('seed', curSeed);\n rand('seed', curSeed);\n \n dataSetName = 'oil';\n experimentNo = curSeed;\n % This is for when we bootstrap: we try to populate the output\n % labelled space as follows: if Y_i is in the labelled set,\n % (i.e. labels_i exists), then we find this point's embeding, q(x_i) ~\n % N(mu_i, S_i), from which we sample samplesPerObserved points\n % x_samp_i,k, k=1,..., samplesPerObserved and form the pairs\n % {x_samp_i,k, labels_i}, for all k. Here we try two different\n % numbers for samplesPerObserved (a small and a big number).\n samplesPerObserved3 = 6;\n samplesPerObserved4 = 50;\n \n % Number of iterations for initialization of the model (helps\n % avoiding early local minima)\n initVardistIters = 500;\n % Number of optimization iterations\n itNo = [1200 1000];\n \n % Load data\n [Y, lbls] = lvmLoadData(dataSetName);\n labels = transformLabels(lbls)';\n \n % Use Nts test points randomly from the data set. Use the rest\n % NtrObs as training points.\n Nts = 700;\n perm = randperm(size(Y,1));\n ts = perm(1:Nts); t = Nts;\n trObs = perm(t+1:t+NtrObs); t = t+NtrObs;\n trMis = perm(t+1:end);\n \n %%%%% ATTENTION!!!! For compatibility with the rest of the code,\n %%%%% the notation here differs than from the paper:\n %%%%% Y here is Z in paper\n %%%%% labels here is Y in paper\n % SO:\n % YtrObs: Training points in the labelled set (observed and we also not know their corresponding labelsObs\n % YtrMis: Training points in the unlabelled set (observed, but we do not know their labels labelsMis (we have the below but not show them to the model))\n % Yts: Test points (we'll infer their corresponding labels labelsTs at test time)\n YtrObs = Y(trObs,:); lblsObs = lbls(trObs, :); labelsObs = labels(trObs,:);\n YtrMis = Y(trMis,:); lblsMis = lbls(trMis, :); labelsMis = labels(trMis,:);\n Yts = Y(ts,:); lblsTs = lbls(ts, :); labelsTs = labels(ts,:);\n \n % Options for bgplvm\n options = vargplvmOptions('dtcvar');\n options.kern = 'rbfardjit';\n options.numActive = min(25, size(YtrObs,1)); % number of ind. points\n options.latentDim = 8; % number of latent dimensions\n options.optimiser = 'scg2';\n options.initSNR = 100; % Initial signal to noise ratio\n \n %----- BGPLVM embed only from the labelled data (no semi-supervised learning here)\n % X is the embedding of only labelled data\n [X, sigma2, W, ~, modelInitVardist] = vargplvmEmbed(YtrObs, options.latentDim, options, initVardistIters, 0 );\n modelInitVardist.globalOpt.experimentNo = experimentNo;\n modelInitVardist.throwSNRError = false;\n model = vargplvmOptimiseModel(modelInitVardist, 1,1, {[], itNo}, 1);\n SNR = vargplvmShowSNR(model,false);\n [x_star_all, varx_star_all, mini] = vargplvmPredictLatent(model, Yts, [], false, 1000, false);\n \n %----- BGPLVM embed from the labelled and unlabelled data (semi-supervised learning)\n % X2 is a riccher embedding because it is learned from more data\n [X2, sigma22, W2, ~, modelInitVardist2] = vargplvmEmbed([YtrObs; YtrMis], options.latentDim, options, initVardistIters, 0 );\n modelInitVardist2.globalOpt.experimentNo = experimentNo;\n modelInitVardist2.throwSNRError = false;\n model2 = vargplvmOptimiseModel(modelInitVardist2, 1,1, {[], itNo}, 1);\n SNR2 = vargplvmShowSNR(model2,false);\n [x_star_all2, varx_star_all2, mini2] = vargplvmPredictLatent(model2, Yts, [], false, 1000, false);\n \n %---- X3 is an even richer embedding, because it is a superset of X2:\n % it starts as X2, but for every point in X2 which has a known\n % label we sample extra points and assign that label. So, X3 is a\n % larger set.\n % First copy X3 = X2 (later we'll augment it)\n X3 = model2.X(1:length(trObs),:);\n % We'll need the variances too in order to sample\n varX3 = model2.vardist.covars(1:length(trObs),:);\n % Copy the labels\n labels3 = labelsObs;\n % Xnew, labelsNew is initialized in size\n Xnew = nan(size(X3,1)*samplesPerObserved3, size(X3,2));\n labelsNew = nan(size(Xnew,1), size(labelsObs,2));\n k=1;\n % Now for each labelled point in the embedding we sample more\n % points\n for n=1:size(X3,1) % At this point X3 == X2\n for kk = 1:samplesPerObserved3\n Xnew(k,:) = X3(n,:) + randn(size(X3(n,:))).*sqrt(varX3(n,:));\n labelsNew(k,:) = labels3(n,:);\n k = k + 1;\n end\n end\n X3 = [X3; Xnew];\n labels3 = [labels3; labelsNew];\n clear 'Xnew' 'labelsNew';\n \n \n \n %---------- As above but obtain many more samples ----------------\n \n %samplesPerObserved4 = min(samplesPerObserved4, floor(10000/NtrObs));\n X4 = model2.X(1:length(trObs),:);\n varX4 = model2.vardist.covars(1:length(trObs),:);\n labels4 = labelsObs;\n Xnew = nan(size(X4,1)*samplesPerObserved4, size(X4,2));\n labelsNew = nan(size(Xnew,1), size(labelsObs,2));\n k=1;\n for n=1:size(X4,1)\n for kk = 1:samplesPerObserved4\n Xnew(k,:) = X4(n,:) + randn(size(X4(n,:))).*sqrt(varX4(n,:));\n labelsNew(k,:) = labels4(n,:);\n k = k + 1;\n end\n end\n X4 = [X4; Xnew];\n labels4 = [labels4; labelsNew];\n clear 'Xnew' 'labelsNew';\n \n \n %% %%%%%%%%%%%%%%%%%%% CLASSIFICATION STEP: %%%%%%%%%%%%%%%%\n % Now we have all 4 embeddings / models. Recap:\n % - Model 1: Embedding only from the labelled data\n % - model 2: Embedding from the labelled and unlabelled data\n % - model 3: As above but bootstrap\n % - model 4: As above but bootstrap more points\n %\n % Given these embeddings, we'll train classifiers from the embedded\n % point to the label space.\n %\n %--------- Train classifiers from X to Z\n %\n %---- Model 1\n % Training of logistic regression classifier (replace with any\n % classifier you want). Do this for each of the embeddings.\n LogRegError = util_fitLogReg(model.X, labelsObs, x_star_all, lblsTs);\n LogRegError2 = util_fitLogReg(model2.X(1:length(trObs),:), labelsObs, x_star_all2, lblsTs);\n LogRegError3 = util_fitLogReg(X3, labels3, x_star_all2, lblsTs);\n LogRegError4 = util_fitLogReg(X4, labels4, x_star_all2, lblsTs);\n % We can also classify not from the embeddings to the labels, but\n % directly from the points. However, when the dimensionality of\n % these points is too big, the following method will automatially\n % do a PCA embedding. Notice that the directly classifying from the\n % points might be better than going through an embedding, if tjhe\n % points' dimensionality is small or the data is relatively\n % simple-structured.\n LogRegErrorOutputs = util_fitLogReg(YtrObs, labelsObs, Yts, lblsTs);\n \n \n %% -------------- Save results in a structure 'res'\n tmp=['tr' num2str(trial) '_NtrObs' num2str(NtrObs)];\n res.(tmp).seed = curSeed;\n res.(tmp).LogRegError = LogRegError;\n res.(tmp).LogRegError2 = LogRegError2;\n res.(tmp).LogRegError3 = LogRegError3;\n res.(tmp).LogRegError4 = LogRegError4;\n res.(tmp).LogRegErrorOutputs = LogRegErrorOutputs;\n res.(tmp).samplesPerObserved3 = samplesPerObserved3;\n res.(tmp).samplesPerObserved4 = samplesPerObserved4;\n res.(tmp).trObs = trObs;\n res.(tmp).ts = ts;\n res.(tmp).trMis = trMis;\n res.(tmp).W = W;\n res.(tmp).W2 = W2;\n res.(tmp).SNR = SNR;\n res.(tmp).SNR2 = SNR2;\n diary(['LOG_demOilSemiSup4.txt']);\n res.(tmp)\n diary off\n save([saveDir 'demOilSemiSup4.mat'], 'res');\n end\nend\n\n%% ------------ PLOTS ------------------\nclose all\ncd(saveDir);\nll = [];\nlw = 1.7;\nms = 12;\nfs = 40;\nerrorBars = true;\nstdMult = 0.8; % Smaller error bar to be in 0\n\nresAll = [];\ndoneTrials = [];\ntry\n load(['demOilSemiSup4.mat']);\n ff = fieldnames(res);\n for jj=1:length(ff)\n if isfield(resAll, ff{jj})\n warning('field already exists')\n end\n resAll.(ff{jj}) = res.(ff{jj});\n try\n doneTrials(end+1) = str2num(ff{jj}(3:find(ff{1}=='_')-1));\n catch ee\n error('ll')\n end\n end\ncatch e\n warning(['Did not find demOilSemiSup4.mat'])\nend\ndoneTrials = unique(doneTrials);\n\n\n%%% ATTENTION: Reject trials with low SNR (or repeat them with more\n%%% initiVardistIters).\n% If embedding results in low SNR (i.e. close to 1), then it has to be rejected. There's no\n% automatic check for this now, so you can use the next array manually.\nexcludeTrials = [];\nallTrials = setdiff(doneTrials, excludeTrials);\nallNtrObs = [10:10:160];\nlogRegErrorMatrix = NaN(length(allTrials), length(allNtrObs));\nlogRegErrorSemiSupMatrix = logRegErrorMatrix;\nlogRegErrorSemiSupMatrix3 = logRegErrorMatrix;\nlogRegErrorSemiSupMatrix4 = logRegErrorMatrix;\nweightKeptMatrix = logRegErrorMatrix;\nweigthKeptSemiSupMatrix = logRegErrorMatrix;\nSNRMatrix = logRegErrorMatrix;\nSNRSemiSupMatrix = logRegErrorMatrix;\n\nthresh = 0.0002;\n%\n\nfor i=1:length(allTrials)\n for j=1:length(allNtrObs)\n trial = allTrials(i);\n NtrObs = allNtrObs(j);\n try\n logRegErrorMatrix(i, j) = resAll.(['tr' num2str(trial) '_NtrObs' num2str(NtrObs)]).LogRegError;\n logRegErrorSemiSupMatrix(i, j) = resAll.(['tr' num2str(trial) '_NtrObs' num2str(NtrObs)]).LogRegError2;\n logRegErrorSemiSupMatrix3(i, j) = resAll.(['tr' num2str(trial) '_NtrObs' num2str(NtrObs)]).LogRegError3;\n logRegErrorSemiSupMatrix4(i, j) = resAll.(['tr' num2str(trial) '_NtrObs' num2str(NtrObs)]).LogRegError4;\n weightKeptMatrix(i, j) = sum(resAll.(['tr' num2str(trial) '_NtrObs' num2str(NtrObs)]).W > thresh);\n weigthKeptSemiSupMatrix(i, j) = sum(resAll.(['tr' num2str(trial) '_NtrObs' num2str(NtrObs)]).W2 > thresh);\n SNRMatrix(i, j) = resAll.(['tr' num2str(trial) '_NtrObs' num2str(NtrObs)]).SNR;\n SNRSemiSupMatrix(i, j) = resAll.(['tr' num2str(trial) '_NtrObs' num2str(NtrObs)]).SNR2;\n catch e\n warning(['Could not find tr' num2str(trial) '_NtrObs' num2str(NtrObs)])\n end\n end\nend\n\ninds = 1:size(logRegErrorMatrix,2);\n\nmeanlogRegErrorMatrix = nanmean(logRegErrorMatrix(:,inds));\nmeanlogRegErrorSemiSupMatrix = nanmean(logRegErrorSemiSupMatrix(:,inds));\nmeanlogRegErrorSemiSupMatrix3 = nanmean(logRegErrorSemiSupMatrix3(:,inds));\nmeanlogRegErrorSemiSupMatrix4 = nanmean(logRegErrorSemiSupMatrix4(:,inds));\nif errorBars\n ll(end+1)=errorbar(allNtrObs(inds), meanlogRegErrorMatrix, stdMult*nanstd(logRegErrorMatrix(:,inds)), 'x-', 'LineWidth', lw, 'MarkerSize', ms); hold on;\n ll(end+1)=errorbar(allNtrObs(inds), meanlogRegErrorSemiSupMatrix, stdMult*nanstd(logRegErrorSemiSupMatrix(:,inds)), 'ro-', 'LineWidth', lw, 'MarkerSize', ms);\n ll(end+1)=errorbar(allNtrObs(inds), meanlogRegErrorSemiSupMatrix3, stdMult*nanstd(logRegErrorSemiSupMatrix3(:,inds)), 'g+-', 'LineWidth', lw, 'MarkerSize', ms);\n ll(end+1)=errorbar(allNtrObs(inds), meanlogRegErrorSemiSupMatrix4, stdMult*nanstd(logRegErrorSemiSupMatrix4(:,inds)), 'ks-', 'LineWidth', lw, 'MarkerSize', ms);\n xlabel('# Observed')\n ylabel('# Errors')\n legend('Without Z^u','With Z^u', 'With Samples', 'With More Samples');\n xlim([17,163])\n pp = ylim;\n ylim([-20 pp(2)]);\nelse\n plot(allNtrObs(inds), meanlogRegErrorMatrix, 'x-'); hold on; title('# Errors')\n plot(allNtrObs(inds), meanlogRegErrorSemiSupMatrix, 'ro-');\n plot(allNtrObs(inds), meanlogRegErrorSemiSupMatrix3, 'g+-'); legend('GP','Semi-supervised GP', 'SS-GP with Samples');\n plot(allNtrObs(inds), meanlogRegErrorSemiSupMatrix4, 'ks-'); legend('GP','Semi-supervised GP', 'SS-GP with More Samples');\nend\n\n% figure\n% plot(allNtrObs(inds), nanmean(weightKeptMatrix(:,inds)), 'x-'); hold on; title(['Weights kept (threshold=' num2str(thresh) ')'])\n% plot(allNtrObs(inds), nanmean(weigthKeptSemiSupMatrix(:,inds)), 'ro-'); legend('GP','Semi-supervised GP');\n%\n% figure\n% plot(allNtrObs(inds), nanmean(SNRMatrix(:,inds)), 'x-'); hold on; title('SNR')\n% plot(allNtrObs(inds), nanmean(SNRSemiSupMatrix(:,inds)), 'ro-'); legend('GP','Semi-supervised GP');\n%\n\n\n\n", "meta": {"author": "SheffieldML", "repo": "vargplvm", "sha": "480201fde5ac84ff36e4a9f06d3fafeafa8ef06d", "save_path": "github-repos/MATLAB/SheffieldML-vargplvm", "path": "github-repos/MATLAB/SheffieldML-vargplvm/vargplvm-480201fde5ac84ff36e4a9f06d3fafeafa8ef06d/vargplvm/matlab/missingData/demOilSemiSupervisedScript_master.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4940224480078644}} {"text": "function mask=getMask(l,h,w,batchS,depth,posTempX,posTempY)\nmask=abs(posTempX-repmat(l.mu_x,[h,w,1]));\nmask=mask+abs(posTempY-repmat(l.mu_y,[h,w,1]));\nmask=max(1-mask.*repmat(reshape(l.weights{3},[1,1,depth]),[h,w,1,batchS]),-1);\nmask(:,:,l.filter~=1,:)=1;\nend\n", "meta": {"author": "zqs1022", "repo": "interpretableCNN", "sha": "6d7d1a6aaf0f1b2b03a3b54d4ac4803b3f1ce823", "save_path": "github-repos/MATLAB/zqs1022-interpretableCNN", "path": "github-repos/MATLAB/zqs1022-interpretableCNN/interpretableCNN-6d7d1a6aaf0f1b2b03a3b54d4ac4803b3f1ce823/code/tool/main/getMask.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4940224422121135}} {"text": "function F = minus (F,w)\n%MINUS downdate a dense Cholesky factorization\n%\n% Example\n% % F becomes the Cholesky factorization of A-w*w'\n% F = factorize (A) ;\n% w = rand (size (A,1),1) ;\n% F = F - w ;\n% x = F\\b ; % computes x = (A-w*w')\\b\n%\n% See also factorize, cholupdate.\n\n% Copyright 2009, Timothy A. Davis, University of Florida\n\nif (F.kind ~= 6)\n error ('Only dense Cholesky factorization downdate supported.') ;\nend\n\nF.R = cholupdate (F.R, w, '-') ;\nF.A = F.A - w*w' ;\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/SuiteSparse/MATLAB_Tools/Factorize/@factorize/minus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4940224422121135}} {"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 hyperDemo_detectors\n% HYPERDEMO_DETECTORS Demonstrates target detector algorithms\nclear; clc; dbstop if error; close all;\n%--------------------------------------------------------------------------\n% Parameters\nresultsDir = 'results\\\\';\ndataDir = 'data\\\\AVIRIS\\\\';\n%--------------------------------------------------------------------------\n\nmkdir(resultsDir);\n\n% Read part of AVIRIS data file that we will further process\nM = hyperReadAvirisRfl(sprintf('%s\\\\f970620t01p02_r03_sc02.a.rfl', dataDir), [1 100], [1 614], [1 224]);\nM = hyperNormalize(M);\n\n% Read AVIRIS .spc file\nlambdasNm = hyperReadAvirisSpc(sprintf('%s\\\\f970620t01p02_r03.a.spc', dataDir));\n\n% Isomorph\n[h, w, p] = size(M);\nM = hyperConvert2d(M);\n\n% Resample AVIRIS image.\ndesiredLambdasNm = 400:(2400-400)/(224-1):2400;\nM = hyperResample(M, lambdasNm, desiredLambdasNm);\n\n% Remove low SNR bands.\ngoodBands = [10:100 116:150 180:216];\nM = M(goodBands, :);\np = length(goodBands);\n\n% Demonstrate difference spectral similarity measurements\nM = hyperConvert3d(M, h, w, p);\ntarget = squeeze(M(11, 77, :));\nfigure; plot(desiredLambdasNm(goodBands), target); grid on;\n title('Target Signature; Pixel (32, 257)');\n\nM = hyperConvert2d(M);\n \n% RX Anomly Detector\nr = hyperRxDetector(M);\nr = hyperConvert3d(r.', h, w, 1);\nfigure; imagesc(r); title('RX Detector Results'); axis image;\n colorbar;\nhyperSaveFigure(gcf, sprintf('%s\\\\rx detector.png', resultsDir));\n\n% Constrained Energy Minimization (CEM)\nr = hyperCem(M, target);\nr = hyperConvert3d(r, h, w, 1);\nfigure; imagesc(abs(r)); title('CEM Detector Results'); axis image;\n colorbar; \nhyperSaveFigure(gcf, sprintf('%s\\\\cem detector.png', resultsDir));\n\n% Adaptive Cosine Estimator (ACE)\nr = hyperAce(M, target);\nr = hyperConvert3d(r, h, w, 1);\nfigure; imagesc(r); title('ACE Detector Results'); axis image;\n colorbar;\nhyperSaveFigure(gcf, sprintf('%s\\\\ace detector.png', resultsDir)); \n\n% Signed Adaptive Cosine Estimator (S-ACE)\nr = hyperSignedAce(M, target);\nr = hyperConvert3d(r, h, w, 1);\nfigure; imagesc(r); title('Signed ACE Detector Results'); axis image;\n colorbar;\nhyperSaveFigure(gcf, sprintf('%s\\\\signed ace detector.png', resultsDir)); \n\n% Matched Filter\nr = hyperMatchedFilter(M, target);\nr = hyperConvert3d(r, h, w, 1);\nfigure; imagesc(r); title('MF Detector Results'); axis image;\n colorbar;\nhyperSaveFigure(gcf, sprintf('%s\\\\mf detector.png', resultsDir)); \n\n% Generalized Likehood Ratio Test (GLRT) detector\nr = hyperGlrt(M, target);\nr = hyperConvert3d(r, h, w, 1);\nfigure; imagesc(r); title('GLRT Detector Results'); axis image;\n colorbar;\nhyperSaveFigure(gcf, sprintf('%s\\\\cem detector.png', resultsDir));\n\n\n% Estimate background endmembers\nU = hyperAtgp(M, 5);\n\n% Hybrid Unstructured Detector (HUD)\nr = hyperHud(M, U, target);\nr = hyperConvert3d(r, h, w, 1);\nfigure; imagesc(abs(r)); title('HUD Detector Results'); axis image;\n colorbar;\nhyperSaveFigure(gcf, sprintf('%s\\\\hud detector.png', resultsDir));\n \n% Adaptive Matched Subspace Detector (AMSD)\nr = hyperAmsd(M, U, target);\nr = hyperConvert3d(r, h, w, 1);\nfigure; imagesc(abs(r)); title('AMSD Detector Results'); axis image;\n colorbar;\nhyperSaveFigure(gcf, sprintf('%s\\\\amsd detector.png', resultsDir)); \nfigure; mesh(r); title('AMSD Detector Results');\n\n% Orthogonal Subspace Projection (OSP)\nr = hyperOsp(M, U, target);\nr = hyperConvert3d(r, h, w, 1);\nfigure; imagesc(abs(r)); title('OSP Detector Results'); axis image;\n colorbar; \nhyperSaveFigure(gcf, sprintf('%s\\\\osp detector.png', resultsDir)); \n\n", "meta": {"author": "davidkun", "repo": "HyperSpectralToolbox", "sha": "147d58e6efe839e8945dc0d4e8d65029884137f1", "save_path": "github-repos/MATLAB/davidkun-HyperSpectralToolbox", "path": "github-repos/MATLAB/davidkun-HyperSpectralToolbox/HyperSpectralToolbox-147d58e6efe839e8945dc0d4e8d65029884137f1/functions/hyperDemo_detectors.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4939495310107406}} {"text": "function obj_val = test_binary_classifier(objective_function,classf, ...\n\t\t\t\t prior,system,input_data)\n% Returns the result of the objective function evaluated on the\n% scores.\n%\n% Inputs:\n% objective_function: a function handle to the objective function\n% to feed the scores into\n% classf: length T vector where T is the number of trials with entries +1 for target scores; -1 \n% for non-target scores\n% prior: the prior (given to the system that produced the scores)\n% system: a function handle to the system to be run\n% input_data: the data to run the system on (to produce scores)\n%\n% Outputs\n% obj_val: the value returned by the objective function\n\nif nargin==0\n test_this();\n return;\nend\n\nscores = system(input_data);\nobj_val = evaluate_objective(objective_function,scores,classf,prior);\n\nend\n\nfunction test_this()\n\nnum_trials = 100;\ninput_data = randn(20,num_trials);\n\nprior = 0.5;\nmaxiters = 1000;\nclassf = [ones(1,num_trials/2),-ones(1,num_trials/2)];\ntar = input_data(:,1:num_trials/2);\nnon = input_data(:,num_trials/2+1:end);\n[sys,run_sys,w0] = linear_fusion_factory(tar,non);\n\nw = train_binary_classifier(@cllr_obj,classf,sys,[],w0,[],maxiters,[],prior,[],true);\n\nsystem = @(data) run_sys(w,data);\ntest_binary_classifier(@cllr_obj,classf,prior,system,input_data)\n\n\nend\n\n", "meta": {"author": "nesl", "repo": "asvspoof2019", "sha": "8b780369f7273345c22d979192119198bbf3db13", "save_path": "github-repos/MATLAB/nesl-asvspoof2019", "path": "github-repos/MATLAB/nesl-asvspoof2019/asvspoof2019-8b780369f7273345c22d979192119198bbf3db13/baseline/tDCF_v1/bosaris_toolkit.1.06/bosaris_toolkit/utility_funcs/Optimization_Toolkit/applications/fusion2class/test_binary_classifier.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.49394953101074046}} {"text": "classdef CSMaster < handle\n %CS_LAB superclass\n %\n % (c) Thomas Kuestner \n % ---------------------------------------------------------------------\n \n properties\n type % reconstruction type\n kSpace % save kSpace in class to reduce memory overhead\n iNOUTER % outer loop iterations\n iNINNER % inner loop iterations\n p % L-p norm for reweighted minimum norm\n lambda % lagrange multiplier for noise stability\n lambdaCalib % lagrange multiplier for calibration\n lambdaTV % lagrange multiplier for TV\n lambdaESPReSSo % lagrange multiplier for ESPReSSo constraint\n lambdaMC % lagrange multiplier for motion correction\n% oversampling % oversampling along space directions\n% dimension % 2D (x-y or x-y-t), 3D (x,y,z) or 4D (x,y,z,t) problem\n% dim % nPha x nFreq x nZ x nTime x nCha\n measPara % struct containing all measurement parameters (dim, dimension, ...)\n kernelSize % kernel window dimension for convolution with calibration data\n calibSize % k-space center needed for initial estimate of W or GRAPPA calibration\n fullMask % mask of acquired data points\n currSlice % current slice, just needed for 2D with several slices\n currCha % current channel, just needed for 2D/3D with several channels\n trafo % struct of (tight frame) transformation in sparse basis\n espresso % espresso parameters\n window % cut out window options\n lSense % apply sense mask for multicoil reconstruction\n dRecontime % reconstruction time\n end\n \n methods\n function obj = CSMaster(iNOUTER, iNINNER, p, lambda, measPara)\n % constructor\n obj.iNOUTER = iNOUTER;\n obj.iNINNER = iNINNER;\n obj.p = p;\n obj.lambda = lambda;\n obj.measPara = measPara;\n end\n end\n \nend\n\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/@CSMaster/CSMaster.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4939495310107404}} {"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 [BG, FG, L_hat, S_hat, T_hat, t_hat, ...\n P_track_full, T_calc]= ...\n MEDRoP(M1, P_init, mu, ev_thresh, alpha, K)\n%%%This is the MEDRoP algorithm. This is the main function for the real video Background-\n%%%Foreground separation problem. \n\n%This folder contains the code accompanying pre-print.\n\n\n%%% Inputs %%%\n%%% M - measurement matrix %%%\n%%% ev_thres - threshold for subspace change detection %%%\n%%% P_init - an initial estimate of the subspace %%%\n%%% t_train - the dimension of the training data %%%\n\n\n%%% Algorithm parameters %%%\n%%% alpha - frame length %%%\n%%% mu - column-averages of data %%%\n%%% K - number of projection PCA steps %%%\n%%% omega - threshold for non-zero value in S %%%\n\n\n%%% Outputs %%%\n%%% BG - Estimated Background %%%\n%%% FG - Estimated Foreground %%%\n%%% L_hat - estimate of the low rank matrix %%%\n%%% P_hat - estimate of the subspace in which L lies %%%\n%%% S_hat - estimate of the sparse signal %%%\n%%% t_hat - estimate of subspace change times %%%\n\n%% Initializations\n\nP_hat_old = P_init;\n[~, r] = size(P_init);\nP_hat = P_hat_old;\n\n[n, t_max] = size(M1);\nT_hat = zeros(n, t_max);\nS_hat = zeros(n, t_max);\nL_hat = zeros(n, t_max);\n\nFG = zeros(n, t_max);\nBG = zeros(n, t_max);\n\nt_hat = [];\nM = M1 - repmat(mu, 1, t_max);\nk = 0;\ncnt = 1;\nph = 0; %ph - 0 => detect, 1 => ppca\nopts.delta = 0.4;\n\nphi_t = speye(n) - P_hat * P_hat';\n%% Main Algorithm Loop\nfor ii = 2 : t_max\n %% Estimate support\n Atf.times = @(x) x - (P_hat * (P_hat' * x));\n Atf.trans = @(y) y - (P_hat * (P_hat' * y));\n phi.times = @(x) x - (P_hat_old * (P_hat_old' * x));\n y_t = Atf.times(M(:, ii));\n opts.tol = 1e-3; \n opts.print = 0;\n \n opts.delta = norm(Atf.times(L_hat(:, ii - 1)));\n \n x_t_hat_cs = yall1(Atf, y_t, opts); \n omega = sqrt(M(:, ii)' * M(:, ii) / n);\n \n t_hat_temp = find(abs(x_t_hat_cs) > omega);\n T_hat(t_hat_temp, ii) = 255;\n \n LS.times = @(x) phi(:, t_hat_temp) * x;\n LS.trans = @(y) phi(:, t_hat_temp)' * x;\n \n %% Estimate signal components\n \n S_hat(t_hat_temp, ii) = cgls(phi_t(:, t_hat_temp), y_t, 0, 1e-3);\n L_hat(:, ii) = M(:, ii) - S_hat(:, ii);\n FG(t_hat_temp, ii) = M1(t_hat_temp, ii);\n BG(:, ii) = L_hat(:, ii) + mu;\n %% Subspace update\n if(~mod(ii - 1 , alpha))\n MM = (1 / sqrt(alpha)) * phi.times(L_hat(:, ii - alpha + 1 : ii));\n \n if(~ph) %%detect phase\n aa = svds(MM, 1);\n if(aa >= sqrt(ev_thresh))\n ph = 1;\n t_hat = [t_hat, ii];\n k = 0;\n end\n else %%ppca phase\n P_hat = simpleEVD((L_hat(:, ii - alpha + 1 : ii)), r);\n phi_t = speye(n) - P_hat * P_hat';\n k = k + 1;\n \n if(k==K + 1)\n P_hat_old = P_hat;\n k = 1;\n ph = 0;\n phi_t = speye(n) - P_hat * P_hat';\n end\n end\n end\n \n %% Return subspace estimates\n if((ii == 0) || (~(mod(ii - 1, alpha))))\n P_track_full{cnt} = P_hat;\n %P_track_new{cnt} = P_hat_new;\n T_calc(cnt) = ii;\n cnt = cnt + 1;\n end\nend\n%L_hat = L_hat + repmat(mu, n, 1);\nend\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/st/MEDRoP/MEDRoP.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 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": "% This is a test script which demonstrates the usage of the \"MofN_TrackInitiatorX\" class.\n% =========================================================================>\n\n% Load the ground truth data\nload('multiple-robot-tracking.mat');\n\n% Plot settings\nShowPlots = 1; % Set to 0 to hide plots\nnumTrueTracks = 3;\n\n% Model parameter shortcuts\nlambdaV = 10; % Expected number of clutter measurements over entire surveillance region\nV = 10^2; % Volume of surveillance region (10x10 2D-grid)\nV_bounds = [0 10 0 10]; % [x_min x_max y_min y_max]\nP_D = 0.9; % Probability of detection\ntimestep_duration = duration(0,0,1);\n\n%% Models\ntransition_model = ConstantVelocityX('VelocityErrVariance', 0.0001,...\n 'NumDims', 2,...\n 'TimestepDuration', timestep_duration);\nmeasurement_model = LinearGaussianX('NumMeasDims', 2,...\n 'NumStateDims', 4,...\n 'MeasurementErrVariance', 2,...\n 'Mapping', [1 3]);\nclutter_model = PoissonRateUniformPositionX('ClutterRate',lambdaV,...\n 'Limits',[V_bounds(1:2);...\n V_bounds(3:4)]);\ndetection_model = ConstantDetectionProbabilityX('DetectionProbability',P_D);\n\n% Compile the State-Space model\nmodel = StateSpaceModelX(transition_model,measurement_model,'Clutter',clutter_model, 'Detection', detection_model);\n\n\n%% Generate DataList\nmeas_simulator = MultiTargetMeasurementSimulatorX('Model',model);\n% meas_simulator.DetectionProbability = 1;\nDataList = meas_simulator.simulate(GroundTruthStateSequence);\nN = numel(DataList);\n\n%% Base Filter\nobs_covar= measurement_model.covar();\nPriorState = GaussianStateX(zeros(4,1), transition_model.covar() + blkdiag(obs_covar(1,1), 0, obs_covar(2,2),0));\nbase_filter = KalmanFilterX('Model', model, 'StatePrior', PriorState);\n\n%% Data Associator\nconfig.ClutterModel = clutter_model;\nconfig.Clusterer = NaiveClustererX();\nconfig.Gater = EllipsoidalGaterX(2,'GateLevel',10)';\nconfig.DetectionModel = detection_model;\njpdaf = JointProbabilisticDataAssocX(config);\n\n%% Track Initiator\n\n% Initiate Data Associator\nconfig_pdaf.ClutterModel = clutter_model;\nconfig_pdaf.DetectionModel = detection_model;\nconfig_pdaf.Gater = EllipsoidalGaterX(2,'GateLevel',5);\nconfig_pdaf.DetectionProbability = P_D;\npdaf = ProbabilisticDataAssocX(config_pdaf);\n\n% Initiate Tag Generator\ntag_gen = RandSampleTagGeneratorX(1:10000);\n\n% Prepare initiator parameters\nconfig_ti.TagGenerator = tag_gen;\nconfig_ti.InitFilter = base_filter;\nconfig_ti.DataAssociator = pdaf;\nCovarThreshold = 4*PriorState.Covar;\nconfig_ti.CustomDeleteConditionFcn = ...\n @(x,t) t.Filter.StatePosterior.Covar(1,1)>CovarThreshold(1,1) ...\n || t.Filter.StatePosterior.Covar(3,3)>CovarThreshold(3,3);\n\n% Create the track initiator\nmyti = LLR_TrackInitiatorX(config_ti);\n\n%% Metric Generators\nospa = OSPAX('CutOffThreshold',1,'Order',2);\ngospa = GOSPAX('CutOffThreshold',1,'Order',2);\n\n%% START OF SIMULATION\n% ===================>\n\n% Create figure windows\nif(ShowPlots)\n img = imread('maze.png');\n \n % set the range of the axes\n % The image will be stretched to this.\n min_x = 0;\n max_x = 10;\n min_y = 0;\n max_y = 10;\n\n % make data to plot - just a line.\n x = min_x:max_x;\n y = (6/8)*x;\n\n figure('units','normalized','outerposition',[0 0 .5 1])\n ax(1) = gca;\nend\n\nTrackList = [];\ngospa_vals= zeros(N,4);\nfor k=2:N\n fprintf('Iteration = %d/%d\\n================>\\n',k,N);\n \n %% Extract DataList at time k\n MeasurementList = DataList(k);\n timestamp_km1 = DataList(k-1).Timestamp;\n timestamp_k = MeasurementList.Timestamp;\n dt = timestamp_k - timestamp_km1;\n transition_model.TimestepDuration = dt;\n fprintf('Timestamp = %s\\n================>\\n',timestamp_k);\n \n %% Process JPDAF\n jpdaf.MeasurementList = MeasurementList;\n jpdaf.TrackList = TrackList;\n jpdaf.predictTracks();\n jpdaf.associate(); \n jpdaf.updateTracks();\n \n %% Perform Track initiation\n [TrackList, TentativeTrackList] = myti.initiateTracks(jpdaf.TrackList, MeasurementList, jpdaf.AssocWeightsMatrix, jpdaf.LikelihoodMatrix);\n \n [gospa_vals(k,1), gospa_vals(k,2), gospa_vals(k,3), gospa_vals(k,4)]= ...\n gospa.evaluate(GroundTruthStateSequence{k},jpdaf.TrackList);\n %% Plot update step results\n if(ShowPlots)\n \n cla(ax(1));\n %imagesc(ax(1),[min_x max_x], [min_y max_y], flipud(img));\n hold on;\n if(exist('data_plot','var'))\n delete(data_plot);\n end\n data_inv = measurement_model.finv(MeasurementList.Vectors);\n data_plot = plot(ax(1), data_inv(1,:), data_inv(3,:),'k*','MarkerSize', 10);\n\n % Plot confirmed tracks\n for j=1:numel(TrackList)\n means = [TrackList{j}.Trajectory.Mean];\n h2 = plot(ax(1), means(1,:),means(3,:),'-','LineWidth',1);\n h2 = plotgaussellipse(TrackList{j}.Filter.StatePosterior.Mean([1 3]),...\n TrackList{j}.Filter.StatePosterior.Covar([1 3],[1 3]),...\n 'Color','r',...\n 'Axis',ax(1)); \n end\n\n % Plot tentative tracks\n for j=1:numel(TentativeTrackList)\n h2 = plot(ax(1), TentativeTrackList{j}.Filter.StatePosterior.Mean(1),TentativeTrackList{j}.Filter.StatePosterior.Mean(3),'.','LineWidth',1);\n if j==2\n set(get(get(h2,'Annotation'),'LegendInformation'),'IconDisplayStyle','off');\n end\n h2 = plotgaussellipse(TentativeTrackList{j}.Filter.StatePosterior.Mean([1 3]),...\n TentativeTrackList{j}.Filter.StatePosterior.Covar([1 3],[1 3]),...\n 'Color','g',...\n 'Axis',ax(1));\n end\n \n % set the y-axis back to normal.\n set(ax(1),'ydir','normal');\n str = sprintf('Robot positions (Update)');\n title(ax(1),str)\n xlabel('X position (m)')\n ylabel('Y position (m)')\n axis(ax(1),V_bounds)\n pause(0.01)\n end\nend\n\nfigure\ntitle(\"GOSPA\");\nsubplot(2,3,[1 2 3]), plot(1:k,gospa_vals(1:k,1)), title(\"GOSPA Metric\");\nsubplot(2,3,4), plot(1:k,gospa_vals(1:k,2)), title(\"GOSPA Localisation\");\nsubplot(2,3,5), plot(1:k,gospa_vals(1:k,3)), title(\"GOSPA Missed\");\nsubplot(2,3,6), plot(1:k,gospa_vals(1:k,4)), title(\"GOSPA False\");", "meta": {"author": "sglvladi", "repo": "TrackingX", "sha": "f737445c070f0d7d470f52f8a2b5540d5bb682da", "save_path": "github-repos/MATLAB/sglvladi-TrackingX", "path": "github-repos/MATLAB/sglvladi-TrackingX/TrackingX-f737445c070f0d7d470f52f8a2b5540d5bb682da/TrackInitiators/LLR_TrackInitiatorX/Example/example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.6187804407739559, "lm_q1q2_score": 0.493902360208512}} {"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\u03b1,\n% Diversity\u03b1, and (Entropy+Diversity)\u03b1 operate on the top or bottom \u03b1 percent of the candidate\u2019s patches based on the majority\n% prediction as described in Sec. 3.3. In this illustration, we choose \u03b1 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": "% MatrixUser, a multi-dimensional matrix analysis software package\n% https://sourceforge.net/projects/matrixuser/\n% \n% The MatrixUser is a matrix analysis software package developed under Matlab\n% Graphical User Interface Developing Environment (GUIDE). It features \n% functions that are designed and optimized for working with multi-dimensional\n% matrix under Matlab. These functions typically includes functions for \n% multi-dimensional matrix display, matrix (image stack) analysis and matrix \n% processing.\n%\n% Author:\n% Fang Liu \n% University of Wisconsin-Madison\n% Aug-30-2014\n\n\n\n% display montage\nfunction MU_dispMontage(Temp,Event,Disp_Matrix,handles)\n \n % Montage slice selection checking\n if str2num(get(handles.Sli_from,'String'))>str2num(get(handles.Sli_to,'String'))\n errordlg('No slice is chosen for creating montage !');\n return;\n end\n if str2num(get(handles.Sli_from,'String'))<1\n set(handles.Sli_from,'String','1')\n return;\n end\n if str2num(get(handles.Sli_to,'String'))>handles.V.Layer\n set(handles.Sli_to,'String',num2str(handles.V.Layer))\n return;\n end\n\n % Montage layout initialization\n [Row,Column,Layer]=size(Disp_Matrix);\n ind=0;\n b_flag=0;\n for i=1:str2num(get(handles.Mont_row,'String'))\n for j=1:str2num(get(handles.Mont_col,'String'))\n DMatrix((i-1)*Row+1:i*Row,(j-1)*Column+1:j*Column)=Disp_Matrix(:,:,str2num(get(handles.Sli_from,'String'))+ind);\n ind=ind+1;\n if ind>str2num(get(handles.Sli_to,'String'))-str2num(get(handles.Sli_from,'String'))\n b_flag=1;\n break;\n end\n end\n if b_flag==1\n break;\n end\n end\n \n\n %-------------------------Windows Contrast Change\n Color_map=handles.V.Color_map;\n Contrast_Low=handles.V.C_lower;\n Contrast_High=handles.V.C_upper;\n Contrast_Change=0;\n point=[0 0];\n point2=[0 0];\n Contrast_Interval=(Contrast_High-Contrast_Low)/100;\n %-------------------------End\n\n delete(handles.Cre_Mont);\n figure ('KeyReleaseFcn',@WindowKeyRelease,'KeyPressFcn',@WindowKeyPress, 'WindowScrollWheelFcn',@MouseScrollWheel,...\n 'WindowButtonUpFcn',@MouseUp,'WindowButtonDownFcn', @MouseClick,'Name',['Display ' handles.V.Current_matrix ' Montage']);\n imagesc(DMatrix,[Contrast_Low Contrast_High]);\n colormap(Color_map);\n colorbar;\n\n \n \n function MouseScrollWheel (Temp, Event)\n if Contrast_Change==-1\n Contrast_Low=Contrast_Low + Event.VerticalScrollCount*Contrast_Interval;\n end\n if Contrast_Change==1\n Contrast_High=Contrast_High + Event.VerticalScrollCount*Contrast_Interval;\n end\n \n imagesc (DMatrix,[Contrast_Low Contrast_High]); \n colormap(Color_map);\n colorbar;\n \n end\n\n function MouseClick(Temp,Event)\n tpoint=get(gca,'currentpoint');\n point=[round(tpoint(1)),round(tpoint(3))];\n\n end\n \n function MouseUp(Temp,Event)\n tpoint2=get(gca,'currentpoint');\n point2=[round(tpoint2(1)),round(tpoint2(3))];\n \n if sum(abs(point2-point))~=0\n rectangle('Position',[point(1),point(2),point2(1)-point(1),point2(2)-point(2)],'EdgeColor',[0 1 0]);\n DispS=DMatrix(point(2):point2(2),point(1):point2(1));\n DispS=DispS(:);\n tmean=mean(double(DispS));\n tstd=std(double(DispS));\n xlabel(['ROI mean:' num2str(tmean) ' ROI std:' num2str(tstd) ' RSD(%):' num2str(abs(tstd./tmean)*100)],'FontSize',18);\n end\n end\n \n function WindowKeyPress(Temp,Event)\n %------------------------------Windows Contrast Change\n if Event.Character=='l'\n Contrast_Change=-1;\n elseif Event.Character=='u'\n Contrast_Change=1;\n end\n %------------------------------End\n end\n \n function WindowKeyRelease(Temp,Event)\n Contrast_Change=0;\n end\n\nend\n\n\n\n\n", "meta": {"author": "leoliuf", "repo": "MRiLab", "sha": "5cdcf1f7b67759700685d3a26ffeb70e55325567", "save_path": "github-repos/MATLAB/leoliuf-MRiLab", "path": "github-repos/MATLAB/leoliuf-MRiLab/MRiLab-5cdcf1f7b67759700685d3a26ffeb70e55325567/External/MatrixUser2.2/Src/Main/MU_dispMontage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.4938864805000204}} {"text": "function plot_large_point_cloud(P,fig,ms,rel)\n\n% Plots a random subset of a large point cloud. The user specifies the\n% relative size of the subset (input \"rel\" given as in percentage points).\n%\n% Inputs:\n% P Point cloud\n% fig Figure number\n% ms Marker size\n% rel Subset size in percentage points (%). \n% E.g. if rel = 12, then about 12 % poinst are plotted\n\nrel = 0.5/(1-rel/100); % Compute a coeffiecient\n\nI = logical(round(rel*rand(size(P,1),1)));\nplot_point_cloud(P(I,:),fig,ms)", "meta": {"author": "InverseTampere", "repo": "TreeQSM", "sha": "6630bbf516f8b53adb7d60a2cccbd21e6fe51226", "save_path": "github-repos/MATLAB/InverseTampere-TreeQSM", "path": "github-repos/MATLAB/InverseTampere-TreeQSM/TreeQSM-6630bbf516f8b53adb7d60a2cccbd21e6fe51226/src/plotting/plot_large_point_cloud.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.4938864805000203}} {"text": "function rs = minus(s1,s2)\n\n%tstoolbox/@signal/minus\n% Syntax:\n% * rs=minus(s, offset)\n% * rs=minus(s1,s2)\n%\n% Input arguments:\n% * s, s1, s2 - signal object\n% * offset - scalar value\n%\n% Calculate difference of signals s1 and s2 or substract a scalar value\n% from s.\n%\n% Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt\n\nnarginchk(2,2);\n\nif isa(s2, 'signal')\n\tc = s1.core - s2.core;\n%\td = merge(s1.description, s2.description);\n\trs = signal(c, s1);\n%\trs.description = d;\n\trs = addhistory(rs, ['Subtracted second signal from first signal']);\n\trs = addcommandlines(rs, 's = minus(s, s2');\nelseif isa(s2, 'double') \n\tif size(s2)==[1 1]\n\t\tc = core(data(s1)-s2);\n\t\trs = signal(c, s1);\n\t\trs = addhistory(rs, ['Subtracted ' num2str(s2) ' from signal']);\n\t\trs = addcommandlines(rs, 's = minus(s', s2);\n\telse\n\t \terror('second argument must be a signal or a scalar');\n\tend\nelse\n\terror('second argument must be a signal or a scalar');\nend\n\n", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Toolboxes/OpenTSTOOL/tstoolbox/@signal/minus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.4938864730268785}} {"text": "function arrMean = slarrmean(data, arrsiz, n, varargin)\n%SLARRMEAN Computes the mean of a set of arrays\n%\n% $ Syntax $\n% - slarrmean(arrs, arrsiz, n, ...)\n% - slarrmean(fns, arrsiz, n, ...)\n%\n% $ Arguments $\n% - arrs: the super-array consisting of all arrays\n% - fns: the file paths of all array files\n% - arrsiz: the size of each array unit. (for a column vector, it\n% is the length of the vector)\n% - n: the total number of array units\n%\n% $ Description $\n% - slarrmean(arrs, arrsiz, n, ...) computes the mean of all array units\n% with the size of each unit specified by arrsiz. If there are more \n% than one array unit, the size of arrs should be [arrsiz, n].\n%\n% - slarrmean(fns, arrsiz, n, ...) computes the mean of all array units\n% stored in the array files given in fns. Each array file stores\n% an super-array of a set of array units.\n%\n% - You can specify additional properties.\n% \\t The properties of slarrmean\n% \\h name & description\n% 'weights' & The weights of each array unit, default = []\n% \n% $ History $\n% - Created by Dahua Lin on Jul 27th, 2006\n%\n\n%% parse and verify input arguments\n\nif nargin < 3\n raise_lackinput('slarrmean', 3);\nend\n \nif isnumeric(data)\n isdirect = true;\n arrs = data;\n arrsiz = arrsiz(:)';\n if ~isequal(size(arrs), [arrsiz, n])\n error('sltoolbox:sizmismatch', ...\n 'The size of arrs (data) is invalid');\n end\n \nelseif iscell(data)\n isdirect = false;\n fns = data;\n arrsiz = arrsiz(:)';\n nfiles = numel(fns);\n \nelse\n error('sltoolbox:invalidarg', ...\n 'The first argument for slarrmean should be an numeric array or a cell array of file names');\nend\n\nopts.weights = [];\n\nopts = slparseprops(opts, varargin{:});\nhasweights = ~isempty(opts.weights);\n\nif (hasweights)\n opts.weights = opts.weights(:);\n if length(opts.weights) ~= n\n error('sltoolbox:invalidarg', ...\n 'The length of weights is inconsistent with the number of units');\n end\nend\n\n\n%% Main skeleton\n\nif isdirect\n arrMean = compute_array_sum(arrs, arrsiz, n, opts.weights);\nelse\n arrMean = zeros(arrsiz);\n c = 0; \n for i = 1 : nfiles\n curarrs = slreadarray(fns{i});\n curn = size(curarrs, length(arrsiz) + 1);\n if ~hasweights\n arrMean = arrMean + compute_array_sum(curarrs, arrsiz, curn, []);\n else\n arrMean = arrMean + compute_array_sum(curarrs, arrsiz, curn, opts.weights(c+1:c+curn));\n end\n c = c + curn;\n \n if c > n\n error('sltoolbox:sizmismatch', ...\n 'The total number of units in the set of array files is not n');\n end\n end\n \n if c ~= n\n error('sltoolbox:sizmismatch', ...\n 'The total number of units in the set of array files is not n');\n end\n \nend\n\nif ~hasweights\n arrMean = arrMean / n;\nelse\n arrMean = arrMean / sum(opts.weights);\nend\n\n\n\n%% Compute function\n\nfunction S = compute_array_sum(arrs, arrsiz, n, w)\n\nif ~isequal(size(arrs), [arrsiz, n])\n error('sltoolbox:sizmismatch', ...\n 'The size of array is not consistent as specified');\nend\n\nd = length(arrsiz);\nif isempty(w)\n S = sum(arrs, d+1);\nelse\n S = reshape(arrs, [prod(arrsiz), n]) * w;\n if d == 1\n S = reshape(S, [arrsiz, 1]);\n else\n S = reshape(S, arrsiz);\n end\nend\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "lmthang", "repo": "nmt.hybrid", "sha": "50d5c025f18ed280ff0fd2e2adce327f4170a2c3", "save_path": "github-repos/MATLAB/lmthang-nmt.hybrid", "path": "github-repos/MATLAB/lmthang-nmt.hybrid/nmt.hybrid-50d5c025f18ed280ff0fd2e2adce327f4170a2c3/code/wordsim/code/sltoolbox_r101/sltoolbox_r101/sltoolbox/subspace_ex/slarrmean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.49388647302687844}} {"text": "function [codebook,scheme] = code_OneVsAll(m)\n% Generate the codebook for multiclass classification with One-Versus-All encoding.\n%\n% codebook = code_OneVsAll(m)\n%\n% see also:\n% code, codedist_hamming\n\n% (c) SCD-KULeuven, rights & help @ http://www.esat.kuleuven.be/sista/lssvmlab\n\n\ncodebook = eye(m).*2-1;\nscheme = []; for i=1:m, scheme = [scheme 'b']; end", "meta": {"author": "peterhcharlton", "repo": "RRest", "sha": "f5022e7029c5b6d6b8159b665dccc2c8f267976e", "save_path": "github-repos/MATLAB/peterhcharlton-RRest", "path": "github-repos/MATLAB/peterhcharlton-RRest/RRest-f5022e7029c5b6d6b8159b665dccc2c8f267976e/RRest_v3.0/Algorithms/extract_resp_sig/feat_based_extraction/LSSVMlabv1_8_R2009b_R2011a/code_OneVsAll.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.4938864730268784}} {"text": "function [Y,index] = Shuffle(X)\n% [Y,index] = Shuffle(X)\n%\n% Randomly sorts X.\n% If X is a vector, sorts all of X, so Y = X(index).\n% If X is an m-by-n matrix, sorts each column of X, so\n%\tfor j=1:n, Y(:,j)=X(index(:,j),j).\n%\n% Also see SORT, Sample, Randi, and RandSample.\n%\n% xx/xx/92 dhb Wrote it.\n% 10/25/93 dhb Return index.\n% 5/25/96 dgp Made consistent with sort and \"for i=Shuffle(1:10)\"\n% 6/29/96\tdgp\t Edited comments above.\n%\n% Probably from PTB. I think this is Pelli and Brainard.\n\n% I guess rand() never returns two identical numbers.\n[null,index] = sort(rand(size(X)));\nY = X(index);\n\nreturn", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/external/pyrTools/Shuffle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6619228891883799, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.49388647052988105}} {"text": "function testvlfeatsift()\n dir='\\\\File.ceegs.ohio-state.edu\\SPIN\\UAV\\August 08, 2013\\Nikon D800\\109ND800\\';\nfn1=[dir,'DSC_1023.jpg'];\nfn2=[dir,'DSC_1024.jpg'];\nim1=imread(fn1);\nim2=imread(fn2);\nNimg1 = gaussdownsample(im1,4,[5 5],1.6);\nNimg2 = gaussdownsample(im2,4,[5 5],1.6);\n\nfigure; imshow(Nimg1);\n\nsift_mosaic(Nimg1, Nimg2); \n\nfunction Nimg = gaussdownsample(img,levels,gsize,sigma);\n%\n% Function to generate a gaussian-pyramid for the given input image\n% image is resize to width/2^(levels-1)*height/2^(levels-1)\n% Input: \n% img: input image-matrix grayscale\n% levels: number of levels of the pyramid, we only return the level\n% of the least size\n% gsize: size of the gaussian kernel [w h] ([5 5] normally provides a smooth output)\n% sigma: sigma for gaussian kernel \n% Output:\n% Nimg: the smoothed image of the smallest size\n% Usage:\n% im = imread('cameraman.tif');\n% Nimg = Gscale(im,3,[5 5],1.6);\n% figure; imshow(Nimg);\nNimg=img;\nif(levels==1)\n return;\nend\n%guassian filter with a sigma=1.6\ng = fspecial('gaussian',gsize,sigma);\n%pyramid\nfor i = 2:levels\n %perform guassian filtering\n im = imfilter(Nimg,g,'conv');\n %perform downsampling (horizontal)\n im1 = im(:,1:2:size(Nimg,2),:);\n %vertical\n im2 = im1(1:2:size(Nimg,1),:,:);\n %store it in a struct format\n Nimg = im2; \nend\n \n%End\n", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/tests/testvlfeatsift.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.4938864655537364}} {"text": "function v = null(N, prefs, nullity)\n%NULL Null space of a linear CHEBOP.\n% Z = NULL(N) returns a CHEBMATRIX with orthonormal columns which span the\n% null space of the linear CHEBOP N. That is, N(Z) has negligible elements,\n% SIZE(Z, 2) is the nullity of N, and Z'*Z = I. N may contain linear boundary\n% conditions, but they will be treated as homogeneous. The nullity is\n% determined by comparing the differential order of the system and the number\n% of supplied boundary conditions.\n%\n% NULL(N, PREFS) allows additional preferences to be passed via the \n% CHEBOPPREF, PREFS.\n%\n% NULL(n, PREFS, K) or NULL(N, K) attempts to find K null vectors. If the\n% nullity of N is determined to be less than K then a warning is thrown. This\n% is useful in situations where the nullity is known in advance and the\n% algorithm struggles to determine it automatically.\n%\n% Systems of equations are not yet supported.\n%\n% Example 1:\n% N = chebop(@(u) diff(u), [0, pi]);\n% V = null(N);\n% norm(N(V))\n%\n% Example 2:\n% N = chebop(@(x, u) 0.2*diff(u, 3) - sin(3*x).*diff(u));\n% N.rbc = 1;\n% V = null(N)\n% norm(N(V))\n% plot(V)\n%\n% See also CHEBOP/SVDS, CHEBOP/EIGS, NULL.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nif ( nargin < 3 )\n nullity = [];\nend\nif ( nargin < 2 )\n prefs = cheboppref();\nelseif ( ~isa(prefs, 'cheboppref') )\n nullity = prefs;\n prefs = cheboppref();\nend\n\n% Linearize and check whether the CHEBOP is linear:\n[L, ignored, fail] = linop(N); %#ok\nif ( fail )\n error('CHEBFUN:CHEBOP:null:nonlinear', ...\n ['The operator appears to be nonlinear.\\n', ...\n 'NULL() supports only linear CHEBOP instances.']);\nend\n\n% Determine the discretization:\nprefs = determineDiscretization(N, L, prefs);\n\n% Call LINOP/NULL:\nv = null(L, prefs, nullity);\n\n% Return a CHEBFUN rather than a CHEBMATRIX for scalar problems:\nif ( isa(v, 'chebmatrix') && all(size(v, 1) == 1) )\n v = chebfun(v);\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/@chebop/null.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.49388646307458867}} {"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 outsig = signal_from_spectrum(amplitude,phase,f,dim,conf)\n%SIGNAL_FROM_SPECTRUM time signal from single-sided spectrum\n%\n% Usage: outsig = signal_from_spectrum(amplitude,phase,f,[dim],conf)\n%\n% Input parameters:\n% amplitude - the single-sided amplitude spectrum\n% phase - the single-sided phase spectrum / rad\n% f - the corresponding frequency vector\n% dim - dimension along which the ifft is performed\n% conf - configuration struct (see SFS_config)\n%\n% Output parameters:\n% outsig - one channel audio (time) signal\n%\n% SIGNAL_FROM_SPECTRUM(amplitude,phase,f,conf) generates the time signal from\n% single-sided amplitude and phase spectra using ifft. It is the counterpart\n% of SPECTRUM_FROM_SIGNAL and not interchangeable with calling ifft.\n%\n% See also: spectrum_from_signal, ifft\n\n%*****************************************************************************\n% The MIT License (MIT) *\n% *\n% Copyright (c) 2010-2019 SFS Toolbox Developers *\n% *\n% Permission is hereby granted, free of charge, to any person obtaining a *\n% copy of this software and associated documentation files (the \"Software\"), *\n% to deal in the Software without restriction, including without limitation *\n% the rights to use, copy, modify, merge, publish, distribute, sublicense, *\n% and/or sell copies of the Software, and to permit persons to whom the *\n% Software is furnished to do so, subject to the following conditions: *\n% *\n% The above copyright notice and this permission notice shall be included in *\n% all copies or substantial portions of the Software. *\n% *\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *\n% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *\n% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *\n% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *\n% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *\n% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *\n% DEALINGS IN THE SOFTWARE. *\n% *\n% The SFS Toolbox allows to simulate and investigate sound field synthesis *\n% methods like wave field synthesis or higher order ambisonics. *\n% *\n% https://sfs.readthedocs.io sfstoolbox@gmail.com *\n%*****************************************************************************\n\n\n%% ===== Checking input arguments ========================================\nnargmin = 4;\nnargmax = 5;\nnarginchk(nargmin,nargmax);\nif nargin == nargmin\n conf = dim;\n dim = find(size(amplitude)~=1, 1); % find first non-singleton dimension \nelse \n isargpositivescalar(dim); \nend\nisargstruct(conf);\n\nNdims = ndims(amplitude);\ndim = min(dim,Ndims);\namplitude = permute(amplitude, [dim:Ndims, 1:dim-1]); % move dim to first dimension\nphase = permute(phase, [dim:Ndims, 1:dim-1]); % move dim to first dimension\ns = size(amplitude);\nNx = s(1);\namplitude = reshape(amplitude, Nx, []); % squeeze all other dimensions\nphase = reshape(phase, Nx, []); % squeeze all other dimensions\n\n%% ===== Configuration ===================================================\nfs = conf.fs;\n\n\n%% ===== Regenerating wave form from spectrum ============================\n% Provided number of frequency bins\nbins = length(f);\nif bins ~= Nx\n error('%s: size of spectrum does not match length of frequency vector',...\n upper(mfilename));\nend\n\nif f(end) == fs/2 % -> even time signal length\n % Length of the signal to generate\n samples = 2 * (bins-1);\n % Rescaling (see spectrum_from_signal())\n amplitude = [amplitude(1,:); amplitude(2:end-1,:)/2; amplitude(end,:)] ...\n * samples;\n % Mirror the amplitude spectrum ( 2*pi periodic [0, fs[ )\n amplitude = [amplitude; amplitude(end-1:-1:2,:)];\n % Mirror the phase spectrum and build the inverse (complex conjugate)\n phase = [phase; -1 * phase(end-1:-1:2,:)];\n\nelse % -> odd time signal length\n % Length of the signal to generate\n samples = 2*bins - 1;\n % Rescaling (see signal_from_spectrum)\n amplitude = [amplitude(1,:); amplitude(2:end,:)/2] * samples;\n % Mirror the amplitude spectrum ( 2*pi periodic [0, fs-bin] )\n amplitude = [amplitude; amplitude(end:-1:2,:)];\n % Mirror the phase spectrum and build the inverse (complex conjugate)\n phase = [phase; -1*phase(end:-1:2,:)];\nend\n\n% Convert to complex spectrum\ncompspec = amplitude .* exp(1i*phase);\n\n% Build the inverse fft and assume spectrum is conjugate symmetric\noutsig = real(ifft(compspec));\n\n\n%% ===== Output ==========================================================\n% undo reshape and permute\noutsig = reshape(outsig, [samples, s(2:end)]);\noutsig = permute(outsig, [Ndims-dim+2:Ndims, 1:Ndims-dim+1]); \n", "meta": {"author": "sfstoolbox", "repo": "sfs-matlab", "sha": "02194f0243d1ead26572f760032c40527718919d", "save_path": "github-repos/MATLAB/sfstoolbox-sfs-matlab", "path": "github-repos/MATLAB/sfstoolbox-sfs-matlab/sfs-matlab-02194f0243d1ead26572f760032c40527718919d/SFS_general/signal_from_spectrum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4937592526151671}} {"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": "function [pvec, pstruct] = tapas_ph_binary_transp(r, ptrans)\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2015 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\npvec = NaN(1,length(ptrans));\npstruct = struct;\n\npvec(1) = tapas_sgm(ptrans(1),1); % v_0\npstruct.v_0 = pvec(1);\npvec(2) = tapas_sgm(ptrans(2),1); % al_0\npstruct.al_0 = pvec(2);\npvec(3) = exp(ptrans(3)); % S\npstruct.S = pvec(3);\n\nreturn;", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/HGF/tapas_ph_binary_transp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.493676199946273}} {"text": "function [b,R,t,s] = FitEdges( im,xp,landmarks,shapePC,shapeMU,shapeEV,Ef,Ev,tri,ndims,w_prior, w_edges, w_landmarks,niter )\n%FITEDGES Perform morphable model fitting using edges\n% This function initialises by fitting to a sparse set of landmarks, then\n% iteratively fits to edges by finding nearest neighbour between\n% projected model edges and image edges\n%\n% Inputs:\n% im - Image to fit to\n% xp - 2 by nlandmarks matrix containing locations of 2D landmarks\n% landmarks - Indices of vertices corresponding to points in xp\n% shapePC - 3DMM principal components\n% shapeMU - 3DMM average shape\n% shapeEV - standard deviations of each 3DMM dimension\n% Ef - nedges by 2 matrix storing faces adjacent to each edge\n% Ev - nedges by 2 matrix storing vertices adjacent to each edge\n% tri - Face structure of 3DMM mesh\n% ndims - Number of model dimensions to use\n% numsd - Hard limit on number of standard deviations each parameter\n% may deviate\n%\n% Outputs:\n% b - Estimated shape parameters\n% R,t,s - Estimated rotation, translation and scale of face\n\nFV.faces = tri;\n% PARAMETERS\n% Number of model dimensions used for initial landmark fit\n%ndims = 40;\n% Number of edge fitting iterations (may want to replace with a convergence\n% test)\n%niter = 1;\n% Proportion of nearest-neighbour edge matches used at each iteration, may\n% be more sensible to threshold on distance to nearest neighbour\npercentile = 1;\n\n% Perform initial landmark-only fit\n%w_prior = 0.7;\n[b,R,t,s] = FitSingleSOP( xp,shapePC,shapeMU,shapeEV,ndims,landmarks,w_prior );\n%b=zeros(20,1);\nFV.vertices = reshape(shapePC(:,1:ndims)*b+shapeMU,3,size(shapePC,1)/3)';\n\n% Display input image\n%figure; imshow(im);\n\n% Extract image edges\nedges = edge(rgb2gray(im),'canny',0.15);\n%figure; imshow(edges);\n\n% Store pixel locations of edges\n[r,c]=find(edges);\nr = size(edges,1)+1-r;\n%bold=b;\nfor iter=1:niter\n % Compute vertices lying on occluding boundary\n [ occludingVertices ] = occludingBoundaryVertices( FV,Ef,Ev,R );\n \n % Project occluding boundary vertices\n x2 = R*FV.vertices(occludingVertices,:)';\n x2 = x2(1:2,:);\n x2(1,:) = x2(1,:)+t(1);\n x2(2,:) = x2(2,:)+t(2);\n x2 = x2.*s;\n \n % Find edge correspondences\n [idx,d] = knnsearch([c r],x2'); %its correct, searching based on columns dont change!\n\n % Filter edge matches - probably want to do something better here\n sortedd=sort(d);\n threshold = sortedd(round(percentile*length(sortedd)));\n idx = idx(d 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": "%**************************************************************\n%* mex interface to Andy Liaw et al.'s C code (used in R package randomForest)\n%* Added by Abhishek Jaiantilal ( abhishek.jaiantilal@colorado.edu )\n%* License: GPLv2\n%* Version: 0.02\n%\n% Calls Classification Random Forest\n% A wrapper matlab file that calls the mex file\n% This does training given the data and labels \n% Documentation copied from R-packages pdf \n% http://cran.r-project.org/web/packages/randomForest/randomForest.pdf \n% Tutorial on getting this working in tutorial_ClassRF.m\n%**************************************************************\n% function model = classRF_train(X,Y,ntree,mtry, extra_options)\n% \n%___Options\n% requires 2 arguments and the rest 3 are optional\n% X: data matrix\n% Y: target values \n% ntree (optional): number of trees (default is 500). also if set to 0\n% will default to 500\n% mtry (default is floor(sqrt(size(X,2))) D=number of features in X). also if set to 0\n% will default to 500\n%\n%\n% Note: TRUE = 1 and FALSE = 0 below\n% extra_options represent a structure containing various misc. options to\n% control the RF\n% extra_options.replace = 0 or 1 (default is 1) sampling with or without\n% replacement\n% extra_options.classwt = priors of classes. Here the function first gets\n% the labels in ascending order and assumes the\n% priors are given in the same order. So if the class\n% labels are [-1 1 2] and classwt is [0.1 2 3] then\n% there is a 1-1 correspondence. (ascending order of\n% class labels). Once this is set the freq of labels in\n% train data also affects.\n% extra_options.cutoff (Classification only) = A vector of length equal to number of classes. The ?winning?\n% class for an observation is the one with the maximum ratio of proportion\n% of votes to cutoff. Default is 1/k where k is the number of classes (i.e., majority\n% vote wins). \n% extra_options.strata = (not yet stable in code) variable that is used for stratified\n% sampling. I don't yet know how this works. Disabled\n% by default\n% extra_options.sampsize = Size(s) of sample to draw. For classification, \n% if sampsize is a vector of the length the number of strata, then sampling is stratified by strata, \n% and the elements of sampsize indicate the numbers to be\n% drawn from the strata. \n% extra_options.nodesize = Minimum size of terminal nodes. Setting this number larger causes smaller trees\n% to be grown (and thus take less time). Note that the default values are different\n% for classification (1) and regression (5).\n% extra_options.importance = Should importance of predictors be assessed?\n% extra_options.localImp = Should casewise importance measure be computed? (Setting this to TRUE will\n% override importance.)\n% extra_options.proximity = Should proximity measure among the rows be calculated?\n% extra_options.oob_prox = Should proximity be calculated only on 'out-of-bag' data?\n% extra_options.do_trace = If set to TRUE, give a more verbose output as randomForest is run. If set to\n% some integer, then running output is printed for every\n% do_trace trees.\n% extra_options.keep_inbag Should an n by ntree matrix be returned that keeps track of which samples are\n% 'in-bag' in which trees (but not how many times, if sampling with replacement)\n%\n% Options eliminated\n% corr_bias which happens only for regression ommitted\n% norm_votes - always set to return total votes for each class.\n%\n%___Returns model which has\n% importance = a matrix with nclass + 2 (for classification) or two (for regression) columns.\n% For classification, the first nclass columns are the class-specific measures\n% computed as mean decrease in accuracy. The nclass + 1st column is the\n% mean decrease in accuracy over all classes. The last column is the mean decrease\n% in Gini index. For Regression, the first column is the mean decrease in\n% accuracy and the second the mean decrease in MSE. If importance=FALSE,\n% the last measure is still returned as a vector.\n% importanceSD = The ?standard errors? of the permutation-based importance measure. For classification,\n% a p by nclass + 1 matrix corresponding to the first nclass + 1\n% columns of the importance matrix. For regression, a length p vector.\n% localImp = a p by n matrix containing the casewise importance measures, the [i,j] element\n% of which is the importance of i-th variable on the j-th case. NULL if\n% localImp=FALSE.\n% ntree = number of trees grown.\n% mtry = number of predictors sampled for spliting at each node.\n% votes (classification only) a matrix with one row for each input data point and one\n% column for each class, giving the fraction or number of ?votes? from the random\n% forest.\n% oob_times number of times cases are 'out-of-bag' (and thus used in computing OOB error\n% estimate)\n% proximity if proximity=TRUE when randomForest is called, a matrix of proximity\n% measures among the input (based on the frequency that pairs of data points are\n% in the same terminal nodes).\n% errtr = first column is OOB Err rate, second is for class 1 and so on\n\nfunction model=classRF_train(X,Y,ntree,mtry, extra_options)\n DEFAULTS_ON =0;\n %DEBUG_ON=0;\n\n TRUE=1;\n FALSE=0;\n \n orig_labels = sort(unique(Y));\n Y_new = Y;\n new_labels = 1:length(orig_labels);\n \n for i=1:length(orig_labels)\n Y_new(find(Y==orig_labels(i)))=Inf;\n Y_new(isinf(Y_new))=new_labels(i);\n end\n \n Y = Y_new;\n \n if exist('extra_options','var')\n if isfield(extra_options,'DEBUG_ON'); DEBUG_ON = extra_options.DEBUG_ON; end\n if isfield(extra_options,'replace'); replace = extra_options.replace; end\n if isfield(extra_options,'classwt'); classwt = extra_options.classwt; end\n if isfield(extra_options,'cutoff'); cutoff = extra_options.cutoff; end\n if isfield(extra_options,'strata'); strata = extra_options.strata; end\n if isfield(extra_options,'sampsize'); sampsize = extra_options.sampsize; end\n if isfield(extra_options,'nodesize'); nodesize = extra_options.nodesize; end\n if isfield(extra_options,'importance'); importance = extra_options.importance; end\n if isfield(extra_options,'localImp'); localImp = extra_options.localImp; end\n if isfield(extra_options,'nPerm'); nPerm = extra_options.nPerm; end\n if isfield(extra_options,'proximity'); proximity = extra_options.proximity; end\n if isfield(extra_options,'oob_prox'); oob_prox = extra_options.oob_prox; end\n %if isfield(extra_options,'norm_votes'); norm_votes = extra_options.norm_votes; end\n if isfield(extra_options,'do_trace'); do_trace = extra_options.do_trace; end\n %if isfield(extra_options,'corr_bias'); corr_bias = extra_options.corr_bias; end\n if isfield(extra_options,'keep_inbag'); keep_inbag = extra_options.keep_inbag; end\n end\n keep_forest=1; %always save the trees :)\n \n %set defaults if not already set\n if ~exist('DEBUG_ON','var') DEBUG_ON=FALSE; end\n if ~exist('replace','var'); replace = TRUE; end\n %if ~exist('classwt','var'); classwt = []; end %will handle these three later\n %if ~exist('cutoff','var'); cutoff = 1; end \n %if ~exist('strata','var'); strata = 1; end\n if ~exist('sampsize','var'); \n if (replace) \n sampsize = size(X,1); \n else\n sampsize = ceil(0.632*size(X,1));\n end; \n end\n if ~exist('nodesize','var'); nodesize = 1; end %classification=1, regression=5\n if ~exist('importance','var'); importance = FALSE; end\n if ~exist('localImp','var'); localImp = FALSE; end\n if ~exist('nPerm','var'); nPerm = 1; end\n %if ~exist('proximity','var'); proximity = 1; end %will handle these two later\n %if ~exist('oob_prox','var'); oob_prox = 1; end\n %if ~exist('norm_votes','var'); norm_votes = TRUE; end\n if ~exist('do_trace','var'); do_trace = FALSE; end\n %if ~exist('corr_bias','var'); corr_bias = FALSE; end\n if ~exist('keep_inbag','var'); keep_inbag = FALSE; end\n \n\n if ~exist('ntree','var') | ntree<=0\n\t\tntree=500;\n DEFAULTS_ON=1;\n end\n if ~exist('mtry','var') | mtry<=0 | mtry>size(X,2)\n mtry =floor(sqrt(size(X,2)));\n end\n \n addclass =isempty(Y);\n \n if (~addclass && length(unique(Y))<2)\n error('need atleast two classes for classification');\n end\n [N D] = size(X);\n \n if N==0; error(' data (X) has 0 rows');end\n \n if (mtry <1 || mtry > D)\n DEFAULTS_ON=1;\n end\n \n mtry = max(1,min(D,round(mtry)));\n \n if DEFAULTS_ON\n fprintf('\\tSetting to defaults %d trees and mtry=%d\\n',ntree,mtry);\n end\n \n if ~isempty(Y)\n if length(Y)~=N, \n error('Y size is not the same as X size'); \n end\n addclass = FALSE;\n else\n if ~addclass, \n addclass=TRUE;\n end\n error('have to fill stuff here')\n end\n \n if ~isempty(find(isnan(X))); error('NaNs in X'); end\n if ~isempty(find(isnan(Y))); error('NaNs in Y'); end\n \n %now handle categories. Problem is that categories in R are more\n %enhanced. In this i ask the user to specify the column/features to\n %consider as categories, 1 if all the values are real values else\n %specify the number of categories here\n if exist ('extra_options','var') && isfield(extra_options,'categories')\n ncat = extra_options.categories; \n else\n ncat = ones(1,D);\n end\n \n maxcat = max(ncat);\n if maxcat>32\n error('Can not handle categorical predictors with more than 32 categories');\n end\n\n %classRF - line 88 in randomForest.default.R\n nclass = length(unique(Y));\n if ~exist('cutoff','var') \n cutoff = ones(1,nclass)* (1/nclass);\n else\n if sum(cutoff)>1 || sum(cutoff)<0 || length(find(cutoff<=0))>0 || length(cutoff)~=nclass\n error('Incorrect cutoff specified');\n end\n end\n if ~exist('classwt','var')\n classwt = ones(1,nclass);\n ipi=0;\n else\n if length(classwt)~=nclass\n error('Length of classwt not equal to the number of classes')\n end\n if ~isempty(find(classwt<=0))\n error('classwt must be positive');\n end\n ipi=1;\n end\n\n if ~exist('proximity','var')\n proximity = addclass;\n oob_prox = proximity;\n end\n \n if ~exist('oob_prox','var')\n oob_prox = proximity;\n end\n \n %i handle the below in the mex file\n% if proximity\n% prox = zeros(N,N);\n% proxts = 1;\n% else\n% prox = 1;\n% proxts = 1;\n% end\n \n %i handle the below in the mex file\n if localImp\n importance = TRUE;\n% impmat = zeors(D,N);\n else\n% impmat = 1;\n end\n \n if importance\n if (nPerm<1)\n nPerm = int32(1);\n else\n nPerm = int32(nPerm);\n end\n \n %classRF\n% impout = zeros(D,nclass+2);\n% impSD = zeros(D,nclass+1);\n else\n% impout = zeros(D,1);\n% impSD = 1;\n end\n \n %i handle the below in the mex file\n %somewhere near line 157 in randomForest.default.R\n if addclass\n% nsample = 2*n;\n else\n% nsample = n;\n end\n \n Stratify = (length(sampsize)>1);\n if (~Stratify && sampsize>N) \n error('Sampsize too large')\n end\n \n if Stratify\n if ~exist('strata','var')\n strata = Y;\n end\n nsum = sum(sampsize);\n if ( ~isempty(find(sampsize<=0)) || nsum==0)\n error('Bad sampsize specification');\n end\n else\n nsum = sampsize;\n end\n %i handle the below in the mex file\n %nrnodes = 2*floor(nsum/nodesize)+1;\n %xtest = 1;\n %ytest = 1;\n %ntest = 1;\n %labelts = FALSE;\n %nt = ntree;\n \n \n \n \n\t%[ldau,rdau,nodestatus,nrnodes,upper,avnode,mbest,ndtree]=\n %keyboard\n \n \n \n if Stratify\n strata = int32(strata);\n else\n strata = int32(1);\n end\n \n Options = int32([addclass, importance, localImp, proximity, oob_prox, do_trace, keep_forest, replace, Stratify, keep_inbag]);\n\n \n if DEBUG_ON\n %print the parameters that i am sending in\n fprintf('size(x) %d\\n',size(X));\n fprintf('size(y) %d\\n',size(Y));\n fprintf('nclass %d\\n',nclass);\n fprintf('size(ncat) %d\\n',size(ncat));\n fprintf('maxcat %d\\n',maxcat);\n fprintf('size(sampsize) %d\\n',size(sampsize));\n fprintf('sampsize[0] %d\\n',sampsize(1));\n fprintf('Stratify %d\\n',Stratify);\n fprintf('Proximity %d\\n',proximity);\n fprintf('oob_prox %d\\n',oob_prox);\n fprintf('strata %d\\n',strata);\n fprintf('ntree %d\\n',ntree);\n fprintf('mtry %d\\n',mtry);\n fprintf('ipi %d\\n',ipi);\n fprintf('classwt %f\\n',classwt);\n fprintf('cutoff %f\\n',cutoff);\n fprintf('nodesize %f\\n',nodesize);\n end \n \n \n [nrnodes,ntree,xbestsplit,classwt,cutoff,treemap,nodestatus,nodeclass,bestvar,ndbigtree,mtry ...\n outcl, counttr, prox, impmat, impout, impSD, errtr, inbag] ...\n = mexClassRF_train(X',int32(Y_new),length(unique(Y)),ntree,mtry,int32(ncat), ... \n int32(maxcat), int32(sampsize), strata, Options, int32(ipi), ...\n classwt, cutoff, int32(nodesize),int32(nsum));\n \tmodel.nrnodes=nrnodes;\n \tmodel.ntree=ntree;\n \tmodel.xbestsplit=xbestsplit;\n \tmodel.classwt=classwt;\n \tmodel.cutoff=cutoff;\n \tmodel.treemap=treemap;\n \tmodel.nodestatus=nodestatus;\n \tmodel.nodeclass=nodeclass;\n \tmodel.bestvar = bestvar;\n \tmodel.ndbigtree = ndbigtree;\n model.mtry = mtry;\n model.orig_labels=orig_labels;\n model.new_labels=new_labels;\n model.nclass = length(unique(Y));\n model.outcl = outcl;\n model.counttr = counttr;\n if proximity\n model.proximity = prox;\n else\n model.proximity = [];\n end\n model.localImp = impmat;\n model.importance = impout;\n model.importanceSD = impSD;\n model.errtr = errtr';\n model.inbag = inbag;\n model.votes = counttr';\n model.oob_times = sum(counttr)';\n \tclear mexClassRF_train\n %keyboard\n 1;\n\n", "meta": {"author": "chaoma99", "repo": "sr-metric", "sha": "51218dbd5a1a5827cec9259b2fe0024b0b8702d4", "save_path": "github-repos/MATLAB/chaoma99-sr-metric", "path": "github-repos/MATLAB/chaoma99-sr-metric/sr-metric-51218dbd5a1a5827cec9259b2fe0024b0b8702d4/external/randomforest-matlab/RF_Class_C/classRF_train.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.4936655933482885}} {"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": "classdef NonLinear_Solver < handle\n\n properties (Access = public)\n end\n\n properties (Access = private)\n tol\n state\n solver\n element\n free_dof\n end\n\n methods (Access = public)\n\n function obj = NonLinear_Solver(cParams)\n obj.init(cParams);\n obj.createSolver();\n end\n\n function x = solve(obj, params)\n switch params.state\n case 'Steady'\n x = obj.solveSteady();\n case 'Transient'\n x = obj.solveTransient(params);\n end\n end\n\n end\n\n methods (Access = private)\n\n function init(obj,cParams)\n obj.tol = cParams.tol;\n% obj.state = cParams.state;\n obj.element = cParams.element;\n obj.free_dof = cParams.free_dof;\n end\n\n function createSolver(obj)\n s.type = 'DIRECT';\n obj.solver = Solver.create(s);\n end\n\n function sol = solveSteady(obj)\n total_free_dof = sum(obj.free_dof);\n dt = Inf;\n dr = obj.element.computedr(dt);\n x0 = zeros(total_free_dof,1);\n \n r = obj.element.computeResidual(x0,dr);\n x = obj.convergeSolution(dr, r, x0);\n sol = x;\n end\n \n function sol = solveTransient(obj,params)\n dt = params.dt;\n final_time = params.final_time;\n total_free_dof = sum(obj.free_dof);\n x_n(:,1) = zeros(total_free_dof,1);\n x0 = zeros(total_free_dof,1);\n \n dr = obj.element.computedr(dt);\n \n for istep = 2: final_time/dt\n u_previous_step = x_n(1:obj.free_dof(1),istep-1);\n \n r = obj.element.computeResidual(x0,dr,u_previous_step);\n while dot(r,r) > obj.tol\n inc_x = obj.solver.solve(dr,-r);\n x = x0 + inc_x;\n % Compute r\n r = obj.element.computeResidual(x,dr,u_previous_step);\n x0 = x;\n end\n x_n(:,istep) = x;\n end\n sol = x_n;\n end\n\n function sol = convergeSolution(obj, dr, r, x0, u_previous_step)\n while dot(r,r) > obj.tol\n inc_x = obj.solver.solve(dr,-r);\n x = x0 + inc_x;\n % Compute r\n r = obj.element.computeResidual(x,dr);\n x0 = x;\n end\n sol = x0;\n end\n\n end\n\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/FEM/Solver/NonLinear_Solver.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.4935930572720869}} {"text": "function varargout = polynomialCurveSetFit(seg, varargin)\n%POLYNOMIALCURVESETFIT Fit a set of polynomial curves to a segmented image\n%\n% COEFS = polynomialCurveSetFit(IMG);\n% COEFS = polynomialCurveSetFit(IMG, DEG);\n% Result is a cell array of matrices. Each matrix is DEG+1-by-2, and\n% contains coefficients of polynomial curve for each coordinate.\n% IMG is first binarised, then skeletonized. Each cure\n%\n% [COEFS LBL] = polynomialCurveSetFit(...);\n% also returns an image of labels for the segmented curves. The max label\n% is the number of curves, and the length of COEFS.\n%\n% Requires the toolboxes:\n% - Optimization\n% - Image Processing\n%\n% Example\n% % Fit a set of curves to a binary skeleton\n% img = imread('circles.png');\n% % compute skeleton, and ensure one-pixel thickness\n% skel = bwmorph(img, 'skel', 'Inf');\n% skel = bwmorph(skel, 'shrink');\n% figure; imshow(skel==0)\n% coeffs = polynomialCurveSetFit(skel, 2);\n% % Display segmented image with curves\n% figure; imshow(~img); hold on;\n% for i = 1:length(coeffs)\n% hc = drawPolynomialCurve([0 1], coeffs{i});\n% set(hc, 'linewidth', 2, 'color', 'g');\n% end\n%\n% See also\n% polynomialCurves2d, polynomialCurveFit\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2007-03-21\n% Copyright 2007 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas.\n\n\n%% Initialisations\n\n% default degree for curves\ndeg = 2;\nif ~isempty(varargin)\n deg = varargin{1};\nend\n\n% ensure image is binary\nseg = seg > 0;\n\n\n%% Extract branching points and terminating points\n\n% compute image of end points\nimgEndPoints = imfilter(double(seg), ones([3 3])) .* seg == 2;\n\n% compute centroids of end points\nlblEndPoints = bwlabel(imgEndPoints, 4);\nregEndPoints = bwconncomp(imgEndPoints, 4);\nstruct = regionprops(regEndPoints, 'Centroid');\n\nendPoints = cat(1, struct.Centroid);\n\n\n% compute image of multiple points (intersections between curves)\nimgBranching = imfilter(double(seg), ones([3 3])) .* seg > 3;\n\n% compute coordinate of nodes, as centroids of the multiple points\nlblBranching = bwlabel(imgBranching, 4);\nregBranching = bwconncomp(imgBranching, 4);\nstruct = regionprops(regBranching, 'Centroid');\n\nbranchPoints = cat(1, struct.Centroid);\n\n\n% list of nodes (all categories)\nnodes = [branchPoints; endPoints];\n\n% image of node labels\nlblNodes = lblBranching;\nlblNodes(lblEndPoints > 0) = lblEndPoints(lblEndPoints > 0) + size(branchPoints, 1);\n\n% isolate branches\nimgBranches = seg & ~imgBranching & ~imgEndPoints;\nlblBranches = bwlabel(imgBranches, 8);\n\n% number of curves\nnBranches = max(lblBranches(:));\n\n% allocate memory\ncoefs = cell(nBranches, 1);\n\n\n% For each curve, find interpolated polynomial curve\nfor i = 1:nBranches\n %disp(i);\n \n % extract points corresponding to current curve\n imgBranch = lblBranches == i;\n points = chainPixels(imgBranch);\n \n % if number of points is not sufficient, simply create a line segment\n if size(points, 1) < max(deg+1-2, 2)\n % find labels of nodes\n inds = unique(lblNodes(imdilate(imgBranch, ones(3,3))));\n inds = inds(inds~=0);\n \n if length(inds)<2\n disp(['Could not find extremities of branch number ' num2str(i)]);\n coefs{i} = [0 0;0 0];\n continue;\n end\n \n % consider extremity nodes\n node0 = nodes(inds(1),:);\n node1 = nodes(inds(2),:);\n \n % use only a linear approximation\n xc = zeros(1, deg+1);\n yc = zeros(1, deg+1);\n xc(1) = node0(1);\n yc(1) = node0(2);\n xc(2) = node1(1)-node0(1);\n yc(2) = node1(2)-node0(2);\n \n % assigne au tableau de courbes\n coefs{i} = [xc;yc];\n \n % next branch\n continue;\n end\n\n % find nodes closest to first and last points of the current curve\n [dist, ind0] = minDistancePoints(points(1, :), nodes); %#ok<*ASGLU>\n [dist, ind1] = minDistancePoints(points(end, :), nodes);\n \n % add nodes to the curve.\n points = [nodes(ind0,:); points; nodes(ind1,:)]; %#ok\n \n % parametrization of the polyline\n t = parametrize(points);\n t = t/max(t);\n \n % fit a polynomial curve to the set of points\n [xc, yc] = polynomialCurveFit(...\n t, points, deg, ...\n 0, {points(1,1), points(1,2)},...\n 1, {points(end,1), points(end,2)});\n \n % stores result\n coefs{i} = [xc ; yc];\nend\n\n\n%% Post-processing\n\n% manage outputs\nif nargout == 1\n varargout = {coefs};\nelseif nargout == 2\n varargout = {coefs, lblBranches};\nend\n\n\n\nfunction points = chainPixels(img, varargin)\n%CHAINPIXELS return the list of points which constitute a curve on image\n% output = chainPixels(input)\n%\n% Example\n% chainPixels\n%\n% See also\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2007-03-21\n% Copyright 2007 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas.\n\n\nconn = 8;\nif ~isempty(varargin)\n conn = varargin{1};\nend\n\n% matrice de voisinage\nif conn==4\n f = [0 1 0;1 1 1;0 1 0];\nelseif conn==8\n f = ones([3 3]);\nend\n\n% find extremity points\nnb = imfilter(double(img), f).*img;\nimgEnding = nb==2 | nb==1;\n[yi, xi] = find(imgEnding);\n\n% extract coordinates of points\n[y, x] = find(img);\n\n% index of first point\nif isempty(xi)\n % take arbitrary point\n ind = 1;\nelse\n ind = find(x==xi(1) & y==yi(1));\nend\n\n% allocate memory\npoints = zeros(length(x), 2);\n\nif conn==8\n for i=1:size(points, 1)\n % avoid multiple neighbors (can happen in loops)\n ind = ind(1);\n \n % add current point to chained curve\n points(i,:) = [x(ind) y(ind)];\n\n % remove processed coordinate\n x(ind) = []; y(ind) = [];\n\n % find next candidate\n ind = find(abs(x-points(i,1))<=1 & abs(y-points(i,2))<=1);\n end\nelse\n for i=1:size(points, 1)\n % avoid multiple neighbors (can happen in loops)\n ind = ind(1);\n \n % add current point to chained curve\n points(i,:) = [x(ind) y(ind)];\n\n % remove processed coordinate\n x(ind) = []; y(ind) = [];\n\n % find next candidate\n ind = find(abs(x-points(i,1)) + abs(y-points(i,2)) <=1 );\n end\nend \n", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/matGeom/polynomialCurves2d/polynomialCurveSetFit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.4935930572720869}} {"text": "function Value = bst_units_ui(Units, Value)\n% BST_UNITS_IU: Scale values to international units (meters)\n%\n% USAGE: Value = bst_units_ui(Units, Value) % Scale values in input\n% Factor = bst_units_ui(Units) % Returns scaling factor\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2022\n\n% Supported units\nswitch strtrim(str_remove_spec_chars(lower(Units)))\n case 'mm'\n factor = 0.001;\n case 'cm'\n factor = 0.01;\n case 'm'\n factor = 1;\n otherwise\n disp(['BST> Warning: Unknown units \"' Units '\"']);\n factor = 1;\nend\n% Return scaling factor\nif (nargin < 2)\n Value = factor;\n% Apply scaling factor\nelseif (factor ~= 1)\n Value = factor .* Value;\nend\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/math/bst_units_ui.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.49359305527493746}} {"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": "%% Copyright (C) 2016 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 bessely (@var{alpha}, @var{x})\n%% Symbolic Bessel function of the second kind.\n%%\n%% Example:\n%% @example\n%% @group\n%% syms n x\n%% A = 2*bessely(n, x)\n%% @result{} A = (sym) 2\u22c5bessely(n, x)\n%% diff(A)\n%% @result{} (sym) bessely(n - 1, x) - bessely(n + 1, x)\n%% @end group\n%% @end example\n%%\n%% @seealso{@@sym/besselj, @@sym/besseli, @@sym/besselk}\n%% @end defmethod\n\nfunction Y = bessely(n, x)\n\n if (nargin ~= 2)\n print_usage ();\n end\n\n Y = elementwise_op ('bessely', sym(n), sym(x));\n\nend\n\n\n%!test\n%! X = [1 2 3; 4 5 6];\n%! ns = [sym(0) 1 -2; sym(1)/2 -sym(3)/2 pi];\n%! n = double(ns);\n%! A = double(bessely(ns, X));\n%! B = bessely(n, X);\n%! assert (all (all (abs (A - B) < 50*eps*abs(A))))\n\n%!test\n%! % roundtrip\n%! syms x\n%! A = bessely(2, 10);\n%! q = bessely(2, x);\n%! h = function_handle(q);\n%! B = h(10);\n%! assert (abs (A - B) <= eps*abs(A))\n\n%!error bessely(sym('x'))\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/bessely.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.49359304814914157}} {"text": "function determ = cheby_diff1_determinant ( n )\n\n%*****************************************************************************80\n%\n%% CHEBY_DIFF1_DETERMINANT returns the determinant of the CHEBY_DIFF1 matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 June 2003\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Output, real DETERM, the determinant.\n%\n determ = 0.0;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/cheby_diff1_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.49359303632610046}} {"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 blks = toBlocks__(im, w, mode)\n% Crop blocks with no padding\n% Set the anchor at the center of each block\nhw = floor((w-1)/2);\noffsetU = hw; offsetL = hw;\noffsetD = w - hw - 1;\noffsetR = w - hw - 1;\n\n[rows, cols, chns] = size(im);\nif strcmp(mode, 'distinct')\n step = w;\nelseif strcmp(mode, 'sliding')\n step = 1;\nelse\n error('Invalid mode');\nend\n\niiSeries = 1+offsetU:step:rows-offsetD;\njjSeries = 1+offsetL:step:cols-offsetR;\nblks = zeros(length(iiSeries) * length(jjSeries), w*w*chns);\ncnt = 1; % Counter\nfor jj = jjSeries\n for ii = iiSeries\n blks(cnt, :) = reshape(im(ii-offsetU:ii+offsetD, jj-offsetL:jj+offsetR, :), 1, []);\n cnt = cnt + 1;\n end\nend\nend", "meta": {"author": "Bobholamovic", "repo": "ChangeDetectionToolbox", "sha": "167877b866665511d9d5e7e184f964bcda5f4016", "save_path": "github-repos/MATLAB/Bobholamovic-ChangeDetectionToolbox", "path": "github-repos/MATLAB/Bobholamovic-ChangeDetectionToolbox/ChangeDetectionToolbox-167877b866665511d9d5e7e184f964bcda5f4016/+Algorithms/@PCAkMeans/toBlocks__.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.49357182892149365}} {"text": "function f = p24_f ( n, x )\n\n%*****************************************************************************80\n%\n%% P24_F evaluates the objective function for problem 24.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 31 December 2000\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Zbigniew Michalewicz,\n% Genetic Algorithms + Data Structures = Evolution Programs,\n% Third Edition,\n% Springer Verlag, 1996,\n% ISBN: 3-540-60676-9,\n% LC: QA76.618.M53.\n%\n% Parameters:\n%\n% Input, integer N, the number of variables.\n%\n% Input, real X(N), the argument of the objective function.\n%\n% Output, real F, the value of the objective function.\n%\n f = ( sum ( floor ( x(1: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/test_opt/p24_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.4935484902946163}} {"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": "% Question No: 6\n\n% Consider an image composed of small, no overlapping blobs. Segmenting the\n% blobs based on region growing.\n\nfunction regrow(x)\nf1=imread(x);\nf=double(f1);\ns=255;\nt=65; \nif numel(s)==1\n si=f==s;\n s1=s;\nelse\n si=bwmorph(s,'shrink',Inf);\n j=find(si);\n s1=f(j);\nend\nti=false(size(f));\nfor k=1:length(s1)\n sv=s1(k);\n s=abs(f-sv)<=t;\n ti=ti|s;\nend\n[g nr]=bwlabel(imreconstruct(si,ti));\nfigure,imshow(f1),title('Original Image');\nfigure,imshow(g),title('Segmented Image - Region Growing');\ndisplay('No: of regions');\nnr\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/13628-edge-detection-and-segmentation/Edge Detection and Segmentation/regrow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.4935233054555173}} {"text": "% pop_xfirws() - Design and export xfir compatible windowed sinc FIR filter\n%\n% Usage:\n% >> pop_xfirws; % pop-up window mode\n% >> [b, a] = pop_xfirws; % pop-up window mode\n% >> pop_xfirws('key1', value1, 'key2', value2, 'keyn', valuen);\n% >> [b, a] = pop_xfirws('key1', value1, 'key2', value2, 'keyn', valuen);\n%\n% Inputs:\n% 'srate' - scalar sampling rate (Hz)\n% 'fcutoff' - vector or scalar of cutoff frequency/ies (-6 dB; Hz)\n% 'forder' - scalar filter order. Mandatory even\n%\n% Optional inputs:\n% 'ftype' - char array filter type. 'bandpass', 'highpass',\n% 'lowpass', or 'bandstop' {default 'bandpass' or\n% 'lowpass', depending on number of cutoff frequencies}\n% 'wtype' - char array window type. 'rectangular', 'bartlett',\n% 'hann', 'hamming', 'blackman', or 'kaiser' {default\n% 'blackman'} \n% 'warg' - scalar kaiser beta\n% 'filename' - char array export filename\n% 'pathname' - char array export pathname {default '.'}\n%\n% Outputs:\n% b - filter coefficients\n% a - filter coefficients\n%\n% Note:\n% Window based filters' transition band width is defined by filter\n% order and window type/parameters. Stopband attenuation equals\n% passband ripple and is defined by the window type/parameters. Refer\n% to table below for typical parameters. (Windowed sinc) FIR filters\n% are zero phase in passband when shifted by the filters group delay\n% (what firfilt does). Pi phase jumps noticable in the phase reponse\n% reflect a negative frequency response and only occur in the\n% stopband.\n%\n% Beta Max stopband Max passband Max passband Transition width Mainlobe width\n% attenuation deviation ripple (dB) (normalized freq) (normalized rad freq)\n% (dB)\n% Rectangular -21 0.0891 1.552 0.9 / m* 4 * pi / m\n% Bartlett -25 0.0562 0.977 (2.9** / m) 8 * pi / m\n% Hann -44 0.0063 0.109 3.1 / m 8 * pi / m\n% Hamming -53 0.0022 0.038 3.3 / m 8 * pi / m\n% Blackman -74 0.0002 0.003 5.5 / m 12 * pi / m\n% Kaiser 5.653 -60 0.001 0.017 3.6 / m\n% Kaiser 7.857 -80 0.0001 0.002 5.0 / m\n% * m = filter order\n% ** estimate for higher m only\n%\n% Example:\n% fs = 500; tbw = 2; dev = 0.001;\n% beta = pop_kaiserbeta(dev);\n% m = pop_firwsord('kaiser', fs, tbw, dev);\n% pop_xfirws('srate', fs, 'fcutoff', [1 25], 'ftype', 'bandpass', 'wtype', 'kaiser', 'warg', beta, 'forder', m, 'filename', 'foo.fir')\n%\n% Author: Andreas Widmann, University of Leipzig, 2011\n%\n% See also:\n% firfilt, firws, pop_firwsord, pop_kaiserbeta, plotfresp, windows\n\n%123456789012345678901234567890123456789012345678901234567890123456789012\n\n% Copyright (C) 2011 Andreas Widmann, University of Leipzig, widmann@uni-leipzig.de\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\nfunction [varargout] = pop_xfirws(varargin)\n\n% Pop-up window mode\nif nargin < 1\n\n drawnow;\n ftypes = {'bandpass' 'highpass' 'lowpass' 'bandstop'};\n wtypes = {'rectangular' 'bartlett' 'hann' 'hamming' 'blackman' 'kaiser'};\n uigeom = {[1 0.75 0.75] 1 [1 0.75 0.75] [1 0.75 0.75] 1 [1 0.75 0.75] [1 0.75 0.75] [1 0.75 0.75] 1 [1 0.75 0.75]};\n uilist = {{'Style' 'text' 'String' 'Sampling frequency (Hz):'} ...\n {'Style' 'edit' 'String' '2' 'Tag' 'srateedit'} {} ...\n {} ...\n {'Style' 'text' 'String' 'Cutoff frequency(ies) [hp lp] (-6 dB; Hz):'} ...\n {'Style' 'edit' 'String' '' 'Tag' 'fcutoffedit'} {} ...\n {'Style' 'text' 'String' 'Filter type:'} ...\n {'Style' 'popupmenu' 'String' ftypes 'Tag' 'ftypepop'} {} ...\n {} ...\n {'Style' 'text' 'String' 'Window type:'} ...\n {'Style' 'popupmenu' 'String' wtypes 'Tag' 'wtypepop' 'Value' 5 'Callback' 'temp = {''off'', ''on''}; set(findobj(gcbf, ''-regexp'', ''Tag'', ''^warg''), ''Enable'', temp{double(get(gcbo, ''Value'') == 6) + 1}), set(findobj(gcbf, ''Tag'', ''wargedit''), ''String'', '''')'} {} ...\n {'Style' 'text' 'String' 'Kaiser window beta:' 'Tag' 'wargtext' 'Enable' 'off'} ...\n {'Style' 'edit' 'String' '' 'Tag' 'wargedit' 'Enable' 'off'} ...\n {'Style' 'pushbutton' 'String' 'Estimate' 'Tag' 'wargpush' 'Enable' 'off' 'Callback' @comwarg} ...\n {'Style' 'text' 'String' 'Filter order (mandatory even):'} ...\n {'Style' 'edit' 'String' '' 'Tag' 'forderedit'} ...\n {'Style' 'pushbutton' 'String' 'Estimate' 'Callback' {@comforder, wtypes}} ...\n {'Style' 'edit' 'Tag' 'devedit' 'Visible' 'off'} ...\n {} {} {'Style' 'pushbutton' 'String', 'Plot filter responses' 'Callback' {@comfresp, wtypes, ftypes}}};\n result = inputgui(uigeom, uilist, 'pophelp(''pop_firws'')', 'Filter the data -- pop_firws()');\n if isempty(result), return; end\n\n Arg = struct;\n Arg.srate = str2double(result{1});\n Arg.fcutoff = str2num(result{2});\n Arg.ftype = ftypes{result{3}};\n Arg.wtype = wtypes{result{4}};\n Arg.warg = str2num(result{5});\n Arg.forder = str2double(result{6});\n\n% Command line mode\nelse\n Arg = struct(varargin{:});\nend\n\n% Sampling rate\nif ~isfield(Arg, 'srate') || isempty(Arg.srate) % Use default\n Arg.srate = 2;\nend\n\n% Filter order and cutoff frequencies\nif ~isfield(Arg, 'fcutoff') || ~isfield(Arg, 'forder') || isempty(Arg.fcutoff) || isempty(Arg.forder)\n error('Not enough input arguments.');\nend\nfirwsArgArray = {Arg.forder sort(Arg.fcutoff / Arg.srate * 2)}; % Sorting and normalization\n\n% Filter type\nif ~isfield(Arg, 'ftype') || isempty(Arg.ftype) % Use default\n switch length(Arg.fcutoff)\n case 1\n Arg.ftype = 'lowpass';\n case 2\n Arg.ftype = 'bandpass';\n otherwise\n error('Wrong number of arguments.')\n end\nelse\n if any(strcmpi(Arg.ftype, {'bandpass' 'bandstop'})) && length(Arg.fcutoff) ~= 2\n error('Not enough input arguments.');\n elseif any(strcmpi(Arg.ftype, {'highpass' 'lowpass'})) && length(Arg.fcutoff) ~= 1\n error('Too many input arguments.');\n end\n switch Arg.ftype\n case 'bandstop'\n firwsArgArray(end + 1) = {'stop'};\n case 'highpass'\n firwsArgArray(end + 1) = {'high'};\n end\nend\n\n% Window type\nif ~isfield(Arg, 'wtype') || isempty(Arg.wtype) % Use default\n Arg.wtype = 'blackman';\nend\n\n% Window parameter\nif ~isfield(Arg, 'warg') || isempty(Arg.warg)\n Arg.warg = [];\n firwsArgArray(end + 1) = {windows(Arg.wtype, Arg.forder + 1)};\nelse\n firwsArgArray(end + 1) = {windows(Arg.wtype, Arg.forder + 1, Arg.warg)};\nend\n\nb = firws(firwsArgArray{:});\na = 1;\n\nif nargout == 0 || isfield(Arg, 'filename')\n \n % Open file\n if ~isfield(Arg, 'filename') || isempty(Arg.filename)\n [Arg.filename Arg.pathname] = uiputfile('*.fir', 'Save filter -- pop_xfirws');\n end\n if ~isfield(Arg, 'pathname') || isempty(Arg.pathname)\n Arg.pathname = '.';\n end\n [fid message] = fopen(fullfile(Arg.pathname, Arg.filename), 'w', 'l'); \n if fid == -1\n error(message)\n end\n\n % Author\n fprintf(fid, '[author]\\n');\n fprintf(fid, '%s\\n\\n', 'pop_xfirws 1.5.1');\n\n % FIR design\n fprintf(fid, '[fir design]\\n');\n fprintf(fid, 'method %s\\n', 'fourier');\n fprintf(fid, 'type %s\\n', Arg.ftype);\n fprintf(fid, 'fsample %f\\n', Arg.srate);\n fprintf(fid, 'length %d\\n', Arg.forder + 1);\n fprintf(fid, 'fcrit%d %f\\n', [1:length(Arg.fcutoff); Arg.fcutoff]);\n fprintf(fid, 'window %s %s\\n\\n', Arg.wtype, num2str(Arg.warg)); % fprintf bug\n \n % FIR\n fprintf(fid, '[fir]\\n');\n fprintf(fid, '%d\\n', Arg.forder + 1);\n fprintf(fid, '% 18.10e\\n', b);\n\n % Close file\n fclose(fid);\n\nend\n\nif nargout > 0\n varargout = {b a};\nend\n\n% Callback estimate Kaiser beta\nfunction comwarg(varargin)\n [warg, dev] = pop_kaiserbeta;\n set(findobj(gcbf, 'Tag', 'wargedit'), 'String', warg);\n set(findobj(gcbf, 'Tag', 'devedit'), 'String', dev);\n\n% Callback estimate filter order\nfunction comforder(obj, evt, wtypes)\n srate = str2double(get(findobj(gcbf, 'Tag', 'srateedit'), 'String'));\n wtype = wtypes{get(findobj(gcbf, 'Tag', 'wtypepop'), 'Value')};\n dev = str2double(get(findobj(gcbf, 'Tag', 'devedit'), 'String'));\n [forder, dev] = pop_firwsord(wtype, srate, [], dev);\n set(findobj(gcbf, 'Tag', 'forderedit'), 'String', forder);\n set(findobj(gcbf, 'Tag', 'devedit'), 'String', dev);\n\n% Callback plot filter responses\nfunction comfresp(obj, evt, wtypes, ftypes)\n Arg.srate = str2double(get(findobj(gcbf, 'Tag', 'srateedit'), 'String'));\n Arg.fcutoff = str2num(get(findobj(gcbf, 'Tag', 'fcutoffedit'), 'String'));\n Arg.ftype = ftypes{get(findobj(gcbf, 'Tag', 'ftypepop'), 'Value')};\n Arg.wtype = wtypes{get(findobj(gcbf, 'Tag', 'wtypepop'), 'Value')};\n Arg.warg = str2num(get(findobj(gcbf, 'Tag', 'wargedit'), 'String'));\n Arg.forder = str2double(get(findobj(gcbf, 'Tag', 'forderedit'), 'String'));\n xfirwsArgArray(1, :) = fieldnames(Arg);\n xfirwsArgArray(2, :) = struct2cell(Arg);\n [b a] = pop_xfirws(xfirwsArgArray{:});\n H = findobj('Tag', 'filter responses', 'type', 'figure');\n if ~isempty(H)\n figure(H);\n else\n H = figure;\n set(H, 'color', [.93 .96 1], 'Tag', 'filter responses');\n end\n plotfresp(b, a, [], Arg.srate);\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/eeglab14_0_0b/plugins/firfilt1.6.2/pop_xfirws.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.4935233054555172}} {"text": "function using_gpu()\n% Manopt example on how to use GPU with manifold factories that allow it.\n%\n% We are still working on this feature, and so far only few factories have\n% been adapted to work on GPU. But the adaptations are rather easy. If\n% there is a manifold you'd like to use on GPU, let us know via the forum\n% on http://www.manopt.org, we'll be happy to help!\n%\n% See also: spherefactory stiefelfactory grassmannfactory complexcirclefactory\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, Aug. 3, 2018.\n% Contributors: \n% Change log: \n\n\n if exist('OCTAVE_VERSION', 'builtin')\n warning('manopt:usinggpu', 'Octave does not handle GPUs at this time.');\n return;\n end\n\n if gpuDeviceCount() <= 0\n warning('manopt:usinggpu', 'No GPU available: cannot run example.');\n return;\n end\n\n % Construct a large problem to illustrate the use of GPU.\n % Below, we will compute p left-most eigenvectors of A (symmetric).\n % On a particular test computer, we found that for n = 100, 1000, CPU\n % is faster, but for n = 10000, GPU tends to be 10x faster.\n p = 3;\n n = 10000;\n A = randn(n);\n A = A+A';\n \n inner = @(U, V) U(:)'*V(:);\n \n % First, setup and run the optimization problem on the CPU.\n problem.M = grassmannfactory(n, p, 1); % 1 copy of Grassmann(n, p)\n problem.cost = @(X) .5*inner(X, A*X); % Rayleigh quotient to be minimized\n problem.egrad = @(X) A*X; % Could use caching to save here\n problem.ehess = @(X, Xdot) A*Xdot;\n X0 = problem.M.rand(); % Random initial guess\n tic_cpu = tic();\n X_cpu = trustregions(problem, X0); % run any solver\n time_cpu = toc(tic_cpu);\n \n % Then, move the data to the GPU, redefine the problem using the moved\n % data, activate the GPU flag in the factory, and run it again.\n A = gpuArray(A);\n problem.M = grassmannfactory(n, p, 1, true); % true is the GPU flag;\n problem.cost = @(X) .5*inner(X, A*X); % Code for cost and gradient etc.\n problem.egrad = @(X) A*X; % basically didn't change, but\n problem.ehess = @(X, Xdot) A*Xdot; % operates on gpuArrays now.\n X0 = gpuArray(X0);\n tic_gpu = tic();\n X_gpu = trustregions(problem, X0);\n time_gpu = toc(tic_gpu);\n \n fprintf('Total time CPU: %g\\nTotal time GPU: %g\\nSolution difference: %g\\n', ...\n time_cpu, time_gpu, norm(X_cpu - X_gpu, 'fro'));\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/examples/using_gpu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.493523301032109}} {"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 g = cos( f )\n%COS Cosine of a BALLFUN.\n% COS(F) computes the cosine of F.\n%\n% See also COSH, COS.\n\n% Copyright 2019 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\ng = compose( f, @cos ); \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/@ballfun/cos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891130942474, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4934683347896394}} {"text": "function res = imQuantile(img, q, varargin)\n%IMQUANTILE Computes value that threshold a given proportion of pixels\n%\n% RES = imQuantile(IMG, Q)\n%\n% Example\n% % compute the median value in an imag by two different ways\n% img = imread('cameraman.tif');\n% imQuantile(img, .5)\n% ans = \n% 144\n% imMedian(img)\n% ans = \n% 144\n%\n% See also\n% imHistogram, imMedian\n \n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2014-05-26, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2014 INRA - Cepia Software Platform.\n\n\nif q < 0 || q > 1\n error('Requires a quantile value between 0 and 1');\nend\n\n% compute cumulative histogram\n[h, x] = imHistogram(img);\ncs = cumsum(h);\n\n% iterate for all quantiles to compute\nres = zeros(size(q));\nfor i = 1:length(q)\n % find index of quantile\n qi = sum(h) * q(i);\n ind = find(cs > qi, 1, 'first');\n\n % coonvert to grey level\n res(i) = x(ind);\nend", "meta": {"author": "mattools", "repo": "matImage", "sha": "94d892c7beac0db32daadf2646ce37f58e894caf", "save_path": "github-repos/MATLAB/mattools-matImage", "path": "github-repos/MATLAB/mattools-matImage/matImage-94d892c7beac0db32daadf2646ce37f58e894caf/matImage/imMeasures/imQuantile.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.49344778198728184}} {"text": "function [indices, bestSqDist] = nearpoints2d(src, dst)\n%\n% [indices, bestSqDist] = nearpoints2d(src, dest)\n% \n% For each point in one set, find the nearest point in another.\n%\n%- src is a 2xM array of points\n%- dest is a 2xN array of points\n%- indices is a 1xM vector, in which each element tells which point\n% in dest is closest to the corresponding point in src. For\n% example, dest[indices[i]] is near src[i].\n%- bestSqDist is a 1xM array of the squared distance between\n% dest[indices[i]] and src[i].\n%\n% SEE ALSO: nearpoints\n% \n% HISTORY:\n% 2006.05.05 RFD wrote it.\n\nif(size(src,1)~=2) src = src'; end\nif(size(dst,1)~=2) dst = dst'; end\n\nif(size(src,1)~=2 || size(dst,1)~=2)\n error('arrays must be 2xN and 2xM!');\nend\n\nsrc = [src; zeros(size(src(1,:)))];\ndst = [dst; zeros(size(dst(1,:)))];\n[indices, bestSqDist] = nearpoints(src, dst);\nreturn;", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAnatomy/mex/nearpoints2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6959583250334525, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.4934477773240077}} {"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": "% This function performs the binary decision tree testing. \n\n% Copyright (C) 2012 Quan Wang , \n% Signal Analysis and Machine Perception Laboratory, \n% Department of Electrical, Computer, and Systems Engineering, \n% Rensselaer Polytechnic Institute, Troy, NY 12180, USA\n% \n% You are free to use this software for academic purposes if you cite our paper: \n% Q. Wang, Y. Ou, A.A. Julius, K.L. Boyer, M.J. Kim, \n% Tracking tetrahymena pyriformis cells using decision trees, \n% in: 2012 International Conference on Pattern Recognition, Tsukuba Science City, Japan.\n% \n% For commercial use, please contact the authors. \n\nfunction [y p]=decide01Tree(x,T)\n\n% x: one data sample, row vector\n% T: decision tree\n% y: resulting label\n% p: resulting probability of being label 1\n\nk=1; % node index\nd=1; % depth\nc=1; % column\n\nwhile d0.5\n y=1;\nelse\n y=0;\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/39110-binary-decision-tree/binary_decision_tree_v1.0/code/decide01Tree.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4934334859108571}} {"text": "function [league] = m2league(m)\n% Convert length from meters to leagues.\n% Chad A. Greene 2012\nleague = m*0.0002071237307458;", "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/m2league.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4934334859108571}} {"text": "function [ W, confidences, d ] = mergeBestIOU( W, confidences, mergeThreshold, d )\n\n % Get most similar windows\n if(isempty(d))\n d = squareform(pdist(W, @IOU));\n end\n [v, p] = max(d);\n [v2, p2] = max(v);\n\n % Only keep merge if their IoU >= mergeThreshold\n if(size(W,1) > 1 && v2 >= mergeThreshold)\n w1 = W(p(p2),:);\n w2 = W(p2,:);\n\n % Create merged window\n w_new = mean([w1; w2]);\n conf_new = mean([confidences(p(p2)) confidences(p2)]);\n\n % Remove old windows\n W([p(p2), p2],:) = [];\n confidences([p(p2) p2]) = [];\n\n % Remove old windows' distances\n d([p(p2) p2],:) = [];\n d(:,[p(p2) p2]) = [];\n\n % Calculate distances to new window and insert\n d_new = pdist2(w_new, W, @IOU);\n d(:,end+1) = d_new';\n d(end+1,:) = [d_new 0];\n W(end+1,:) = w_new;\n confidences(end+1) = conf_new;\n end\n \nend\n\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u68c0\u6d4b\u7b97\u6cd5/Object-Detection-CNN-master/Windows_Merging/mergeBestIOU.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931215562245, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4933427840564076}} {"text": "function obj = stat_violin(obj,varargin)\n% stat_violin display violin plots of y data for unique x\n%\n% Options can be given as 'name',value pairs:\n% - all options from see stat_density() are present:\n% 'bandwidth', 'kernel', 'npoints', 'extra_y'\n% - 'normalization': 'area' (default) all violins have the same\n% areas. With 'count', the violin areas are proportional to the number of\n% points in each category. With 'width', the maximum widths of all violins\n% are matched\n% - 'half': If set to true, only half violins are drawn, and the color\n% index determines if the left half or right hald is drawn. Useful for\n% comparing distributions across two colors.\n% - 'fill' see stat_bin()\n% - 'width' and 'dodge' see stat_summary()\n%\n% See also stat_summary(), stat_bin(), stat_density()\n\n\np=inputParser;\nmy_addParameter(p,'bandwidth',-1);\nmy_addParameter(p,'kernel','normal')\nmy_addParameter(p,'npoints',100)\nmy_addParameter(p,'extra_y',0)\nmy_addParameter(p,'normalization','area') %'count' 'width'\nmy_addParameter(p,'fill','face')\nmy_addParameter(p,'width',0.6)\nmy_addParameter(p,'dodge',0.7)\nmy_addParameter(p,'half',false)\nparse(p,varargin{:});\n\nobj.geom=vertcat(obj.geom,{@(dobj,dd)my_violin(dobj,dd,p.Results)});\nobj.results.stat_violin={};\n\nend\n\nfunction hndl=my_violin(obj,draw_data,params)\n\nx=comb(draw_data.x);\ny=comb(draw_data.y);\n\nuni_x=unique(x);\nuni_x(diff(uni_x)<1e-10)=[];\n\ndens=cell(length(uni_x),1);\ndens_pos=cell(length(uni_x),1);\n\nif params.half\n params.dodge=0;\nend\n\nif params.dodge>0\n boxw=draw_data.dodge_avl_w*params.width./(draw_data.n_colors);\nelse\n boxw=draw_data.dodge_avl_w*params.width;\nend\nboxmid=dodger(uni_x,draw_data,params.dodge);\n\n\n[face_color , face_alpha , edge_color , ~] = parse_fill (params.fill,draw_data.color);\ntemp_line_params={'LineStyle',draw_data.line_style,'Color',edge_color,'lineWidth',1};\n\n%Maximum area\nmax_area=draw_data.dodge_avl_w*(obj.var_lim.maxy-obj.var_lim.miny);\n\nif obj.handle_graphics\n lines=gobjects(1,length(uni_x));\n patches=gobjects(1,length(uni_x));\nelse\n lines=zeros(1,length(uni_x));\n patches=zeros(1,length(uni_x));\nend\n\n\nfor ind_x=1:length(uni_x)\n %And here we have a loose selection also because of\n %potential numerical errors\n ysel=y(abs(x-uni_x(ind_x))<1e-10);\n \n if ~isempty(ysel)\n \n extra_y=(max(ysel)-min(ysel))*params.extra_y;\n binranges=linspace(min(ysel)-extra_y,max(ysel)+extra_y,params.npoints);\n \n if params.bandwidth>0\n [dens{ind_x},dens_pos{ind_x}] = ksdensity(ysel,binranges,'function','pdf',...\n 'bandwidth',params.bandwidth,'kernel',params.kernel);\n else\n [dens{ind_x},dens_pos{ind_x}] = ksdensity(ysel,binranges,'function','pdf',...\n 'kernel',params.kernel);\n end\n \n area=sum(dens{ind_x})*2*(binranges(2)-binranges(1));\n \n \n switch params.normalization\n case 'area'\n %Normalized area is a third of the max available area\n dens{ind_x}=dens{ind_x}*max_area/(3*area);\n case 'count'\n %Normalized count makes area/max available area correspond to\n %n points/n total points\n dens{ind_x}=dens{ind_x}*length(ysel)*max_area/(obj.data_size*area);\n case 'width'\n %Makes maximum widths equal\n dens{ind_x}=0.5*dens{ind_x}/max(dens{ind_x});\n end\n \n \n %Adjust width\n dens{ind_x}=dens{ind_x}*boxw;\n \n \n if params.half %If in half mode\n if ~mod(draw_data.color_index,2) %We draw right half if even index\n xpatch=[boxmid(ind_x)-dens{ind_x}(1:end-1) ; ...\n boxmid(ind_x)+zeros(1,length(dens{ind_x})-1) ; ...\n boxmid(ind_x)+zeros(1,length(dens{ind_x})-1); ...\n boxmid(ind_x)-dens{ind_x}(2:end)];\n else %left half if odd\n xpatch=[boxmid(ind_x)+zeros(1,length(dens{ind_x})-1) ; ...\n boxmid(ind_x)+dens{ind_x}(1:end-1) ; ...\n boxmid(ind_x)+dens{ind_x}(2:end) ; ...\n boxmid(ind_x)+zeros(1,length(dens{ind_x})-1)];\n \n end\n \n else %Otherwise draw full violin\n xpatch=[boxmid(ind_x)-dens{ind_x}(1:end-1) ; ...\n boxmid(ind_x)+dens{ind_x}(1:end-1) ; ...\n boxmid(ind_x)+dens{ind_x}(2:end); ...\n boxmid(ind_x)-dens{ind_x}(2:end)];\n end\n \n ypatch=[dens_pos{ind_x}(1:end-1) ; ...\n dens_pos{ind_x}(1:end-1) ; ...\n dens_pos{ind_x}(2:end) ; ...\n dens_pos{ind_x}(2:end)];\n \n %Draw patch\n patches(ind_x)=patch(xpatch,ypatch,[1 1 1],'EdgeAlpha',1,'FaceColor',face_color,'EdgeColor','none','FaceAlpha',face_alpha);\n \n %Draw lines\n if params.half %If in half mode\n if ~mod(draw_data.color_index,2) %We draw right half if even index\n lines(ind_x)=line(boxmid(ind_x)-[0 dens{ind_x} 0 0] , ...\n [dens_pos{ind_x}(1) dens_pos{ind_x} dens_pos{ind_x}(end) dens_pos{ind_x}(1)],temp_line_params{:});\n \n else %left half if odd\n lines(ind_x)=line(boxmid(ind_x)+[0 dens{ind_x} 0 0] , ...\n [dens_pos{ind_x}(1) dens_pos{ind_x} dens_pos{ind_x}(end) dens_pos{ind_x}(1)],temp_line_params{:});\n end\n \n else %Otherwise draw full violin\n lines(ind_x)=line([boxmid(ind_x) dens{ind_x}+boxmid(ind_x) boxmid(ind_x) boxmid(ind_x)-fliplr(dens{ind_x}) boxmid(ind_x)] , ...\n [dens_pos{ind_x}(1) dens_pos{ind_x} dens_pos{ind_x}(end) fliplr(dens_pos{ind_x}) dens_pos{ind_x}(1)],temp_line_params{:});\n end\n \n end\n \nend\n\nobj.results.stat_violin{obj.result_ind,1}.densities=dens;\nobj.results.stat_violin{obj.result_ind,1}.densities_y=dens_pos;\nobj.results.stat_violin{obj.result_ind,1}.unique_x=uni_x;\nobj.results.stat_violin{obj.result_ind,1}.line_handle=lines;\nobj.results.stat_violin{obj.result_ind,1}.fill_handle=patches;\n\n\nend\n\n", "meta": {"author": "piermorel", "repo": "gramm", "sha": "b0fc59245c17d6fbcd86a105d893aeb745fb51e2", "save_path": "github-repos/MATLAB/piermorel-gramm", "path": "github-repos/MATLAB/piermorel-gramm/gramm-b0fc59245c17d6fbcd86a105d893aeb745fb51e2/@gramm/stat_violin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6261241842048093, "lm_q1q2_score": 0.4933427770814274}} {"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 r8vec_sorted_unique_hist_test ( )\n\n%*****************************************************************************80\n%\n%% R8VEC_SORTED_UNIQUE_HIST_TEST tests R8VEC_SORTED_UNIQUE_HIST.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n n = 30;\n tol = 0.25;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8VEC_SORTED_UNIQUE_HIST_TEST\\n' );\n fprintf ( 1, ' R8VEC_SORTED_UNIQUE_HIST makes a historgram of\\n' );\n fprintf ( 1, ' the unique entries in a real vector.\\n' );\n \n b = 0.0;\n c = n;\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Using random number seed %d\\n', seed );\n\n [ a, seed ] = r8vec_uniform_ab ( n, b, c, seed );\n \n a(1:n) = round ( a(1:n) ) + 0.5;\n\n r8vec_print ( n, a, ' Unsorted array:' );\n\n a = r8vec_sort_bubble_a ( n, a );\n\n r8vec_print ( n, a, ' Ascending sorted array:' );\n\n [ unique_num, auniq, acount ] = r8vec_sorted_unique_hist ( n, a, tol );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' R8VEC_SORTED_UNIQUE_HIST counts %d unique entries.\\n', ...\n unique_num );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Value Multiplicity\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : unique_num\n fprintf ( 1, ' %6d %12f %6d\\n', i, auniq(i), acount(i) );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8vec_sorted_unique_hist_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.4933427653484271}} {"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 best_acc = COPAR_top(dataset, N_train, k, k0, lambda, eta)\n% * function `COPAR_top(dataset, N_train, k, k0, lambda, eta)`\n% * The top function of COPAR\n% * INPUT:\n% + `dataset`: name of the dataset stored in `.mat` file in `data` folder. \n% Note that `dataset` is the file name of the `.mat`, excluding `.mat`.\n% + `N_train`: number of training samples in each class \n% + `k`: number of bases in EACH PARTICULAR dictionary \n% + `k0`: number of bases in the COMMON dictionary\n% + `lambda, eta`: regularization parameters.\n% * To run an small example, type `COPAR_top` without input in \n% MATLAB command window.\n% -----------------------------------------------\n% Author: Tiep Vu, thv102@psu.edu, 5/11/2016\n% (http://www.personal.psu.edu/thv102/)\n% -----------------------------------------------\n addpath(genpath('utils')); \n addpath(genpath('DLSI')); \n addpath(genpath('COPAR')); \n addpath('ODL')\n %% test mode \n if nargin == 0 \n dataset = 'myYaleB';\n N_train = 10;\n k = 8;\n k0 = 5;\n lambda = 0.001;\n eta = 0.01;\n end \n %% get data \n t = getTimeStr();\n [dataset, Y_train, Y_test, label_train, label_test] = ...\n train_test_split(dataset, N_train);\n %% main \n [acc, rt] = COPAR_wrapper(Y_train, label_train, Y_test , label_test, ...\n k, k0, lambda, eta);\n disp(rt);\n %% output filename \n if ~exist('results', 'dir')\n mkdir('results');\n end \n if ~exist(fullfile('results', 'COPAR'), 'dir')\n mkdir('results', 'COPAR');\n end \n fn = fullfile('results', 'COPAR', strcat(dataset, '_N_', ...\n num2str(N_train), '_k_', num2str(k), '_k0_', num2str(k0), ...\n '_l_', num2str(lambda), '_e_', num2str(eta), '_', t, '.mat'));\n disp(fn);\n save(fn, 'acc', 'rt'); \n best_acc = max(acc);\nend \n", "meta": {"author": "tiepvupsu", "repo": "DICTOL", "sha": "1a0361aa35c32d70525d06910d0e9b87997ff246", "save_path": "github-repos/MATLAB/tiepvupsu-DICTOL", "path": "github-repos/MATLAB/tiepvupsu-DICTOL/DICTOL-1a0361aa35c32d70525d06910d0e9b87997ff246/COPAR_top.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.49321214797973434}} {"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 out = ClampImg(img, a, b)\n%\n%\n% out = ClampImg(img, a, b)\n%\n%\n% Image is clamped if its values are over [a,b]\n%\n% Input:\n% -img: the input img to be clamped\n% -a: the lower bound\n% -b: the upper bound\n% \n% Output:\n% -out: output clamped image\n%\n% Copyright (C) 2011 Francesco Banterle\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n\nout = img;\n\nout(img < a) = a;\nout(img > b) = b;\n\nend\n", "meta": {"author": "banterle", "repo": "HDR_Toolbox", "sha": "a2b45dc48b7169192fb633097a83879e71a0c0f2", "save_path": "github-repos/MATLAB/banterle-HDR_Toolbox", "path": "github-repos/MATLAB/banterle-HDR_Toolbox/HDR_Toolbox-a2b45dc48b7169192fb633097a83879e71a0c0f2/source_code/util/ClampImg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.4932121369153332}} {"text": "classdef GFTTDetector < handle\n %GFTTDETECTOR Wrapping class for feature detection using the goodFeaturesToTrack function\n %\n % The function finds the most prominent corners in the image or in the\n % specified image region, as described in [Shi94]:\n %\n % 1. Function calculates the corner quality measure at every source image\n % pixel using the cv.cornerMinEigenVal or cv.cornerHarris.\n % 2. Function performs a non-maximum suppression (the local maximums in\n % `3x3` neighborhood are retained).\n % 3. The corners with the minimal eigenvalue less than\n % `QualityLevel * max_{x,y}(qualityMeasureMap(x,y))` are rejected.\n % 4. The remaining corners are sorted by the quality measure in the\n % descending order.\n % 5. Function throws away each corner for which there is a stronger\n % corner at a distance less than `maxDistance`.\n %\n % ## References\n % [Shi94]:\n % > Jianbo Shi and Carlo Tomasi. \"Good features to track\".\n % > In Computer Vision and Pattern Recognition, 1994. Proceedings CVPR'94.,\n % > 1994 IEEE Computer Society Conference on, pages 593-600. IEEE, 1994.\n %\n % See also: cv.goodFeaturesToTrack, cv.cornerHarris, cv.cornerMinEigenVal,\n % cv.FeatureDetector\n %\n\n properties (SetAccess = private)\n % Object ID\n id\n end\n\n properties (Dependent)\n % Maximum number of corners to return.\n %\n % If there are more corners than are found, the strongest of them is\n % returned. Default 1000\n MaxFeatures\n % Parameter characterizing the minimal accepted quality of image\n % corners.\n %\n % The parameter value is multiplied by the best corner quality\n % which is the minimal eigenvalue (see cv.cornerMinEigenVal) or the\n % Harris function response (see cv.cornerHarris). The corners with the\n % quality measure less than the product are rejected. For example, if\n % the best corner has the quality measure = 1500, and the\n % `QualityLevel=0.01`, then all the corners with the quality measure\n % less than 15 are rejected. Default 0.01\n QualityLevel\n % Minimum possible Euclidean distance between the returned corners.\n %\n % Default 1.0\n MinDistance\n % Size of an average block for computing a derivative covariation\n % matrix over each pixel neighborhood.\n %\n % See cv.cornerEigenValsAndVecs. Default 3\n BlockSize\n % Parameter indicating whether to use a Harris detector\n % (see cv.cornerHarris) or cv.cornerMinEigenVal.\n %\n % Default false\n HarrisDetector\n % Free parameter of the Harris detector.\n %\n % Default 0.04\n K\n end\n\n methods\n function this = GFTTDetector(varargin)\n %GFTTDETECTOR Constructor\n %\n % obj = cv.GFTTDetector()\n % obj = cv.GFTTDetector(..., 'OptionName',optionValue, ...)\n %\n % ## Options\n % * __MaxFeatures__ See cv.GFTTDetector.MaxFeatures, default 1000\n % * __QualityLevel__ See cv.GFTTDetector.QualityLevel,\n % default 0.01\n % * __MinDistance__ See cv.GFTTDetector.MinDistance, default 1\n % * __BlockSize__ See cv.GFTTDetector.BlockSize, default 3\n % * __GradientSize__ default 3\n % * __HarrisDetector__ See cv.GFTTDetector.HarrisDetector,\n % default false\n % * __K__ See cv.GFTTDetector.K, default 0.04\n %\n % See also: cv.GFTTDetector.detect\n %\n this.id = GFTTDetector_(0, 'new', varargin{:});\n end\n\n function delete(this)\n %DELETE Destructor\n %\n % obj.delete()\n %\n % See also: cv.GFTTDetector\n %\n if isempty(this.id), return; end\n GFTTDetector_(this.id, 'delete');\n end\n\n function typename = typeid(this)\n %TYPEID Name of the C++ type (RTTI)\n %\n % typename = obj.typeid()\n %\n % ## Output\n % * __typename__ Name of C++ type\n %\n typename = GFTTDetector_(this.id, 'typeid');\n end\n end\n\n %% Algorithm\n methods\n function clear(this)\n %CLEAR Clears the algorithm state\n %\n % obj.clear()\n %\n % See also: cv.GFTTDetector.empty, cv.GFTTDetector.load\n %\n GFTTDetector_(this.id, 'clear');\n end\n\n function b = empty(this)\n %EMPTY Checks if detector object is empty\n %\n % b = obj.empty()\n %\n % ## Output\n % * __b__ Returns true if the detector object is empty (e.g in the\n % very beginning or after unsuccessful read).\n %\n % See also: cv.GFTTDetector.clear, cv.GFTTDetector.load\n %\n b = GFTTDetector_(this.id, 'empty');\n end\n\n function save(this, filename)\n %SAVE Saves the algorithm parameters to a file\n %\n % obj.save(filename)\n %\n % ## Input\n % * __filename__ Name of the file to save to.\n %\n % This method stores the algorithm parameters in the specified\n % XML or YAML file.\n %\n % See also: cv.GFTTDetector.load\n %\n GFTTDetector_(this.id, 'save', filename);\n end\n\n function load(this, fname_or_str, varargin)\n %LOAD Loads algorithm from a file or a string\n %\n % obj.load(fname)\n % obj.load(str, 'FromString',true)\n % obj.load(..., 'OptionName',optionValue, ...)\n %\n % ## Input\n % * __fname__ Name of the file to read.\n % * __str__ String containing the serialized model you want to\n % load.\n %\n % ## Options\n % * __ObjName__ The optional name of the node to read (if empty,\n % the first top-level node will be used). default empty\n % * __FromString__ Logical flag to indicate whether the input is a\n % filename or a string containing the serialized model.\n % default false\n %\n % This method reads algorithm parameters from the specified XML or\n % YAML file (either from disk or serialized string). The previous\n % algorithm state is discarded.\n %\n % See also: cv.GFTTDetector.save\n %\n GFTTDetector_(this.id, 'load', fname_or_str, varargin{:});\n end\n\n function name = getDefaultName(this)\n %GETDEFAULTNAME Returns the algorithm string identifier\n %\n % name = obj.getDefaultName()\n %\n % ## Output\n % * __name__ This string is used as top level XML/YML node tag\n % when the object is saved to a file or string.\n %\n % See also: cv.GFTTDetector.save, cv.GFTTDetector.load\n %\n name = GFTTDetector_(this.id, 'getDefaultName');\n end\n end\n\n %% Features2D: FeatureDetector\n methods\n function keypoints = detect(this, img, varargin)\n %DETECT Detects keypoints in an image or image set\n %\n % keypoints = obj.detect(img)\n % keypoints = obj.detect(imgs)\n % [...] = obj.detect(..., 'OptionName',optionValue, ...)\n %\n % ## Input\n % * __img__ Image (first variant), 8-bit grayscale image where\n % keypoints (corners) are detected.\n % * __imgs__ Image set (second variant), cell array of images.\n %\n % ## Output\n % * __keypoints__ The detected keypoints. In the first variant, a\n % 1-by-N structure array. In the second variant of the method,\n % `keypoints{i}` is a set of keypoints detected in `imgs{i}`.\n %\n % ## Options\n % * __Mask__ A mask specifying where to look for keypoints\n % (optional). It must be a logical or 8-bit integer matrix with\n % non-zero values in the region of interest. In the second\n % variant, it is a cell-array of masks for each input image,\n % `masks{i}` is a mask for `imgs{i}`. Not set by default.\n %\n % See also: cv.GFTTDetector.GFTTDetector\n %\n keypoints = GFTTDetector_(this.id, 'detect', img, varargin{:});\n end\n end\n\n %% Getters/Setters\n methods\n function value = get.MaxFeatures(this)\n value = GFTTDetector_(this.id, 'get', 'MaxFeatures');\n end\n function set.MaxFeatures(this, value)\n GFTTDetector_(this.id, 'set', 'MaxFeatures', value);\n end\n\n function value = get.QualityLevel(this)\n value = GFTTDetector_(this.id, 'get', 'QualityLevel');\n end\n function set.QualityLevel(this, value)\n GFTTDetector_(this.id, 'set', 'QualityLevel', value);\n end\n\n function value = get.MinDistance(this)\n value = GFTTDetector_(this.id, 'get', 'MinDistance');\n end\n function set.MinDistance(this, value)\n GFTTDetector_(this.id, 'set', 'MinDistance', value);\n end\n\n function value = get.BlockSize(this)\n value = GFTTDetector_(this.id, 'get', 'BlockSize');\n end\n function set.BlockSize(this, value)\n GFTTDetector_(this.id, 'set', 'BlockSize', value);\n end\n\n function value = get.HarrisDetector(this)\n value = GFTTDetector_(this.id, 'get', 'HarrisDetector');\n end\n function set.HarrisDetector(this, value)\n GFTTDetector_(this.id, 'set', 'HarrisDetector', value);\n end\n\n function value = get.K(this)\n value = GFTTDetector_(this.id, 'get', 'K');\n end\n function set.K(this, value)\n GFTTDetector_(this.id, 'set', 'K', 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/GFTTDetector.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.49321213558259136}} {"text": "function [ee,tt] = tricon2(varargin)\n%TRICON2 edge-centred connectivity for a conforming 2-simpl-\n%ex triangulation in the two-dimensional plane.\n% [EE,TT] = TRICON2(TT,CC) returns the edge-based adjacen-\n% cy for a mesh of 2-simlexes (triangles). EE = [V1,V2,T1,\n% T2,CE] is the set of unique 1-simplexes (edges) in the \n% mesh TT. Each row of {V1,V2} defines an edge, each row\n% of {T1,T2} defines the two triangles adjacent to an edge \n% and CE is a \"constraint\" flag, indicating which row in\n% CC (if any) the edge matches. TT = [V1,V2,V3,E1,E2,E3],\n% is the set of unique 2-simplexes in the mesh, where\n% {E1,E2,E3} define the tria-to-edge mapping. Each row of \n% {E1,E2,E3} are the indicies of the three edges that make \n% up each triangle.\n\n% Darren Engwirda : 2014 --\n% Email : de2363@columbia.edu\n% Last updated : 01/10/2017\n\n%---------------------------------------------- extract args\n tt = []; cc = [];\n\n if (nargin>=1), tt = varargin{1}; end\n if (nargin>=2), cc = varargin{2}; end\n\n%---------------------------------------------- basic checks\n if (~isnumeric(tt))\n error('tricon2:incorrectInputClass' , ...\n 'Incorrect input class.') ;\n end\n if (~isnumeric(cc))\n error('tricon2:incorrectInputClass' , ...\n 'Incorrect input class.') ;\n end\n \n%---------------------------------------------- basic checks\n if (ndims(tt) ~= +2 || size(tt,2) ~= +3)\n error('tricon2:incorrectDimensions' , ...\n 'Incorrect input dimensions.');\n end\n if (min(tt(:)) < +1 )\n error('tricon2:invalidInputs', ...\n 'Invalid TRIA input array.') ;\n end\n \n if (~isempty(cc))\n if (ndims(cc) ~= +2 || size(cc,2) ~= +2)\n error('tricon2:incorrectDimensions' , ...\n 'Incorrect input dimensions.');\n end\n end\n\n isoctave = ...\n exist('OCTAVE_VERSION','builtin') > +0;\n \n nt = size(tt,1);\n nc = size(cc,1);\n\n%------------------------------ assemble non-unique edge set\n ee = zeros(nt*3,2);\n ee((1:nt)+nt*0,:) = tt(:,[1,2]);\n ee((1:nt)+nt*1,:) = tt(:,[2,3]);\n ee((1:nt)+nt*2,:) = tt(:,[3,1]);\n \n%------------------------------ unique edges and re-indexing\n %[ee, iv, jv] = ...\n % unique(sort(ee, 2), 'rows');\n \n%-- as a (much) faster alternative to the 'ROWS' based call\n%-- to UNIQUE above, the edge list (i.e. pairs of UINT32 va-\n%-- lues) can be cast to DOUBLE, and the sorted comparisons \n%-- performed on vector inputs! \n ee = sort(ee,2);\n [ed,iv,jv] = unique(ee*[2^31;1]); \n ee = ee (iv,:);\n \n%------------------- tria-to-edge indexing: 3 edges per tria \n tt = [tt, zeros(nt*1,3)] ;\n tt(:,4) = jv((1:nt)+nt*0);\n tt(:,5) = jv((1:nt)+nt*1);\n tt(:,6) = jv((1:nt)+nt*2);\n \n%------------------- edge-to-tria indexing: 2 trias per edge\n\n if (isoctave)\n \n %-- OCTAVE is *shockingly* bad at executing loops, so -- \n %-- even though it involves far more operations! -- call\n %-- the vectorised version below.\n \n ne = size(ee,1);\n ee = [ee, zeros(ne*1,3)] ;\n \n ei = [tt(:,4);tt(:,5);tt(:,6)] ;\n ti = [(+1:nt),(+1:nt),(+1:nt)]';\n \n [ei,ix] = sort(ei,'ascend') ;\n ti = ti (ix,:);\n \n ix = find(diff(ei)>=+1);\n \n ni = length(ti);\n \n ep = [+1; ix+1];\n ep = [ep; ni+1];\n \n in = ep(2:ne+1)-ep(1:ne+0) > 1 ;\n \n ee( :,3) = ti(ep(1:ne)+0);\n ee(in,4) = ti(ep( in)+1);\n \n else\n \n %-- MATLAB is actually pretty good at JIT-ing code these\n %-- days, so use the asymptotically faster version based\n %-- on the pre-computed ordering.\n \n ne = size(ee,1);\n ee = [ee, zeros(ne*1,3)] ;\n ep = +3 * ones (ne*1,1) ;\n for ti = +1 : nt\n ei = tt(ti,4) ; \n ee(ei,ep(ei)) = ti;\n ej = tt(ti,5) ;\n ee(ej,ep(ej)) = ti;\n ek = tt(ti,6) ;\n ee(ek,ep(ek)) = ti;\n \n ep(ei) = ep(ei)+1 ;\n ep(ej) = ep(ej)+1 ;\n ep(ek) = ep(ek)+1 ;\n end\n \n end\n \n if (isempty(cc)), return; end\n \n%------------------------------------ find constrained edges\n %[ip,ip] = ismember( ...\n % ee(:,1:2),sort(cc,2),'rows');\n \n%-- as above, the 'ROWS' based call to ISMEMBER can be sped\n%-- up by casting the edge lists (i.e. pairs of UINT32 valu-\n%-- es) to DOUBLE, and performing the sorted queries on vec-\n%-- tor inputs!\n cc = sort(cc,2);\n [ip,ip] = ismember(ed, cc*[2^31;+1]);\n \n%------------------------------------ mark constrained edges\n ee(:,5) = ip;\n \nend\n\n\n\n", "meta": {"author": "CHLNDDEV", "repo": "OceanMesh2D", "sha": "56222604a5c1fe897d10c8b08cb3380ef8b43740", "save_path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D", "path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D/OceanMesh2D-56222604a5c1fe897d10c8b08cb3380ef8b43740/utilities/GEOM_UTIL/mesh-util/tricon2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.49321213322719937}} {"text": "%--- help for abstvar/autocov ---\n%\n% Compute the autocovariances (and the auto-correlation) of endogenous variables given the parameter values\n% \n% ::\n% \n% [C,R] = autocov(self);\n% [C,R] = autocov(self, params);\n% [C,R] = autocov(self, params, max_periods);\n% \n% Args:\n% self (var object): var object\n% params (cell of struct): struct containing var model related parameters (default: [])\n% max_periods (integer): maximum number of period to calculate auto-covariance (default: 5)\n% \n% Returns:\n% :\n% \n% - **C** [4-dimensional array]: auto-covariance where dimensions correspond to\n% \n% - 1,2: covariance\n% - 3: time lags\n% - 4: Number of parameters\n% \n% - **R** [4-dimensional array]: auto-correlation with same dimensions\n% \n%", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/classes/models/+vartools/autocov.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.4932121329171071}} {"text": "function [Q1,Q2] = mpc(T1_meas,T1_sp,T2_meas,T2_sp)\n\ns = 'http://byu.apmonitor.com';\nc = 'mpc';\n\n% input measurement\napm_meas(s,c,'TC1',T1_meas);\napm_meas(s,c,'TC2',T2_meas);\n\n% input setpoint with deadband +/- DT\nDT = 0.1;\napm_option(s,c,'TC1.sphi',T1_sp+DT);\napm_option(s,c,'TC1.splo',T1_sp-DT);\napm_option(s,c,'TC2.sphi',T2_sp+DT);\napm_option(s,c,'TC2.splo',T2_sp-DT);\n\n% solve MPC\noutput = apm(s,c,'solve');\n\n% test for successful solution\nif (apm_tag(s,c,'apm.appstatus')==1)\n % retrieve the first Q value\n Q1 = apm_tag(s,c,'Q1.Newval');\n Q2 = apm_tag(s,c,'Q2.Newval');\nelse\n % display output for debugging\n disp(output)\n % not successful, set voltage to zero\n Q1 = 0;\n Q2 = 0;\nend\n\nend\n\n\n", "meta": {"author": "APMonitor", "repo": "arduino", "sha": "f36e65a70dd7122d1829883899e40e56bf6c4279", "save_path": "github-repos/MATLAB/APMonitor-arduino", "path": "github-repos/MATLAB/APMonitor-arduino/arduino-f36e65a70dd7122d1829883899e40e56bf6c4279/6_Model_Predictive_Control/2nd_order_nonlinear/MATLAB/mpc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4932121305617157}} {"text": "% lineSegmentFitting extracts LineSegments from each EdgeContour.\n% Input - EdgeContours : The list of Edge Contours.\n% - DeviationThreshold : The threshold chosen to determine how\n% close the line segments fit on to the edge contour.\n% output - SegmentList : The list of Segments. Each of them corresponds\n% to each Edge Contour.\nfunction SegmentList = lineSegmentFitting(EdgeContours, DeviationThreshold)\n\n%% Initialize\nNumberOfContours = length(EdgeContours);\nSegmentList = cell(1,NumberOfContours);\n\n%% Exctrace Line Segemnts from each Edge Contour.\nfor i =1:NumberOfContours\n EdgePoints = EdgeContours{i};\n LastIndex = length(EdgePoints);\n LastPoint = EdgePoints(LastIndex,:);\n LineSegments = [extractLinearCue(EdgePoints, DeviationThreshold);\n LastPoint];\n SegmentList{i} = LineSegments;\nend\n\nend\n\n% extractLinearCue transforms the point-wise Edge Contour into\n% the piece-wise linear segments.\n% Input - EdgePoints : The subset points of EdgeContour which will be\n% transformed into the LineSegment\n% - DeviationThreshold : The threshold chosen to determine how\n% close the line segments fit on to the edge contour.\n% output - LineSegments : The Line Segments extracted from edge points.\n% For efficient recursion, It doesn't contain the\n% last point.\n% Example - Given EdgePoints = [first, p_2, p_3, ..., p_n-1, last],\n% LineSegments could be [first, p_k1, p_k2, ..., p_km], (last)\n% , where k1 < k2 < ... < km\n% and each p_ki belongs to p_j for 2<=j<=n-1\nfunction LineSegments = extractLinearCue(EdgePoints, DeviationThreshold)\n%% Initialize\nEdgeLength = length(EdgePoints);\n\n% Initialize first and last points.\nFirstPoint = EdgePoints(1,:);\nLastPoint = EdgePoints(EdgeLength,:);\n\n% If EdgePoints contains only two points, which are first and last,\n% return only first point. (Since we remove the last point from the output)\nif EdgeLength == 2\n LineSegments = FirstPoint;\nelse\n \n \n max_d = 0;\n \n % Find maximum deviation\n for i = 2:EdgeLength-1\n CurPoint = EdgePoints(i,:);\n % The deviation di for Point i is denoted :\n % di = | xi(y1-yn)+yi(xn-x1)+ynx1-y1xn |/sqrt((y1-yn)^2+(xn-x1)^2)\n d = abs( CurPoint(2)*(FirstPoint(1)-LastPoint(1)) + ...\n CurPoint(1)*(LastPoint(2)-FirstPoint(2)) + ...\n LastPoint(1)*FirstPoint(2) - FirstPoint(1)*LastPoint(2) ) / ...\n sqrt((FirstPoint(1)-LastPoint(1))^2 + (LastPoint(2)-FirstPoint(2))^2);\n \n % Compare di with maximum value\n if max_d < d\n max_d = d;\n max_idx = i;\n \n end\n end\n \n % If the maximum deviation is smaller than the Threshold,\n % consider FirstPoint-LastPoint as one line segment.\n % Since we remove the last point from the output, return only\n % first point.\n if max_d < DeviationThreshold\n LineSegments = FirstPoint;\n else\n LeftEdgePoints = EdgePoints(1:max_idx,:);\n RightEdgePoints = EdgePoints(max_idx:EdgeLength,:);\n LineSegments = [ extractLinearCue(LeftEdgePoints, DeviationThreshold) ;\n extractLinearCue(RightEdgePoints, DeviationThreshold)];\n end\n \nend\nend", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u68c0\u6d4b\u7b97\u6cd5/Sushi-Dish-master/src/lineSegmentFitting.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.49321213056171564}} {"text": "function[varargout]=ridgemap(varargin)\n%RIDGEMAP Maps ridge quantities back onto the time series.\n%\n% X=RIDGEMAP(M,XR,IR) where IR is a ridge index and XR is a quantity \n% along the ridge, maps the values of XR to their correct row locations \n% in a time series of length M, and returns the result in the array X.\n%\n% If IR and XR contain L different ridges separated by NaNs, as output by\n% RIDGEWALK, then X is M x L with the values of XR from each ridge in a \n% separate column. Values not specified by the IR are left as NaNs. \n%\n% [X1,X2,...,XM]=RIDGEMAP(M,X1R,X2R,...,XPR,IR) also works for any P\n% different ridge quantities X1R--XPR.\n%\n% When using RIDGEWALK's joint ridges algorithm, in which some quantities\n% have more than one column, they should be passed to RIDGEMAP \n% individually, for example [X1,X2]=RIDGEMAP(M,X(:,1),X(:,2),IR).\n% __________________________________________________________________\n%\n% Collapsing \n%\n% X=RIDGEMAP(...'collapse') combines values from all the ridges using\n% a power-weighted mean. Then X is a column vector of size M x 1.\n% __________________________________________________________________\n% \n% Ridge multiplicity\n%\n% [...,MULT]=RIDGEMAP returns the ridge multiplicity MULT after all the\n% expected output quantities. MULT is a column vector with size M x 1.\n% \n% The ridge multiplicity is the number of ridges present at each time. \n% __________________________________________________________________\n%\n% See also RIDGEWALK.\n%\n% 'ridgemap --t' runs some a test.\n%\n% Usage: x=ridgemap(M,xr,ir);\n% [x,f]=ridgemap(M,xr,fr,ir);\n% [x,f]=ridgemap(M,xr,fr,ir,'collapse');\n% [x,mult]=ridgemap(M,xr,ir);\n% [x,f,mult]=ridgemap(M,xr,fr,ir);\n% __________________________________________________________________\n% This is part of JLAB --- type 'help jlab' for more information\n% (C) 2009--2019 J.M. Lilly --- type 'help jlab_license' for details\n\nif strcmpi(varargin{1}, '--t')\n ridgemap_test,return \nend\n\nif ischar(varargin{end})\n str=varargin{end};\n varargin=varargin(1:end-1);\nelse\n str='all';\nend\n\nM=varargin{1}(1);\nN=1;\nbNinput=false;\nif length(M)==2\n N=M(2);\n M=M(1);\n bNinput=true;\nend\n\nvarargin=varargin(2:end);\nif bNinput\n kr=varargin{end};\n ir=varargin{end-1};\n varargin=varargin(1:end-2);\nelse\n ir=varargin{end};\n kr=1+0*ir;\n varargin=varargin(1:end-1);\nend\n\nif ~isempty(ir)\n if iscell(ir)\n ir=cell2col(ir);\n for i=1:length(varargin)\n varargin{i}=cell2col(varargin{i});\n end\n end\n for i=1:length(varargin)\n [~,varargin{i}]=col2mat(ir,varargin{i});\n end\n ir=col2mat(ir);\n for i=1:length(varargin)\n varargout{i}=nan*zeros(M,size(ir,2));\n% size(varargout{i})\n % size(ir)\n for k=1:size(ir,2)\n %ir(isfinite(ir(:,k)),k)\n varargout{i}(ir(isfinite(ir(:,k)),k),k)=varargin{i}(isfinite(ir(:,k)),k);\n end\n end\n mult=vsum(0+isfinite(varargout{1}),2);\nelse\n for i=1:length(varargin)\n varargout{i}=nan*zeros(M,1);\n end\n mult=zeros(M,1);\nend\n\nvarargout{end+1}=mult;\n\n% for i=1:length(varargin)\n% varargout{i}=vswap(varargout{i},inf+sqrt(-1)*inf,nan+sqrt(-1)*nan);\n% varargout{i}=vswap(varargout{i},inf,nan);\n% end\n\n%Calculate multiplicity\n%mult=~isnan(vswap(varargout{1}(:,1,:),0,nan));\n%The \"+0\" is to convert the logical into a numerical value\n\nif strfind(str,'col') \n for i=length(varargin):-1:1\n if i==1\n varargout{i}=vsum(varargout{i},2);\n else\n varargout{i}=vmean(varargout{i},2,squared(varargout{1}));\n end\n end\nend\n\nfor i=1:length(varargin) \n varargout{i}=squeeze(varargout{i});\n %anyany(isinf(varargout{i}))\nend\n\n\nfunction[]=ridgemap_test\n\nload npg2006\nuse npg2006\n\n%Decide on frequencies\nfs=2*pi./(logspace(log10(10),log10(100),50)');\n\n%Compute wavelet transforms using generalized Morse wavelets\n[wx,wy]=wavetrans(real(cx),imag(cx),{1,2,4,fs,'bandpass'},'mirror');\n[wp,wn]=vectmult(tmat,wx,wy);\n\n%Form ridges of component time series\n[wr,ir,jr,fr]=ridgewalk(dt,wn,fs); \n[wa,fa,mult]=ridgemap(length(wn),wr,fr,ir);\nreporttest('RIDGEMAP has one column per ridge, non-joint ridges',size(fa,2)==size(wa,2)&&size(fa,2)==length(find(~isfinite(ir))))\n\n%[ir,jr,wpr,wnr,fpr,fnr]=ridgewalk(dt,wp,wn,fs,{0,0}); \n%[wpa,wna,fpa,fna,mult]=ridgemap(length(wn),wpr,wnr,fpr,fnr,ir);\n\n\n", "meta": {"author": "jonathanlilly", "repo": "jLab", "sha": "9f32f63e647209bc1cb81c8713deb954857f1919", "save_path": "github-repos/MATLAB/jonathanlilly-jLab", "path": "github-repos/MATLAB/jonathanlilly-jLab/jLab-9f32f63e647209bc1cb81c8713deb954857f1919/jRidges/ridgemap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.49321212554084}} {"text": "function [Tmin,Tsec] = sec2min(T)\n\n% Transforms the given number of seconds into minutes and residual seconds\n\nTmin = floor(T/60);\nTsec = round((T-Tmin*60)*10)/10;", "meta": {"author": "InverseTampere", "repo": "TreeQSM", "sha": "6630bbf516f8b53adb7d60a2cccbd21e6fe51226", "save_path": "github-repos/MATLAB/InverseTampere-TreeQSM", "path": "github-repos/MATLAB/InverseTampere-TreeQSM/TreeQSM-6630bbf516f8b53adb7d60a2cccbd21e6fe51226/src/tools/sec2min.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7490872019117029, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.49321211816457255}} {"text": "% convnet_classify\n% Copyright (C) 2013 KyungHyun Cho\n%\n%This program is free software; you can redistribute it and/or\n%modify it under the terms of the GNU General Public License\n%as published by the Free Software Foundation; either version 2\n%of the License, or (at your option) any later version.\n%\n%This program is distributed in the hope that it will be useful,\n%but WITHOUT ANY WARRANTY; without even the implied warranty of\n%MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n%GNU General Public License for more details.\n%\n%You should have received a copy of the GNU General Public License\n%along with this program; if not, write to the Free Software\n%Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n%\nfunction [c, posterior] = convnet_classify(C, x0, raw)\n\nif nargin < 3\n raw = 0;\nend\n\nlayers = C.structure.layers;\nn_layers = length(layers);\n\nposterior = x0;\n\nfull_layers = C.structure.full_layers;\nconv_layers = C.structure.conv_layers;\nn_full = length(full_layers);\nn_conv = size(conv_layers,1);\n\nstrides = C.structure.strides;\npoolratios = C.structure.poolratios;\n\nmb_sz = size(x0, 1);\n\ncin = C.structure.channel_in;\nszin = C.structure.size_in;\n\nrepost = reshape(posterior, [mb_sz, szin, szin, cin]);\n\nif C.lcn.use\n subwindow = fspecial('gaussian', C.lcn.neigh);\n %subwindow_sum = ones(C.lcn.neigh);\nend\n\nif C.lcn.use \n subsum = convn(repost, reshape(subwindow_sum, [1, C.lcn.neigh, C.lcn.neigh, 1]), 'same');\n repost = repost - subsum / C.lcn.neigh^2;\n repost2 = repost.^2;\n subsum = convn(repost2, reshape(subwindow_sum, [1, C.lcn.neigh, C.lcn.neigh, 1]), 'same');\n repost = repost ./(sqrt(subsum + 1e-12) / C.lcn.neigh);\nend\n\nfor l = 1:n_conv\n fsz = length(C.cW{l}(:,1)) / cin;\n n_filters = size(C.cW{l}, 2);\n szout_prepool = (floor((szin - sqrt(fsz)) / strides(l)) + 1);\n szout = ceil(szout_prepool / poolratios(l));\n respfull = zeros(mb_sz, szout, szout, n_filters);\n\n % for each filter map\n for fidx = 1:n_filters\n fil = reshape(C.cW{l}(:, fidx), [1, sqrt(fsz), sqrt(fsz), cin]);\n resp = convn(repost, fil, 'valid');\n\n % stride\n resp = resp(:, 1:strides(l):end, :);\n resp = resp(:, :, 1:strides(l):end);\n\n resp = resp + C.cbiases{l}(fidx);\n\n % nonlinearity\n resp = sigmoid(resp, C.hidden.use_tanh);\n \n if C.lcn.use \n subsum = convn(resp, reshape(subwindow_sum, [1, C.lcn.neigh, C.lcn.neigh, 1]), 'same');\n resp = resp - subsum / C.lcn.neigh^2;\n resp2 = resp.^2;\n subsum = convn(resp2, reshape(subwindow_sum, [1, C.lcn.neigh, C.lcn.neigh, 1]), 'same');\n resp = resp ./(sqrt(subsum + 1e-12) / C.lcn.neigh);\n end\n\n if C.structure.poolratios(l) > 1\n % pooling\n switch C.pooling(l)\n case 0\n resp = convnet_maxpool (resp, C.structure.poolratios(l));\n case 1\n resp = convnet_avgpool (resp, C.structure.poolratios(l));\n case 2\n error('NOT SUPPORTED');\n end\n end\n\n respfull(:,:,:,fidx) = resp;\n end\n\n szin = szout;\n cin = n_filters;\n repost = respfull;\nend\n\n% stretch\nposterior = reshape(repost, [mb_sz C.structure.layers(n_conv+1)]);\n\nfor l = 2:n_full+1\n if C.dropout.use && l > 2\n posterior = (1 - C.dropout.prob) * posterior;\n end\n\n posterior = bsxfun(@plus, posterior * C.W{l-1}, C.biases{l}');\n\n if l < n_full + 1\n posterior = sigmoid(posterior, C.hidden.use_tanh);\n end\n if l == n_full + 1 && C.output.binary\n posterior = softmax(posterior);\n end\nend\n\nif raw\n c = posterior;\nelse\n [maxp, c] = max(posterior, [], 2);\nend\n\n\n", "meta": {"author": "kyunghyuncho", "repo": "deepmat", "sha": "6fd133406b5d78e1b87e2f736e27cfb2024807af", "save_path": "github-repos/MATLAB/kyunghyuncho-deepmat", "path": "github-repos/MATLAB/kyunghyuncho-deepmat/deepmat-6fd133406b5d78e1b87e2f736e27cfb2024807af/convnet_classify.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.4931705354624004}} {"text": "%% Author: epokh\n%% Website: www.epokh.org/drupy\n%% This software is under GPL\n\n%%Calculate the force/torque needed to produce the force torque needed\n%%at the end effector:\n%% we now that [T]=[J]'*[F]\n%% where F=force\\torque of the end effector (in this case only torques)\n%% T=forces\\torques of the joints (in this case only torques)\n\nfunction T=staticForce(J6,F)\n\nT=J6'*F;\n\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/14886-robotic-toolbox/staticForce.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4931705272119608}} {"text": "function [ segmentedImage, binaryImage ] = ColorSegments( regionMatrix )\n%COLORSEGMENTS Summary of this function goes here\n% Detailed explanation goes here\n\nuniqueRegionLabels = unique(regionMatrix);\nuniqueRegionLabelCount = numel(uniqueRegionLabels);\n\nlabelColors = [];\n\nfor ii = 1 : uniqueRegionLabelCount\n \n rValue = randi(255);\n \n gValue = randi(255);\n \n bValue = randi(255);\n \n labelColors = [labelColors; rValue gValue bValue];\nend\n\nfrequentLabel = mode(mode(regionMatrix));\n\n[rows, cols] = size(regionMatrix);\n\nsegmentedImage = uint8(zeros(rows, cols, 3));\n\nbinaryImage = uint8(zeros(rows, cols, 1));\n\nfor ii = 1 : rows\n \n for jj = 1 : cols\n \n regionLabel = regionMatrix(ii, jj);\n \n colorIndex = find(uniqueRegionLabels == regionLabel);\n \n segmentedImage(ii, jj, 1) = labelColors(colorIndex, 1);\n \n segmentedImage(ii, jj, 2) = labelColors(colorIndex, 2);\n \n segmentedImage(ii, jj, 3) = labelColors(colorIndex, 3);\n \n if regionLabel == frequentLabel\n binaryImage(ii, jj) = 0;\n else\n binaryImage(ii, jj) = 255;\n end\n \n end\n \nend\n\n\n\n\nend\n\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u5206\u5272\u7b97\u6cd5/RegionGrowingAlgorithm-master/ColorSegments.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484144, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.4931457748781121}} {"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 vis_wp(img, opt, heatmap, center, scale, cad, dict)\n\n img_crop = cropImage(img,center,scale);\n S = bsxfun(@plus,opt.R*opt.S,[opt.T;0]);\n model = fullShape(S,cad,dict.kpt_id);\n mesh2d = model.vertices(:,1:2)'*200/size(heatmap,2);\n \n % visualization\n nplot = 4;\n h = figure('position',[100,100,nplot*300,300]);\n % cropped image\n subplot('position',[0 0 1/nplot 1]);\n imshow(img_crop); hold on;\n % heatmap\n subplot('position',[1/nplot 0 1/nplot 1]);\n response = sum(heatmap,3);\n max_value = max(max(response));\n mapIm = imresize(mat2im(response, jet(100), [0 max_value]),[200,200],'nearest');\n imToShow = mapIm*0.5 + (single(img_crop)/255)*0.5;\n imagesc(imToShow); axis equal off\n % project cad model on image\n subplot('position',[2/nplot 0 1/nplot 1]);\n imshow(img_crop); hold on;\n patch('vertices',mesh2d','faces',model.faces,'FaceColor','blue','FaceAlpha',0.3,'EdgeColor','none');\n % object viewpoint\n subplot('position',[3/nplot 0 1/nplot 1]);\n h2 = subplot('position',[3/nplot 0 1/nplot 1]);\n trisurf(model.faces,model.vertices(:,1),model.vertices(:,2),model.vertices(:,3),'EdgeColor','none');axis equal;\n view(0,-90);\n set(h2,'XTick',[],'YTick',[]);\n set(h2,'visible','off')\n\nend\n", "meta": {"author": "geopavlakos", "repo": "object3d", "sha": "44033b2b4fe15d41a411cba0bbff906c23e8a802", "save_path": "github-repos/MATLAB/geopavlakos-object3d", "path": "github-repos/MATLAB/geopavlakos-object3d/object3d-44033b2b4fe15d41a411cba0bbff906c23e8a802/code/vis_wp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4930783265774414}} {"text": "filename='test2d_micro';\n%filename = 'MicroQuad';\nptype = 'MICRO';\nmethod = 'SIMPALL';\nmaterialType = 'ISOTROPIC';\ninitial_case = 'circleInclusion';\ncost={'chomog_alphabeta'};\nweights=[1];\nconstraint = {'volumeConstraint'};\nconstraint_case = 'EQUALITY';\n%incrementFactor = 1;\n%designVariable = 'Density';\ndesignVariable = 'LevelSet';\nfilterType = 'P1';\nfracRadius = 0.51;\n%optimizer = 'IPOPT';\noptimizer = 'DualNestedInPrimal';\n%optimizer = 'AlternatingPrimalDual';\n\n%optimizerUnconstrained = 'PROJECTED GRADIENT';\n%line_search_initiator = 'INCREASING LAST STEP';\n%incrementFactor = 1.95;\n\noptimizerUnconstrained = 'SLERP';\n\n\nnsteps = 1;\nVfrac_final = 0.4;\nPerimeter_target=1;\noptimality_final = 0.5*1e-3;\nconstr_final =1e-12;\n\nVfrac_initial = 0.8;\noptimality_initial = 0.5*1e-3;\nconstr_initial = 1e-12;\n\nTOL.rho_plus = 1;\nTOL.rho_minus = 0;\nTOL.E_plus = 1;\nTOL.E_minus = 1e-3;\nTOL.nu_plus = 1/3;\nTOL.nu_minus = 1/3;\n\n%Micro\nepsilon_isotropy_initial=1e-1;\nepsilon_isotropy_final = 1e-3;\nmicro.alpha =[1 1 0]';\nmicro.beta = [1 1 0]';\n\n%nsteps = 10;\n\n% For all tests\nplotting = true;\nprinting = true;\nmonitoring = true;\nmonitoring_interval = 1;\nmaxiter = 200;", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/Applications/MaterialDesign/CompositeMaterialDesignTriLevelSetP1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4930783214845431}} {"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 [Y_train, label_train, Y_test, label_test] = pickTrainTest_2(dataset, N_train_c)\n data_fn = fullfile('data', strcat(dataset, '.mat'))\n load(data_fn);\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n %% ================== block: random projection ==========================\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% fprintf('random projection...')\n% d_new = 3000;\n% A = randn(d_new, size(Y,1)) ;\n% Y = A*Y;\n\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n %% ------------------end of block: random projection ----------------------------\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n\n\n Y = normc(Y);\n d = size(Y,1);\n if ~exist('Y_range', 'var')\n Y_range = label_to_range(label);\n end\n\n C = numel(Y_range) - 1;\n N_total = Y_range(C+1);\n N_train = C*N_train_c;\n N_test = N_total - N_train;\n\n Y_train = zeros(d, N_train);\n Y_test = zeros(d, N_test);\n label_train = zeros(1, N_train);\n label_test = zeros(1, N_test);\n %%\n cur_train = 0;\n cur_test = 0;\n for c = 1: C \n Yc = get_block_col(Y, c, Y_range);\n N_total_c = size(Yc, 2);\n N_test_c = N_total_c - N_train_c;\n label_train(:, cur_train + 1: cur_train + N_train_c) = c*ones(1, N_train_c);\n label_test(:, cur_test + 1: cur_test + N_test_c) = c*ones(1, N_test_c);\n\n idx = randperm(N_total_c);\n\n Y_train(:, cur_train + 1: cur_train + N_train_c) = Yc(:, idx(1: N_train_c));\n Y_test(:, cur_test + 1: cur_test + N_test_c) = Yc(:, idx(N_train_c + 1: end));\n\n cur_train = cur_train + N_train_c;\n cur_test = cur_test + N_test_c;\n end \n\n % d_new = 3000;\n % if size(Y,1) > d_new\n % fprintf('pca...')\n % [W,frac] = pcam(Y',d_new);\n % Y_train = normc((Y_train'*W)');\n % Y_test = normc((Y_test'*W)'); \n % fprintf('DONE\\n');\n % else\n Y_train = normc(Y_train);\n Y_test = normc(Y_test);\n % end\nend \n\n\n", "meta": {"author": "tiepvupsu", "repo": "DICTOL", "sha": "1a0361aa35c32d70525d06910d0e9b87997ff246", "save_path": "github-repos/MATLAB/tiepvupsu-DICTOL", "path": "github-repos/MATLAB/tiepvupsu-DICTOL/DICTOL-1a0361aa35c32d70525d06910d0e9b87997ff246/utils/pickTrainTest_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.4930705437536879}} {"text": "%==============================================================================\n% This code is part of the Matlab-based toolbox\n% FAIR - Flexible Algorithms for Image Registration. \n% For details see \n% - https://github.com/C4IR and\n% - http://www.siam.org/books/fa06/\n% ##2\n%==============================================================================\n% \n% - data Hand, Omega=(0,20)x(0,25), \n% - viewer viewImage2D\n% - interpolation splineInter\n% - distance SSD\n% - transformation affine2D\n% - regularizer mfElastic\n% - optimizer Gauss-Newton\n% ===============================================================================\n\nclose all, help(mfilename);\n\n% load data, set viewer, interpolator, transformation, distance\nsetup2DHNSPData\nimgModel('reset','imgModel','splineInter','regularizer','moments','theta',1e-2);\ndistance('reset','distance','SSD');\ntrafo('reset','trafo','affine2D');\nregularizer('reset','regularizer','mfElastic','alpha',5e2,'mu',1,'lambda',0);\n\n% run MLIR\n[yc,wc,his] = MLIR(ML,'maxLevel',8);\n\n%==============================================================================\n", "meta": {"author": "C4IR", "repo": "FAIR.m", "sha": "975edebd37b833ae76696792870de5c05efcb9cb", "save_path": "github-repos/MATLAB/C4IR-FAIR.m", "path": "github-repos/MATLAB/C4IR-FAIR.m/FAIR.m-975edebd37b833ae76696792870de5c05efcb9cb/kernel/examples/E9_HNSP_MLIR_SSD_mfElas.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4930502414847156}} {"text": "function f = eval(SO3F,rot,varargin)\n% pointwise evaluation of SO3F at rotations rot\n%\n% sum_i \\sum_j \\sum_k weights * psi(g*s_j h_i . s_k r_i)\n\n% if isa(rot,'orientation')\n% ensureCompatibleSymmetries(SO3F,rot)\n% end\n\ns = size(rot);\nrot = rot(:);\n\nh = symmetrise(SO3F.h.normalize,'unqiue');\n\n% rot x SS x CS x h\ngh = reshape((SO3F.SS.properGroup * rot).' * h, length(rot),[],length(SO3F.h));\n\nf = mean(SO3F.psi.eval(dot(gh,reshape(normalize(SO3F.r),1,1,[]),'noSymmetry')),2);\n\nf = reshape(reshape(f,length(rot),[]) * SO3F.weights,s);\n\nif isalmostreal(f)\n f = real(f);\nend\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/SO3Fun/@SO3FunCBF/eval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240825770431, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.4930502375239097}} {"text": "function [L,e] = spm_mci_like_ind (P,R,M,U,Y)\n% Compute likelihood wrt selected time points\n% FORMAT [L,e] = spm_mci_like_ind (P,R,M,U,Y)\n%\n% P Flow parameters\n% R Initial state parameters\n% M Model structure\n% U Inputs [Nin x N]\n% Y data\n% \n% L Log likelihood\n% e Prediction errors\n%__________________________________________________________________________\n% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny and Biswa Sengupta\n% $Id: spm_mci_like_ind.m 6697 2016-01-27 14:57:28Z spm $\n\n% Read data points and time indices\ntry, ind=Y.ind; catch, ind=1:M.N; end\nNt=length(ind);\ny=Y.y;\n\nM.x0=R; % Initial conditions\n[G,sy,st] = spm_mci_fwd (P,M,U);\n\nif st==-1, disp('Problem !'); return; end\n\n% Prediction errors\ng=G(ind,:);\ne=Y.y-g;\n\n% Log Likelihood\nL = -0.5*trace(M.iCe*e'*e) + M.logdet_Ce - 0.5*Nt*log(2*pi);", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/mci/inference/spm_mci_like_ind.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4930502335631035}} {"text": "function tests = test_ft_connectivity_mim\n\n% MEM 1gb\n% WALLTIME 00:10:00\n% DEPENDENCY ft_connectivity_mim\n\nif nargout\n % assume that this is called by RUNTESTS\n tests = functiontests(localfunctions);\nelse\n % assume that this is called from the command line\n func = localfunctions;\n for i=1:numel(func)\n fprintf('evaluating %s\\n', func2str(func{i}));\n feval(func{i});\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction test_chan_chan_freq(testCase)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nnchan = 6;\nnfreq = 5;\ndimord = 'chan_chan_freq';\ninput = zeros(nchan, nchan, nfreq);\n\nfor freq=1:nfreq\n fdat = 10 * randn(nchan, 1) + 1i * 10 * randn(nchan, 1);\n input(:,:,freq) = fdat * ctranspose(fdat); % compute the cross-spectral density\nend\n\nresult = {};\nresult{end+1} = ft_connectivity_cancorr(input, 'dimord', dimord, 'indices', [1 1 2 2 3 3]); % e.g. three pair of planar channels\nresult{end+1} = ft_connectivity_cancorr(input, 'dimord', dimord, 'indices', [1 1 1 2 2 2]); % e.g. two dipole moments (xyz)\n\n% all iterations were done with (slightly) different options, hence the results should not be equal\nfor i=1:numel(result)\n for j=(i+1):numel(result)\n assert(~isequaln(result{i}, result{j}), 'the results %d and %d should not be equal', i, j);\n end\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_ft_connectivity_mim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.4929009435890912}} {"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 varargout = process_test_permutation2( varargin )\n% PROCESS_TEST_PERMUTATION2: Permutation two-sample tests (independent).\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, Dimitrios Pantazis, 2016\n\neval(macro_method);\nend\n\n\n%% ===== GET DESCRIPTION =====\nfunction sProcess = GetDescription() %#ok\n % Description the process\n sProcess.Comment = 'Permutation test: Independent';\n sProcess.Category = 'Stat2';\n sProcess.SubGroup = 'Test';\n sProcess.Index = 104;\n sProcess.Description = 'https://neuroimage.usc.edu/brainstorm/Tutorials/Statistics';\n % Definition of the input accepted by this process\n sProcess.InputTypes = {'data', 'results', 'timefreq', 'matrix'};\n sProcess.OutputTypes = {'pdata', 'presults', 'ptimefreq', 'pmatrix'};\n sProcess.nInputs = 2;\n sProcess.nMinFiles = 2;\n\n % === GENERIC EXTRACT OPTIONS\n % Label\n sProcess.options.extract_title.Comment = 'Select data to test:';\n sProcess.options.extract_title.Type = 'label';\n % Options\n sProcess = process_extract_values('DefineExtractOptions', sProcess);\n % DISABLE ABSOLUTE VALUE\n sProcess.options.isabs.Value = 0;\n sProcess.options.isnorm.Value = 0;\n sProcess.options.isabs.Hidden = 1;\n sProcess.options.isnorm.Hidden = 1;\n \n % === EXCLUDE ZERO VALUES\n sProcess.options.iszerobad.Comment = 'Exclude the zero values from the computation';\n sProcess.options.iszerobad.Type = 'checkbox';\n sProcess.options.iszerobad.Value = 1;\n % === OUTPUT COMMENT\n sProcess.options.Comment.Comment = 'Comment (empty=default): ';\n sProcess.options.Comment.Type = 'text';\n sProcess.options.Comment.Value = '';\n \n % === TEST: title\n sProcess.options.test_title.Comment = '
Test statistic:';\n sProcess.options.test_title.Type = 'label';\n % === TEST: type\n sProcess.options.test_type.Comment = {['Student''s t-test   (equal variance)
t = (mean(A)-mean(B)) / (Sx * sqrt(1/nA + 1/nB))
' ...\n 'Sx = sqrt(((nA-1)*var(A) + (nB-1)*var(B)) / (nA+nB-2))'], ...\n ['Student''s t-test   (unequal variance)
', ...\n 't = (mean(A)-mean(B)) / sqrt(var(A)/nA + var(B)/nB)'], ...\n ['Absolute mean test:    (works with unconstrained sources)
' ...\n 'T = (|mean(A)|-|mean(B)|) / sqrt(|var(A)|/nA + |var(B)|/nB)']; ...\n ... ['Wilcoxon rank-sum test
', ...\n ... 'R = tiedrank([A,B]),    W = sum(R(1:nA))']; ...\n 'ttest_equal', 'ttest_unequal', 'absmean'}; % , 'wilcoxon'};\n sProcess.options.test_type.Type = 'radio_label';\n sProcess.options.test_type.Value = 'ttest_equal';\n \n % ===== STATISTICAL TESTING OPTIONS =====\n sProcess.options.label2.Comment = '
Statistical testing (Monte-Carlo):';\n sProcess.options.label2.Type = 'label';\n % === NUMBER OF RANDOMIZATIONS\n sProcess.options.randomizations.Comment = 'Number of randomizations:';\n sProcess.options.randomizations.Type = 'value';\n sProcess.options.randomizations.Value = {1000, '', 0};\n % === TAIL FOR THE TEST STATISTIC\n sProcess.options.tail.Comment = {'One-tailed (-)', 'Two-tailed', 'One-tailed (+)', ''; ...\n 'one-', 'two', 'one+', ''};\n sProcess.options.tail.Type = 'radio_linelabel';\n sProcess.options.tail.Value = 'two';\nend\n\n\n%% ===== FORMAT COMMENT =====\nfunction Comment = FormatComment(sProcess) %#ok\n Comment = process_test_parametric2('FormatComment', sProcess);\n Comment = ['Perm ' Comment];\nend\n\n\n%% ===== RUN =====\nfunction sOutput = Run(sProcess, sInputsA, sInputsB) %#ok\n % Initialize returned variables\n sOutput = [];\n \n % ===== GET OPTIONS =====\n % Get generic extract options\n OPTIONS = process_extract_values('GetExtractOptions', sProcess, sInputsA(1));\n % Exclude zero values\n if isfield(sProcess.options, 'iszerobad') && isfield(sProcess.options.iszerobad, 'Value') && ~isempty(sProcess.options.iszerobad.Value)\n OPTIONS.isZeroBad = sProcess.options.iszerobad.Value;\n else\n OPTIONS.isZeroBad = 1;\n end\n % Get test type\n OPTIONS.TestType = sProcess.options.test_type.Value;\n OPTIONS.TestTail = sProcess.options.tail.Value;\n Randomizations = sProcess.options.randomizations.Value{1};\n % Invalid test/tail combinations\n if ismember(OPTIONS.TestType, {'ttest_onesample'}) && OPTIONS.isAbsolute && ismember(OPTIONS.TestTail, {'two', 'one-'})\n bst_report('Warning', sProcess, [], 'Testing |X|>0: Using a positive one-tailed test (one+) instead.');\n OPTIONS.TestTail = 'one+';\n elseif strcmpi(OPTIONS.TestType, 'chi2_onesample') && ismember(OPTIONS.TestTail, {'two', 'one-'})\n bst_report('Warning', sProcess, [], 'Testing |X|>0: Using a positive one-tailed test (one+) instead.');\n OPTIONS.TestTail = 'one+';\n elseif strcmpi(OPTIONS.TestType, 'signtest') && ismember(OPTIONS.TestTail, {'two', 'one-'})\n bst_report('Warning', sProcess, [], 'The sign test statistic produces positive values only: Using a positive one-tailed test (one+) instead.');\n OPTIONS.TestTail = 'one+';\n end\n\n\n % ===== CHECK INPUT FILES =====\n % Make sure that file type is indentical for both sets\n if ~isempty(sInputsA) && ~isempty(sInputsB) && ~strcmpi(sInputsA(1).FileType, sInputsB(1).FileType)\n bst_report('Error', sProcess, [], 'Cannot process inputs from different types.');\n return;\n end\n % Check the number of files in input\n if (length(sInputsA) < 2)\n bst_report('Error', sProcess, [], 'Not enough files in input.');\n return;\n end\n % Load time vector from the first file: if same as input, discard input\n TimeVector = in_bst(sInputsA(1).FileName, 'Time');\n if ~isempty(OPTIONS.TimeWindow) && (abs(TimeVector(1) - OPTIONS.TimeWindow(1)) < 1e-4) && (abs(TimeVector(end) - OPTIONS.TimeWindow(2)) < 1e-4)\n OPTIONS.TimeWindow = [];\n end\n % Load freq range from the first file: if same as input, discard input\n if ~isempty(OPTIONS.FreqRange)\n % Load Freqs field from the input file\n TfMat = in_bst_timefreq(sInputsA(1).FileName, 0, 'Freqs');\n if iscell(TfMat.Freqs)\n BandBounds = process_tf_bands('GetBounds', TfMat.Freqs);\n FreqList = unique(BandBounds(:));\n else\n FreqList = TfMat.Freqs;\n end\n if (abs(OPTIONS.FreqRange(1) - FreqList(1)) < 1e-4) && (abs(OPTIONS.FreqRange(2) - FreqList(end)) < 1e-4)\n OPTIONS.FreqRange = [];\n end\n end\n \n % ===== INPUT DATA =====\n % Concatenante values in the 4th dimension\n OPTIONS.Dim = 4;\n % Set all the bad values to 0\n OPTIONS.isBadZero = 1;\n % Call extraction process: FilesA\n [sDataA, OutputType, matName] = process_extract_values('Extract', sProcess, sInputsA, OPTIONS);\n if isempty(sDataA)\n bst_report('Error', sProcess, [], 'No data read from FilesA.');\n return;\n end\n % Read FilesB\n sDataB = process_extract_values('Extract', sProcess, sInputsB, OPTIONS);\n if isempty(sDataB)\n bst_report('Error', sProcess, [], 'No data read from FilesB.');\n return;\n elseif (size(sDataA.(matName),1) ~= size(sDataB.(matName),1)) || (size(sDataA.(matName),2) ~= size(sDataB.(matName),2)) || (size(sDataA.(matName),3) ~= size(sDataB.(matName),3))\n bst_report('Error', sProcess, [], 'Files A and B do not have the same number of signals or time samples.');\n return;\n end\n% WARNING ONLY APPLIES TO PARAMETRIC TESTS\n% % Time-frequency: Warning if processing power\n% if strcmpi(sInputsA(1).FileType, 'timefreq') && isfield(sDataA, 'Measure') && isequal(sDataA.Measure, 'power')\n% bst_report('Warning', sProcess, [], ['You are testing power values, while a more standard analysis is to test the magnitude (ie. sqrt(power)).' 10 ...\n% 'Option #1: Recompute the time-frequency maps using the option \"Measure: Magnitude\".' 10 ...\n% 'Option #2: Run the process \"Extract > Measure from complex values\", with option \"Magntiude\".']);\n% end\n\n % ===== UNCONSTRAINED SOURCES =====\n % Detect if the source model is unconstrained\n isUnconstrained = panel_scout('isUnconstrained', sDataA);\n % Do not allow unconstrained sources without a norm\n if isUnconstrained && ~OPTIONS.isAbsolute\n % Unconstrained models: Ok if using \n if strcmpi(OPTIONS.TestType, 'absmean') % && (sDataA.nComponents == 3)\n OPTIONS.TestType = 'absmean_unconstr';\n else\n bst_report('Error', sProcess, [], ['Cannot run this test on unconstrained sources:' 10 'you must compute the norm of the three orientations first.']);\n return;\n end\n end\n\n \n % === COMPUTE TEST ===\n % Run the permutation test\n [pmap, tmap, nA, nB] = bst_permtest(sDataA.(matName), sDataB.(matName), OPTIONS.TestType, OPTIONS.Dim, Randomizations, OPTIONS.TestTail, OPTIONS.isZeroBad);\n % Finished processing\n bst_progress('text', 'Saving the results...');\n\n % Bad channels: For recordings, keep only the channels that are good in BOTH A and B sets\n switch lower(sInputsA(1).FileType)\n case 'data'\n ChannelFlag = sDataA.ChannelFlag;\n ChannelFlag(sDataB.ChannelFlag == -1) = -1;\n case {'results', 'timefreq', 'matrix'}\n ChannelFlag = [];\n end\n \n % === DISPLAYED UNITS ===\n switch (OPTIONS.TestType)\n case 'ttest_equal', DisplayUnits = 't';\n case 'ttest_unequal', DisplayUnits = 't';\n case 'ttest_paired', DisplayUnits = 't';\n case 'signtest', DisplayUnits = 'N';\n case 'wilcoxon_paired', DisplayUnits = 'W';\n case 'absmean', DisplayUnits = 'T';\n case 'absmean_unconstr', DisplayUnits = 'T';\n % case 'wilcoxon', DisplayUnits = 'W';\n otherwise, error('Invalid statistic.');\n end\n \n % === CONVERT BACK MATRIX => DATA ===\n % If processing recordings with only some sensor types selected\n if strcmpi(sInputsA(1).FileType, 'data') && strcmpi(OutputType, 'matrix') && ~isempty(OPTIONS.SensorTypes) && ~OPTIONS.isAvgTime && ~OPTIONS.isAvgRow && ~OPTIONS.isAvgFreq\n % Get the list of selected sensors\n dataTypes = strtrim(str_split(OPTIONS.SensorTypes, ',;'));\n % If only major data types were selected: save results in \"data\" format\n if ~isempty(dataTypes) && all(ismember(dataTypes, {'MEG','EEG','MEG MAG''MEG GRAD','MEG GRAD2','MEG GRAD3','SEEG','ECOG','NIRS'}))\n % Load channel file\n ChannelMat = in_bst_channel(sInputsA(1).ChannelFile);\n % Find channel names in the output row names\n iChannels = channel_find(ChannelMat.Channel, OPTIONS.SensorTypes);\n % Convert output data matrices\n % tmap\n tmap_tmp = zeros(length(ChannelMat.Channel), size(tmap,2), size(tmap,3));\n tmap_tmp(iChannels,:,:) = tmap;\n tmap = tmap_tmp;\n % pmap\n pmap_tmp = zeros(size(tmap_tmp));\n pmap_tmp(iChannels,:,:) = pmap;\n pmap = pmap_tmp;\n % nA\n if ~isempty(nA)\n nA_tmp = zeros(size(tmap_tmp));\n nA_tmp(iChannels,:,:) = nA;\n nA = nA_tmp;\n end\n % nB\n if ~isempty(nB)\n nB_tmp = zeros(size(tmap_tmp));\n nB_tmp(iChannels,:,:) = nB;\n nB = nB_tmp;\n end\n % New channel flag\n tmpChannelFlag = -1 .* ones(length(ChannelMat.Channel), 1);\n if ~isempty(ChannelFlag) && (length(ChannelFlag) == length(iChannels))\n tmpChannelFlag(iChannels) = ChannelFlag;\n else\n tmpChannelFlag(iChannels) = 1;\n end\n ChannelFlag = tmpChannelFlag;\n % Convert Stat structure\n OutputType = 'data';\n sDataA.RowNames = [];\n end\n end\n \n % === OUTPUT STRUCTURE ===\n % Initialize output structure\n sOutput = db_template('statmat');\n sOutput.pmap = pmap;\n sOutput.tmap = tmap;\n sOutput.df = [];\n sOutput.Correction = 'no';\n sOutput.Type = OutputType;\n sOutput.ChannelFlag = ChannelFlag;\n sOutput.Time = sDataA.Time;\n sOutput.ColormapType = 'stat2';\n sOutput.DisplayUnits = DisplayUnits;\n if strcmpi(OPTIONS.TestType, 'absmean_unconstr')\n sOutput.nComponents = 1;\n elseif isfield(sDataA, 'nComponents')\n sOutput.nComponents = sDataA.nComponents;\n end\n if isfield(sDataA, 'GridAtlas')\n sOutput.GridAtlas = sDataA.GridAtlas;\n end\n if isfield(sDataA, 'Freqs')\n sOutput.Freqs = sDataA.Freqs;\n end\n if isfield(sDataA, 'TFmask')\n sOutput.TFmask = sDataA.TFmask;\n end\n % Row names\n if isfield(sDataA, 'Description') && ~isempty(sDataA.Description)\n RowNames = sDataA.Description;\n elseif isfield(sDataA, 'RowNames') && ~isempty(sDataA.RowNames)\n RowNames = sDataA.RowNames;\n else\n RowNames = [];\n end\n if ~isempty(RowNames)\n if strcmpi(OutputType, 'matrix')\n sOutput.Description = RowNames;\n elseif strcmpi(OutputType, 'timefreq')\n sOutput.RowNames = RowNames;\n end\n end\n % Save options\n sOutput.Options = OPTIONS;\n % Save the number of good samples used for both sets: \n % In compressed format (keeping only one value per row, if all the other dimensions are the same)\n if isequal(nA(1:size(nA,1))', mean(mean(nA,2),3))\n sOutput.Options.nGoodSamplesA = nA(1:size(nA,1))';\n sOutput.Options.nGoodSamplesB = nB(1:size(nB,1))';\n % Or saving the full list of good samples \n else\n sOutput.Options.nGoodSamplesA = nA;\n sOutput.Options.nGoodSamplesB = nB;\n end\nend\n\n\n \n ", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/process/functions/process_test_permutation2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.4927481476326507}} {"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 permutations = dtiBootGetPermutations(permuteMatrix, numPermutations, bRepetition)\n%\n% permutations = dtiBootGetPermutations(permuteMatrix, numPermutations, [bRepetition=0])\n%\n%\n% HISTORY:\n% 2007.06.22 RFD wrote it\n\nif ieNotDefined('bRepetition')\n bRepetition = 0;\nend\n\nif(bRepetition==0)\n numVols = permuteMatrix;\n permutations = zeros(numVols,numPermutations);\n for(ii=1:numVols)\n %permutations(ii,:) = randsample(1:numVols,numPermutations,true);\n permutations(ii,:) = ceil(numVols*rand(1,numPermutations));\n end\nelse\n numVols = size(permuteMatrix,1);\n permutations = zeros(numVols,numPermutations);\n for(ii=1:numVols)\n permutations(ii,:) = permuteMatrix{ii}(ceil(length(permuteMatrix{ii}).*rand(1,numPermutations)));\n end\nend\n\nreturn", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrDiffusion/preprocess/dtiBootGetPermutations.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.49274813728845696}} {"text": "function z=smooth_lf(x,y,varargin)\n\n% must (unlike R smooth.lf() function) give x and y.\n% also R's direct=T is automatic.\n%\n\nxev = x;\nif (k>1)\n if (strcmp(varargin{1},'xev'))\n xev = varargin{2};\n varargin(1:2) = [];\n end;\nend;\nfit = locfit(x,y,varargin{:},'ev',xev,'module','simple');\nz = lfknots(fit);\nfv = invlink(z(:,1),fit.fit_points.family_link);\n\nz = { xev, fv };\n\nreturn;\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/chronux_2_12/locfit/m/smooth_lf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.49274813025874803}} {"text": "% This is used to set the evaluation metrics that to be computed\n%\n% Author:Xingchen Zhang, Ping Ye, Gang Xiao\n% Contact: xingchen.zhang@imperial.ac.uk\n\nfunction metrics=configMetrics\n\n metricVIFB={struct('name','Avg_gradient'),...\n struct('name','Cross_entropy'),...\n struct('name','Edge_intensity'),...\n struct('name','Entropy'),...\n struct('name','Mutinf'),...\n struct('name','Psnr'),...\n struct('name','Qabf'),...\n struct('name','Qcb'),...\n struct('name','Qcv'),... \n struct('name','Rmse'),...\n struct('name','Spatial_frequency'),...\n struct('name','Ssim'),...\n struct('name','Variance'),...\n };\n\n metrics = [metricVIFB];\n", "meta": {"author": "xingchenzhang", "repo": "VIFB", "sha": "7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa", "save_path": "github-repos/MATLAB/xingchenzhang-VIFB", "path": "github-repos/MATLAB/xingchenzhang-VIFB/VIFB-7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa/util/configMetrics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.49274811991455436}} {"text": "function a = one_vs_one(c,hyper) \n\n%=========================================================================\n% ONE_VS_ONE one_vs_one object\n%========================================================================= \n% A=ONE_VS_ONE(C,H) returns an one_vs_one object which trains several \n% algorithm C on pairwise problems of class i against class j, \n% and is initialized with hyperparameters H. The classifiers are combined\n% by outputting the class with the most votes.\n%\n% Model\n% child=svm -- classifier to use for each sub-problem\n%\n% Methods:\n% train, test, get_w \n%=========================================================================\n% Reference : Multi-class Support Vector Machines \n% Author : Jason Weston , C. Watkins\n% Link : http://citeseer.ist.psu.edu/8884.html\n%========================================================================= \n \n % model\n a.nrofclasses=[];\n if nargin==0\n a.child={svm}; \n else\n a.child=c; %% algorithms to use \n if ~isa(c,'cell') \n a.child={c}; \n end; \n end\n \n %% set to use unsigned output if possible \n for i=1:length(a.child)\n a.child{i}.algorithm.use_signed_output=0;\n end\n \n p=algorithm('one-vs-one');\n a= class(a,'one_vs_one',p);\n %hyperparams are supplied\n if nargin==2\n eval_hyper; \n end\n \n \n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/spider/mclass/@one_vs_one/one_vs_one.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.4927003698395125}} {"text": "% DEMSILHOUETTELINEAR1 Model silhouette data with independent linear models.\n\n% FORMAT\n% DESC runs a simple regression on the Agawal and Triggs data.\n%\n% SEEALSO : demSilhouetteGp1, demSilhouetteAverage\n% \n% COPYRIGHT : Neil D. Lawrence, 2008\n\n% GP\n\nrandn('seed', 1e7)\nrand('seed', 1e7)\n\ndataSetName = 'silhouette';\nexperimentNo = 1;\n\n% load data\n[X, y, XTest, yTest] = mapLoadData(dataSetName);\n\n\n% Set up the model\noptions = linearOptions;\n\nq = size(X, 2);\nd = size(y, 2);\nmodel = linearCreate(q, d, options);\n\n\nmodel = linearOptimise(model, X, y);\nmodelDisplay(model)\n\n% Save results\ncapName = dataSetName;;\ncapName(1) = upper(capName(1));\nfileBaseName = ['dem' capName 'Linear' num2str(experimentNo)];\nsave([fileBaseName '.mat'], 'model');\n\n\ndemSilhouettePlot\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/gp/demSilhouetteLinear1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.4926429556092759}} {"text": "function tfc_data = readBESAtfcs(filename)\n\n% readBESAtfcs reads single trial TFC data exported from BESA Research.\n%\n% Use as\n% tfc = readBESAtfcs(filename)\n%\n% The output is a structure containing a 3D matrix with complex numbers \n% for every trial. The size of the matrix is \n% [NChannels x NFreqSamples x NTimeSamples]. \n%\n% Created June 28, 2012 Todor Jordanov\n\nif isempty(findstr(filename,'.'))\n \n filename = [filename,'.tfcs'];\n \nend\n\nfp = fopen(filename, 'r');\n\nif (fp)\n \n tfc_data.trials = {};\n \n n_trials = 0;\n n_channels = 0;\n n_freqs = 0;\n\n tline = fgetl(fp);\n tline = strtrim(tline);\n \n while ischar(tline)\n \n if(strncmpi(tline, 'Trial', 5))\n \n n_trials = n_trials + 1;\n n_channels = 0;\n n_freqs = 0;\n \n elseif(strncmpi(tline, 'Channel', 7))\n\n n_channels = n_channels + 1;\n n_freqs = 0;\n\n else\n \n tline = strtrim(tline);\n tmp = regexp(tline, '\\t', 'split');\n n_samples = size(tmp, 2);\n n_freqs = n_freqs + 1;\n \n for i=1:n_samples\n \n two_reals = sscanf(tmp{i}, '%f +i* %f');\n tfc_data.trials{n_trials}(n_channels, n_freqs, i) = ...\n complex(two_reals(1), two_reals(2));\n \n end\n \n end\n \n tline = fgetl(fp);\n\n end\n\n fclose(fp);\n\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/besa/readBESAtfcs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.49264294628843175}} {"text": "function res = im2row(im, winSize)\n%res = im2row(im, winSize)\n[sx,sy,sz] = size(im);\n\nres = zeros((sx-winSize(1)+1)*(sy-winSize(2)+1),prod(winSize),sz);\ncount=0;\nfor y=1:winSize(2)\n for x=1:winSize(1)\n count = count+1;\n res(:,count,:) = reshape(im(x:sx-winSize(1)+x,y:sy-winSize(2)+y,:),...\n (sx-winSize(1)+1)*(sy-winSize(2)+1),1,sz);\n end\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/utils/utils_SPIRiT/im2row.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.4926429381177526}} {"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 spm_dartel_dotprods(job)\n% Generate a kernel from dot-products of images\n% FORMAT spm_dartel_dotprods(job)\n% job.images - Images to use\n% job.dotprod - Part of filename for results\n%_______________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% John Ashburner\n% $Id: spm_dartel_dotprods.m 4492 2011-09-16 12:11:09Z guillaume $\n\nP = strvcat(job.images);\n[pth,nam,ext] = fileparts(job.dotprod);\nofname = fullfile(pwd,['dp_' nam '.mat']);\n\nN = nifti(P);\nn = numel(N);\ndm= size(N(1).dat);\ndat=cell(1,numel(N));\nfor i=1:numel(N),\n dat{i} = reshape(N(i).dat,[prod(dm),1]);\nend\nPhi = zeros(n,n);\n\nif isfield(job,'weight') && ~isempty(job.weight),\n Pmsk = strvcat(job.weight);\n Nmsk = nifti(Pmsk);\n msk = Nmsk.dat;\n dmsk = size(msk);\n if any(dmsk(1:3) ~= dm(1:3)),\n error('Wrong sized weighting image.');\n end\n msk = reshape(msk,[prod(dmsk),1]);\n if numel(dmsk)==3,\n msk1 = msk;\n for i=2:prod(dm(4:end)),\n msk = [msk;msk1];\n end\n end\nend\n\nmem = 32*1024*1024; % Mbytes of RAM to use\nbs = ceil(mem/8/n); % Block size\nnd = prod(dm);\nnblock = ceil(prod(dm)/bs);\nspm_progress_bar('Init',nblock,...\n 'Generating kernel','Blocks complete');\nfor k=1:nblock,\n o = bs*(k-1)+(1:bs);\n o = o(o0;\n o = o(tmp);\n wt = wt(tmp);\n end\n if ~isempty(o),\n X = zeros(numel(o),numel(dat));\n for i=1:n,\n tmp = dat{i}(o);\n tmp(~isfinite(tmp)) = 0;\n if exist('wt','var'), tmp = tmp.*wt; end\n X(:,i) = tmp;\n end\n Phi = Phi + X'*X;\n clear X\n end\n spm_progress_bar('Set',k);\nend\nspm_progress_bar('Clear');\ninput = job;\ntyp = 'images';\nsave(ofname,'Phi','input','typ', spm_get_defaults('mat.format'));\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/spm12/toolbox/DARTEL/spm_dartel_dotprods.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.49259071929189374}} {"text": "report_this_filefun(mfilename('fullpath'));\n\nclf\n[X,Y,Z] = meshgrid(gx,gy,gz);\nv = [];\ni = 0.05\nii = 0.05\nfor i3 = 1:2:length(gy)\n i3 = gy(i3);\n l = loc(2,:) == i3;\n re3 = reshape(as(l),length(gz),length(gx));\n r = reshape(loc(4,l),length(gz),length(gx));\n l = r > tresh;\n re3(l) = zeros(1,length(find(l)))*nan;\n rect = [i ii 0.15 0.15];\n i = i+0.20;\n if i > 0.9 ; i = 0.05 ; ii = ii + 0.20; end\n axes('position',rect)\n pcolor(gx,-gz,re3)\n caxis([min(as) max(as)])\n colormap(jet)\n title([ 'Lat=' num2str(i3) ' km'],'FontSize',8)\n set(gca,'FontSize',8)\n hold on\n l = a.Latitude > i3-dy/2 & a.Latitude < i3+dy/2;\n plot3(a(l,1),-a(l,7),a(l,7)*0,'k.')\n shading interp\n % axis('off')\n hold on\nend\n\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/map3dy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.492553167132284}} {"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": "function [x] = spm_gen_phase(P,M,U)\n% Generate state activities for trial-specific phase-coupled activity\n% FORMAT [x] = spm_gen_phase(P,M,U)\n%\n% P - parameters\n% M - model structure\n% U - trial-specific effects\n%\n% x - states\n%\n%__________________________________________________________________________\n% Copyright (C) 2009 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny\n% $Id: spm_gen_phase.m 2908 2009-03-20 14:54:03Z will $\n\n\n% between-trial inputs\n%==========================================================================\ntry, X = U.X; catch, X = sparse(1,0); end\n\nif isfield(M,'trial')\n Mx=M.x;\nend\n\n% cycle over trials\n%--------------------------------------------------------------------------\nfor c = 1:size(X,1)\n \n % baseline parameters\n %----------------------------------------------------------------------\n Q = P;\n\n % trial-specific inputs\n %----------------------------------------------------------------------\n for i = 1:size(X,2)\n Q.As = Q.As + X(c,i)*Q.Bs{i};\n end\n if isfield(Q,'Ac')\n for i = 1:size(X,2)\n Q.Ac = Q.Ac + X(c,i)*Q.Bc{i};\n end\n end\n \n if isfield(M,'trial')\n % Set up trial-specific initial state\n M.x=M.trial{c}.x;\n end\n \n x{c,1} = spm_int_ode(Q,M,U);\n \nend\n\nif isfield(M,'trial')\n M.x=Mx;\nend\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/dcm_meeg/spm_gen_phase.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.49254899744864633}} {"text": "%% Copyright (C) 2014-2016 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 isallconstant (@var{x})\n%% Whether all elements of a symbolic array are constant.\n%%\n%% Example:\n%% @example\n%% @group\n%% A = [1 2 sym(pi); sym(4) 5 6]\n%% @result{} A = (sym 2\u00d73 matrix)\n%% \u23a11 2 \u03c0\u23a4\n%% \u23a2 \u23a5\n%% \u23a34 5 6\u23a6\n%%\n%% isallconstant (A)\n%% @result{} ans = 1\n%% @end group\n%%\n%% @group\n%% A(1) = sym('x')\n%% @result{} A = (sym 2\u00d73 matrix)\n%% \u23a1x 2 \u03c0\u23a4\n%% \u23a2 \u23a5\n%% \u23a34 5 6\u23a6\n%%\n%% isallconstant (A)\n%% @result{} ans = 0\n%% @end group\n%% @end example\n%%\n%% @seealso{@@sym/isconstant, @@sym/symvar, findsymbols}\n%% @end defmethod\n\n\nfunction z = isallconstant(x)\n\n z = isempty (findsymbols (x));\n\nend\n\n\n%!assert (isallconstant([sym(1) 2 3]))\n\n%!test\n%! syms x\n%! assert (~isallconstant([sym(1) x 3]))\n\n%!test\n%! syms x\n%! assert (~isallconstant([sym(1) x; sym(2) 3]))\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/isallconstant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.4925198336196468}} {"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": "% SYNTAX:\n% [data_dN, tInc, svs, nSV, tInc0] = hmrR_MotionCorrectPCArecurse(data_d, probe, mlActMan, mlActAuto, tIncMan, tMotion, tMask, STDEVthresh, AMPthresh, nSV, maxIter, turnon)\n%\n%\n% UI NAME:\n% Motion_Correct_PCA_Recurse\n%\n%\n% DESCRIPTION:\n% Identified motion artifacts in an input data matrix d. If any active\n% data channel exhibits a signal change greater than STDEVthresh or\n% AMPthresh, then a segment of data around that time point is marked as a\n% motion artifact. Set maxIter=0 to skip this function.\n%\n%\n% INPUTS:\n% data_d: data matrix, timepoints x sd pairs\n% sd: Source Detector Structure. The active data channels are indicated in\n% SD.MeasListAct.\n% mlActMan: Cell array of vectors, one for each time base in data, specifying\n% active/inactive channels with 1 meaning active, 0 meaning inactive\n% mlActAuto: Cell array of vectors, one for each time base in data, specifying\n% active/inactive channels with 1 meaning active, 0 meaning inactive\n% tIncMan: Data that has been manually excluded. 0-excluded. 1-included.\n% Vector same length as d.\n% tMotion: Check for signal change indicative of a motion artifact over\n% time range tMotion. Units of seconds. Typically tMotion=0.5.\n% tMask: Mark data over +/- tMask seconds around the identified motion\n% artifact as a motion artifact. Units of seconds. Typicall tMask=1.\n% STDEVthresh: If the signal d for any given active channel changes by more\n% that stdev_thresh * stdev(d) over the time interval tMotion, then\n% this time point is marked as a motion artifact. The standard deviation is\n% determined for each channel independently.\n% AMPthresh: If the signal d for any given active channel changes by more\n% that AMPthresh over the time interval tMotion, then this time point\n% is marked as a motion artifact.\n% nSV: This is the number of principal components to remove from the data.\n% If this number is less than 1, then the filter removes the first n\n% components of the data that removes a fraction of the variance\n% up to nSV. Yucel et al uses nSV=0.97.\n% maxIter: Maximum number of iterations. Yucel et al uses maxIter=5;\n%\n%\n% OUTPUTS:\n% data_dN: This is the the motion corrected data.\n% tInc: a vector of length time points with 1's indicating data included\n% and 0's indicate motion artifact AFTER correction of motion\n% artifacts\n% svs: the singular values of the PCA for each iteration in each column\n% vector\n% nSV: number of singular values removed from the data.\n% tInc0: a vector of length time points with 1's indicating data included\n% and 0's indicate motion artifact BEFORE correction of motion\n% artifacts\n%\n% USAGE OPTIONS:\n% Motion_Correct_PCA_Recurse: [dod, tInc, svs, nSV, tInc0] = hmrR_MotionCorrectPCArecurse(dod, probe, mlActMan, mlActAuto, tIncMan, tMotion, tMask, STDEVthresh, AMPthresh, nSV, maxIter, turnon)\n%\n% PARAMETERS:\n% tMotion: 0.5\n% tMask: 1.0\n% STDEVthresh: 20.0\n% AMPthresh: 5.00\n% nSV: 0.97 \n% maxIter: 5 \n% turnon: 1\n%\n% PREREQUISITES:\n% Intensity_to_Delta_OD: dod = hmrR_Intensity2OD( intensity )\n%\n\nfunction [data_dN, tInc, svs, nSV, tInc0] = hmrR_MotionCorrectPCArecurse(data_d, probe, mlActMan, mlActAuto, tIncMan, tMotion, tMask, STDEVthresh, AMPthresh, nSV, maxIter, turnon)\n\nnBlks = length(data_d);\nfor iBlk=1:nBlks\n data_dN(iBlk) = DataClass(data_d(iBlk));\nend\n\n% Initialize output \ntInc = tIncMan;\nsvs = cell(nBlks,1);\nnSV = repmat({nSV}, nBlks,1);\ntInc0 = tIncMan;\n\n% Check input args\nif isempty(mlActMan)\n mlActMan = cell(nBlks,1);\nend\nif isempty(mlActAuto)\n mlActAuto = cell(nBlks,1);\nend\nif isempty(tIncMan)\n tIncMan = cell(nBlks,1);\nend\nif ~exist('turnon','var')\n turnon = 1;\nend\nif turnon==0\n return;\nend\n\nfor iBlk=1:nBlks\n data_dN(iBlk) = DataClass(data_d(iBlk));\n \n tInc(iBlk) = hmrR_MotionArtifact(data_d(iBlk), probe, mlActMan(iBlk), mlActAuto(iBlk), tIncMan(iBlk), tMotion, tMask, STDEVthresh, AMPthresh);\n\n tInc0{iBlk} = tInc{iBlk};\n \n ii=0;\n while length(find(tInc{iBlk}==0))>0 & ii 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 tests = test_imDistanceMap(varargin)\n% Test suite for function imDistanceMap.\n%\n% output = test_imDistanceMap(input)\n%\n% Example\n% test_imDistanceMap\n%\n% See also\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2018-02-22, using Matlab 2017b\n% Copyright 2010 INRA - Cepia Software Platform.\n\ntests = functiontests(localfunctions);\n\n\nfunction test_TouchingParticles(testCase)\n% Aim is to compute distance map within each label, even if some of them\n% touch each other.\n% Uses an image with a completely landlocked label region.\n\nimg = [...\n 0 0 0 0 0 0 0 0 0 0 0; ...\n 0 1 1 1 2 2 2 3 3 3 0; ...\n 0 1 1 1 2 2 2 3 3 3 0; ...\n 0 1 1 1 2 2 2 3 3 3 0; ...\n 0 1 1 1 4 4 4 3 3 3 0; ...\n 0 1 1 1 4 4 4 3 3 3 0; ...\n 0 1 1 1 4 4 4 3 3 3 0; ...\n 0 1 1 1 5 5 5 3 3 3 0; ...\n 0 1 1 1 5 5 5 3 3 3 0; ...\n 0 1 1 1 5 5 5 3 3 3 0; ...\n 0 0 0 0 0 0 0 0 0 0 0; ...\n];\n\nexp = [...\n 0 0 0 0 0 0 0 0 0 0 0; ...\n 0 1 1 1 1 1 1 1 1 1 0; ...\n 0 1 2 1 1 2 1 1 2 1 0; ...\n 0 1 2 1 1 1 1 1 2 1 0; ...\n 0 1 2 1 1 1 1 1 2 1 0; ...\n 0 1 2 1 1 2 1 1 2 1 0; ...\n 0 1 2 1 1 1 1 1 2 1 0; ...\n 0 1 2 1 1 1 1 1 2 1 0; ...\n 0 1 2 1 1 2 1 1 2 1 0; ...\n 0 1 1 1 1 1 1 1 1 1 0; ...\n 0 0 0 0 0 0 0 0 0 0 0; ...\n];\n\ndist = imDistanceMap(img, [3 4]);\n\nassertEqual(testCase, dist, exp);\n", "meta": {"author": "mattools", "repo": "matImage", "sha": "94d892c7beac0db32daadf2646ce37f58e894caf", "save_path": "github-repos/MATLAB/mattools-matImage", "path": "github-repos/MATLAB/mattools-matImage/matImage-94d892c7beac0db32daadf2646ce37f58e894caf/tests/imFilters/test_imDistanceMap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.8006919973399709, "lm_q1q2_score": 0.4924959235727187}} {"text": "% This is material illustrating the methods from the book\n% Financial Modelling - Theory, Implementation and Practice with Matlab\n% source\n% Wiley Finance Series\n% ISBN 978-0-470-74489-5\n%\n% Date: 02.05.2012\n%\n% Authors: Joerg Kienitz\n% Daniel Wetterau\n%\n% Please send comments, suggestions, bugs, code etc. to\n% kienitzwetterau_FinModelling@gmx.de\n%\n% (C) Joerg Kienitz, Daniel Wetterau\n% \n% Since this piece of code is distributed via the mathworks file-exchange\n% it is covered by the BSD license \n%\n% This code is being provided solely for information and general \n% illustrative purposes. The authors will not be responsible for the \n% consequences of reliance upon using the code or for numbers produced \n% from using the code. \n\n\n\nfunction y = StuCVaR4(x)\n% General method to compute CVaR for Student distribution with 4 degrees\n% of freedom\n f = @(t,n) -(n^(n-2)*(n+t.^2).^(.5-.5*n)*gamma(.5*(n-1))/(2*sqrt(pi)*gamma(.5*n)));\n arg = InverseCDF4(x);\n y = 1 / sqrt(2)*f(arg,4)./x;\nend\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/38362-student-var-cvar/VaR_CVaR/StuCVaR4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4924959206473711}} {"text": "function D = compute_deviator_tensor(T)\n\n% compute_deviator_tensor - compute trace free tensor\n%\n% D = compute_deviator_tensor(T);\n%\n% D = T - trace(T)/2*Id\n%\n% Copyright (c) Gabriel Peyre\n\nn = size(T,1);\n\nif size(T,3)==2 && size(T,4)==2\n t = (T(:,:,1)+T(:,:,4))/2;\n D = cat(3, t, zeros(n), zeros(n), t);\n D = T - reshape(D,[n n 2 2]);\nelseif size(T,3)==3 && size(T,4)==1\n t = (T(:,:,1)+T(:,:,2))/2;\n D = cat(3, t, t, zeros(n));\n D = T - D;\nelse\n error('Wrong size');\nend", "meta": {"author": "gpeyre", "repo": "matlab-toolboxes", "sha": "0cd622c988cda6f63f64d35cd7bd096fa578e5c6", "save_path": "github-repos/MATLAB/gpeyre-matlab-toolboxes", "path": "github-repos/MATLAB/gpeyre-matlab-toolboxes/matlab-toolboxes-0cd622c988cda6f63f64d35cd7bd096fa578e5c6/toolbox_diffc/compute_deviator_tensor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.49248906566347556}} {"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: Unified Solutions, \n% Solvability/Observability Analysis and Uncertainty Description \n% in A Globally Optimal Framework.\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\nfunction x = sym2vec(X)\nn = size(X, 1);\nx = [];\nfor i = 1 : n\n x = [x; X(i, i : n).'];\nend\nend", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/utils/sym2vec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.49248906566347556}} {"text": "function h = fh03 ( p, varargin )\n\n%*****************************************************************************80\n%\n%% FH03 returns a uniform mesh size function.\n%\n% Copyright:\n%\n% (C) 2004 Per-Olof Persson. \n% See COPYRIGHT.TXT for details.\n%\n% Reference:\n%\n% Per-Olof Persson and Gilbert Strang,\n% A Simple Mesh Generator in MATLAB,\n% SIAM Review,\n% Volume 46, Number 2, June 2004, pages 329-345.\n%\n% Parameters:\n%\n% Input, real P(NP,ND), the point coordinates.\n%\n% Input, VARARGIN, room for extra arguments.\n%\n% Output, real H(NP,1), the mesh size function.\n%\n np = size ( p, 1 );\n h = ones ( np, 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/distmesh_3d/fh03.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.49234971002340966}} {"text": "function M = spm_mesh_refine(M)\n% Refine a triangle mesh\n% FORMAT M = spm_mesh_refine(M)\n% M - a patch structure or gifti object\n%__________________________________________________________________________\n%\n% See also:\n%\n% R.E. Bank, A.H. Sherman and A. Weiser. Refinement Algorithms and Data \n% Structures for Regular Local Mesh Refinement. Scientific Computing \n% (Applications of Mathematics and Computing to the Physical Sciences)\n% (R. S. Stepleman, ed.), North-Holland (1983), 3-17.\n% https://ccom.ucsd.edu/~reb/reports/a23.pdf.gz\n%__________________________________________________________________________\n% Copyright (C) 2018-2019 Wellcome Trust Centre for Neuroimaging\n\n% Guillaume Flandin\n% $Id: spm_mesh_refine.m 7514 2019-01-16 16:18:52Z guillaume $\n\n\nV = M.vertices;\nF = M.faces;\n\nNv = size(V,1);\nNf = size(F,1);\n\nVo = V;\nFo = zeros(4*Nf,3);\nA = spm_mesh_adjacency(M);\nif isfield(M,'cdata')\n cdata = M.cdata;\nelse\n cdata = [];\nend\n\nfor f=1:Nf\n T0 = F(f,:);\n T1 = T0([2 3 1]);\n v = (V(T0,:) + V(T1,:)) / 2;\n if ~isempty(cdata), C = (cdata(T0,:) + cdata(T1,:)) / 2; end\n \n s = 1:3;\n b = [false false false];\n for j=1:3\n if A(T0(j),T1(j)) == 1\n s(j) = Nv + 1;\n A(T0(j),T1(j)) = s(j);\n A(T1(j),T0(j)) = s(j);\n Nv = s(j);\n b(j) = true;\n else\n s(j) = A(T0(j),T1(j));\n end\n end\n Vo(end+1:end+nnz(b),:) = v(b,:);\n if ~isempty(cdata), cdata(end+1:end+nnz(b),:) = C(b,:); end\n T0(4:6) = s;\n \n Fo(4*f+(-3:0),:) = T0([1 4 6;4 2 5;6 5 3;4 5 6]);\nend\n\nM.faces = Fo;\nM.vertices = Vo;\nif ~isempty(cdata), M.cdata = cdata; end\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_mesh_refine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.4923497058007778}} {"text": "function cin_test ( )\n\n%*****************************************************************************80\n%\n%% CIN_TEST tests R4_CIN and R8_CIN.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 September 2011\n%\n% Author:\n%\n% John Burkardt\n%\n addpath ( '../test_values' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CIN_TEST:\\n' );\n fprintf ( 1, ' Test CIN_VALUES, R4_CIN, R8_CIN.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X CIN(X)\\n' );\n fprintf ( 1, ' R4_CIN(X) Diff\\n' );\n fprintf ( 1, ' R8_CIN(X) Diff\\n' );\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, x, fx1 ] = cin_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n fx2 = r4_cin ( single ( x ) );\n fx3 = r8_cin ( x );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' %14.4f %14.6g\\n', x, fx1 );\n fprintf ( 1, ' %14.6g %14.6g\\n', fx2, abs ( fx1 - fx2 ) );\n fprintf ( 1, ' %14.6g %14.6g\\n', fx3, abs ( fx1 - fx3 ) );\n\n end\n\n rmpath ( '../test_values' );\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/cin_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778403, "lm_q2_score": 0.7772998508568417, "lm_q1q2_score": 0.492349703487978}} {"text": "function mObject3 = timeAlignedDirectSTRAIGHTmorphing(mObject1,mObject2,mRate,mixMethod);\n% Morphing based on time-aligned mixing of STRAIGHT parameters\n% mObject3 = timeAlignedDirectSTRAIGHTmorphing(mObject1,mObject2,mRate,mixMethod);\n\n% Designed and coded by Hideki Kawahara\n% 28/Feb./2005\n% Copyright(c) 2005, Hideki Kawahara\n\nmObject3 = checkForSimilarity(mObject1,mObject2);\nif length(mObject3) ==0;return;end;\ndtFrame = mObject1.frameUpdateInterval;\nendLocation1 = (length(mObject1.F0)-1)*dtFrame; % in ms\nendLocation2 = (length(mObject2.F0)-1)*dtFrame; % in ms\ntimeAnchor1 = [0;mObject1.anchorTimeLocation;endLocation1];\ntimeAnchor2 = [0;mObject2.anchorTimeLocation;endLocation2];\nlocationOn1 = (0:length(mObject1.F0)-1)*dtFrame;\nlocationOn2 = (0:length(mObject2.F0)-1)*dtFrame;\nmapFrom1to2 = interp1(timeAnchor1,timeAnchor2,locationOn1);\n[nr1,nc1] = size(mObject1.spectrogram);\n[nr2,nc2] = size(mObject2.spectrogram);\n\n%---- mixing on mObject1's time axis\nnAxis1 = length(locationOn1); \nnAxis2 = length(locationOn2);\nmorphedF0 = zeros(nAxis1,1);\nmorphedAp = zeros(nr1,nAxis1);\nmorphedSgram = zeros(nr1,nAxis1);\nweightSumF0 = zeros(nAxis1,1);\nfor ii=1:nAxis1\n mappedIndexOn2 = mapFrom1to2(ii)/dtFrame+1;\n iFloor = floor(mappedIndexOn2);\n iFraction = mappedIndexOn2-iFloor;\n dAp = iFraction*(mObject2.aperiodicityIndex(:,min(iFloor+1,nAxis2))-mObject2.aperiodicityIndex(:,iFloor));\n morphedAp(:,ii) = (1-mRate)*mObject1.aperiodicityIndex(:,ii)+mRate*(mObject2.aperiodicityIndex(:,iFloor)+dAp);\n switch mixMethod\n case 'linear'\n dSgram = iFraction*(mObject2.spectrogram(:,min(iFloor+1,nAxis2))-mObject2.spectrogram(:,iFloor));\n morphedSgram(:,ii) = (1-mRate)*mObject1.spectrogram(:,ii)+mRate*(mObject2.spectrogram(:,iFloor)+dSgram);\n case 'log'\n dSgram = iFraction*(log(mObject2.spectrogram(:,min(iFloor+1,nAxis2)))-log(mObject2.spectrogram(:,iFloor)));\n tmp = (1-mRate)*log(mObject1.spectrogram(:,ii))+mRate*(log(mObject2.spectrogram(:,iFloor))+dSgram);\n morphedSgram(:,ii) = exp(tmp);\n end;\n if mObject1.F0(ii)>0\n morphedF0(ii) = (1-mRate)*log(mObject1.F0(ii));\n weightSumF0(ii) = (1-mRate);\n end;\n if (mObject2.F0(iFloor)>0) & (mObject2.F0(min(iFloor+1,nAxis2))>0)\n dF0 = iFraction*(log(mObject2.F0(min(iFloor+1,nAxis2)))-log(mObject2.F0(iFloor)));\n morphedF0(ii) = mRate*(log(mObject2.F0(iFloor))+dF0)+morphedF0(ii);\n weightSumF0(ii) = weightSumF0(ii)+mRate;\n end;\nend;\nmorphedF0(weightSumF0>0) = exp(morphedF0(weightSumF0>0)./weightSumF0(weightSumF0>0));\n\n%----- mapping back onto morphed time axis\ntimeAnchorMorph = (1-mRate)*timeAnchor1 + mRate*timeAnchor2;\nlocationOnMorph = (0:(timeAnchorMorph(end)/dtFrame))*dtFrame;\nmapFormMorphTo1 = interp1(timeAnchorMorph,timeAnchor1,locationOnMorph);\nnAxisMorph = length(locationOnMorph);\nmorphedApOnMorph = zeros(nr1,nAxisMorph);\nmorphedSgramOnMorph = zeros(nr1,nAxisMorph);\nmorphedF0onMorph = zeros(nAxisMorph,1);\nfor ii=1:nAxisMorph\n mappedIndexOn1 = mapFormMorphTo1(ii)/dtFrame+1;\n iFloor = floor(mappedIndexOn1);\n iFraction = mappedIndexOn1-iFloor;\n morphedApOnMorph(:,ii) = morphedAp(:,iFloor) ...\n +iFraction*(morphedAp(:,min(iFloor+1,nAxis1))-morphedAp(:,iFloor));\n morphedSgramOnMorph(:,ii) = morphedSgram(:,iFloor) ...\n +iFraction*(morphedSgram(:,min(iFloor+1,nAxis1))-morphedSgram(:,iFloor));\n if (morphedF0(iFloor)>0) & (morphedF0(min(iFloor+1,nAxis1))>0)\n dF0 = iFraction*(morphedF0(min(iFloor+1,nAxis1))-morphedF0(iFloor));\n morphedF0onMorph(ii) = morphedF0(iFloor)+dF0;\n end;\nend;\nmObject3.F0 = morphedF0onMorph; \nmObject3.aperiodicityIndex = morphedApOnMorph;\nmObject3.spectrogram = morphedSgramOnMorph;\nmObject3.anchorTimeLocation = timeAnchorMorph(2:end-1);\nmObject3.anchorFrequency = (1-mRate)*mObject1.anchorFrequency+mRate*mObject2.anchorFrequency;\n%mObject3 = morphedAp; % This line is a dummy.\n\n%%% ------ Internal function to check for object's similarity\nfunction mObject3 = checkForSimilarity(mObject1,mObject2)\nmObject3 = [];\nif mObject1.samplingFrequency ~= mObject2.samplingFrequency;mObject3 = [];return;end;\nif mObject1.frameUpdateInterval ~= mObject2.frameUpdateInterval;mObject3 = [];return;end;\nif length(mObject1.anchorTimeLocation) ~= length(mObject2.anchorTimeLocation);mObject3 = [];return;end;\nnAnchor = length(mObject1.anchorTimeLocation);\nfor ii=1:nAnchor % check for similarity of anchor structure\n frequencyAnchor1 = mObject1.anchorFrequency;\n frequencyAnchor2 = mObject2.anchorFrequency;\n if (sum(frequencyAnchor1>0) ~= sum(frequencyAnchor2>0)) | ...\n (sum(frequencyAnchor1<0) ~= sum(frequencyAnchor2<0))\n return;\n end;\nend;\nmObject3 = createMobject;\n", "meta": {"author": "HidekiKawahara", "repo": "legacy_STRAIGHT", "sha": "964684981fe12cd232c5e882259dff126b3af0f2", "save_path": "github-repos/MATLAB/HidekiKawahara-legacy_STRAIGHT", "path": "github-repos/MATLAB/HidekiKawahara-legacy_STRAIGHT/legacy_STRAIGHT-964684981fe12cd232c5e882259dff126b3af0f2/morphing_src/timeAlignedDirectSTRAIGHTmorphing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.4923496992653464}} {"text": "function Cu = computeCu(nu)\n Cu_tmp1 = cell(nu,nu);\n Cu_tmp2 = cell(nu,nu);\n \n for i=1:nu\n for j=1:nu \n if i==j\n Cu_tmp1{i,j} = eye(2);\n Cu_tmp2{i,j} = -eye(2);\n else\n Cu_tmp1{i,j} = zeros(2,2);\n Cu_tmp2{i,j} = zeros(2,2);\n end\n end\n end\n \n Cu = [cell2mat(Cu_tmp1);cell2mat(Cu_tmp2)];\nend", "meta": {"author": "ccalas", "repo": "mpc", "sha": "2b30095dc94efb7799e861eb5acc6fe02110a328", "save_path": "github-repos/MATLAB/ccalas-mpc", "path": "github-repos/MATLAB/ccalas-mpc/mpc-2b30095dc94efb7799e861eb5acc6fe02110a328/computeCu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.6334102567576902, "lm_q1q2_score": 0.4923496981089464}} {"text": "function y = UpDyadLo(x,qmf)\n% UpDyadLo -- Lo-Pass Upsampling operator; periodized\n% Usage\n% u = UpDyadLo(d,f)\n% Inputs\n% d 1-d signal at coarser scale\n% f filter\n% Outputs\n% u 1-d signal at finer scale\n%\n% See Also\n% DownDyadLo, DownDyadHi, UpDyadHi, IWT_PO, iconv\n%\n\ty = iconv(qmf, UpSampleN(x) );\n\n\n% Revision History\n% 10/1/05 AM UpSample is changed to UpSampleN\n\n%\n% Copyright (c) 1993. Iain M. Johnstone\n% Last modified on October 2005. \n% \n \n \n \n \n%\n% Part of Wavelab Version 850\n% Built Tue Jan 3 13:20:40 EST 2006\n% This is Copyrighted Material\n% For Copying permissions see COPYING.m\n% Comments? e-mail wavelab@stat.stanford.edu \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/@Wavelet/private/UpDyadLo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4923376642688862}} {"text": "function n = dim(A)\n%DIM Dimension of a square matrix\n%\n% n = dim(A)\n%\n\n% written 10/16/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%\n\n if A.complex\n [m n] = size(A.mid);\n else\n [m n] = size(A.inf);\n end\n\n if m ~= n\n error('function dim called with non-square matrix')\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/dim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.7248702761768249, "lm_q1q2_score": 0.49231646065897533}} {"text": "function [C,Atp,Btp]=etprod(Cidx,A,Aidx,B,Bidx)\n% tprod wrapper to make calls more similar to Einstein Summation Convention\n%\n% [C,Atp,Btp]=etprod(Cidx,A,Aidx,B,Bidx);\n% Wrapper function for tprod to map between Einstein summation\n% convetion (ESC) and tprod's numeric calling convention e.g.\n% 1) Matrix Matrix product: \n% ESC: C_ij = A_ik B_kj <=> C = etprod('ij',A,'ik',B,'kj'); \n% 2) Vector outer product\n% ESC: C_ij = A_i B_j <=> C = etprod('ij',A,'i',B,'j'); % A,B col vec\n% C = etprod('ij',A,' i',B,' j'); % A,B row vec\n% N.B. use spaces ' ' to indicate empty/ignored *singlenton* dimensions\n% 3) Matrix vector product\n% ESC: C_i = A_ik B_k <=> C = etprod('i',A,'ik',B,'k');\n% 4) Spatial Filtering\n% ESC: FX_fte = A_cte B_cf <=> C = etprod('fte',A,'cte',B,'cf') \n% OR:\n% C = etprod({'feat','time','epoch'},A,{'ch','time','epoch'},B,{'ch','feat'})\n%\n% Inputs:\n% Cidx -- the list of dimension labels for the output\n% A -- [n-d] array of the A values\n% Aidx -- [ndims(A) x 1] (array, string, or cell array of strings) \n% list of dimension labels for A array\n% B -- [m-d] array of the B values\n% Bidx -- [ndims(B) x 1] (array, string or cell array of strings)\n% list of dimension labels for B array\n% Outputs:\n% C -- [p-d] array of output values. Dimension labels are as in Cidx\n% Atp -- [ndims(A) x 1] A's dimspec as used in the core tprod call\n% Btp -- [ndims(B) x 1] B's dimspec as used in the core tprod call\n%\n% See Also: tprod, tprod_testcases\n%\n% Copyright 2006- by Jason D.R. Farquhar (jdrf@zepler.org)\n% Permission is granted for anyone to copy, use, or modify this\n% software and accompanying documents for any uncommercial\n% purposes, provided this copyright notice is retained, and note is\n% made of any changes that have been made. This software and\n% documents are distributed without any warranty, express or\n% implied\nif ( iscell(Aidx)~=iscell(Bidx) || iscell(Cidx)~=iscell(Aidx) )\n error('Aidx,Bidx and Cidx cannot be of different types, all cells or arrays');\nend\n\nAtp = zeros(size(Aidx));\nBtp = zeros(size(Bidx));\n% Map inner product dimensions, to unique *negative* index\nfor i=1:numel(Aidx)\n if ( iscell(Aidx) ) Bmatch = strcmp(Aidx{i}, Bidx);\n else Bmatch = (Aidx(i)==Bidx);\n end\n if ( any(Bmatch) ) Btp(Bmatch)=-i; Atp(i)=-i; end;\nend\n% Spaces/empty values in the input become 0's, i.e. ignored dimensions\nif ( iscell(Aidx) ) \n Btp(strcmp(' ',Bidx))=0;Btp(strcmp('',Bidx))=0;\n Atp(strcmp(' ',Aidx))=0;Atp(strcmp('',Aidx))=0;\nelse \n Btp(' '==Bidx)=0;\n Atp(' '==Aidx)=0; \nend\n\n% Map to output position numbers, to correct *positive* index\nfor i=1:numel(Cidx);\n if ( iscell(Aidx) ) \n Atp(strcmp(Cidx{i}, Aidx))=i;\n Btp(strcmp(Cidx{i}, Bidx))=i;\n else\n Atp(Cidx(i)==Aidx)=i;\n Btp(Cidx(i)==Bidx)=i;\n end\nend\n\n% now do the tprod call.\nglobal LOG; if ( isempty(LOG) ) LOG=0; end; % N.B. set LOG to valid fd to log\nif ( LOG>0 ) \n fprintf(LOG,'tprod(%s,[%s], %s,[%s])\\n',mxPrint(A),sprintf('%d ',Atp),mxPrint(B),sprintf('%d ',Btp));\nend\nC=tprod(A,Atp,B,Btp,'n');\nreturn;\n\nfunction [str]=mxPrint(mx)\nsz=size(mx);\nif ( isa(mx,'double') ) str='d'; else str='s'; end;\nif ( isreal(mx)) str=[str 'r']; else str=[str 'c']; end;\nstr=[str ' [' sprintf('%dx',sz(1:end-1)) sprintf('%d',sz(end)) '] '];\nreturn;\n\n%----------------------------------------------------------------------------\nfunction testCase();\nA=randn(10,10); B=randn(10,10);\nC2 = tprod(A,[1 -2],B,[-2 2]);\nC = etprod('ij',A,'ik',B,'kj'); mad(C2,C)\nC = etprod({'i' 'j'},A,{'i' 'k'},B,{'k' 'j'});\nA=randn(100,100);B=randn(100,100,4);\nC3 = tprod(A,[-1 -2],B,[-1 -2 3]);\nC3 = tprod(B,[-1 -2 1],A,[-1 -2]);\nC3 = tprod(A,[-1 -2],B,[-1 -2 1]);\nC = etprod('3',A,'12',B,'123');\nC = etprod([3],A,[1 2],B,[1 2 3]);\nC = etprod({'3'},A,{'1' '2'},B,{'1' '2' '3'})\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/svm/tprod/etprod.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.49231644653753787}} {"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 [sys,x0,str,ts] = scrqp(t,x,u,flag,T0,nr,nq,np)\n% FBFW feedforward feedback controller\n% Output of the controller is calculated follows:\n%\n% R(z^-1) Q(z^-1) \n% U(z^-1) = ---------- * W(z^-1) - --------- * Y(z^-1)\n% P(z^-1) P(z^-1)\n%\n% Orders of polynomials R, Q and P are determined by parameters nr, nq and np.\n%\n% [sys,x0,str,ts] = scrqp(t,x,u,flag,T0,nr,nq,np)\n% States: x(1:nr) ... w(k-1), w(k-2), ...\n% x(nr+1:nr+nq) ... y(k-1), y(k-2), ...\n% x(nr+nq+1:nr+nq+np-1) ... u(k-2), u(k-3), ... (u(k-1) is input - see below)\n% Inputs: u(1) ... w(k)\n% u(2) ... y(k)\n% u(2+1:2+nr+1) ... r0, r1, ....\n% u(2+nr+1+1:2+nr+1+nq+1) ... q0, q1, ...\n% u(2+nr+1+nq+1+1:2+nr+1+nq+1+np+1) ... p0, p1, ...\n% u(2+nr+1+nq+1+np+1+1) ... u(k-1) real input to the controlled system, can differ to u(k) computed\n% in previous loop (case of saturation, ...)\n% T0 ... sample time\n% nr ... odrer of polynomial R (R has nr+1 coefficients)\n% nq ... odrer of polynomial R (R has nq+1 coefficients)\n% np ... odrer of polynomial R (R has np+1 coefficients)\n\nif flag == 0 %initialization \n %zero initial conditions\n x0 = zeros(nr+nq+np-1,1); \n %information about this function\n sys(1) = 0; %Number of continuous states.\n sys(2) = nr+nq+np-1; %Number of discrete states.\n sys(3) = 1; %Number of outputs.\n sys(4) = 2 + nr+1 + nq+1 + np+1 + 1; %Number of inputs.\n sys(5) = 0; %Reserved for root finding. Must be zero.\n sys(6) = 1; %Direct feedthrough flag (1=yes, 0=no)\n sys(7) = 1; %Number of sample times. This is the number of rows in TS.\n ts = [T0 0];\n str = [];\n \nelseif (flag==2 | flag==3)\n W = [u(1); x(1:nr)]; %[w(k), w(k-1), w(k-2), ...]\n Y = [u(2); x(nr+1:nr+nq)]; %[y(k), y(k-1), y(k-2), ...]\n U1 = [u(2+nr+1+nq+1+np+1+1); x(nr+nq+1:nr+nq+np-1)]; %[u(k-1), u(k-2), u(k-3),...]\n R = u(2+1:2+nr+1); % [r0, r1, ...]\n Q = u(2+nr+1+1:2+nr+1+nq+1); % [q0, q1, ...]\n p0 = u(2+nr+1+nq+1+1);\n P1 = u(2+nr+1+nq+1+2:2+nr+1+nq+1+np+1); % [p0, p1, ...]\n \n if (flag==2) %update states\n sys = [W(1:nr); Y(1:nq); U1(1:np-1)]; %[y(k-1) y(k-2) u(k-2)]\n \n else %flag == 3 compute output\n u = 1/p0*( R'*W - Q'*Y - P1'*U1);\n sys = u; \n end\n \nelse\n \n sys=[];\nend\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/8381-stcsl-standard-version/scfbfw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933535169629, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4920904466156932}} {"text": "% DEMBARENCOMAP3 Optimise model using MAP approximation with MLP kernel and linear response, using SCG optimisation and new PUMA processed data with noise variance estimation.\n\n% SHEFFIELDML\nclear,clc\nexpNo = 1;\ntype = 'mapMLPwithNoise';\nrand('seed',1);\n\nload demBarenco1;\norigModel = model;\nclear model\nsaveFigures = true;\n\ncolordef white\n[y, yvar, gene, times, scale, rawExp, rawVar] = gpsimLoadBarencoPUMAData;\n\nnumGenes = size(gene, 1);\n% Get the default options structure.\noptions = gpsimMapOptions(numGenes);\noptions.kern = 'mlp';\noptions.nonLinearity = 'linear';\noptions.includeNoise = 0;\noptions.startPoint = 0; % TF starts from 0;\noptions.endPoint = 12;\noptions.priorProteinTimes = [0]';\noptions.priorProtein = [0]';\noptions.includeNoise = 1;\n% Modify according to the range of the TF\noptions.intPoints = (options.endPoint-options.startPoint)/0.1 + 1 ;\noptions.gParam = [];\noptions.ngParam = 0;\noptions.optimiser = 'scg';\n\noptions.fix(1).index = 14; % S of p21\noptions.fix(1).value = expTransform(1, 'xtoa');\noptions.fix(2).index = 15; % D of p21\noptions.fix(2).value = expTransform(0.8, 'xtoa');\noptions.fix(3).index = 3;\noptions.fix(3).value = expTransform(1, 'xtoa');\n% options.fix(2).index = 1;\n% options.fix(2).value = expTransform(1, 'xtoa');;\n\nfor i =1:3\n times = times;\n% options.B = origModel.comp{1}.B;\n% options.D = origModel.comp{1}.D; % [0.6417 0.4094 0.4894 0.8000 0.4992];\n% options.S = origModel.comp{1}.S; % [0.4206 0.3255 0.1486 1 0.1870];\n options.S = ones(1, 5); \n options.D = rand(1, 5);\n mu = mean(y{i}, 1);\n options.B = options.D.*mu;\n model.comp{i} = gpsimMapCreate(numGenes, 1, times, y{i}, yvar{i}, options);\n if strcmp(options.kern, 'mlp')\n model.comp{i}.kern.weightVariance = 30;\n model.comp{i}.kern.biasVariance = 1000;\n % This forces kernel recompute.\n params = gpsimMapExtractParam(model.comp{i});\n model.comp{i} = gpsimMapExpandParam(model.comp{i}, params);\n end\n\nend\n\nparam = 0;\nNrep = length(model.comp);\n\nfor i = 1:Nrep\n paramvec{i} = gpsimMapExtractParam(model.comp{i}); %vector of gamma estimates\n param = param + paramvec{i};\nend\n\nparam = param/Nrep;\n\niters = 300;\n\noptions = optOptions;\noptions(14) = iters;\noptions(9) = 0;\noptions(1) = 1;\n\nnewparam = scg('gpsimMapObjective', param, options, ...\n 'gpsimMapGradients', model);\n\n% [newparam, ll, index] = minimize(param', 'gpsimMapGradFuncWrapper', iters, model);\n\nfor rep = 1:Nrep\n options = defaultOptions; \n model.comp{rep} = gpsimMapExpandParam(model.comp{rep}, newparam); \n model.comp{rep} = gpsimMapUpdateF(model.comp{rep}, options);\n model.comp{rep} = gpsimMapUpdateYpredVar(model.comp{rep});\nend\n\ntype(1) = upper(type(1)); \nsave(['demBarenco' type num2str(expNo)], 'model', 'type', 'expNo', 'scale')\ngpsimMapBarencoResults(model, type, expNo, saveFigures, scale)\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/gpsim/demBarencoMap3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49209044133300733}} {"text": "function [score] = processOneImage_CNN(net,img_path)\n\nI = imread(img_path);\nfilter_size = 7;\nfilter_ = gpuArray(fspecial('gaussian',filter_size,1.0));\nI = localNormalization(I,filter_);\npatchsize = size(net.meta.normalization.averageImage,1);\n\nif strcmp(net.meta.modelType,'DirectTraining')\n step = patchsize / 2;\nelse\n step = 64;\nend\n[x1,x2,~] = size(I);\nX = 1:step:x1-patchsize;\nY = 1:step:x2-patchsize;\ndata = zeros(patchsize,patchsize,3,length(X)*length(Y),'single');\ncnt = 1;\nfor p = 1:length(X)\n for q = 1:length(Y)\n data(:,:,:,cnt) = I(X(p):X(p)+patchsize-1,Y(q):Y(q)+patchsize-1,:);\n cnt = cnt+1;\n end\nend\n\ndata = bsxfun(@minus, single(data), net.meta.normalization.averageImage);\ndata = gpuArray(data) ;\n\nnet.eval({'data', data}) ;\nindex = find(arrayfun(@(a) strcmp(a.name, 'myLoss'), net.layers)==1);\ntlayerName = net.layers(index).inputs{1};\nscore = net.vars(net.getVarIndex(tlayerName)).value ;\nif strcmp(net.layers(end).block.lossType,'CE')\n score = squeeze(gather(vl_nnsoftmax(score)));\nelse\n score = squeeze(gather(score));\nend\n\n\nif size(score,2) == 1\n score = mean(score);\nelse\n% score_map = net.meta.classes.weights;\n% score = score_map * score;\n [score, ~,~] = svmpredict([1:size(score,2)]', double(score'), net.meta.svm_model1,'-q');\n score = mean(score);\nend\n\nend\n", "meta": {"author": "HuiZeng", "repo": "BIQA_Toolbox", "sha": "39d606574f0cbfde82ecbc3c208b353d9fa9a450", "save_path": "github-repos/MATLAB/HuiZeng-BIQA_Toolbox", "path": "github-repos/MATLAB/HuiZeng-BIQA_Toolbox/BIQA_Toolbox-39d606574f0cbfde82ecbc3c208b353d9fa9a450/tools/src/processOneImage_CNN.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4920904307676351}} {"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\u20131134.\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": "clc;\nclear all;\nclose all;\ntic;\n\n\nnegfiles = getAllFiles('data\\txt_sentoken\\neg\\');\nposfiles = getAllFiles('data\\txt_sentoken\\pos\\');\nlabels = [-ones(size(negfiles,1),1); ones(size(posfiles,1),1)];\n\nallfiles = [negfiles;posfiles];\nmycellarray ={};\n\nfor i = 1:size(allfiles,1)\n disp(sprintf('Processing review %d out of %d', i, size(allfiles,1)));\n myfile = allfiles{i};\n fid = fopen( myfile);\n s = textscan(fid,'%s','Delimiter','\\n');\n mystr = '';\n for mycellindex = 1:size(s{1,1},1)\n mystr = strcat(mystr, s{1,1}{mycellindex});\n end\n fclose(fid);\n mycellarray{end+1} = mystr;\nend\nmycellarray = mycellarray';\n%mycellarray2 = mycellarray;\n%mycellarray = mycellarray(1:5);\n\nn=70\ntic;\n\nfeatureVector = featurize(mycellarray, n, 0, 0);\nfeatureVectorOrig = featureVector;\nsave('featureVectorn70.dump','featureVector')\ntoc;\ndisp('Naive Bayes - Multinomial');\n\n%10 fold random permutation\nFresults = [];\n\nfor i = 1:10\n randomindices = randperm(2000);\n randomindices = randomindices(1:1800);\n otherindices = (1:2000)';\n testsetindex = setdiff(otherindices,randomindices)';\n trainingsetindex = randomindices ;\n trainingset = featureVector(trainingsetindex,:);\n traininglabel = labels(trainingsetindex,:);\n \n testset = featureVector(testsetindex,:);\n testlabel = labels(testsetindex,:);\n O1 = NaiveBayes.fit(trainingset,traininglabel,'dist','mn'); % or 'mvmn'\n C2 = O1.predict(testset);\n cMat2 = confusionmat(testlabel,C2);\n Fresults = [Fresults,F1measureConfusionMatrix(cMat2)];\nend\n%disp(n);\nfprintf('F1-measure for Naive Bayes classifier = %0.5f\\n', mean(Fresults))\n\ntoc;\n\ntic;\n\n\n\ndisp('Naive Bayes - Bernoulli');\n%10 fold validation\nFresults = [];\nfeatureVector = bernoulli(featureVectorOrig);\n\nfor i = 1:10\n randomindices = randperm(2000);\n randomindices = randomindices(1:1800);\n otherindices = (1:2000)';\n testsetindex = setdiff(otherindices,randomindices)';\n trainingsetindex = randomindices ;\n trainingset = featureVector(trainingsetindex,:);\n traininglabel = labels(trainingsetindex,:);\n \n testset = featureVector(testsetindex,:);\n testlabel = labels(testsetindex,:);\n O1 = NaiveBayes.fit(trainingset,traininglabel,'dist','mn'); % or 'mvmn'\n C2 = O1.predict(testset);\n cMat2 = confusionmat(testlabel,C2);\n Fresults = [Fresults,F1measureConfusionMatrix(cMat2)];\nend\n%disp(n);\nfprintf('F1-measure for Naive Bayes classifier = %0.5f\\n', mean(Fresults))\n\ntoc;\n\n\n\n\n", "meta": {"author": "faridani", "repo": "MatlabNLP", "sha": "e18e8bc44ecbc8bb6aa57312c1ee22930f805a6f", "save_path": "github-repos/MATLAB/faridani-MatlabNLP", "path": "github-repos/MATLAB/faridani-MatlabNLP/MatlabNLP-e18e8bc44ecbc8bb6aa57312c1ee22930f805a6f/examples/sentiment/sentimentanalysis.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 [segments, fs] = detectVoiced(wavFileName,t)\n\n% \n% function [segments, fs] = detectVoiced(wavFileName)\n% \n% Theodoros Giannakopoulos\n% http://www.di.uoa.gr/~tyiannak\n%\n% (c) 2010\n%\n% This function implements a simple voice detector. The algorithm is\n% described in more detail, in the readme.pdf file\n%\n% ARGUMENTS:\n% - wavFileName: the path of the wav file to be analyzed\n% - t: if provided, the detected voiced segments are played and some\n% intermediate results are also ploted\n% \n% RETURNS:\n% - segments: a cell array of M elements. M is the total number of\n% detected segments. Each element of the cell array is a vector of audio\n% samples of the respective segment. \n% - fs: the sampling frequency of the audio signal\n%\n% EXECUTION EXAMPLE:\n%\n% [segments, fs] = detectVoiced('example.wav',1);\n%\n\n\n\n% Check if the given wav file exists:\nfp = fopen(wavFileName, 'rb');\nif (fp<0)\n\tfprintf('The file %s has not been found!\\n', wavFileName);\n\treturn;\nend \nfclose(fp);\n\n% Check if .wav extension exists:\nif (strcmpi(wavFileName(end-3:end),'.wav'))\n % read the wav file name:\n [x,fs] = wavread(wavFileName);\nelse\n fprintf('Unknown file type!\\n');\n return;\nend\n\n\n% Convert mono to stereo\nif (size(x, 2)==2)\n\tx = mean(x')';\nend\n\n% Window length and step (in seconds):\nwin = 0.050;\nstep = 0.050;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% THRESHOLD ESTIMATION\n%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nWeight = 5; % used in the threshold estimation method\n\n% Compute short-time energy and spectral centroid of the signal:\nEor = ShortTimeEnergy(x, win*fs, step*fs);\nCor = SpectralCentroid(x, win*fs, step*fs, fs);\n\n% Apply median filtering in the feature sequences (twice), using 5 windows:\n% (i.e., 250 mseconds)\nE = medfilt1(Eor, 5); E = medfilt1(E, 5);\nC = medfilt1(Cor, 5); C = medfilt1(C, 5);\n\n% Get the average values of the smoothed feature sequences:\nE_mean = mean(E);\nZ_mean = mean(C);\n\n% Find energy threshold:\n[HistE, X_E] = hist(E, round(length(E) / 10)); % histogram computation\n[MaximaE, countMaximaE] = findMaxima(HistE, 3); % find the local maxima of the histogram\nif (size(MaximaE,2)>=2) % if at least two local maxima have been found in the histogram:\n T_E = (Weight*X_E(MaximaE(1,1))+X_E(MaximaE(1,2))) / (Weight+1); % ... then compute the threshold as the weighted average between the two first histogram's local maxima.\nelse\n T_E = E_mean / 2;\nend\n\n% Find spectral centroid threshold:\n[HistC, X_C] = hist(C, round(length(C) / 10));\n[MaximaC, countMaximaC] = findMaxima(HistC, 3);\nif (size(MaximaC,2)>=2)\n T_C = (Weight*X_C(MaximaC(1,1))+X_C(MaximaC(1,2))) / (Weight+1);\nelse\n T_C = Z_mean / 2;\nend\n\n% Thresholding:\nFlags1 = (E>=T_E);\nFlags2 = (C>=T_C);\nflags = Flags1 & Flags2;\n\nif (nargin==2) % plot results:\n\tclf;\n\tsubplot(3,1,1); plot(Eor, 'g'); hold on; plot(E, 'c'); legend({'Short time energy (original)', 'Short time energy (filtered)'});\n L = line([0 length(E)],[T_E T_E]); set(L,'Color',[0 0 0]); set(L, 'LineWidth', 2);\n axis([0 length(Eor) min(Eor) max(Eor)]);\n\t\n subplot(3,1,2); plot(Cor, 'g'); hold on; plot(C, 'c'); legend({'Spectral Centroid (original)', 'Spectral Centroid (filtered)'}); \n\tL = line([0 length(C)],[T_C T_C]); set(L,'Color',[0 0 0]); set(L, 'LineWidth', 2); \n axis([0 length(Cor) min(Cor) max(Cor)]);\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SPEECH SEGMENTS DETECTION\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ncount = 1;\nWIN = 5;\nLimits = [];\nwhile (count < length(flags)) % while there are windows to be processed:\n\t% initilize:\n\tcurX = [];\t\n\tcountTemp = 1;\n\t% while flags=1:\n\twhile ((flags(count)==1) && (count < length(flags)))\n\t\tif (countTemp==1) % if this is the first of the current speech segment:\n\t\t\tLimit1 = round((count-WIN)*step*fs)+1; % set start limit:\n\t\t\tif (Limit1<1)\tLimit1 = 1; end \n\t\tend\t\n\t\tcount = count + 1; \t\t% increase overall counter\n\t\tcountTemp = countTemp + 1;\t% increase counter of the CURRENT speech segment\n\tend\n\n\tif (countTemp>1) % if at least one segment has been found in the current loop:\n\t\tLimit2 = round((count+WIN)*step*fs);\t\t\t% set end counter\n\t\tif (Limit2>length(x))\n Limit2 = length(x);\n end\n \n Limits(end+1, 1) = Limit1;\n Limits(end, 2) = Limit2;\n end\n\tcount = count + 1; % increase overall counter\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%\n% POST - PROCESS %\n%%%%%%%%%%%%%%%%%%%%%%%\n\n% A. MERGE OVERLAPPING SEGMENTS:\nRUN = 1;\nwhile (RUN==1)\n RUN = 0;\n for (i=1:size(Limits,1)-1) % for each segment\n if (Limits(i,2)>=Limits(i+1,1))\n RUN = 1;\n Limits(i,2) = Limits(i+1,2);\n Limits(i+1,:) = [];\n break;\n end\n end\nend\n\n% B. Get final segments:\nsegments = {};\nfor (i=1:size(Limits,1))\n segments{end+1} = x(Limits(i,1):Limits(i,2)); \nend\n\nif (nargin==2) \n subplot(3,1,3);\n % Plot results and play segments:\n time = 0:1/fs:(length(x)-1) / fs;\n for (i=1:length(segments))\n hold off;\n P1 = plot(time, x); set(P1, 'Color', [0.7 0.7 0.7]); \n hold on;\n for (j=1:length(segments))\n if (i~=j)\n timeTemp = Limits(j,1)/fs:1/fs:Limits(j,2)/fs;\n P = plot(timeTemp, segments{j});\n set(P, 'Color', [0.4 0.1 0.1]);\n end\n end\n timeTemp = Limits(i,1)/fs:1/fs:Limits(i,2)/fs;\n P = plot(timeTemp, segments{i});\n set(P, 'Color', [0.9 0.0 0.0]);\n axis([0 time(end) min(x) max(x)]);\n sound(segments{i}, fs);\n clc;\n fprintf('Playing segment %d of %d. Press any key to continue...', i, length(segments));\n pause\n end\n clc\n hold off;\n P1 = plot(time, x); set(P1, 'Color', [0.7 0.7 0.7]); \n hold on; \n for (i=1:length(segments))\n for (j=1:length(segments))\n if (i~=j)\n timeTemp = Limits(j,1)/fs:1/fs:Limits(j,2)/fs;\n P = plot(timeTemp, segments{j});\n set(P, 'Color', [0.4 0.1 0.1]);\n end\n end\n axis([0 time(end) min(x) max(x)]);\n end\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/28826-silence-removal-in-speech-signals/detectVoiced.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.4920729734539146}} {"text": "function [C_df,Df,S_df] = extract_DF_F(Y,A,C,S,i,options)\n\n% extract DF/F signals after performing NMF\n% inputs: Y raw data (d X T matrix, d # number of pixels, T # of timesteps)\n% A matrix of spatial components (d x K matrix, K # of components)\n% C matrix of temporal components (K x T matrix)\n% S matrix of deconvolved activity ((K-1) x T matrix) (optional)\n% i index of component that represent the background (optional, if not\n% given it's estimated)\n% options structure used for specifying method for determining DF\n% default method is the median of the trace. By changing\n% options.df_prctile an arbitray percentile can be used (between 0 and 100).\n% a moving window can also be established by specifying options.df_window\n\n% outputs: C_df temporal components in the DF/F domain\n% Df background for each component to normalize the filtered raw data \n% S_df deconvolved activity/spikes in the DF/F domain\n\n% Written by: \n% Eftychios A. Pnevmatikakis, Simons Foundation, 2015\n\ndefoptions = CNMFSetParms;\nif nargin < 6 || isempty(options)\n options = defoptions;\nend\nif ~isfield(options,'df_prctile') || isempty(options.df_prctile)\n options.df_prctile = defoptions.df_prctile;\nend\nif ~isfield(options,'df_window') || isempty(options.df_window)\n options.df_window = defoptions.df_window;\nend\n\nnA = sqrt(sum(A.^2))';\n[K,~] = size(C);\nA = A/spdiags(nA,0,K,K); % normalize spatial components to unit energy\nC = spdiags(nA,0,K,K)*C;\n\nif nargin < 5 || isempty(i)\n [~,i] = min(sum(A.^6)); % identify background component\nend\n\nnon_bg = true(1,K); \nnon_bg(i) = false; % non-background components\nYf = A'*Y - (A'*A(:,non_bg))*C(non_bg,:);\n\nif isempty(options.df_window) || (options.df_window > size(C,2))\n if options.df_prctile == 50\n Df = median(Yf,2);\n else\n Df = prctile(Yf,options.df_prctile,2);\n end\n C_df = spdiags(Df,0,K,K)\\C;\nelse\n if options.df_prctile == 50\n Df = medfilt1(Yf,options.df_window,[],2,'truncate');\n else\n Df = zeros(size(Yf));\n for i = 1:size(Df,1);\n df_temp = running_percentile(Yf(i,:), options.df_window, options.df_prctile);\n Df(i,:) = df_temp(:)';\n end\n end\n C_df = C./Df;\nend\n \nC_df(i,:) = 0;\n\nif nargin < 4 || isempty(S) || nargout < 3\n S_df = [];\n if nargout == 3\n warning('Merged spikes matrix is returned as empty because the original matrix was not provided.');\n end\nelse\n if isempty(options.df_window) || (options.df_window > size(C,2))\n S_df = spdiags(Df(non_bg(:)),0,sum(non_bg),sum(non_bg))\\S;\n else\n S_df = S./Df(non_bg,:);\n end\nend", "meta": {"author": "zhoupc", "repo": "CNMF_E", "sha": "ccca6f9db7d1d15b7dd1266eb9b29e417f92e79f", "save_path": "github-repos/MATLAB/zhoupc-CNMF_E", "path": "github-repos/MATLAB/zhoupc-CNMF_E/CNMF_E-ccca6f9db7d1d15b7dd1266eb9b29e417f92e79f/ca_source_extraction/utilities/extract_DF_F.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6224593171945417, "lm_q1q2_score": 0.4920729623807092}} {"text": "function [f]=comp_isepdgtreal(coef,g,L,a,M,phasetype)\n%COMP_ISEPDGTREAL Separable IDGT.\n% Usage: f=comp_isepdgtreal(c,g,L,a,M);\n% \n% This is a computational routine. Do not call it directly.\n%\n% Input must be in the M x N x W format, so the N and W dimension is\n% combined.\n%\n% See also: idgt\n\n% AUTHOR : Peter L. S\u00f8ndergaard.\n% TESTING: OK\n% REFERENCE: OK\n\nLwindow=size(g,1);\n\nif phasetype==1\n % Change from time-invariant phase convention to a\n % frequency-invariant one\n b=L/M;\n M2=floor(M/2)+1;\n N=size(coef,2);\n %M2short=ceil(M/2);\n\n TimeInd = (0:(N-1))/N;\n FreqInd = (0:(M2-1))*b;\n\n phase = FreqInd'*TimeInd;\n phase = exp(-2*1i*pi*phase);\n\n % Handle multisignals\n coef = bsxfun(@times,coef,phase);\nend;\n\n\nif L==Lwindow\n % Do full-window algorithm.\n\n % Call the computational subroutine.\n f = comp_idgtreal_long(coef,g,L,a,M);\n\nelse\n % Do filter bank algorithm.\n % Call the computational subroutine.\n f = comp_idgtreal_fb(coef,g,L,a,M);\nend;\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/comp/comp_isepdgtreal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.49199879015221964}} {"text": "% MatrixUser, a multi-dimensional matrix analysis software package\n% https://sourceforge.net/projects/matrixuser/\n% \n% The MatrixUser is a matrix analysis software package developed under Matlab\n% Graphical User Interface Developing Environment (GUIDE). It features \n% functions that are designed and optimized for working with multi-dimensional\n% matrix under Matlab. These functions typically includes functions for \n% multi-dimensional matrix display, matrix (image stack) analysis and matrix \n% processing.\n%\n% Author:\n% Fang Liu \n% University of Wisconsin-Madison\n% Aug-30-2014\n\n\n\nfunction MU_funcFlipZ(Temp,Event,handles)\nhandles=guidata(handles.MU_matrix_display);\n\nif ~isempty(handles.V.Segs)\n choice = questdlg('Segmentation mask is detected, transform operation will reset them, preceed?','Mask Reset', ...\n 'No, go save mask','Yes','No, go save mask');\n if isempty(choice)\n warndlg('Transform is cancelled.');\n return;\n end\n % Handle response\n switch choice\n case 'No, go save mask'\n warndlg('Save your mask before transform.');\n return;\n end\n \n handles.Mask=handles.Mask*0;\n handles.V.Segs=[];\nend\n\n% close 3D slicer\nglobal Figure_handles\nif isfield(Figure_handles,'MU_display2')\n slicer_display_handles=guidata(Figure_handles.MU_display2);\n if Figure_handles.MU_display == slicer_display_handles.Parent\n close(Figure_handles.MU_display2);\n end\nend\n\nhandles.TMatrix=flipdim(handles.TMatrix,3);\nhandles.Mask=flipdim(handles.Mask,3);\n\nMergeM=get(handles.Matrix_name_edit,'String');\nset(handles.Matrix_name_edit,'String',[MergeM '_fpz']);\n\n% update current display matrix\nhandles=MU_update_image(handles.Matrix_display_axes,{handles.TMatrix,handles.Mask},handles,0);\nguidata(handles.MU_matrix_display, handles);\n\nend", "meta": {"author": "leoliuf", "repo": "MRiLab", "sha": "5cdcf1f7b67759700685d3a26ffeb70e55325567", "save_path": "github-repos/MATLAB/leoliuf-MRiLab", "path": "github-repos/MATLAB/leoliuf-MRiLab/MRiLab-5cdcf1f7b67759700685d3a26ffeb70e55325567/External/MatrixUser2.2/Src/FuncLib/MU_funcFlipZ.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7279754371026368, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.4919400308053301}} {"text": "%% STEP 0: Calculate Distortion Parameters\n% This is a main script to perform the following steps:\n% 1) Estimate camera parameters from checkerboard images\n% 2) Use these parameters to correct the distortion\n% 3) Plot the camera parameters before and after the correction\n% 4) Save the parameters to correct the distortion from image points in Step 1p and Step 3.\n\n%%\nclear all; close all\n\nfs=get(0, 'DefaultUIControlFontSize');\nset(0, 'DefaultUIControlFontSize', 10);\n\n%% NEW or REPEAT?\n% select repeat if you already ran analysis with these same images, but want to repeat with a different distortion model\n% repeat is faster because the point detection is skipped (which is the slowest part in this code)\n\nrepeatButton = questdlg('New analysis of repeat calibration with a different model?', 'New analysis of repeat calibration with a different model?', 'New', 'Repeat', 'New');\nswitch repeatButton\n case 'Repeat'\n repeatLogic=true(1);\n case 'New'\n repeatLogic=false(1);\nend\n\n%% CHOOSE PATHS OPTIONS\n\nif repeatLogic % if a repeated analysis, request to point to the existing parameters\n initialPath=pwd;\n folder_paths = uipickfiles('FilterSpec',initialPath,'Prompt','Select one or multiple cameraCBparameters files');\nelse\n % initial image path. Change this path if you want the UI to start with a specific path. Otherwise leave [] or pwd.\n imagePath=pwd;\n % select the folder containing the checkerboard images (if imagePath=[] then the initial path is the current path)\n folder_paths = uipickfiles('FilterSpec',imagePath,'Prompt','Select one or multiple folders containing checkerboard images for analysis');\nend\n\n% save camera parameters? y/n. if y, choose save path and overwrite options\n[saveCameraParametersLogic,savePath]=QsaveCameraParameters(folder_paths);\n\n% save undistorted images? y/n. if yes, warn for overwriting. undistorted images will be saved in savePath\n[saveUndistortedImagesLogic,overWriteUDimagesLogic]=QsaveUndistortedImages;\n\n% figures path to save the plotted results\nfiguresPath=fullfile(savePath, 'figures');\nwarning('off','MATLAB:MKDIR:DirectoryExists');\nmkdir(figuresPath);\n\n%% SELECT CHECKERBOARD PARAMETERS\n\nif repeatLogic % if repeated analysis, extract the checkerboard parameters from the files\n cameraCBparameters1=load(folder_paths{1});\n Nrows=cameraCBparameters1.cameraCBparameters.boardSize(1); \n Ncols=cameraCBparameters1.cameraCBparameters.boardSize(2); \n squareSize=cameraCBparameters1.cameraCBparameters.squareSize;\nelse % new analysis. ask for checkerboard parameters\n %initial parameters: these are the default parameters which appear in the dialog box. Change them if you want other numbers to appear instead\n Nrows=15; % Number of black rows (should be uneven)\n Ncols=20; % Number of black columns (should be even)\n squareSize=10; %[mm]\n % dialog box\n answer = inputdlg({'Enter number of rows (odd):','Enter number of columns (even):','Enter square size [mm]:'},'Input',[1,50],{num2str(Nrows),num2str(Ncols),num2str(squareSize)});\n % extract answers\n Nrows=str2double(answer{1}); \n Ncols=str2double(answer{2}); \n squareSize=str2double(answer{3});\nend\n\n%% SELECT DISTORTION MODEL\n\n% dialog box for selecting the distortion model. \n% The default is the full model (3 radial parameters, 2 tangential (1 stands for true), and a skew parameter (1 = true).\nanswer = inputdlg({'Enter number of radial distortion coefficients (2 or 3):',...\n 'Estimate tangential distortion? (1 or 0 for yes/no):',...\n 'Estimate skew? (1 or 0 for yes/no)'},...\n 'Input',[1,70],{'3','1','1'});\noptStruct=struct;\noptStruct.NumRadialDistortionCoefficients=str2num(answer{1});\noptStruct.EstimateTangentialDistortion=logical(str2num(answer{2}));\noptStruct.EstimateSkew=logical(str2num(answer{3}));\n\n%% compute and plot camera parameters for each camera\n\nNcam=numel(folder_paths); % number of cameras in this analysis\ncameraCBparametersAllCams=cell(Ncam,1); % assign cell array for all camera parmaters\n\nfor ic=1:Ncam % loop over all cameras\n \n % Extract images and info\n if repeatLogic % if repeated analysis, extract cameraCBparameters and image info from files\n cameraCBparameters=load(folder_paths{ic});\n cameraCBparameters=cameraCBparameters.cameraCBparameters;\n CBimagesInfo=cameraCBparameters.imagesInfo;\n I1=imread(CBimagesInfo.imageFileNames{1}); % read first image from path\n I=zeros([size(I1) CBimagesInfo.Nimages],'uint8'); % reallocate image var\n for ip=1:CBimagesInfo.Nimages\n I(:,:,:,ip)=imread(CBimagesInfo.imageFileNames{ip}); % load all images into I\n end\n CBimagesInfo.I=I;\n % plot all images in one figure\n plotAllCameraImages(CBimagesInfo);\n % re-calculate the distortion parameters with the selected model \n hm=msgbox(['Please wait while computing distortion parameters for camera ' num2str(CBimagesInfo.icam)]);\n cameraCBparameters=RecalculateCBcalibrationParameters(cameraCBparameters,optStruct);\n delete(hm);\n else\n % if New, extract only image info\n CBimagesInfo=extractImagesInfo(folder_paths{ic});\n % plot all images in one figure\n plotAllCameraImages(CBimagesInfo);\n % Extract images, Detect the checkerboard points, calculate camera paramters, and save a structure containing all necessary parameters\n set(0, 'DefaultUIControlFontSize', 11);\n hm=msgbox(['Please wait while computing distortion parameters for camera ' num2str(CBimagesInfo.icam)]);\n cameraCBparameters=calculateCBcalibrationParameters(CBimagesInfo,squareSize,optStruct);\n delete(hm);\n % check if detected boardsize matches entered values\n if (cameraCBparameters.boardSize(1)~=Nrows) || (cameraCBparameters.boardSize(2)~=Ncols)\n error('Detected number of columns or rows does not match entered values');\n end\n end\n \n % plot camera parameters and reorojection errors before and after distortion correction\n plot_camera_parameters_2tabs(cameraCBparameters);\n if saveCameraParametersLogic\n savefig(fullfile(figuresPath,[ 'params_cam' num2str(CBimagesInfo.icam)]));\n end\n \n % plot reprojected points vs. true points and straight lines on each image\n plot_reprojectVSreal_points(CBimagesInfo,cameraCBparameters);\n \n % undistort images and save if required\n hm=msgbox(['Please wait while correcting distortion from images of ' num2str(CBimagesInfo.icam)]);\n undistortImagesSavePlot(CBimagesInfo,cameraCBparameters,saveUndistortedImagesLogic,overWriteUDimagesLogic,savePath)\n delete(hm);\n \n % remove images with high errors\n answer=questdlg('Do you want to remove some of the images with higher errors?','Remove images?','Yes','No','No');\n switch answer\n case 'Yes'\n % reprojection errors per image\n Error=cameraCBparameters.cameraParameters.ReprojectionErrors;\n ErrorMgn=squeeze(sqrt(Error(:,1,:).^2+Error(:,2,:).^2));\n meanError=squeeze(mean(ErrorMgn,1));\n prctile80Error=prctile(meanError,80);\n % select threshold\n answer=inputdlg('Select threshold (mean error in pixels) for removing images','select threshold',1,{num2str(prctile80Error)});\n threshold=str2num(answer{1});\n indImgHighError=cameraCBparameters.imagesUsed(find(meanError>threshold));\n if length(indImgHighError)>0\n msgbox([ num2str(length(indImgHighError)) ' images will be removed from the calibration parameters calculation']);\n fileNamesImgHighError=cameraCBparameters.imagesInfo.imageFileNames(indImgHighError)';\n % delete high error images\n CBimagesInfo.I(:,:,:,indImgHighError)=[];\n CBimagesInfo.imageFileNames(indImgHighError)=[];\n CBimagesInfo.Nimages=numel(CBimagesInfo.imageFileNames);\n % plot all images in one figure\n plotAllCameraImages(CBimagesInfo);\n % Extract images, Detect the checkerboard points, calculate camera paramters, and save a structure containing all necessary parameters\n hm=msgbox(['Please wait while re-computing distortion parameters for camera ' num2str(CBimagesInfo.icam)]);\n cameraCBparameters=calculateCBcalibrationParameters(CBimagesInfo,squareSize,optStruct);\n delete(hm);\n % plot camera parameters and reorojection errors before and after distortion correction\n plot_camera_parameters_2tabs(cameraCBparameters);\n if saveCameraParametersLogic\n savefig(fullfile(figuresPath,[ 'params_cam', num2str(CBimagesInfo.icam)]));\n end\n end\n end\n \n % save camera parameters into the cell array of all cameras\n cameraCBparametersAllCams{ic}=cameraCBparameters;\n % save parameters into savePath\n if saveCameraParametersLogic\n save(fullfile(savePath, ['cameraCBparameters_cam_', num2str(cameraCBparameters.icam)]),'cameraCBparameters');\n end\n \nend\n\n% save cell array containing the camera parameters for all cameras in this analysis\nif saveCameraParametersLogic\n save(fullfile(savePath, 'cameraCBparametersAllCams'),'cameraCBparametersAllCams');\nend\n\n%% plot camera instrinsic statistics for all cameras (if more than 1 camera)\n\nNcam=numel(cameraCBparametersAllCams);\nif Ncam>1\n plotButton = questdlg('Plot intrinsic parameters statistics for all cameras?', 'Plot?', 'Yes', 'No', 'Yes'); \n if strcmp(plotButton,'Yes') \n plotIntrinsicStatsAll(cameraCBparametersAllCams);\n if saveCameraParametersLogic \n savefig(fullfile(figuresPath, 'IntrinsicStats')); \n end \n end\nend\n\n%% finish\n\nh=msgbox('STEP0 is completed');\nh.CurrentAxes.Children.FontSize=11;\n\nset(0, 'DefaultUIControlFontSize', fs);\n\n%% \n% MultiDIC: a MATLAB Toolbox for Multi-View 3D Digital Image Correlation\n% \n% License: \n% \n% Copyright (C) 2018 Dana Solav\n% \n% If you use the toolbox/function for your research, please cite our paper:\n% ", "meta": {"author": "MultiDIC", "repo": "MultiDIC", "sha": "d363c3ea74673e58df275d4a4c8e528ef5472acb", "save_path": "github-repos/MATLAB/MultiDIC-MultiDIC", "path": "github-repos/MATLAB/MultiDIC-MultiDIC/MultiDIC-d363c3ea74673e58df275d4a4c8e528ef5472acb/main_scripts/STEP0_CalcDistortionParameters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.4919400292744082}} {"text": "% The COBRAToolbox: testSolveCobraMILP.m\n%\n% Purpose:\n% - testSolveCobraMILP tests the SolveCobraMILP function and its different methods\n%\n% Author:\n% - Original file: Joseph Kang 11/16/09\n% - CI integration: Laurent Heirendt, March 2017\n%\n% Note:\n% test is performed on objective as solution can vary between machines, solver version etc..\n\n% save the current path\ncurrentDir = pwd;\n\n% initialize the test\nfileDir = fileparts(which('testSolveCobraMILP'));\ncd(fileDir);\n\n% save original solve\nglobal CBT_MILP_SOLVER;\norig_solver = CBT_MILP_SOLVER;\n\n% test solver packages\n\nglobal SOLVERS\n\n% Do this test for all available MIQP solvers\nUseIfAvailable = fieldnames(SOLVERS); % We will simply use all available solvers that are MIQP solvers.\nsolverPkgs = prepareTest('needsMILP', true, 'useSolversIfAvailable', UseIfAvailable);\n\n% set the tolerance\ntol = 1e-8;\n\nfor k = 1:length(solverPkgs.MILP)\n fprintf(' Running solveCobraMILP using %s ... ', solverPkgs.MILP{k});\n\n % change the COBRA solver (LP)\n solverOK = changeCobraSolver(solverPkgs.MILP{k}, 'MILP', 0);\n\n if solverOK\n % MILP Solver test: chemeng.ed.ac.uk/~jwp/MSO/section5/milp.html\n\n % set up MILP problem.\n MILPproblem.c = [20; 6; 8];\n MILPproblem.A = [0.8, 0.2, 0.3;\n 0.4, 0.3, 0;\n 0.2, 0, 0.1];\n MILPproblem.b = [20; 10; 5];\n MILPproblem.lb = [0; 0; 0];\n MILPproblem.ub = [1000; 1000; 1000];\n MILPproblem.osense = -1;\n MILPproblem.csense = ['L'; 'L'; 'L'];\n MILPproblem.vartype = ['I'; 'I'; 'I'];\n MILPproblem.x0 = [0, 0, 0];\n pass = 1;\n\n % solve MILP problem setting the relative MIP gap tolerance and integrality tolerance to 1e-12 using parameters structure.\n if strcmp(solverPkgs.MILP{k}, 'cplex_direct') || strcmp(solverPkgs.MILP{k}, 'tomlab_cplex')\n parameters.relMipGapTol = 1e-12;\n parameters.intTol = 1e-12;\n MILPsolution = solveCobraMILP(MILPproblem, parameters);\n % check if MILP can be solved without x0 supplied\n MILPsolution2 = solveCobraMILP(rmfield(MILPproblem, 'x0'), parameters);\n else\n MILPsolution = solveCobraMILP(MILPproblem);\n % check if MILP can be solved without x0 supplied\n MILPsolution2 = solveCobraMILP(rmfield(MILPproblem, 'x0'));\n end\n\n % check results with expected answer.\n assert(all(abs(MILPsolution.int - [0; 31; 46]) < tol))\n assert(abs(MILPsolution.obj - 554) < tol)\n assert(abs(MILPsolution2.obj - 554) < tol)\n\n if strcmp(solverPkgs.MILP{k}, 'ibm_cplex')\n % test IBM-Cplex-specific parameters. Solve with the below parameters changed\n cplexParams = struct();\n cplexParams.emphasis.mip = 0; % MIP emphasis: balance optimality and integer feasibility\n cplexParams.mip.strategy.search = 2; % MIP search method: dynamic search\n MILPsolution = solveCobraMILP(MILPproblem, cplexParams, 'logFile', 'testIBMcplexMILPparam1.log');\n % check expected answer\n assert(all(abs(MILPsolution.int - [0; 31; 46]) < tol))\n assert(abs(MILPsolution.obj - 554) < tol)\n\n % solve with the parameters changed to other values\n cplexParams.emphasis.mip = 1; % MIP emphasis: integer feasibility.\n cplexParams.mip.strategy.search = 1; % MIP search method: traditional branch-and-cut search\n MILPsolution = solveCobraMILP(MILPproblem, cplexParams, 'logFile', 'testIBMcplexMILPparam2.log');\n % check expected answer\n assert(all(abs(MILPsolution.int - [0; 31; 46]) < tol))\n assert(abs(MILPsolution.obj - 554) < tol)\n\n % compare the log files to see whether the parameter changes are implemented\n testLog = {''; ''};\n paramsInLog = cell(2, 1);\n % text that should be found during the first test\n paramsInLog{1} = {'balance optimality and feasibility'; 'dynamic search'};\n % text that should be found during the second test\n paramsInLog{2} = {'integer feasibility'; 'branch-and-cut'};\n for jTest = 1:2\n % read the log files\n f = fopen(['testIBMcplexMILPparam' num2str(jTest) '.log'], 'r');\n l = fgets(f);\n while ~isequal(l, -1)\n testLog{jTest} = [testLog{jTest}, l];\n l = fgets(f);\n end\n fclose(f);\n % check that the expected parameter values are set, and the unexpected are not set.\n for p = 1:2\n assert(~isempty(strfind(testLog{jTest}, paramsInLog{jTest}{p})));\n assert(isempty(strfind(testLog{jTest}, paramsInLog{setdiff(1:2, jTest)}{p})));\n end\n % delete the log files\n delete(['testIBMcplexMILPparam' num2str(jTest) '.log']);\n end\n fprintf('Test ibm_cplex output to command window ...\\n')\n % solve without logToFile = 1\n diary test_ibm_cplex_output_to_console1.txt\n sol = solveCobraMILP(MILPproblem);\n diary off\n % read the diary, which should be empty\n f = fopen('test_ibm_cplex_output_to_console1.txt', 'r');\n l = fgets(f);\n assert(isequal(l, -1))\n fclose(f);\n delete('test_ibm_cplex_output_to_console1.txt')\n\n % solve wit logToFile = 1\n diary test_ibm_cplex_output_to_console2.txt\n sol = solveCobraMILP(MILPproblem, 'logFile', 1);\n diary off\n % read the diary, which should be non-empty\n f = fopen('test_ibm_cplex_output_to_console2.txt', 'r');\n l = fgets(f);\n line = 0;\n while ~isequal(l, -1)\n line = line + 1;\n l = fgets(f);\n end\n fclose(f);\n assert(line > 3)\n delete('test_ibm_cplex_output_to_console2.txt')\n fprintf('Test ibm_cplex output to command window ... Done\\n')\n\n end\n\n if strcmp(solverPkgs.MILP{k}, 'gurobi')\n % check additional parameters for Gurobi\n % temporarily shut down warning\n warning_stat = warning;\n warning off\n MILPproblem = struct();\n MILPproblem.A = [speye(10, 20), -3 * rand(10, 30)];\n MILPproblem.b = zeros(10, 1);\n MILPproblem.c = ones(50, 1);\n MILPproblem.lb = [-1000 * ones(35, 1); zeros(15, 1)];\n MILPproblem.ub = [1000 * ones(35, 1); ones(15, 1)];\n MILPproblem.vartype = char(['C' * ones(1, 20), 'I' * ones(1, 15), 'B' * ones(1, 15)]);\n MILPproblem.csense = char('E' * ones(1, 10));\n MILPproblem.osense = -1;\n % test TimeLimit as a gurobi-specific parameter\n sol = solveCobraMILP(MILPproblem, struct('TimeLimit', 0));\n assert(strcmp(sol.origStat, 'TIME_LIMIT'))\n % restore previous warning state\n warning(warning_stat)\n\n % check user-supplied x0\n MILPproblem.A = rand(10, 20);\n MILPproblem.b = 1000 * ones(10, 1);\n MILPproblem.c = zeros(20, 1);\n MILPproblem.lb = zeros(20, 1);\n MILPproblem.ub = ones(20, 1);\n MILPproblem.vartype = char(['C' * ones(1, 10), 'B' * ones(1, 10)]);\n MILPproblem.csense = char('L' * ones(1, 10));\n\n % no objective function. The supplied should be the returned\n % (if not everything becomes zero after presolve)\n MILPproblem.x0 = zeros(20, 1);\n sol = solveCobraMILP(MILPproblem);\n assert(isequal(sol.full, MILPproblem.x0));\n\n MILPproblem.x0 = ones(20, 1);\n sol = solveCobraMILP(MILPproblem);\n assert(isequal(sol.full, MILPproblem.x0));\n\n end\n end\n\n % output a success message\n fprintf('Done.\\n');\nend\n\n% test ibm_cplex output to command window\nsolverOK = changeCobraSolver('ibm_cplex', 'MILP', 0);\nif solverOK\n fprintf('Test ibm_cplex output to command window ...\\n')\n % solve without logToFile = 1\n diary test_ibm_cplex_output_to_console1.txt\n sol = solveCobraMILP(MILPproblem);\n diary off\n % read the diary, which should be empty\n f = fopen('test_ibm_cplex_output_to_console1.txt', 'r');\n l = fgets(f);\n assert(isequal(l, -1))\n fclose(f);\n delete('test_ibm_cplex_output_to_console1.txt')\n\n % solve wit logToFile = 1\n diary test_ibm_cplex_output_to_console2.txt\n sol = solveCobraMILP(MILPproblem, 'logFile', 1);\n diary off\n % read the diary, which should be non-empty\n f = fopen('test_ibm_cplex_output_to_console2.txt', 'r');\n l = fgets(f);\n line = 0;\n while ~isequal(l, -1)\n line = line + 1;\n l = fgets(f);\n end\n fclose(f);\n assert(line > 3)\n delete('test_ibm_cplex_output_to_console2.txt')\n fprintf('Test ibm_cplex output to command window ... Done\\n')\nend\n\n% remove the generated file\nfullFileNamePath = [fileparts(which(mfilename)), filesep, 'MILPProblem.mat'];\nif exist(fullFileNamePath, 'file') == 2\n delete(fullFileNamePath);\nend\n\n% change back to the original solver\nif ~isempty(orig_solver)\n changeCobraSolver(orig_solver, 'MILP', 0);\nend\n\n% change the directory\ncd(currentDir)\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/test/verifiedTests/base/testSolvers/testSolveCobraMILP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.4919400292744082}} {"text": "function jed = transition_to_jed_jed ( )\n\n%*****************************************************************************80\n%\n%% TRANSITION_TO_JED_JED returns the JED calendar transition as a JED.\n%\n% Discussion:\n%\n% In Scaliger's design of the JED, three cycles with different periods\n% began on JED = 0. These three cycles coincide once more on the\n% transition day.\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 = 2913943.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/calpak/transition_to_jed_jed.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.4919199154131484}} {"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 domain = CreateDomain(Lx, Ly, dx, dy)\n\n% initialize dependant variables\nx_intervals = Lx/dx + 1;\ny_intervals = Ly/dy + 1;\n%x_Step_Interval = (stepX/dx) + 1; \n%y_Step_Interval = (stepY/dy) + 1;\n\n% Create Domain Matrix\ndomain = zeros(x_intervals,y_intervals);\n\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/41696-2d-transient-heat-conduction/CreateDomain.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.4919199031183214}} {"text": "function dohyst(indir,outdir,hmult,nthresh)\n% function dohyst(indir,outdir,hmult,nthresh)\n%\n% Read pb files from indir, apply hysteresis thresholding, and\n% write the resulting pb files into outdir.\n% \n% David R. Martin \n% April 2003\n\nif nargin<3, hmult=1/3; end\nif nargin<4, nthresh=100; end\n\niids = imgList('test');\nunused = mkdir(outdir);\nfor i = 1:numel(iids),\n iid = iids(i);\n pbold = double(imread(sprintf('%s/%d.bmp',indir,iid)))/255;\n thresh = linspace(1/nthresh,1-1/nthresh,nthresh);\n fwrite(2,sprintf('%3d/%d ',i,numel(iids)));\n progbar(0,nthresh);\n pbnew = zeros(size(pbold));\n for i = 1:nthresh,\n progbar(i,nthresh);\n [r,c] = find(pbold>=thresh(i));\n if numel(r)==0, continue; end\n b = bwselect(pbold>hmult*thresh(i),c,r,8);\n pbnew = max(pbnew,b*thresh(i));\n end\n imwrite(pbnew,sprintf('%s/%d.bmp',outdir,iid),'bmp');\nend\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/external/segbench/lib/matlab/dohyst.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.4918554123726681}} {"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 \u00a0\u00a0\u00a0\u00a0 |\n%| |\n%| Please acknowledge the gypsilab toolbox in programs or publications in |\n%| which you use it. |\n%|________________________________________________________________________|\n%| '&` | |\n%| # | FILE : 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": "% IVP with respect to Alfa\nfunction dy = JacobianAlfa (t, y)\n global SOL;\n global ETA_INF;\n global BETA0;\n global BETA;\n global EX;\n method = 'spline';\n % y(1) = df\\dalfa\n % y(2) = du\\dalfa\n % y(3) = dv\\dalfa\n f = interp1(EX, SOL(:,1), t, method); % Interpolate the data set for f\n u = interp1(EX, SOL(:,2), t, method); % Interpolate the data set for u\n v = interp1(EX, SOL(:,3), t, method); % Interpolate the data set for v\n dy = [ETA_INF*y(2) ETA_INF*y(3), -ETA_INF*(BETA0*(y(1)*v+f*y(3))-2*BETA*u*y(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/28042-a-graphical-user-interface-for-solving-the-falkner-skan-equation/JacobianAlfa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.49177205730302}} {"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 \u00a0\u00a0\u00a0\u00a0 |\n%| |\n%| Please acknowledge the gypsilab toolbox in programs or publications in |\n%| which you use it. |\n%|________________________________________________________________________|\n%| '&` | |\n%| # | FILE : 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": "%compute velmag_head\nfunction [data,units]=compute_velmaghead(trx,n)\nlarvae=trx.exp2flies{n};\nnumlarvae=numel(larvae);\nvelmaghead=cell(1,numlarvae);\nfor i=1:numlarvae\n larva=larvae(i);\n velmaghead{1,i}=bsxfun(@hypot,trx(larva).dxhead_mm,trx(larva).dyhead_mm);\nend\n\nunits=parseunits('mm/s');\ndata=velmaghead;\n \n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/larva_compute_perframe_features/compute_velmaghead.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4917364310141344}} {"text": "classdef DilationComputer < handle\n\n properties (Access = private)\n LHS\n RHS\n end\n \n properties (Access = private)\n mesh\n orientationVector\n dilation\n end\n \n methods (Access = public)\n \n function obj = DilationComputer(cParams)\n obj.init(cParams);\n obj.createDilationFun();\n end\n\n function rF = compute(obj)\n obj.computeLHS();\n obj.computeRHS();\n r = obj.solveSystem();\n s.mesh = obj.mesh;\n s.fValues = r;\n rF = P1Function(s);\n end\n \n end\n \n methods (Access = private)\n \n function init(obj,cParams)\n obj.mesh = cParams.mesh;\n obj.orientationVector = cParams.orientationVector;\n end\n \n function computeLHS(obj)\n K = obj.computeStiffnessMatrix();\n I = ones(size(K,1),1);\n obj.LHS = [K,I;I',0];\n end\n \n function K = computeStiffnessMatrix(obj)\n s.fun = obj.dilation;\n s.mesh = obj.mesh;\n s.type = 'StiffnessMatrix';\n lhs = LHSintegrator.create(s);\n K = lhs.compute();\n end\n\n function createDilationFun(obj)\n obj.dilation = P1Function.create(obj.mesh, 1);\n end\n \n function computeRHS(obj)\n q = Quadrature.set(obj.mesh.type);\n q.computeQuadrature('CUBIC');\n gradT = obj.computeFieldTimesDivField(q);\n\n s.mesh = obj.mesh;\n s.type = 'ShapeDerivative';\n s.quadratureOrder = q.order;\n rhs = RHSintegrator.create(s);\n rhsF = rhs.compute(gradT);\n rhsV = rhsF.fValues;\n obj.RHS = [rhsV;0];\n end\n \n function gradT = computeFieldTimesDivField(obj,q)\n a1 = obj.orientationVector{1};\n a2 = obj.orientationVector{2};\n aDa1 = a1.computeFieldTimesDivergence(q);\n aDa2 = a2.computeFieldTimesDivergence(q); \n s.quadrature = q;\n s.mesh = obj.mesh;\n s.fValues = -aDa1.fValues - aDa2.fValues;\n gradT = FGaussDiscontinuousFunction(s);\n end\n \n function u = solveSystem(obj)\n a.type = 'DIRECT';\n s = Solver.create(a);\n u = s.solve(obj.LHS,obj.RHS);\n u = u(1:end-1);\n end\n \n end\n \nend", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/Applications/Dehomogenizing/DilationComputer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.49173642072417206}} {"text": "function [ patch_expert, corr, rms_error] = CreatePatchExpert( samples, labels, unnormed_samples, normalisation_options)\n%CREATEPATCHEXPERT Summary of this function goes here\n% Detailed explanation goes here\n\n num_examples = size(samples, 1);\n \n region_length = normalisation_options.normalisationRegion - normalisation_options.patchSize + 1;\n region_length = region_length(1) * region_length(2); \n \n % this part sets the split boundaries for SVR training, logit training and test subsets\n train_SVR_start = 1; \n train_SVR_end = int32(normalisation_options.svmRatio * num_examples - 1);\n train_SVR_end = train_SVR_end - mod(train_SVR_end, region_length);\n\n train_logit_start = train_SVR_end + 1;\n train_logit_end = train_logit_start + int32(normalisation_options.logitRatio * num_examples) - 1;\n \n % make sure it ends within same area of interest (region)\n train_logit_end = train_logit_end - mod(train_logit_end, region_length);\n \n test_start = train_logit_end + 1;\n test_end = size(samples,1);\n\n % picking training data for SVR\n examples_train_SVR = samples(train_SVR_start:train_SVR_end, :); \n labels_train_SVR = labels(train_SVR_start:train_SVR_end); \n \n % Train the SVR using liblinear (older version used libSVM,\n % but liblinear is much faster)\n [w, b] = Train_SVR(examples_train_SVR, labels_train_SVR);\n \n % Now create the test dataset\n examples_test = samples(test_start:test_end, :); \n labels_test = labels(test_start:test_end);\n\n % Training the logistic regressor now\n examples_train_logit = samples(train_logit_start:train_logit_end, :); \n labels_train_logit = labels(train_logit_start:train_logit_end, :); \n\n patch_expert = CreateLogisticRegressor(examples_train_logit, labels_train_logit, w, b, normalisation_options);\n\n % Evaluate the patch expert now\n [rms_error, corr, ~] = EvaluatePatchExpert(examples_test, labels_test, patch_expert, false);\n\n fprintf('Rms error %.3f, correlation %.3f\\n', rms_error, corr);\n \n % Assert that our implementation and the convolution based one are equivalent \n [~, ~, responses_svm] = EvaluatePatchExpert(samples(1:size(unnormed_samples,1)*region_length,:), labels(1:size(unnormed_samples,1)*region_length), patch_expert, false);\n [responses_ncc] = SVR_expert_ncc_response(unnormed_samples, patch_expert, normalisation_options, normalisation_options.normalisationRegion, region_length);\n assert(mean(abs(responses_svm-responses_ncc))< 1e-2);\n \nend\n\n", "meta": {"author": "TadasBaltrusaitis", "repo": "OpenFace", "sha": "3d4b5cf8d96138be42bed229447f36cbb09a5a29", "save_path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace", "path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace/OpenFace-3d4b5cf8d96138be42bed229447f36cbb09a5a29/model_training/CCNF/patch_experts/svr_training/CreatePatchExpert.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914997895581, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.491717566506969}} {"text": "% created by: Zoya Bylinskii, Sept 2014\n% based on code by Tilke Judd\n\n% This function applies the chosen center bias\n% and blur parameters to the saliency maps\n% in salDir to produce the saliency maps in resDir.\n\nfunction adjustSalMaps(salDir,resDir,centWeight,blurSigma,targetHist,showOutput)\n% salDir contains all the saliency map files\n% resDir is the output directory for the adjusted saliency maps\n% centWeight: the chosen center weight value [0,1]\n% blurSigma: the chosen blur value \n\nassert(centWeight>=0 && centWeight<= 1, 'centWeight must be between 0 and 1');\n\nif nargin < 6, \n showOutput = 0; \nend\n\nload('center.mat');\n\nif exist(resDir,'dir')\n fprintf('Directory %s already exists. Will overwrite.\\n',resDir);\nelse\n mkdir(resDir)\nend\n\nallfiles = dir(fullfile(salDir,'*.jpg'));\n\nif showOutput, figure; end\n\nfor i = 1:length(allfiles)\n \n fprintf('On %s\\n',allfiles(i).name)\n mapOrig = im2double(imread(fullfile(salDir,allfiles(i).name)));\n cent = imresize(center, size(mapOrig));\n map = processMap(mapOrig,cent,targetHist,blurSigma,centWeight,showOutput);\n imwrite(map,fullfile(resDir,allfiles(i).name));\n\nend\n", "meta": {"author": "cvzoya", "repo": "saliency", "sha": "5951cdc7c2ba73e5951d4c36bea58e8c7d41e55d", "save_path": "github-repos/MATLAB/cvzoya-saliency", "path": "github-repos/MATLAB/cvzoya-saliency/saliency-5951cdc7c2ba73e5951d4c36bea58e8c7d41e55d/code_forOptimization/adjustSalMaps.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.49171755628865094}} {"text": "function [E,C] = nonmanifold_edges(F)\n % NONMANIFOLD_EDGES List of non-manifold edges\n %\n % Inputs:\n % F #F by dim=3 list of facet indices\n % Outputs:\n % E #E by 2 list of nonmanifold edges\n % C #E by 1 list of unsigned Counts (>2)\n % %pC #E by 1 list of positive Counts\n % %nC #E by 1 list of negative Counts\n %\n\n allE = [F(:,[2 3]); F(:,[3 1]); F(:,[1 2])];\n sortallE = sort(allE,2);\n sC = sparse(sortallE(:,1),sortallE(:,2),(allE(:,1)2 | abs(sC)>1).* C);\n E = [EI EJ];\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/nonmanifold_edges.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.49171755628865094}} {"text": "%MDL_P8 Create model of Puma robot on an XY base\n%\n% MDL_P8 is a script that creates the workspace variable p8 which is an\n% 8-axis robot comprising a Puma 560 robot on an XY base. Joints 1 and 2\n% are the base, joints 3-8 are the robot arm.\n%\n% Also define the workspace vectors:\n% qz zero joint angle configuration\n% qr vertical 'READY' configuration\n% qstretch arm is stretched out in the X direction\n% qn arm is at a nominal non-singular configuration\n%\n% Notes::\n% - SI units of metres are used.\n%\n% References::\n% - Robotics, Vision & Control, 1st edn,\n% P. Corke, Springer 2011. Sec 7.3.4.\n%\n% See also mdl_puma560, SerialLink.\n\n% MODEL: Unimation, Puma560, on XY base, redundant, 8DOF, standard_DH\n\n\n% Copyright (C) 1993-2017, by Peter I. Corke\n%\n% This file is part of The Robotics Toolbox for MATLAB (RTB).\n% \n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with RTB. If not, see .\n%\n% http://www.petercorke.com\n\n% create the base\nplatform = SerialLink( [0 0 0 -pi/2 1; -pi/2 0 0 pi/2 1], ...\n 'base', troty(pi/2), 'name', 'platform' ); \n\n% load the standard Puma\nmdl_puma560;\n% add the pedestal height to link 1\np560.links(1).d = 30 * 0.0254;\n\n% compose the two robots\np8 = SerialLink( [platform, p560], 'name', 'P8');\n\n% set the range for the prismatic links\np8.links(1).qlim=[-1 1];\np8.links(2).qlim=[-1 1];\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/models/mdl_p8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.49171755214074714}} {"text": "function img=headPhantom(varargin)\n%HEADXPHANTOM returns the head phantom \n%\n% IMG=HEADXPHANTOM() returns 128^3 image IMG\n%\n% IMG=HEADXPHANTOM(SZ) returns a SZ^3 image IMG if SZ is scalar, or a [SZ(1)\n% SZ(2) SZ(3] image, of SZ is a vector. \n%--------------------------------------------------------------------------\n%--------------------------------------------------------------------------\n% This file is part of the TIGRE Toolbox\n% \n% Copyright (c) 2015, University of Bath and \n% CERN-European Organization for Nuclear Research\n% All rights reserved.\n%\n% License: Open Source under BSD. \n% See the full license at\n% https://github.com/CERN/TIGRE/blob/master/LICENSE\n% and\n% https://www.mathworks.com/matlabcentral/fileexchange/view_license?file_info_id=35548\n%\n% Contact: tigre.toolbox@gmail.com\n% Codes: https://github.com/CERN/TIGRE/\n% Coded by: Kyungsang Kim, modified by Ander Biguri \n%--------------------------------------------------------------------------\n\n% Deal with inputs\nif nargin==0\n sz=[128,128,128];\nend\nif nargin==1\n if ~isnumeric(varargin{1})\n error('TIGRE:headphantom:invalid input','input is not numerical'); \n end\n nsz=max(size(varargin{1}));\n if nsz==2 || nsz>3\n error('TIGRE:headphantom:invalid input','input is not 1x1 or 1x3');\n end\n if nsz==1\n sz=[varargin{1},varargin{1},varargin{1}];\n else\n sz=varargin{1};\n end\nend\n% load data\ncurr_path=mfilename('fullpath');\ndata_path=curr_path(1:end-length('/MATLAB/Test_data/MRheadbrain/headPhantom'));\ndata_path=[data_path '/Common/data/'];\ndata=load([data_path 'head.mat']);\nimg=data.img;\n\n% interpolate data to get desired size\n[y, x, z]=...\n ndgrid(linspace(1,size(img,1),sz(1)),...\n linspace(1,size(img,2),sz(2)),...\n linspace(1,size(img,3),sz(3)));\n \nimOut=interp3(img,x,y,z,'nearest');\n% out!\nimg=imOut;\n\nend", "meta": {"author": "CERN", "repo": "TIGRE", "sha": "8df632662228d1b1c52afd95c90d0f7a9f8dc4b3", "save_path": "github-repos/MATLAB/CERN-TIGRE", "path": "github-repos/MATLAB/CERN-TIGRE/TIGRE-8df632662228d1b1c52afd95c90d0f7a9f8dc4b3/MATLAB/Test_data/MRheadbrain/headPhantom.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.4917175511794917}} {"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 Z = nonlinearreplace(X,Y,W)\n\n% Very slow, but easily coded. Hopefully not used much\n\n% Special case for replace(x,y,-y)\nif isequal(getbase(Y),[0 1]) && isequal(getbase(W),[0 -1]) && isequal(getvariables(Y),getvariables(W)) && is(Y,'linear')\n mt = yalmip('monomtable'); \n xv = getvariables(X);\n yv = getvariables(Y);\n if all(mt(:,yv) == fix(mt(:,yv)) )\n signs = ones(length(xv),1);\n for i = 1:length(xv)\n pow = mt(xv(i),yv);\n if ~even(pow)\n signs(i) = -1;\n end \n end\n Z = X;\n Z = setbase(X,getbase(X)*diag([1;signs]));\n return\n end\nend\n\nU = sdpvar(length(W),1);\nfor kk = 1:length(Y)\n Z = [];\n for ii = 1:size(X,1)\n temp = [];\n for jj = 1:size(X,2);\n\n [coeffs,base] = coefficients(X(ii,jj),Y(kk));\n\n newp = 0;\n for i = 1:length(base)\n newp = newp + coeffs(i)*U(kk)^degree(base(i));\n end\n\n temp = [temp newp];\n end\n Z = [Z;temp];\n end\n X = Z;\nend\n\nY = U;\nfor kk = 1:length(Y)\n Z = [];\n for ii = 1:size(X,1)\n temp = [];\n for jj = 1:size(X,2);\n\n [coeffs,base] = coefficients(X(ii,jj),Y(kk));\n\n newp = 0;\n for i = 1:length(base)\n newp = newp + coeffs(i)*W(kk)^degree(base(i));\n end\n\n temp = [temp newp];\n end\n Z = [Z;temp];\n end\n X = Z;\nend\n\n\n\n", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/extras/nonlinearreplace.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.49171754910554005}} {"text": "function update_num_c = update_cft(i_span,n_times,min_num_c,mid_num_c,max_num_c,num_c)\n\n% determine the time series model\nif i_span < mid_num_c*n_times\n % start with 4 coefficients model\n update_num_c = min(min_num_c,num_c);\nelseif i_span < max_num_c*n_times\n % start with 6 coefficients model\n update_num_c = min(mid_num_c,num_c);\nelse\n % start with 8 coefficients model\n update_num_c = min(max_num_c,num_c);\nend\n\nend", "meta": {"author": "GERSL", "repo": "CCDC", "sha": "11b47273a9599b6943040f068d7a0af0db96c885", "save_path": "github-repos/MATLAB/GERSL-CCDC", "path": "github-repos/MATLAB/GERSL-CCDC/CCDC-11b47273a9599b6943040f068d7a0af0db96c885/update_cft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.4917006898920638}} {"text": "%% Local Labeling of DOFs\nnode = [1,0,0; 0,1,0; 0,0,0; 0,0,1];\nelem = [1 2 3 4];\nlocalEdge = [1 2; 1 3; 1 4; 2 3; 2 4; 3 4];\nedge = zeros(20,2);\nedge([1 12 5 20 11 4],:) = localEdge;\nelem2dof = [1 12 5 20 11 4];\nfigure(1); clf;\nset(gcf,'Units','normal'); \nset(gcf,'Position',[0,0,0.6,0.4]);\nsubplot(1,2,1)\nshowmesh3(node,elem);\nview(-14,12);\nfindnode3(node);\nfindedge3(node,localEdge);\n\n%% Face and face to local DOF mapping\nface1 = [2 3 4];\nf1dof = [6 5 4];\nface2 = [1 4 3];\nf2dof = [6 2 3];\nface3 = [1 2 4];\nf3dof = [5 3 1];\nface4 = [1 3 2];\nf4dof = [4 1 2];\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/doc/MaxwellNeumanBCdoc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.4916880819616935}} {"text": "function gX = ggXgaussianKernGradX(ggKern, gaussianKern, X, X2, covGrad)\n\n% GGXGAUSSIANKERNGRADX Compute gradient between the GG and GAUSSIAN\n% kernels wrt the input locations\n% FORMAT\n% DESC computes the gradient between the GG and GAUSSIAN kernels with \n% respect to the input positions where both the row positions and column \n% positions are provided separately.\n% RETURN g : the returned gradients. \n% ARG kern : kernel structure for which gradients are being computed.\n% ARG x1 : row locations against which gradients are being computed.\n% ARG x2 : column locations against which gradients are being computed.\n%\t\n% SEEALSO : gaussianKernParamInit, kernGradX, gaussianKernDiagGradX\n%\n% COPYRIGHT : Mauricio A. Alvarez and Neil D. Lawrence, 2008\n%\n% MODIFICATIONS : Mauricio A. Alvarez, 2009, 2010\n\n% KERN\n\nif nargin < 5,\n covGrad = X2;\n X2 = X;\nelse\n U = X;\n X = X2;\n X2 = U;\nend\n\n\n[K, Kbase, Pqrinv, Prinv, P] = ggXgaussianKernCompute(ggKern, ....\n gaussianKern, X2, X);\n\nif ggKern.isArd\n PX = X*diag(P);\n PX2 = X2*diag(P);\nelse\n PX = P*X;\n PX2 = P*X2;\nend\n\ntemp = covGrad'.*K;\n\ngX2 = zeros(size(X));\nfor i=1:size(X,2),\n mPX2 = PX2(:,i);\n MPX2 = mPX2(:,ones(1,size(X,1)));\n mPX = PX(:,i)';\n MPX = mPX(ones(size(X2,1),1),:);\n gX2(:,i) = sum(temp.*(MPX2-MPX),1)';\nend\n\ngX = gX2;\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/ggXgaussianKernGradX.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.49168807664294367}} {"text": "function [xi, gamma, Phi] = mfldainit (W, K, w)\n \n % Get the number of documents.\n D = length(w);\n \n % Get the size of the corpus.\n M = 0;\n for d = 1:D\n M = M + length(w{d});\n end\n \n % Generate a random starting point for xi.\n xi = rand(W,K);\n \n % Generate a random starting point for gamma.\n gamma = rand(K,D);\n \n % Generate a random starting point for phi.\n Phi = rand(K,M);\n Phi = Phi ./ repmat(sum(Phi),K,1);\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/OptiToolbox/Solvers/lbfgsb/distribution/mfldainit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.49168807664294367}} {"text": " function [T, reuse] = Gmri_gram(ob, W, reuse)\n%|function [T, reuse] = Gmri_gram(ob, W, reuse)\n%|\n%| build Toeplitz-like gram-matrix object for G'WG gram matrix\n%| to be called by build_gram() indirectly rather than directly by user!\n%|\n%| Jeff Fessler\n\nif nargin < 1, ir_usage, end\nif streq(ob, 'test'), Gmri_gram_test, return, end\n\nif isempty(W)\n\twi = 1; % default unweighted\n\n% 1D column vector or scalar:\nelseif isnumeric(W) && ndims(W) == 2 && size(W,2) == 1\n\twi = W;\nelseif isa(W, 'Fatrix') && streq(W.caller, 'diag_sp')\n\twi = W.arg.diag;\nelseif isa(W, 'fatrix2') && streq(W.caller, 'Gdiag')\n\twi = W.arg.diag;\nelse\n\tfail('Gmri_gram requires W to be Gdiag or diag_sp or wi array')\nend\n\nif ~isreal(wi), fail('only real wi supported; otherwise T not Hermitian'), end\n\narg2.wi = wi;\narg2.Gmri = ob;\narg2.new_zmap = @Gmri_gram_new_zmap;\n\nT = Gmri_gram_work(arg2, reuse);\n\n\n% Gmri_gram_work()\nfunction T = Gmri_gram_work(arg2, reuse)\n\narg1 = arg2.Gmri.arg;\nwi = arg2.wi;\n\nif isempty(arg1.zmap)\n\tT = build_gram(arg1.Gnufft, wi .* abs(arg1.basis.transform).^2);\nelse\n\tLL = ncol(arg1.aB);\n\targ2.T = cell(LL,1);\n\treuse = [];\n\tfor ll=1:LL\n\t\twl = arg1.aB(:,ll) .* wi .* abs(arg1.basis.transform).^2;\n\t\t[arg2.T{ll} reuse] = build_gram(arg1.Gnufft, wl, reuse);\n\tend\n\n\targ2.dim = arg1.dim([2 2]); % [np np]\n\n\tswitch class(arg2.Gmri)\n\tcase 'Fatrix'\n\t\tT = Fatrix(arg2.dim, arg2, ...\n\t\t\t'caller', [mfilename '.Gmri_gram'], ...\n\t\t\t'forw', @Gmri_zmap_forw_Fatrix, ...\n\t\t\t'back', @Gmri_zmap_forw_Fatrix); % trick: Hermitian\n\n\tcase 'fatrix2'\n\t\tT = fatrix2('arg', arg2, ...\n\t\t\t'imask', arg2.Gmri.mask, ...\n\t\t\t'omask', arg2.Gmri.mask, ...\n\t\t\t'idim', arg2.Gmri.Nd, ...\n\t\t\t'odim', arg2.Gmri.Nd, ...\n\t\t\t'forw', @Gmri_zmap_forw, ...\n\t\t\t'back', @Gmri_zmap_forw); % trick: because Hermitian\n\n\totherwise\n\t\tfail('unknown class \"%s\"', class(arg2.Gmri))\n\tend\nend\n\n\n% Gmri_gram_new_zmap()\n% update Toeplitz-like gram-matrix Fatrix object for new zmap\nfunction T = Gmri_gram_new_zmap(T, varargin) % (ti, zmap, L, aL)\nT.arg.Gmri = T.arg.Gmri.arg.new_zmap(T.arg.Gmri, varargin{:}); % yikes!\nT = Gmri_gram_work(T.arg, []);\n\n\n% Gmri_zmap_forw_Fatrix()\n% y = T * x\nfunction y = Gmri_zmap_forw_Fatrix(arg2, x)\n\narg1 = arg2.Gmri.arg;\n\nif size(x,1) ~= arg2.dim(2)\n\tx = reshapee(x, prod(arg1.Nd), []); % [(N) (nc)] to [*N *nc]\n\tx = x(arg1.mask,:); % [np *nc]\nend\nnc = ncol(x);\n\nLL = ncol(arg1.aB);\ny = 0;\nfor ll=1:LL\n\ttmp = repmat(arg1.aCt(:,ll), [1 nc]) .* x;\n\ttmp = arg2.T{ll} * tmp;\n\ttmp = repmat(conj(arg1.aCt(:,ll)), [1 nc]) .* tmp;\n\ty = y + tmp;\n%\ty = y + conj(arg1.aCt(:,ll)) .* (arg2.T{ll} * (arg1.aCt(:,ll) .* x));\nend\n\n\n% Gmri_zmap_forw()\nfunction y = Gmri_zmap_forw(arg2, x)\ny = Gmri_zmap_forw_Fatrix(arg2, x);\ny = embed(y, arg2.Gmri.arg.mask); % required for fatrix2\n\n\n% Gmri_gram_test()\nfunction Gmri_gram_test\nig = image_geom('nx', 6, 'ny', 8, 'dx', 1, 'offsets', 'dsp');\nig.mask = ellipse_im(ig) > 0;\nx = ellipse_im(ig, 'shepplogan-emis', 'type', 'slow');\nkspace = mri_trajectory('spiral1', {}, [ig.nx ig.ny], ig.fov);\nti = linspace(0, 10e-3, size(kspace,1));\nzmap = 20 * ig.ones + 2i * pi * 10;\nL = 8;\n%A = Gmri(kspace, ig.mask, 'exact', 1, 'n_shift', ig.dim/2); % perfect gram\n%A = Gmri(kspace, ig.mask, 'class', 'fatrix2'); % gram mult not so well matched\nA = Gmri(kspace, ig.mask, 'L', L, 'ti', ti, 'zmap', zmap);\nT = build_gram(A);\nfatrix2_tests(T, 'complex', 1)\nx1 = A' * (A * x);\nx1 = ig.embed(x1);\nx2 = T * x;\nim plc 1 3\nim(1, x1)\nim(2, x2)\nim(3, x2 - x1)\ntry\n\tequivs(x2, x1, 'thresh', 5e-3) % todo: why so big - due to nufft?\n%\tequivs(x2, x1)\ncatch\n\tkeyboard\nend\n% fatrix2_tests(A, 'complex', 1)\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/systems/Gmri_gram.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.49168807664294367}} {"text": "function [day] = s2day(s)\n% Convert time from seconds to days. \n% Chad Greene 2012\nday = s*0.00001157407407407;", "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/s2day.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.4916880766429436}} {"text": "classdef S2Grid < vector3d\n%\n% The class S2Grid represent spherical grids. The central difference to a\n% simple list of @vector3d is that S2Grid provides more efficient methods\n% for finding the closes points in the grid with respect to a given\n% direction.\n%\n% Syntax\n%\n% % regular grid with fixed polar and azimuthal spacing\n% S2G = regularS2Grid('resolution',5*degree)\n% S2G = regularS2Grid('theta',(0:5:80)*degree,'rho',(0:5:355)*degree)\n%\n% % regular grid optimized for plotting\n% S2G = plotS2Grid('resolution',1.5*degree,'upper')\n%\n% % equispaced nodes with given resolution\n% S2G = equispacedS2Grid('resolution',5*degree)\n%\n% Options\n% points - [nrho,ntheta] number of points\n% resolution - resolution of a equispaced grid\n% theta - polar angle\n% rho - azimuthal angle\n% minRho - starting rho angle (default 0)\n% maxRho - maximum rho angle (default 2*pi)\n% minTheta - starting theta angle (default 0)\n% maxTheta - maximum theta angle (default pi)\n%\n% Flags\n% lower, uper, complete - restrict hemisphere\n% antipodal - include \n% no_center - ommit point at center\n% restrict2minmax - restrict margins to min / max\n%\n% Examples\n%\n% S2G = equispacedS2Grid('resolution',5*degree,'maxTheta',70*degree)\n% plot(S2G)\n%\n% See also\n% vector3d.vector3d plotS2Grid regularS2Grid equispaceS2Grid\n\nproperties\n\n thetaGrid = S1Grid([],0,pi);\n rhoGrid = S1Grid([],0,2*pi);\n res = 2*pi;\n\nend\n\nmethods\n\n function S2G = S2Grid(thetaGrid,rhoGrid,varargin)\n\n % call superclass method\n v = calcGrid(thetaGrid,rhoGrid);\n [S2G.x,S2G.y,S2G.z] = double(v);\n S2G.thetaGrid = thetaGrid;\n S2G.rhoGrid = rhoGrid;\n S2G.res = get_option(varargin,'resolution',2*pi);\n S2G.antipodal = check_option(varargin,'antipodal');\n end\n\n function v = vector3d(S2G)\n v = vector3d(S2G.x,S2G.y,S2G.z);\n v.opt = S2G.opt;\n v.antipodal = S2G.antipodal;\n end\n\nend\n\nend\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/geometry/@S2Grid/S2Grid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.49168807664294356}} {"text": "function [y, dzdg, dzdb] = vl_nnnonorm(x, g, b, varargin)\n%VL_NNNONORM applies weights and biases, but does no normalization\n% Y = VL_NNNONORM(X,G,B) applies a set of gains and biases to\n% the input X with shape HxWxCxN. \"No normalization\" is defined as:\n%\n% Y(i,j,k,t) = G(k') * X(i,j,k,t) + B(k')\n%\n% where\n% k' = group_idx(k,C,G), where N_G is the number of groups and\n% group_idx(k,C,G) := floor(k / (C/N_G)).\n%\n% VL_NNGNORM(..., 'option', value, ...) takes the following option:\n%\n% This layer was largely inspired by this blog post:\n% http://www.offconvex.org/2018/03/02/acceleration-overparameterization/\n%\n% Copyright (C) 2018 Samuel Albanie\n% All rights reserved.\n\n [~,dzdy] = vl_argparsepos(struct(), varargin) ;\n\n expectedSz = [1 1 size(x,3) 1] ;\n sg = size(g) ; sb = size(b) ;\n assert(all(expectedSz(1:numel(sg)) == sg), 'GAINS have unexpected size') ;\n assert(all(expectedSz(1:numel(sb)) == sb), 'BIASES have unexpected size') ;\n\n if isempty(dzdy)\n y = bsxfun(@times, g, x) ; % apply gain\n y = bsxfun(@plus, y, b) ; % add bias\n else\n dzdy = dzdy{1} ;\n dzdb = chanSum(dzdy) ;\n dzdg = chanSum(x .* dzdy) ;\n dzdx = bsxfun(@times, dzdy, g) ;\n y = dzdx ;\n end\n\n% -----------------------\nfunction res = chanSum(x)\n% -----------------------\n res = sum(sum(sum(x, 1), 2), 4) ;\n", "meta": {"author": "ShuaiBai623", "repo": "MFT", "sha": "8762f8cdf494ce0b1a1c3d431660c5c8fd91744a", "save_path": "github-repos/MATLAB/ShuaiBai623-MFT", "path": "github-repos/MATLAB/ShuaiBai623-MFT/MFT-8762f8cdf494ce0b1a1c3d431660c5c8fd91744a/external_libs/matconvnet/contrib/mcnExtraLayers/matlab/vl_nnnonorm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.49168806995638537}} {"text": "%IMPEXP_DOLFIN Import/export grid in FEniCS/Dolfin XML format.\n%\n% [ GRID ] = IMPEXP_DOLFIN( FILE_NAME, MODE, DATA, USE_MESHFCN, FID )\n% Import or export of a FEniCS/Dolfin (ASCII .xml) grid and data\n% format. FILE_NAME is a string specifying the (root) file name to\n% process. MODE can either be a string indicating import (no\n% boundary reconstruction), import_bdr (boundary reconstruction with\n% gridbdr), or export. For export, DATA can be either a full fea\n% struct or just the grid struct. USE_MESHFCN is a boolean flag to\n% write subdomain numbers in a mesh function instead of the\n% (default) domain field. A GRID struct is output when importing\n% FID is an optional log file handle for message output\n% (negative for gui output or empty for no output).\n%\n% Example:\n%\n% 1) Export and re-import of a unit square with a hole grid.\n%\n% grid1 = quad2tri(holegrid());\n% impexp_hdf5( 'featool-fenics-mesh.xml', 'export', grid1 )\n% grid2 = impexp_hdf5( 'featool-fenics-mesh.h5', 'import' )\n% subplot(1,2,1), plotgrid(grid1), title('grid1')\n% subplot(1,2,2), plotgrid(grid2), title('grid2')\n% is_ok = gridcheck(grid2) == 0\n%\n% See also FENICS, FENICS_IMPORT, IMPEXP_HDF5\n\n% Copyright 2013-2022 Precise Simulation, Ltd.\n", "meta": {"author": "precise-simulation", "repo": "featool-multiphysics", "sha": "861c771adda317a9f091263d16dca060116bd516", "save_path": "github-repos/MATLAB/precise-simulation-featool-multiphysics", "path": "github-repos/MATLAB/precise-simulation-featool-multiphysics/featool-multiphysics-861c771adda317a9f091263d16dca060116bd516/impexp/impexp_dolfin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.4915138699089644}} {"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": "function [ar,ma,ASAsellog,ASAcontrol]=armasel_rs(varargin)\n%ARMASEL_RS ARMAsel model identification\n% [AR,MA,SELLOG] = ARMASEL_RS(ARH,N_OBS) estimates autoregressive, moving \n% average, and autoregressive moving average models from the high-order \n% AR model ARH and selects the model with optimal predictive qualities.\n% ARH has been estimated from N_OBS observations. The AR and MA parts of\n% the selected model, each possibly of order 0, are returned in the\n% parameter vectors AR and MA. The structure SELLOG provides additional\n% information on the selection process.\n% \n% SELLOG contains the fields 'ar', 'ma' and 'arma', in which SELLOG \n% structures are nested, as returned by the functions ARH2AR, ARH2MA \n% and ARH2ARMA, invoked by ARMASEL. In the field 'armasel' a structure \n% is nested that reports information about the final stage of model \n% selection, where the preselected AR, MA and ARMA models are compared.\n% \n% ARMASEL(ARH,N_OBS,CAND_AR_ORDER,CAND_MA_ORDER,CAND_ARMA_ORDER)\n% narrows the selection to candidate models with orders provided by the \n% rows CAND_AR_ORDER, CAND_MA_ORDER and CAND_ARMA_ORDER AR, MA and\n% ARMA(r,r-1) models independently.\n% For any of these arguments it is allowed to pass an \n% empty array. Alternatively, additional arguments may be omitted from \n% the input list. In both cases, default values are automatically \n% determined and substituted for the missing arguments. The functions \n% ARH2AR, ARH2MA and ARH2ARMA provide additional information on \n% defining candidate orders. Note in this respect, that the candidate \n% AR orders of the ARMA model are called CAND_ARMA_ORDER in this help \n% text, while in ARH2ARMA they are called CAND_AR_ORDER.\n%\n% The selection of MA and ARMA models can be conditioned to the \n% selection of AR models from a specific set of candidate orders \n% CAND_AR_ORDER. See ASAGLOB_AR_COND for more information.\n% \n% ARMASEL_RS is an ARMASA_RS main function.\n% ARMASEL_RS can also be used to selected models based on an ARH model\n% that has been estimated from segments of data.\n% \n% See also: ARMASEL, ARH2AR, ARH2MA, ARH2ARMA, DATA_SEGMENTS.\n\n% Reference: P. M. T. Broersen and S. de Waele, Selection of Order and\n% Type of Time Series Models Estimated from Reduced Statistics\n% Proceedings of SYSID 2002, May 2002.\n\n%Header\n%===================================================================================================\n\n%Declaration of variables\n%------------------------\n\n%Declare and assign values to local variables\n%according to the input argument pattern\n[ar_rs,n_obs,cand_ar_order,cand_ma_order,cand_arma_order,arma_order_diff,ASAcontrol] = ASAarg(varargin, ...\n{'ar_rs' ;'n_obs' ;'cand_ar_order';'cand_ma_order';'cand_arma_order';'arma_order_diff';'ASAcontrol'}, ...\n{'isnumeric' ;'isnumeric' ;'isnumeric' ;'isnumeric' ;'isnumeric' ;'isnumeric' ;'isstruct' }, ...\n{'ar_rs' ;'n_obs' }, ...\n{'ar_rs' ;'n_obs' ;'cand_ar_order' }, ...\n{'ar_rs' ;'n_obs' ;'cand_ar_order';'cand_ma_order' }, ...\n{'ar_rs' ;'n_obs' ;'cand_ar_order';'cand_ma_order';'cand_arma_order' }, ...\n{'ar_rs' ;'n_obs' ;'cand_ar_order';'cand_ma_order';'cand_arma_order';'arma_order_diff' });\n\n%Declare ASAglob variables \nASAglob = {'ASAglob_subtr_mean';'ASAglob_mean_adj';'ASAglob_rc';'ASAglob_ar';'ASAglob_final_f'; ...\n 'ASAglob_final_b';'ASAglob_ar_cond'};\n\n%Assign values to ASAglob variables by screening the\n%caller workspace\nfor ASAcounter = 1:length(ASAglob)\n ASAvar = ASAglob{ASAcounter};\n eval(['global ' ASAvar]);\n if evalin('caller',['exist(''' ASAvar ''',''var'')'])\n eval([ASAvar '=evalin(''caller'',ASAvar);']);\n else\n eval([ASAvar '=[];']);\n end\nend\n\n%ARMASA-function version information\n%-----------------------------------\n\n%This ARMASA-function is characterized by\n%its current version,\nASAcontrol.is_version = [2000 12 30 20 0 0];\n%and its compatability with versions down to,\nASAcontrol.comp_version = [2000 12 30 20 0 0];\n\n%This function calls other functions of the ARMASA\n%toolbox. The versions of these other functions\n%must be greater than or equal to:\nASAcontrol.req_version.sig2ar = [2000 12 30 20 0 0];\nASAcontrol.req_version.sig2ma = [2000 12 30 20 0 0];\nASAcontrol.req_version.sig2arma = [2000 12 30 20 0 0];\n\n%Checks\n%------\n\nif ~isfield(ASAcontrol,'error_chk') | ASAcontrol.error_chk\n %Perform standard error checks\n %Input argument format checks\n ASAcontrol.error_chk = 1;\n if ~isnum(ar_rs)\n error(ASAerr(11,'ar_rs'))\n elseif ~isvector(ar_rs)\n error([ASAerr(14) ASAerr(15,'ar_rs')])\n end\n if ~isempty(cand_ar_order)\n if ~isnum(cand_ar_order) | ~isintvector(cand_ar_order) |...\n cand_ar_order(1)<0 | ~isascending(cand_ar_order)\n error(ASAerr(12,{'candidate';'cand_ar_order'}))\n elseif size(cand_ar_order,1)>1\n cand_ar_order = cand_ar_order';\n warning(ASAwarn(25,{'column';'cand_ar_order';'row'},ASAcontrol))\n end\n end\n if ~isempty(cand_ma_order)\n if ~isnum(cand_ma_order) | ~isintvector(cand_ma_order) |...\n cand_ma_order(1)<0 | ~isascending(cand_ma_order)\n error(ASAerr(12,{'candidate';'cand_ma_order'}))\n elseif size(cand_ma_order,1)>1\n cand_ma_order = cand_ma_order';\n warning(ASAwarn(25,{'column';'cand_ma_order';'row'},ASAcontrol))\n end\n end\n if ~isempty(cand_arma_order)\n if ~isnum(cand_arma_order) | ~isintvector(cand_arma_order) |...\n cand_arma_order(1)<0 | ~isascending(cand_arma_order)\n error(ASAerr(12,{'candidate';'cand_arma_order'}))\n elseif size(cand_arma_order,1)>1\n cand_arma_order = cand_arma_order';\n warning(ASAwarn(25,{'column';'cand_arma_order';'row'},ASAcontrol))\n end\n end\n if ~isempty(arma_order_diff) & ...\n (~isnum(arma_order_diff) | ...\n ~isintscalar(arma_order_diff) |...\n arma_order_diff<0)\n error(ASAerr(17,'arma_order_diff'))\n end\n\n %Input argument value checks\n if ~isreal(ar_rs)\n error(ASAerr(13))\n end\n if max(cand_ar_order) > length(ar_rs)-1\n error(ASAerr(37,'cand_ar_order'))\n end\n if max(cand_ma_order) > length(ar_rs)-1\n error(ASAerr(37,'cand_ma_order'))\n end\n if ~isempty(cand_arma_order) & ...\n ~isempty(arma_order_diff)\n if cand_arma_order(1)~=0 & ...\n (arma_order_diff < 1 | ...\n arma_order_diff > cand_arma_order(1))\n error(ASAerr(18,{'arma_order_diff';'1';...\n num2str(cand_arma_order(1))}))\n elseif length(cand_arma_order)>1 & ...\n (arma_order_diff < 1 | ...\n arma_order_diff > cand_arma_order(2))\n error(ASAerr(18,{'arma_order_diff';'1';...\n num2str(cand_arma_order(2))}))\n end\n end\nend\n\nif ~isfield(ASAcontrol,'version_chk') | ...\n ASAcontrol.version_chk %Perform version check\n ASAcontrol.version_chk = 1;\n \n %Make sure the requested version of this function\n %complies with its actual version\n ASAversionchk(ASAcontrol);\n \n %Make sure the requested versions of the called\n %functions comply with their actual versions\n arh2ar(ASAcontrol);\n arh2ma(ASAcontrol);\n arh2arma(ASAcontrol);\nend\n\nif ~isfield(ASAcontrol,'run') | ASAcontrol.run\n ASAcontrol.run = 1;\n ASAdate = now;\nend\n\nif ASAcontrol.run %Run the computational kernel\n ASAcontrol.version_chk = 0;\n ASAcontrol.error_chk = 0;\n\n%Main \n%=====================================================\n \n%Initialization of variables\n%---------------------------\n\nif ASAglob_ar_cond\n ASAglob_ar_cond = 1;\nelse\n ASAglob_ar_cond = 0;\nend\n\nn_obs_tot = sum(n_obs);\n\n%AR-, MA- and ARMA-model identification\n%--------------------------------------\n\n[ar_ar,ar_sellog] = arh2ar...\n (ar_rs,n_obs,cand_ar_order,ASAcontrol);\n[ma_ma,ma_sellog] = arh2ma...\n (ar_rs,n_obs,cand_ma_order,ASAcontrol);\n[arma_ar,arma_ma,arma_sellog] = arh2arma...\n (ar_rs,n_obs,cand_arma_order,arma_order_diff,ASAcontrol);\n\n%Selection of the ARMAsel model\n%------------------------------\n\n%Asess the selected model orders\norder = ...\n [length(ar_ar)-1;length(ma_ma)-1;length(arma_ar)-1];\n\n%Asess the corresponding prediction error estimates\nsel_location = ...\n [find(order(1) == ar_sellog.cand_order);...\n find(order(2) == ma_sellog.cand_order);... \n find(order(3) == arma_sellog.cand_ar_order)];\npe_est = [ar_sellog.pe_est(sel_location(1));...\n ma_sellog.pe_est(sel_location(2));...\n arma_sellog.pe_est(sel_location(3))];\n\n%Select the model with the smallest prediction error\n%estimate\n[sel_pe_est,model] = min(pe_est);\n\n%Arranging output arguments\n%--------------------------\n\n%Retrieve the parameters of the selected model\nar = 1;\nma = 1;\nswitch model\ncase 1 %The AR model has been selected\n ar = ar_ar;\ncase 2 %The MA model has been selected\n ma = ma_ma;\ncase 3 %The ARMA model has been selected\n ar = arma_ar;\n ma = arma_ma;\nend\n\n%Gernerate a structure variable ASAsellog to report\n%the selection process\nASAsellog.funct_name = mfilename;\nASAsellog.funct_version = ASAcontrol.is_version;\nASAsellog.date_time = ...\n [datestr(ASAdate,8) 32 datestr(ASAdate,0)];\nASAsellog.comp_time = ar_sellog.comp_time+...\n ma_sellog.comp_time+...\n arma_sellog.comp_time;\nASAsellog.armasel.ar = ar;\nASAsellog.armasel.ma = ma;\nASAsellog.armasel.ar_pe_est = pe_est(1);\nASAsellog.armasel.ma_pe_est = pe_est(2);\nASAsellog.armasel.arma_pe_est = pe_est(3);\nASAsellog.armasel.ar_cond = ASAglob_ar_cond;\nASAsellog.armasel.mean_adj = ASAglob_mean_adj;\nASAsellog.ar = ar_sellog;\nASAsellog.ma = ma_sellog;\nASAsellog.arma = arma_sellog;\n\n%Footer\n%=====================================================\n\nelse %Skip the computational kernel\n %Return ASAcontrol as the first output argument\n if nargout>1\n warning(ASAwarn(9,mfilename,ASAcontrol))\n end\n ar = ASAcontrol;\n ASAcontrol = [];\nend\n\n%Program history\n%======================================================================\n%\n% Version Programmer(s) E-mail address\n% ------- ------------- --------------\n% former versions P.M.T. Broersen broersen@tn.tudelft.nl\n% S. de Waele waele@tn.tudelft.nl\n% [2000 11 1 12 0 0] W. Wunderink wwunderink01@freeler.nl\n% [2000 12 30 20 0 0] ,, ,,\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/3680-automatic-spectral-analysis/AutomaticSpectra/armasa_rs/armasel_rs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.4915138611696735}} {"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": "% repeat a matrix \n%\nfunction [output] = F_transpose(input_layer, curr_layer)\ninput = input_layer.a;\n\noutput = input';\n\nend\n\n", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/graph/F_transpose.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.49151384369109147}} {"text": "classdef nme_branch_dc < mp.nme_branch & mp.form_dc\n\n% MATPOWER\n% Copyright (c) 2019, Power Systems Engineering Research Center (PSERC)\n% by Ray Zimmerman, PSERC Cornell\n%\n% This file is part of MATPOWER.\n% Covered by the 3-clause BSD License (see LICENSE file for details).\n% See https://matpower.org for more info.\n\n% properties\n% name = 'branch';\n% end\n\n methods\n function obj = build_params(obj, nm, dm)\n build_params@mp.nme_branch(obj, nm, dm); %% call parent\n\n dme = obj.data_model_element(dm);\n nl = obj.nk;\n\n tm = ones(nl, 1); %% default tap ratio = 1\n i = find(dme.tm); %% indices of non-zero tap ratios\n tm(i) = dme.tm(i); %% assign non-zero tap ratios\n\n b = 1 ./ dme.x; %% series susceptance\n b = b ./ tm;\n Pfinj = b .* (-dme.ta);\n obj.B = sparse( ...\n [1:nl 1:nl nl+1:2*nl nl+1:2*nl]', ...\n [1:nl nl+1:2*nl 1:nl nl+1:2*nl]', ...\n [b; -b; -b; b], ...\n 2*nl, 2*nl );\n obj.p = [Pfinj + dme.g_fr; -Pfinj + dme.g_to];\n end\n end %% methods\nend %% classdef\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/+mp/nme_branch_dc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.5851011542032313, "lm_q1q2_score": 0.4913293184021584}} {"text": "\n% This class is for computing superpixel-based affinities described in the paper.\n% This class requires the image graphs methods by Steve Eddins. Find it here:\n% http://www.mathworks.com/matlabcentral/fileexchange/53614-image-graphs\n\nclassdef Superpixels\n properties \n labels\n spcount\n neigh\n centroids\n end\n methods\n function obj = Superpixels(im, spcnt)\n if ~exist('spcnt', 'var') || isempty(spcnt)\n spcnt = 2500;\n end\n [L, N] = superpixels(im, spcnt, 'Compactness', 1e-20);\n obj.labels = L;\n obj.spcount = N;\n % Find neighboring superpixels\n g = adjacentRegionsGraph(L);\n obj.neigh = g.Edges.Labels;\n % Find centroids\n s = regionprops(L, 'centroid');\n cent = cat(1, s.Centroid);\n obj.centroids = round(cent(:, 2:-1:1));\n [h, w, ~] = size(im);\n obj.centroids(:, 3) = sub2ind([h, w], obj.centroids(:, 1), obj.centroids(:, 2));\n end\n\n function regmeans = computeRegionMeans(obj, image)\n [h, w, c] = size(image);\n image = reshape(image, [h*w, c]);\n regmeans = zeros(obj.spcount, c);\n idx = label2idx(obj.labels);\n for i = 1 : length(idx)\n regmeans(i, :) = mean(image(idx{i}, :), 1);\n end\n end\n\n % This is for the semantic affinity, generates affinities in [-1, 1]\n function W = neighborAffinities(obj, features, erfSteepness, erfCenter)\n if ~exist('erfSteepness', 'var') || isempty(erfSteepness)\n erfSteepness = 20;\n end\n if ~exist('erfCenter', 'var') || isempty(erfCenter)\n erfCenter = 0.85;\n end\n [h, w, ~] = size(features);\n N = h * w;\n spMeans = obj.computeRegionMeans(features);\n affs = zeros(size(obj.neigh, 1), 1);\n inds1 = affs;\n inds2 = affs;\n for i = 1 : size(obj.neigh, 1)\n ind1 = obj.neigh(i, 1);\n ind2 = obj.neigh(i, 2);\n affs(i) = sigmoidAff(spMeans(ind1, :), spMeans(ind2, :), erfSteepness, erfCenter);\n inds1(i) = obj.centroids(ind1, 3);\n inds2(i) = obj.centroids(ind2, 3);\n end\n W = sparse(inds1, inds2, affs, N, N);\n W = W' + W;\n end\n \n % This is for the nonlocal color affinity, generates affinities in [0, 1]\n function W = nearbyAffinities(obj, image, erfSteepness, erfCenter, proxThresh)\n if ~exist('erfSteepness', 'var') || isempty(erfSteepness)\n erfSteepness = 50;\n end\n if ~exist('erfCenter', 'var') || isempty(erfCenter)\n erfCenter = 0.95;\n end\n if ~exist('proxThresh', 'var') || isempty(proxThresh)\n proxThresh = 0.2;\n end\n [h, w, ~] = size(image);\n N = h * w;\n spMeans = obj.computeRegionMeans(image);\n combinationCnt = obj.spcount;\n combinationCnt = combinationCnt * (combinationCnt - 1) / 2;\n affs = zeros(combinationCnt, 1);\n inds1 = affs;\n inds2 = affs;\n cnt = 1;\n cents = obj.centroids(:, 1:2);\n cents(:,1) = cents(:,1) / h;\n cents(:,2) = cents(:,2) / w;\n for i = 1 : obj.spcount\n for j = i + 1 : obj.spcount\n centdist = cents(i, 1:2) - cents(j, 1:2);\n centdist = sqrt(centdist * centdist');\n if centdist > proxThresh\n affs(cnt) = 0;\n else\n affs(cnt) = sigmoidAffPos(spMeans(i, :), spMeans(j, :), erfSteepness, erfCenter);\n end\n inds1(cnt) = obj.centroids(i, 3);\n inds2(cnt) = obj.centroids(j, 3);\n cnt = cnt + 1;\n end\n end\n W = sparse(inds1, inds2, affs, N, N);\n W = W' + W;\n end\n\n function vis = visualizeRegionMeans(obj, im)\n vis = label2rgb(obj.labels, obj.computeRegionMeans(im));\n end\n\n end\nend\n\nfunction aff = sigmoidAff(feat1, feat2, steepness, center)\n aff = abs(feat1 - feat2);\n aff = 1 - sqrt(aff * aff');\n aff = (erf(steepness * (aff - center)));\nend\n\nfunction aff = sigmoidAffPos(feat1, feat2, steepness, center)\n aff = abs(feat1 - feat2);\n aff = 1 - sqrt(aff * aff');\n aff = (erf(steepness * (aff - center)) + 1) / 2;\nend", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u5206\u5272\u7b97\u6cd5/SemanticSoftSegmentation-master/Superpixels.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.49132931840215827}} {"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": "clear; clc;\n\n%% dataset related arguments\ntrain_path = 'data/ml1m/validation/train.txt';\ntest_path = 'data/ml1m/validation/test.txt';\nrate_once = 1; % whether each item will only be rated once by each user\nL = 5; % length of sequence\nT = 3; % number of targets\n\n%% training arguments\nseed = 1234; % random seed\nn_iter = 50; % number of iteration\nlearning_rate = 1e-3; % learning rate for ADAM\nl2 = 1e-6; % l2 norm weight\nneg_samples = 3; % negative samples per target\nearly_stop = true; % whether to perform early stop during training\n\n%% Caser related arguments\nd = 50; % number of latent dimensions\nnv = 4; % number of vertical filters\nnh = 16; % number of horizontal filters\nac_conv = 'relu'; % activation function for convolution layer (i.e., phi_c in paper)\nac_fc = 'relu'; % activation function for fully-connected layer (i.e., phi_a in paper)\ndrop_rate = 0.5; % drop ratio when performing dropout\n\n%% Perform training\nargs = struct(...\n 'trainpath',train_path,...\n 'testpath',test_path,... \n 'rateonce',rate_once,... \n 'L',L,...\n 'T', T,...\n 'seed',seed,...\n 'niter',n_iter,...\n 'lrate',learning_rate,...\n 'l2',l2,...\n 'negsample',neg_samples,... \n 'earlystop',early_stop,... \n 'd',d,...\n 'nv',nv,... \n 'nh',nh,...\n 'acconv',ac_conv,...\n 'acfc',ac_fc,...\n 'droprate',drop_rate...\n );\n\ncaser_train(args);\n", "meta": {"author": "graytowne", "repo": "caser", "sha": "a981663a608bc3f393fee3bf9f7d8098676dd0f2", "save_path": "github-repos/MATLAB/graytowne-caser", "path": "github-repos/MATLAB/graytowne-caser/caser-a981663a608bc3f393fee3bf9f7d8098676dd0f2/main_caser.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.4912843450978317}} {"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": "function varargout = cgal_insurftri(varargin)\n% CGAL_INSURFTRI Find whether a point is inside or outside a closed\n% surface.\n%\n% This function evaluates whether one or more points belong inside a\n% closed surface. First, we check whether the point is on the surface\n% itself (in that case, it's considered inside). If not, a ray is\n% projected from the point and the intersections with the surface are\n% counted. An odd number means that the point is inside. This approach\n% fails if the point is not on the surface, but the ray lies on the\n% surface or crosses a vertex, because this spans many arbitrary\n% intersections. To solve this problem, a few rays are used for each\n% point, and the majority vote decides whether it's inside or outside.\n%\n% ISIN = cgal_insurftri(TRI, X, XI)\n%\n% TRI is a 3-column matrix. Each row represents the indices of the three\n% vertices that form a triangle. TRI as a whole represents the closed\n% surface.\n%\n% X is a 3-column matrix. Each row represents the Cartesian coordinates\n% of a vertex on the surface, indexed by TRI values.\n%\n% XI is a 3-column matrix. Each row represents the Carterian coordinates\n% of a point for which we want to find whether it's inside or outside the\n% closed surface. Note that if you want to test all the voxels in an\n% image, it is very slow and memory intensive to generate coordinates for\n% each voxel. In that scenario, it is much better to use the cell array\n% CI syntax shown below, and provide only values for the coordinate axes.\n%\n% ISIN is a boolean vector with one element per point in XI. True means\n% that the corresponding point is inside the closed surface (or on the\n% surface), and false means that it's outside.\n%\n% ISIN = cgal_insurftri(TRI, X, CI)\n%\n% CI is a cell array CI={XI, YI, ZI}, where XI, YI and ZI are row vectors\n% that describe a rectangular grid. For example,\n%\n% CI={linspace(-.25, .25, 5), ...\n% linspace(-.25, .25, 4), ...\n% linspace(-.25, .25, 3)};\n%\n% describes a sampling grid of 4 rows x 5 columns x 3 slices (note that\n% rows correspond to YI and columns to XI), of a domain \n% [-0.25, 0.25] x [-0.25, 0.25] x [-0.25, 0.25].\n%\n% ISIN = cgal_insurftri(..., DIRECTIONS, TOL)\n%\n% DIRECTIONS is a 3-column matrix. Each row represents a vector with a\n% ray direction. By default, \n%\n% DIRECTIONS=[ 1.0, 0.0, 0.0; ...\n% -1.0, 1.0, 1.0; ...\n% -1.0, -1.0, -1.0]\n%\n% This default can fail with regular voxels, as rays may cross vertices.\n% A good practical alternative is to use a few random directions, e.g.\n%\n% DIRECTIONS=rand(5, 3);\n%\n% Warning! For the voting system to make sense, select an odd number of\n% rays.\n%\n% TOL is a scalar with the distance tolerance. Points at distance <= TOL\n% are considered to be on the surface, and thus \"inside\". By default,\n% TOL=1e-15.\n\n% Author: Ramon Casero \n% Copyright \u00a9 2012-2013 University of Oxford\n% Version: 0.2.0\n%\n% University of Oxford means the Chancellor, Masters and Scholars of\n% the University of Oxford, having an administrative office at\n% Wellington Square, Oxford OX1 2JD, UK. \n%\n% This file is part of Gerardus.\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details. The offer of this\n% program under the terms of the License is subject to the License\n% being interpreted in accordance with English Law and subject to any\n% action against the University of Oxford being under the jurisdiction\n% of the English Courts.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see\n% .\n\nerror('MEX file not found')\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/CgalToolbox/cgal_insurftri.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.4912709658618034}} {"text": "function calpak_test010 ( )\n\n%*****************************************************************************80\n%\n%% CALPAK_TEST010 tests JED_TO_YJF_HEBREW and YJF_TO_JED_HEBREW.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 07 March 2013\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CALPAK_TEST010\\n' );\n fprintf ( 1, ' For the Hebrew calendar:\\n' );\n fprintf ( 1, ' JED_TO_YJF_HEBREW: JED -> YJF.\\n' );\n fprintf ( 1, ' YJF_TO_JED_HEBREW: YJF -> JED.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' JED (in) YJF JED (out)\\n' );\n fprintf ( 1, '\\n' );\n\n jed_epoch = epoch_to_jed_hebrew ( );\n\n i = 0;\n\n while ( 1 )\n\n i = i + 1;\n jed1 = jed_test ( i );\n \n if ( jed1 < 0.0 )\n break\n end\n\n if ( jed_epoch <= jed1 )\n\n [ y2, j2, f2 ] = jed_to_yjf_hebrew ( jed1 );\n\n s2 = yjf_to_s_hebrew ( y2, j2, f2 );\n\n jed3 = yjf_to_jed_hebrew ( y2, j2, f2 );\n\n fprintf ( 1, ' %11.2f %20s %11.2f\\n', jed1, s2, jed3 );\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/calpak/calpak_test010.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.69925440852404, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.49124723975424417}} {"text": "% MatrixUser, a multi-dimensional matrix analysis software package\n% https://sourceforge.net/projects/matrixuser/\n% \n% The MatrixUser is a matrix analysis software package developed under Matlab\n% Graphical User Interface Developing Environment (GUIDE). It features \n% functions that are designed and optimized for working with multi-dimensional\n% matrix under Matlab. These functions typically includes functions for \n% multi-dimensional matrix display, matrix (image stack) analysis and matrix \n% processing.\n%\n% Author:\n% Fang Liu \n% University of Wisconsin-Madison\n% Aug-30-2014\n\n\n\nfunction MU_funcFreeROI(Temp,Event,handles)\nglobal Figure_handles;\nMU_main_handles=guidata(Figure_handles.MU_main);\nhandles = guidata(handles.MU_matrix_display);\n\nMU_enable('off',[],handles);\nROI_h=imfreehand;\nMU_enable('on',[],handles);\n\nMU_main_handles.V.ROIs{end+1,1}='imfreehand';\nMU_main_handles.V.ROIs{end,2}=ROI_h;\nMU_main_handles.V.ROIs{end,3}=getPosition(ROI_h);\nROI_ind=length(MU_main_handles.V.ROIs(:,1));\n\np=round(getPosition(ROI_h));\nif max(p(:,1))>handles.V.Column | max(p(:,2))>handles.V.Row | min(p(:,1))<1 | min(p(:,2))<1\n delete(ROI_h); \n errordlg('Out of range subscript.'); \n return; \nend\nBW=createMask(ROI_h); \np=[min(p(:,1)) min(p(:,2)) max(p(:,1))-min(p(:,1)) max(p(:,2))-min(p(:,2))];\nTTMatrix=handles.BMatrix(p(2):p(2)+p(4),p(1):p(1)+p(3));\nTTMatrix=TTMatrix(double(BW(p(2):p(2)+p(4),p(1):p(1)+p(3)))~=0);\nROI_Stat_h=text(p(1)+p(3),p(2)+p(4),{[' ROI#: ' num2str(ROI_ind)]; ...\n [' mean: ' num2str(mean(double(TTMatrix(:))))]; ...\n [' sd:' num2str(std(double(TTMatrix(:))))]; ...\n [' sd(%):' num2str(abs(std(double(TTMatrix(:)))./mean(double(TTMatrix(:)))*100))]},...\n 'FontSize',10,'Color','g');\n \nhandles.V.ROI=struct(...\n 'ROI_flag', 1,...\n 'ROI_mov',[],... % ROI movement track\n 'ROI_Stat_h', ROI_Stat_h,... % ROI stats\n 'ROI_h', ROI_h ... % ROI handle\n );\nhandles.ROIData=TTMatrix;\nguidata(handles.MU_matrix_display, handles);\nguidata(Figure_handles.MU_main,MU_main_handles);\n\naddNewPositionCallback(ROI_h,@(p) MU_ROI_stat(p,ROI_h,ROI_ind,handles));\nfcn=makeConstrainToRectFcn('imfreehand',[0.5 handles.V.Column+0.4],[0.5 handles.V.Row+0.4]);\nsetPositionConstraintFcn(ROI_h,fcn);\n\nend\n", "meta": {"author": "leoliuf", "repo": "MRiLab", "sha": "5cdcf1f7b67759700685d3a26ffeb70e55325567", "save_path": "github-repos/MATLAB/leoliuf-MRiLab", "path": "github-repos/MATLAB/leoliuf-MRiLab/MRiLab-5cdcf1f7b67759700685d3a26ffeb70e55325567/External/MatrixUser2.2/Src/FuncLib/MU_funcFreeROI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389327, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.49124723104414064}} {"text": "function calpak_test275 ( )\n\n%*****************************************************************************80\n%\n%% CALPAK_TEST275 tests JED_TO_YMDF_ZOROASTRIAN and YMDF_TO_JED_ZOROASTRIAN.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 17 March 2013\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CALPAK_TEST275\\n' );\n fprintf ( 1, ' For the Zoroastrian calendar:\\n' );\n fprintf ( 1, ' JED_TO_YMDF_ZOROASTRIAN: JED -> YMDF.\\n' );\n fprintf ( 1, ' YMDF_TO_JED_ZOROASTRIAN: YMDF -> JED.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' JED (in) YMDF JED (out)\\n' );\n fprintf ( 1, '\\n' );\n\n jed_epoch = epoch_to_jed_zoroastrian ( );\n\n i = 0;\n\n while ( 1 )\n\n i = i + 1;\n jed1 = jed_test ( i );\n\n if ( jed1 < 0.0 )\n break\n end\n\n if ( jed_epoch <= jed1 )\n\n [ y2, m2, d2, f2 ] = jed_to_ymdf_zoroastrian ( jed1 );\n\n s2 = ymdf_to_s_numeric ( y2, m2, d2, f2 );\n\n jed3 = ymdf_to_jed_zoroastrian ( y2, m2, d2, f2 );\n\n fprintf ( 1, ' %11.2f %20s %11.2f\\n', jed1, s2, jed3 );\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/calpak/calpak_test275.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.4912472310441406}} {"text": "function family=getclusterstat(c)\n\n%GETCLUSTERSTAT gets detais of individual correlation clusters.\n% family = GETCLUSTERSTAT(C) outputs a structure FAMILY which contains\n% pertinent details of clusters that exist in C. This is a simple routine\n% that assumes all cluster calculation has already been done. Note that in\n% many cases it may be more appropriate to get the direct CLUST field from\n% a correlation object. In some cases however, GETCLUSTERSTAT may be more\n% expedient. The FAMILY structure includes the fields:\n% rank: size order of the cluster (scalar)\n% numel: number of events in the cluster (scalar)\n% index: the index of the cluster events in the correlation object(Nx1)\n% trig: trigger times of the cluster events (Nx1)\n% begin: the eariest trigger time in the cluster (scalar)\n% finish: the last trigger time in the cluster (scalar)\n% The fields index and trig are cell arrays.\n%\n% See also correlation/cluster\n\n% AUTHOR: Michael West, Geophysical Institute, Univ. of Alaska Fairbanks\n% $Date$\n% $Revision$\n\n\n\n\nif nargin <= 0\n error('Wrong number of inputs');\nend\n\nif ~isa(c,'correlation')\n error('First input must be a correlation object');\nend\n\nif isempty(get(c,'CLUST'))\n error('CLUSTER field must be filled in input argument. See HELP CLUSTER');\nend\n\n\nfor n = 1:max(get(c,'CLUST'))\n f = find(c,'CLUST',n);\n c1 = subset(c,f);\n family.rank(n) = n;\n family.numel(n) = numel(f);\n family.index(n) = {f};\n family.begin(n) = min(get(c1,'TRIG'));\n family.finish(n) = max(get(c1,'TRIG'));\n family.trig(n) = {get(c1,'TRIG')};\nend\n\n\n\n\n", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/core/@correlation/getclusterstat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.49121973337558056}} {"text": "function [x_hat,PSNR,estFin,estHist] = VAMP(y,iters,n,M_func,Mt_func,PSNR_func,U_func,Ut_func,d,UtM_func,MtU_func)\n%\n% [x_hat,PSNR] = VAMP(y,iters,n,M_func,Mt_func,PSNR_func)\n%\n% This function implements VAMP for sparse recovery\n%\n% Inputs:\n% y : the measurements \n% iters : the number of iterations\n% n : signal size\n% M_func : function handle that projects onto A. Or a matrix A.\n% Mt_func : function handle that projects onto A'. Or no entry\n% PSNR_func : optional function handle to evaluate PSNR\n%\n% Output:s\n% x_hat : the recovered signal.\n% PSNR : the PSNR trajectory.\n\nvampOpt = VampSlmOpt3;\nvampOpt.nitMax = iters;\n\nif (nargin>4)&&(~isempty(Mt_func)) % function handles\n vampOpt.Ah = Mt_func;\n vampOpt.N = n;\nend\nif (nargin>5)&&(~isempty(PSNR_func)) % error trajectory\n vampOpt.fxnErr = @(x2) PSNR_func(x2);\nend\nif (nargin>6) % external eigendecomposition [U,D]=eig(M_func(Mt_func(I)))\n vampOpt.U = @(x) U_func(x); % function handle to U\n vampOpt.Uh = @(x) Ut_func(x); % function handle to U'\n vampOpt.d = d; % eigenvalues d=diag(D)\nend\nif (nargin>9) % external SVD [U,S,V]=svd(M_func) with U matching eigenvectors above\n vampOpt.UhA = @(x) UtM_func(x); % function handle to U'*M = S*V'\n vampOpt.AhU = @(x) MtU_func(x); % function handle to M'*U = V*S'\nend\n\n% prepare for VAMP\nalf = 1.0;\ndebias = false; % automatically debias the soft thresholder?\ndenoi = SoftThreshDMMEstimIn(alf,'debias',debias);\n\n% run VAMP\nif nargout==4\n [x_hat,estFin,estHist] = VampSlmEst3(denoi,y,M_func,vampOpt);\nelse\n [x_hat,estFin] = VampSlmEst3(denoi,y,M_func,vampOpt);\nend\nPSNR = estFin.err;\n", "meta": {"author": "ricedsp", "repo": "D-AMP_Toolbox", "sha": "6e597d98c84755697b65554d59485d50a549c01a", "save_path": "github-repos/MATLAB/ricedsp-D-AMP_Toolbox", "path": "github-repos/MATLAB/ricedsp-D-AMP_Toolbox/D-AMP_Toolbox-6e597d98c84755697b65554d59485d50a549c01a/Algorithms/VAMP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.49121973337558056}} {"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\u22c5m\n%% ____\n%% \u2572\n%% \u2572 2\u22c5n\n%% \u2572 \u212f\n%% \u2571 \u2500\u2500\u2500\u2500\u2500\u2500\n%% \u2571 sin(n)\n%% \u2571\n%% \u203e\u203e\u203e\u203e\n%% n = 2\u22c5m\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": "% HKS_matching \nclear all; close all; clc;\n\ngptoolbox_path = ''; % complete\naddpath(genpath(gptoolbox_path));\n\ndata_folder = '..\\data\\';\nmeshes = dir([data_folder,'*.o*']); % a list of all the meshes in the data folder\nmeshes = {meshes.name}; % access each mesh name by meshes{i}\n\ncam_folder = [data_folder, 'cams\\'];\ncams = dir([cam_folder,'*.mat']); % a list of all the cam in the cams folder\ncams = {cams.name};\n\naddpath(data_folder); addpath(cam_folder);\n\n\n%% \n% % For dragon model:\n% [V, F] = readOBJ(meshes{8});\n% cam = cams{8};\n% landmarks = [6921; 6827; 9683; 9710]; % right front leg, left front leg, right back leg, left back leg, \n% figure; MESH_VIS.mesh(F,V,'cams',cam,'landmarks',landmarks);\n\n\n% % For cat model:\n[V, F] = readOFF(meshes{4});\ncam = cams{4};\nlandmarks = [3048; 1994; 6621; 5560]; % right front leg, left front leg, right back leg, left back leg, \nfigure; MESH_VIS.mesh(F,V,'cams',cam,'landmarks',landmarks);\n\n\n% % For xyzrgb_dragon1 model:\n% [V, F] = readOBJ(meshes{14});\n% cam = cams{8};\n% landmarks = [91921; 58423; 51903; 52775]; % right front leg, left front leg, right back leg, left back leg, \n\n\n\n%% Matching: \n% to compute the HKS, use gptoolbox's: [K,MK] = hks(V,F)\n% and to mormalize the hks use: K./MK\n\n\n\n", "meta": {"author": "odedstein", "repo": "sgi-introduction-course", "sha": "52278fc3b3dab52febb110a1a09d770f46b5e417", "save_path": "github-repos/MATLAB/odedstein-sgi-introduction-course", "path": "github-repos/MATLAB/odedstein-sgi-introduction-course/sgi-introduction-course-52278fc3b3dab52febb110a1a09d770f46b5e417/301_hks_matching/exercise/HKS_matching.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4912197225357599}} {"text": "function model = dnetCreate(inputDim, outputDim, Y, options)\n\n% DNETCREATE Density network model.\n% FORMAT\n% DESC creates a structure for a density network.\n% ARG inputDimension : dimension of latent data.\n% ARG outputDim : dimension of observed data.\n% ARG Y : the data to be modelled in design matrix format (as many\n% rows as there are data points).\n% ARG options : options structure as returned by dnetCreate.\n% RETURN model : model structure containing the density network\n% specified.\n% \n% COPYRIGHT : Neil D. Lawrence, 2008\n%\n% SEEALSO : dnetOptions, mlpCreate, rbfCreate, kbrCreate\n\n\n% MLTOOLS\n\nmodel.type = 'dnet';\n\nif size(Y, 2) ~= outputDim\n error(['Input matrix Y does not have dimension ' num2str(d)]);\nend\n\nif isstr(options.initX)\n initFunc = str2func([options.initX 'Embed']);\n model.X = initFunc(Y, inputDim);\nelse\n if size(options.initX, 1) == size(Y, 1) ...\n & size(options.initX, 2) == inputDim\n model.X = options.initX;\n else\n error('options.initX not in recognisable form.');\n end\nend\n\n\nmodel.q = inputDim;\nmodel.d = outputDim;\nmodel.N = size(Y, 1);\n\nmodel.mapping = modelCreate(options.mappingType, inputDim, ...\n outputDim, options.mappingOptions);\nmodel.M = options.M;\nmodel.y = Y;\nmodel.w = repmat(1/model.M, model.N, model.M);\nmodel.betaTransform = optimiDefaultConstraint('positive'); \n\nmodel.beta = exp(-2);\nmodel.grid = options.grid;\n\nif ~isempty(model.grid)\n minVals = 1.2*min(model.X);\n maxVals = 1.2*max(model.X);\n x = linspace(minVals(1), maxVals(1), model.grid(1));\n y = linspace(minVals(2), maxVals(2), model.grid(2));\n [mx, my] = meshgrid(x, y);\n for i = 1:size(model.grid)\n model.X_u = [mx(:) my(:)];\n end\nelse\n model.X_u = randn(model.M, model.q);\nend\n\nlogw = -dist2(model.X, model.X_u);\nlogw = logw -repmat(max(logw, [], 2), 1, model.M);\nmodel.w = exp(logw)./repmat(sum(exp(logw), 2), 1, model.M);\n\nmodel.basisStored = options.basisStored;\n\nmodel.alpha = options.alpha;\n\nparams = dnetExtractParam(model);\nmodel = dnetExpandParam(model, params);\n\nif model.basisStored\n model = dnetUpdateOutputWeights(model);\n model = dnetUpdateBeta(model); \nend\n\nmodel.numParams = model.mapping.numParams + 1;\nmodel.outputDim = model.d;\nmodel.inputDim = model.q;\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/mltools/dnetCreate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.4912197171158495}} {"text": "function i4_to_pascal_test ( )\n\n%*****************************************************************************80\n%\n%% I4_TO_PASCAL_TEST tests I4_TO_PASCAL.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 April 2015\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4_TO_PASCAL_TEST\\n' );\n fprintf ( 1, ' I4_TO_PASCAL converts a linear index to\\n' );\n fprintf ( 1, ' Pascal triangle indices.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' K => I J\\n' );\n fprintf ( 1, '\\n' );\n\n for k = 1 : 20\n\n [ i, j ] = i4_to_pascal ( k );\n\n fprintf ( 1, ' %4d %4d %4d\\n', k, i, j );\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/i4_to_pascal_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.4912197160941769}} {"text": "clear; close all; clc;\n\nfx = 1;\nx = 0;\n\nfor i = 1:5\n x = [x, x(i)+0.5];\n fx = [fx, fx(i)*1.5];\nend\n\nstem(x, fx,'linewidth',2)\ngrid on;\nset(gca,'ytick',round(fx,2))\nxlabel('$$x$$','interpreter','latex');\nylabel('$$f(x)$$','interpreter','latex');\nset(gca,'fontsize',11)", "meta": {"author": "angeloyeo", "repo": "gongdols", "sha": "7be9fbd988dec6edab1dc881cb22d63e6f69398d", "save_path": "github-repos/MATLAB/angeloyeo-gongdols", "path": "github-repos/MATLAB/angeloyeo-gongdols/gongdols-7be9fbd988dec6edab1dc881cb22d63e6f69398d/\uae30\ucd08\uc218\ud559/e^x\ub294 \uc65c \ubbf8\ubd84\ud574\ub3c4 e^x\uc77c\uae4c/pics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.4911969704017945}} {"text": "function pass = test_uplus( pref ) \n% This tests the basic arithmetic operations on chebfun2 objects.\n\nif ( nargin < 1 ) \n pref = chebfunpref; \nend \ntol = 1e5 * pref.cheb2Prefs.chebfun2eps;\nj = 1;\n\nD = [-1 1 -1 1; -2 2 -2 2; -1 pi 0 2*pi];\n\nfor r = 1 : size(D,1)\n f = chebfun2(@(x,y) cos(x.*y), D(r,:));\n \n uplusF = f;\n tolr = norm(D(r,:),inf)*tol;\n \n pass(j) = ( norm( f - uplusF ) < tolr ); j = j + 1;\nend\n\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/chebfun2/test_uplus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.49109642742286325}} {"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": "function h=m_text(long,lat,varargin)\n% M_TEXT Text Annotation\n% M_TEXT(LONG,LAT,'string') adds the text in the quotes to location \n% (LONG,LAT) on the currently defined map projection. If LONG and LAT\n% are vectors, M_TEXT writes the text at all locations given. \n% If 'string' is an array the same number of rows as the\n% length of LONG and LAT, M_TEXT marks each point with the \n% corresponding row of the 'string' array.\n% \n% M_TEXT returns a column vector of handles to TEXT objects, one\n% handle per text object. TEXT objects are children of AXES objects.\n% \n% M_TEXT(LONG,LAT,'string',property/value pairs) can be used to\n% change fontsize, weight, color, etc using the standard TEXT\n% properties.\n%\n% See also TEXT.\n\n% Rich Pawlowicz (rich@ocgy.ubc.ca) 17/Jan/1998\n%\n% This software is provided \"as is\" without warranty of any kind. But\n% it's mine, so you can't sell it.\n\n\n% 31/Jul/99 - changed to allow for X/Y vectors.\n% 6/Nov/00 - eliminate returned stuff if ';' neglected (thx to D Byrne)\n\nglobal MAP_PROJECTION\n\n% Have to have initialized a map first\n\nif isempty(MAP_PROJECTION)\n disp('No Map Projection initialized - call M_PROJ first!');\n return;\nend\n\n[X,Y]=m_ll2xy(long,lat,'clip','off');\n%h=text('position',[X(:) Y(:)],'tag','m_text','string',varargin{:});\n% Fix to allow vectors of X/Y to work\nh=text(X(:),Y(:),varargin{:});\nif ~isempty(h) && isempty(get(h(1),'tag'))\n set(h,'tag','m_text');\nend\n\nif nargout==0\n clear h\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/thirdParty/m_map/m_text.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.49109641416725197}} {"text": "classdef TestSparsePyrLKOpticalFlow\n %TestSparsePyrLKOpticalFlow\n\n methods (Static)\n function test_1\n im1 = 255*uint8([...\n 0 0 0 0 0 0 0 0 0 0;...\n 0 0 0 0 0 0 0 0 0 0;...\n 0 0 0 0 0 0 0 0 0 0;...\n 0 0 0 1 1 1 0 0 0 0;...\n 0 0 0 1 0 1 0 0 0 0;...\n 0 0 0 1 1 1 0 0 0 0;...\n 0 0 0 0 0 0 0 0 0 0;...\n 0 0 0 0 0 0 0 0 0 0;...\n 0 0 0 0 0 0 0 0 0 0;...\n 0 0 0 0 0 0 0 0 0 0;...\n ]);\n im2 = circshift(im1, [0 1]);\n alg = cv.SparsePyrLKOpticalFlow();\n pts = alg.calc(im1, im2, {[3,3]});\n end\n\n function test_2\n prevImg = cv.imread(fullfile(mexopencv.root(),'test','RubberWhale1.png'), ...\n 'Grayscale',true, 'ReduceScale',2);\n nextImg = cv.imread(fullfile(mexopencv.root(),'test','RubberWhale2.png'), ...\n 'Grayscale',true, 'ReduceScale',2);\n prevPts = cv.goodFeaturesToTrack(prevImg, 'MaxCorners',200);\n alg = cv.SparsePyrLKOpticalFlow();\n [nextPts,status,err] = alg.calc(prevImg, nextImg, prevPts);\n validateattributes(nextPts, {'cell'}, ...\n {'vector', 'numel',numel(prevPts)});\n cellfun(@(pt) validateattributes(pt, {'numeric'}, ...\n {'vector', 'numel',2}), nextPts);\n validateattributes(status, {'uint8'}, ...\n {'vector', 'binary', 'numel',numel(nextPts)});\n validateattributes(err, {'single'}, ...\n {'vector', 'real', 'numel',numel(nextPts)});\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/test/unit_tests/TestSparsePyrLKOpticalFlow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.49109640564976853}} {"text": "%% tetMeshBox\n% Below is a demonstration of the features of the |tetMeshBox| function\n\n%%\nclear; close all; clc;\n\n%% Syntax\n% |[meshStruct]=tetMeshBox(boxDim,pointSpacing);|\n\n%% Description\n% This function generates a mesh structure containing element and node data\n% for a tetrahedral element meshed box. The box dimensions in each of the 3\n% directions are based on the boxDim input (1x3 vector). The number of\n% elements in each direction is based on the pointSpacing input.\n\n%% Examples\n\n%%\n% Plot settings\n\nfontSize=20;\nfaceAlpha1=0.8;\n\n%% CREATING A MESHED BOX\nboxDim=[5 6 7]; % Box dimenstions\npointSpacing=1; \n\n[meshStruct]=tetMeshBox(boxDim,pointSpacing);\n\n%%\n% Acces output fields\nE=meshStruct.elements;\nV=meshStruct.nodes;\nF=meshStruct.faces;\nFb=meshStruct.facesBoundary;\nfaceBoundaryMarker=meshStruct.boundaryMarker;\n\n%%\n% Plotting model\ncFigure;\ntitle('Box boundaries faces','FontSize',fontSize);\nhold on;\n\ngpatch(Fb,V,faceBoundaryMarker,'k',faceAlpha1);\n% patchNormPlot(Fb,V);\n\naxisGeom(gca,fontSize); \ncolormap(gjet(6)); icolorbar; \ndrawnow; \n\n%%\n% Visualizing model internal mesh with |meshView|\n\nmeshView(meshStruct); \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_tetMeshBox.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879992, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.49109640139102684}} {"text": "function p02_title ( )\n\n%*****************************************************************************80\n%\n%% P02_TITLE prints a title for problem 02.\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 02\\n' );\n fprintf ( 1, ' Name: QuadSum\\n' );\n fprintf ( 1, ' Davis, Rabinowitz, page 370, #1.\\n' );\n fprintf ( 1, ' Region: 0 <= X(i) <= 1\\n' );\n fprintf ( 1, ' Integrand: F(X) = ( sum ( 2 * X(i) - 1 ) )^4\\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/p02_title.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.49104598627566853}} {"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": "%% Percolation Cluster\nclf \nclc, clear\nthreshold = .63; \n% \nax = axes('units','pixels','position',[1 1 500 400],'color','k'); \ntext('units', 'pixels', 'position', [50,255,0],... \n 'string','BioNB','color','w','fontname','helvetica','fontsize',100) \ntext('units', 'pixels', 'position', [120,120,0],... \n 'string','441','color','w','fontname','helvetica','fontsize',100) \ninitial = getframe(gca); \n[a,b,c]=size(initial.cdata); \nz=zeros(a,b); \ncells = double(initial.cdata(:,:,1)==255); \nvisit = z ; \nsum = z; \nimh = image(cat(3,z,cells,z)); \nset(imh, 'erasemode', 'none') \n%return \nfor i=1:1000\n sum(2:a-1,2:b-1) = cells(2:a-1,1:b-2) + cells(2:a-1,3:b) + ... \n cells(1:a-2, 2:b-1) + cells(3:a,2:b-1) + ... \n cells(1:a-2,1:b-2) + cells(1:a-2,3:b) + ... \n cells(3:a,1:b-2) + cells(3:a,3:b); \n \n pick = rand(a,b); \n %edges only \n %cells = (cells & (sum<8)) | ((sum>=1) & (pick>=threshold) & (visit==0)) ; \n cells = cells | ((sum>=1) & (pick>=threshold) & (visit==0)) ; \n visit = (sum>=1) ;%& (pick 1\n [R,C,P] = ndgrid(1:V(1).dim(1),1:V(1).dim(2),1:V(1).dim(3));\n RCP = [R(:)';C(:)';P(:)';ones(1,numel(R))];\n XYZmm = V(1).mat(1:3,:)*RCP;\nend\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_read_vols.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4910459805148371}} {"text": "% In-paints the depth image using a cross-bilateral filter. The operation \n% is implemented via several filterings at various scales. The number of\n% scales is determined by the number of spacial and range sigmas provided.\n% 3 spacial/range sigmas translated into filtering at 3 scales.\n%\n% Args:\n% imgRgb - the RGB image, a uint8 HxWx3 matrix\n% imgDepthAbs - the absolute depth map, a HxW double matrix whose values\n% indicate depth in meters.\n% spaceSigmas - (optional) sigmas for the spacial gaussian term.\n% rangeSigmas - (optional) sigmas for the intensity gaussian term.\n%\n% Returns:\n% imgDepthAbs - the inpainted depth image.\nfunction imgDepthAbs = fill_depth_cross_bfx(imgRgb, imgDepthAbs, mask, ...\n spaceSigmas, rangeSigmas)\n \n error(nargchk(2,4,nargin));\n assert(isa(imgRgb, 'uint8'), 'imgRgb must be uint8');\n assert(isa(imgDepthAbs, 'double'), 'imgDepthAbs must be a double');\n\n if nargin < 4 \n spaceSigmas = [12 5 8];\n end\n if nargin < 5\n rangeSigmas = [0.2 0.08 0.02];\n end\n \n assert(numel(spaceSigmas) == numel(rangeSigmas));\n assert(isa(rangeSigmas, 'double'));\n assert(isa(spaceSigmas, 'double'));\n \n % Create the 'noise' image and get the maximum observed depth.\n maxv = max(imgDepthAbs(~mask));\n minv = min(imgDepthAbs(~mask));\n \n % Convert the depth image to uint8.\n imgDepth = (imgDepthAbs - minv) ./ (maxv - minv);\n imgDepth = uint8(imgDepth * 255);\n \n % Run the cross-bilateral filter.\n imgDepthAbs = mex_cbf(imgDepth, rgb2gray(imgRgb), mask, spaceSigmas(:), rangeSigmas(:));\n \n % Convert back to absolute depth (meters).\n imgDepthAbs = im2double(imgDepthAbs) .* (maxv - minv) + minv;\nend\n", "meta": {"author": "jianxiongxiao", "repo": "ProfXkit", "sha": "7376c50abf5ead846247774a36be026e6f24953c", "save_path": "github-repos/MATLAB/jianxiongxiao-ProfXkit", "path": "github-repos/MATLAB/jianxiongxiao-ProfXkit/ProfXkit-7376c50abf5ead846247774a36be026e6f24953c/segmentGraph/CrossBilateralFiltering/fill_depth_cross_bfx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737775116229, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4910459689931735}} {"text": "% SIN Sine of argument in radians.\n% SIN(X) is the sine of the elements of X.\n% \n% See also ASIN, SIND.\n%\n% Reference page in Doc Center\n% doc sin\n%\n% Other functions named sin\n%\n% codistributed/sin gpuArray/sin sym/sin ts/sin\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/time_series/@ts/sin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.49103806807826533}} {"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).\n%\n% http://www.petercorke.com\nfunction r = mdl_coil(N)\n \n if nargin == 0\n N = 50;\n end\n \n % create the links\n for i=1:N\n links(i) = Link('d', 0, 'a', 1/N, 'alpha', 5*pi/N);\n end\n \n % and build a serial link manipulator\n robot = SerialLink(links, 'name', 'coil');\n \n % place the variables into the global workspace\n if nargin == 1\n r = robot;\n elseif nargin == 0\n assignin('caller', 'coil', robot);\n assignin('caller', 'q', 10*pi/N*ones(1,N));\n end\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/models/mdl_coil.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6688802471698041, "lm_q1q2_score": 0.49103805060517414}} {"text": "function sqi = flatsqi(signal)\n%flatSQI Flatline SQI\n% \n% \n% Input:\n% signal: single channel (F)ECG [1xN double]\n% MIN_AMP: if the median of the filtered ECG is inferior to MINAMP \n% then it is likely to be a flatline note the importance of \n% the units here for the ECG (mV) \n% \n% Output:\n% sqi: resulting xSQI for segment\n% \n% Fetal Extraction Toolbox, version 1.0, February 2014\n% Released under the GNU General Public License\n%\n% Copyright (C) 2014 Fernando Andreotti\n% Dresden University of Technology, Institute of Biomedical Engineering\n% fernando.andreotti@mailbox.tu-dresden.de\n%\n% Last updated : 30-06-2016\n%\n%\n% This program is free software; you can redistribute it and/or modify it\n% under the terms of the GNU General Public License as published by the\n% Free Software Foundation; either version 2 of the License, or (at your\n% option) any later version.\n% This program is distributed in the hope that it will be useful, but\n% WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\n% Public License for more details.\n\nMIN_AMP = 0.1; \n% == Flatline detection\nif (sum(abs(signal-median(signal))>MIN_AMP)/length(signal))<0.05\n % this is a flat line\n sqi = 0;\nelse\n sqi = 1;\nend\n% if 20% of the samples (or more) have an absolute amplitude which is higher\n% than MIN_AMP then we are good to go.", "meta": {"author": "fernandoandreotti", "repo": "cinc-challenge2017", "sha": "78cfc8e6194857cee0cd731f41ba5b2dd589aed2", "save_path": "github-repos/MATLAB/fernandoandreotti-cinc-challenge2017", "path": "github-repos/MATLAB/fernandoandreotti-cinc-challenge2017/cinc-challenge2017-78cfc8e6194857cee0cd731f41ba5b2dd589aed2/featurebased-approach/subfunctions/lib/fernando/sqi_metrics/flatsqi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.49103269004296013}} {"text": "classdef KernelPCA < handle\n %{\n Kernel Principal component analysis (KPCA)\n \n Version 2.2, 14-MAY-2021\n Email: iqiukp@outlook.com\n -------------------------------------------------------------------\n %}\n \n properties\n data\n label\n numComponents\n explainedLevel\n kernelFunc = Kernel('type', 'gaussian', 'gamma', 0.5)\n lambda\n coefficient %\u3000principal component coefficients\n score %\u3000principal component scores.\n cumContribution % cumulative contribution rate\n newData % Transform the mapping data back to original space\n T2\n SPE\n T2Limit\n SPELimit\n numSPEAlarm\n numT2Alarm\n accuracySPE\n accuracyT2\n eigenvalueTolerance = 1e-8 % tolerance for eigenvalues\n alpha = 1 % hyperparameter of the ridge regression that learns the reconstruction\n theta = 0.7 % experience parameter of fault diagnosis\n significanceLevel = 0.95\n display = 'on'\n temporary\n diagnosis = []\n runningTime\n end\n \n properties (Dependent)\n numSamples\n numFeatures\n end\n \n methods\n function obj = KernelPCA(parameter)\n name_ = fieldnames(parameter);\n for i = 1:size(name_, 1)\n obj.(name_{i, 1}) = parameter.(name_{i, 1});\n end\n KernelPCAOption.checkInputForDiagnosis(obj);\n end\n \n function obj = train(obj, data)\n tStart = tic;\n obj.data = data;\n obj.label = ones(obj.numSamples, 1);\n\n % compute the kernel matrix\n K = obj.kernelFunc.computeMatrix(obj.data, obj.data);\n % centralize the kernel matrix\n unit = ones(obj.numSamples, obj.numSamples)/obj.numSamples;\n K_c = K-unit*K-K*unit+unit*K*unit;\n % compute the eigenvalues and eigenvectors\n [obj.coefficient, obj.lambda] = obj.computeEigenvalue(K_c);\n % \n obj.score = K_c* obj.coefficient(:, 1:obj.numComponents);\n obj.newData = obj.reconstruct;\n obj.temporary.K = K;\n obj.temporary.K_c = K_c;\n obj.temporary.unit = unit;\n obj.computeControlLimit;\n\n % compute accuracy\n T2AlarmIndex = find(obj.T2 > 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\u0131r G H, Weston J, Sch\u00f6lkopf 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": "function [D,C,K] = spm_dcm_KL(M)\n% Computes the distance between two models based on prior responses\n% FORMAT [D,C,K] = spm_dcm_KL(Mi,Mj)\n%\n% M{1:n} - structure array of models\n%\n% D(n x n) - distance matrix (KL divergence)\n% C{1:n} - response covariances\n% K{1:n} - response means\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: spm_dcm_KL.m 5219 2013-01-29 17:07:07Z spm $\n \n \n% Volterra kernels\n%==========================================================================\n \n% time bins (if not specified)\n%--------------------------------------------------------------------------\ntry \n dt = M{1}.dt;\n N = M{1}.N;\ncatch\n \n % Bilinear representation\n %----------------------------------------------------------------------\n M0 = spm_bireduce(M{1},P{1});\n s = real(eig(full(M0)));\n s = max(s(find(s < 0)));\n N = 32;\n dt = -4/(s*N);\n \nend\n \n% get covariances of prior responses\n%==========================================================================\nm = length(M);\nfor i = 1:m\n \n % Get parameters (adding a little to prevent expansion around zero)\n %----------------------------------------------------------------------\n P = M{i}.pE;\n pC = M{i}.pC;\n P = spm_vec(P) + sqrt(diag(pC))/8;\n P = spm_unvec(P,M{i}.pE);\n \n % add a little to inputs (to prevent expansion around zero)\n %----------------------------------------------------------------------\n M{i}.u = ones(M{i}.m,1)/8;\n \n % get eigen-space of parameters for computational efficiency\n %----------------------------------------------------------------------\n V = spm_svd(pC);\n pC = V'*pC*V;\n \n % get derivative of kernels w.r.t. parameters\n %----------------------------------------------------------------------\n [dkdp,k] = spm_diff('spm_kernel',M{i},P,N,dt,2,{[],V});\n \n % prior mean and covariance of kernels\n %----------------------------------------------------------------------\n k = spm_vec(k);\n dk = sparse(length(k),length(dkdp));\n for j = 1:length(dkdp)\n dk(:,j) = spm_vec(dkdp{j});\n end\n K{i} = k;\n C{i} = dk*pC*dk';\n n(i) = length(pC);\n \nend\n \n \n% evaluate KL divergence\n%--------------------------------------------------------------------------\nfor i = 1:m\n for j = 1:m\n Pi = spm_pinv(C{i});\n k = K{i} - K{j};\n d = spm_logdet(C{i}) - spm_logdet(C{j}) + ...\n trace(Pi*C{j}) + k'*Pi*k - n(i);\n D(i,j) = d/2;\n end\nend\n\n% ensure D is symmetric\n%--------------------------------------------------------------------------\nD = (D + D')/2;\n\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_dcm_KL.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4910326788080482}} {"text": "clc, clear\na=[-1 -2 0;-1 0 0];b=[-1;0];\n[x,y]=ga(@ycfun1,3,a,b,[],[],[],[],@ycfun2);\nx, y=-y\n", "meta": {"author": "Eurus-Holmes", "repo": "Mathematical_Modeling", "sha": "cb9dd53af84ffbd455ec62ab89886351e0ec98d9", "save_path": "github-repos/MATLAB/Eurus-Holmes-Mathematical_Modeling", "path": "github-repos/MATLAB/Eurus-Holmes-Mathematical_Modeling/Mathematical_Modeling-cb9dd53af84ffbd455ec62ab89886351e0ec98d9/Mathematical_Modeling_Algorithms_and_Applications_Second_Edition_Procedures_and_Data/12\u7b2c12\u7ae0/ex12_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867969424067, "lm_q2_score": 0.6150878555160666, "lm_q1q2_score": 0.49095500523254304}} {"text": "function i4col_sorted_singleton_count_test ( )\n\n%*****************************************************************************80\n%\n%% I4COL_SORTED_SINGLETON_COUNT_TEST tests I4COL_SORTED_SINGLETON_COUNT;\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 November 2014\n%\n% Author:\n%\n% John Burkardt\n%\n m = 3;\n n = 10;\n test_num = 2;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4COL_SORTED_SINGLETON_COUNT_TEST\\n' );\n fprintf ( 1, ' I4COL_SORTED_SINGLETON_COUNT counts singletons\\n' );\n fprintf ( 1, ' in a sorted I4COL;\\n' );\n\n seed = 123456789;\n\n for test = 1 : test_num\n\n b = 0;\n c = 3;\n\n [ a, seed ] = i4mat_uniform_ab ( m, n, b, c, seed );\n\n a = i4col_sort_a ( m, n, a );\n\n i4mat_print ( m, n, a, ' Ascending sorted I4COL:' );\n\n singleton_num = i4col_sorted_singleton_count ( m, n, a );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of singletons = %d\\n', singleton_num );\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/i4col_sorted_singleton_count_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.49095499637399287}} {"text": "%% RESTICTED geometry DEFINITION (OMAS_restrictedGeometry.m) %%%%%%%%%%%%%%\n% This function computes the geometry that can be observed within a defined\n% radius.\n\nfunction [restrictedGeometry] = OMAS_restrictedGeometry(point,radius,geometry)\n% INPUTS:\n% centroid - The 3D cartesian reference point.\n% radius - The detection radius of the observational sphere.\n% geometry - The geometry of the second object in the reference frame of\n% the centroid.\n\n% TO ENSURE FUNCTIONALITY\nsendCompleteGeometryOnDetection = 1;\n\nnewSurfaceMembers = [];\n% EVALUATE THE geometry'S FACE MEMBERS\nfor face = 1:size(geometry.faces,1)\n % NOTE:\n % - If all vertices are outside of the sphere, the sphere may still \n % intersect the plane at an edge or mid-plane.\n \n % MEMBERS IF THE PLANE\n memberID_A = geometry.faces(face,1);\n memberID_B = geometry.faces(face,2);\n memberID_C = geometry.faces(face,3);\n % TEST THE FACE AGAINST THE SPHERE\n faceIsInsideRadius = OMAS_sphereTriangleIntersection(point,radius,...\n geometry.vertices(memberID_A,:)',...\n geometry.vertices(memberID_B,:)',...\n geometry.vertices(memberID_C,:)');\n if sendCompleteGeometryOnDetection && faceIsInsideRadius\n % IF ANY FACE IS VISIBLE, SEND THE COMPLETE GEOMETRY \n restrictedGeometry = geometry;\n return\n elseif faceIsInsideRadius\n % IF THE FACE IS FOUND TO VIOLATE THE CONSTRAINT\n% fprintf('\\t face %d interacts with the sphere\\n',face);\n % add all vertices belonging to that face to the matrix\n newSurfaceMembers = vertcat(newSurfaceMembers,memberID_A,memberID_B,memberID_C);\n end\nend\n% PARSE COMMON POINTS\nnewSurfaceMembers = unique(newSurfaceMembers,'rows'); % The unique vertices\nnewVertices = geometry.vertices(newSurfaceMembers,:); % Extract the common vertices\n\n% THE CONSTRAINT SURFACE\n% sphereGeometry = OMAS_graphics.defineSphere(zeros(3,1),radius,6);\n% [A B] = SurfaceIntersection(sphereGeometry,geometry);\n\n\n% TRIANGULATE THE NEW VOLUME\ntriangulatedVolume = triangulation(boundary(newVertices(:,1),newVertices(:,2),newVertices(:,3),1),newVertices);\nrestrictedGeometry = geometry;\nrestrictedGeometry.vertices = triangulatedVolume.Points;\nrestrictedGeometry.faces = triangulatedVolume.ConnectivityList;\nrestrictedGeometry.normals = OMAS_graphics.normals(restrictedGeometry); % Compute the surface normals\n\n% DEBUG\n% fig = figure(2);\n% ax = axes(fig);\n% axis square vis3d;\n% % THE OBJECT GEOMETRY\n% patch(ax,...\n% 'Faces',geometry.faces,...\n% 'Vertices',geometry.vertices,...\n% 'faceColor','g');\n% % THE CONSTRAINT VOLUME\n% patch(ax,...\n% 'Faces',sphereGeometry.faces,...\n% 'Vertices',sphereGeometry.vertices,...\n% 'faceColor','b',...\n% 'faceAlpha',0.2);\n% % THE RESULTING GEOMETRY\n% patch(ax,...\n% 'Faces',restrictedGeometry.faces,...\n% 'Vertices',restrictedGeometry.vertices,...\n% 'faceColor','b',...\n% 'faceAlpha',0.2);\n% end\n\nend\n\n% THE SQUARED DISTANCE TO ALL VERTICES\n% verticesSq = (geometry.vertices(:,1) - point(1)).^2 ...\n% + (geometry.vertices(:,2) - point(2)).^2 ...\n% + (geometry.vertices(:,3) - point(3)).^2;\n% % VERTEX INSIDE RADIUS LOGICALS\n% vertexDetectionLogicals = verticesSq <= radius^2;\n% vertexIDset = 1:1:numel(vertexDetectionLogicals);\n% \n% % VISIBLE POINT ID's\n% visibleIDs = vertexIDset(vertexDetectionLogicals);\n% if numel(visibleIDs) < 1\n% disp('no vertices are visible');\n% end\n\n% [A,~] = ismember(relativeFaces,vertIndices);\n% completeFaceIndices = sum(A,2) > 2; % Minimum number of connections\n\n", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/environment/OMAS_restrictedGeometry.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": "% [ 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": "clear all; close all;\naddpath(genpath('./visualize'));\ntri = load('tri.mat');\naa = dir('./aflw-2000_shown/2DASL_vertices/*.mat');\ntri = tri.tri;\n\nfor ii = 1:length(aa)\n img = imread(strcat('./aflw-2000_shown/oriImgs/', aa(ii).name(1:end-4), '.jpg'));\n vertex = load(strcat('./aflw-2000_shown/2DASL_vertices/', aa(ii).name(1:end-4)));\n figure\n imshow(img)\n im1 = imagesc(img); \n hold on\n \n vertex = vertex.vertex;\n vertex(3,:,:) = vertex(3,:,:) - min(vertex(3,:,:));\n pcshow(vertex')\n view(2)\n saveas(gca, strcat('./aflw-2000_shown/results/', 'dense_align_', aa(ii).name(1:end-4), '.jpg'))\n close all\n figure\n im1 = imagesc(img); \n hold on\n render_face_mesh_xgtu(vertex, tri);\n saveas(gca, strcat('./aflw-2000_shown/results/', 'recons_align_', aa(ii).name(1:end-4), '.jpg'))\n close all\nend\n\nprint('done')", "meta": {"author": "XgTu", "repo": "2DASL", "sha": "95052f203e6d945bb6563f916cc539bba0815972", "save_path": "github-repos/MATLAB/XgTu-2DASL", "path": "github-repos/MATLAB/XgTu-2DASL/2DASL-95052f203e6d945bb6563f916cc539bba0815972/3D_results_plot/test_good_byXgtu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49095498751544236}} {"text": "function [L,P,Lc,Pc]=corr_meas(rtk,obs,nav,dantr,dants,phw)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SNR test not surpport\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nglobal glc\nlam=nav.lam(obs.sat,:);\nL=zeros(glc.NFREQ,1);P=zeros(glc.NFREQ,1);Lc=0;Pc=0;\n\nfor i=1:glc.NFREQ\n L(i)=0; P(i)=0;\n if lam(i)==0||obs.L(i)==0||obs.P(i)==0,continue;end\n \n %antenna phase center and phase windup correction\n L(i)=obs.L(i)*lam(i)-dants(i)-dantr(i)-phw*lam(i);\n P(i)=obs.P(i) -dants(i)-dantr(i);\n \nend\n\n% DCB correction \n[cbias,~]=getdcb(nav,obs,rtk.opt);\nfor i=1:glc.NFREQ\n if P(i)~=0,P(i)=P(i)-cbias(i);end\nend\nC1= lam(2)^2/(lam(2)^2-lam(1)^2);\nC2=-lam(1)^2/(lam(2)^2-lam(1)^2);\n\n%IFLC measurements\nif L(1)~=0&&L(2)~=0,Lc=C1*L(1)+C2*L(2);end\nif P(1)~=0&&P(2)~=0,Pc=C1*P(1)+C2*P(2);end\n\nreturn\n\n\n", "meta": {"author": "kaichen686", "repo": "GINav", "sha": "bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666", "save_path": "github-repos/MATLAB/kaichen686-GINav", "path": "github-repos/MATLAB/kaichen686-GINav/GINav-bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666/src/gnss/ppp/corr_meas.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.490949832938881}} {"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\u00f1o. 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": "function textscatter(varargin)\n% textscatter(cx,cy,markersize,markerstyle,textcolor, textoffsetx, textoffsety)\n% Uses scatter plot and each marker is labeled by the number of the row in\n% the [cx, cy] matrix. Text is offste by [textoffsetx, textoffsety] from\n% the markers. \n% Examples: \n% textscatter(100*rand(1,30), 100*rand(1,30))\n% textscatter(100*rand(1,30), 100*rand(1,30),[],'d')\n% textscatter(100*rand(1,30), 100*rand(1,30),100,'gx','r', 2,3)\n\nargs = varargin; \nif nargin<5 % textcolor \n% args{5} = [0 0 0]; % black \n args{5} = [1 0 0]; % red \nend\nif nargin<6 % textoffset\n args{6}= .5;\n args{7}= .5;\nend\n\ncx = args{1}; \ncy = args{2};\ntextcolor = args{5};\ntextoffsetx = args{6};\ntextoffsety = args{7};\n\nscatter(args{1:min(nargin,4)})\ntext(cx+textoffsetx, cy+textoffsety, num2str([1:length(cx)]' ),'color' , textcolor)", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/ploting/textscatter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225279, "lm_q2_score": 0.6893056295505784, "lm_q1q2_score": 0.4909456457221644}} {"text": "function Y = nnsoft(X, T) \n%% Soft threshold function\n%% Copyright (c) 2017 Yan Yang\n%% All rights reserved.\nTH = abs(T);\n B = X >= TH;\n S = X <= -TH;\n Y = (X - TH) .* B + (X + TH) .* S; \nend\n\n", "meta": {"author": "yangyan92", "repo": "Deep-ADMM-Net", "sha": "f95738c6629364c87e0534a2a0bbf75843693ed7", "save_path": "github-repos/MATLAB/yangyan92-Deep-ADMM-Net", "path": "github-repos/MATLAB/yangyan92-Deep-ADMM-Net/Deep-ADMM-Net-f95738c6629364c87e0534a2a0bbf75843693ed7/layersfunction/nnsoft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.4909456450512728}} {"text": "function [projOrder, d, dRow, dVar] = getProjOrder(L)\n%GETPROJORDER Get projection order of a LINOP.\n% Each boundary and continuity constraint in a LINOP forces a reduction in the\n% total number of rows in the discrete operator, so that the composite is\n% square. The reduction is found by down-projection of the result of applying\n% the operator.\n%\n% GETPROJORDER(DISC) returns a matrix of dimensions by which each column of\n% the system should be down-projected in order to end with a square system.\n\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nd = L.diffOrder;\ndRow = max(d, [], 2);\ndVar = max(d, [], 1);\nprojOrder = max(dVar, 0);\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/@linop/getProjOrder.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.4909456411762954}} {"text": "function sphere_triangle_quad_test ( )\n\n%*****************************************************************************80\n%\n%% SPHERE_TRIANGLE_QUAD_TEST tests the SPHERE_TRIANGLE_QUAD library.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 22 April 2014\n%\n% Author:\n%\n% John Burkardt\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPHERE_TRIANGLE_QUAD_TEST\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, ' Test the SPHERE_TRIANGLE_QUAD library.\\n' );\n\n sphere_triangle_quad_test01 ( );\n sphere_triangle_quad_test02 ( );\n sphere_triangle_quad_test03 ( );\n sphere_triangle_quad_test04 ( );\n sphere_triangle_quad_test05 ( );\n sphere_triangle_quad_test06 ( );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPHERE_TRIANGLE_QUAD_TEST\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sphere_triangle_quad/sphere_triangle_quad_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.4909456408408496}} {"text": "function params = IEEE80211a_settings(...\n symbolPeriod, ...\n OFDMSymPerFrame, ...\n OFDMTrainPerFrame, ...\n vtbd);\n\n% Note: A sample period of 0.08e-6 corresponds to approx. 12 Msym/s, \n% which, in turn, corresponds to 54 Mb/s for 3/4-coded 64-QAM\n\n% IEEE 802.11a - fundamental sizes\np.NSD = 48; % number of data symbols in OFDM symbol (variable name as in 802.11a standard)\np.NST = 52; % number of data symbols and pilots in OFDM symbol (variable name as in 802.11a standard)\np.NFFT = 64; % number of points on FFT\np.NcyclicPrefix = 16;\n\np.NFFT2 = p.NFFT + p.NcyclicPrefix;\n\n% TX indices\np.TXFFTShiftIndices = [p.NST/2+1:p.NFFT 1:p.NST/2];\np.TXCyclicPrefixIndices = [p.NFFT-[p.NcyclicPrefix-1:-1:0] 1:p.NFFT];\n\n% RX indices\np.RXCyclicPrefixIndices = [p.NcyclicPrefix+1:p.NFFT2];\np.RXSelectFFTIndices = [p.NFFT-[p.NST/2-1:-1:0] 1:p.NST/2+1];\n\n% OFDM symbols\np.OFDMSymPerFrame = OFDMSymPerFrame;\np.OFDMTrainPerFrame = OFDMTrainPerFrame;\np.OFDMTotSymPerFrame = OFDMSymPerFrame + OFDMTrainPerFrame;\n\n% Constellation symbols\np.numTxSymbols = p.NSD * OFDMSymPerFrame;\np.numTrainingSymbols = p.NSD * OFDMTrainPerFrame;\n\n% Training sequence\np.long_training_seq = ...\n [1 1 -1 -1 1 1 -1 1 -1 1 1 1 1 1 1 -1 -1 1 1 -1 1 -1 1 1 1 1 0 ...\n 1 -1 -1 1 1 -1 1 -1 1 -1 -1 -1 -1 -1 1 1 -1 -1 1 -1 1 -1 1 1 1 1].'; \n\n% Modulator/demodulator banks\np.numModulators = 8;\np.txBitsPerSymbol = [1 1 2 2 4 4 6 6];\np.txBitsPerBlock = p.numTxSymbols * p.txBitsPerSymbol;\np.modOrder = 2.^p.txBitsPerSymbol;\np.codeRate = [1/2 3/4 1/2 3/4 1/2 3/4 2/3 3/4];\np.bitsPerBlock = p.txBitsPerBlock .* p.codeRate;\np.bitsPerSymbol = p.txBitsPerSymbol .* p.codeRate;\np.maxBitsPerBlock = max(p.bitsPerBlock);\n\n% Frame size for variable rate source\np.nSource = min( gcd( min(p.bitsPerBlock), p.bitsPerBlock ) ); \n\n% Source blocks per TX frame\np.nS = p.bitsPerBlock/p.nSource;\n\n% Timing-related parameters\np.symbolPeriod = symbolPeriod;\np.blockPeriod = p.numTxSymbols * symbolPeriod;\np.bitPeriod = symbolPeriod ./ p.bitsPerSymbol;\np.minBitPeriod = min(p.bitPeriod);\np.chanSamplePeriod = p.blockPeriod/(p.OFDMTotSymPerFrame * p.NFFT2);\n\n% Viterbi trace back depth and link delay\nvtbd_set = vtbd(ones(1, p.numModulators));\np.vtbd_set = vtbd_set;\np.link_delay = vtbd_set;\n\nparams = p;\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/3540-ieee-802-11a-wlan-model/R13SP1/IEEE80211a_settings.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4909164498375472}} {"text": "classdef GFMMOEA < ALGORITHM\n% \n% Generic front modeling based multi-objective evolutionary algorithm\n% theta --- 0.2 --- Penalty parameter\n% fPFE --- 0.1 --- Frequency of employing generic front modeling\n\n%------------------------------- Reference --------------------------------\n% Y. Tian, X. Zhang, R. Cheng, C. He, and Y. Jin, Guiding evolutionary\n% multi-objective optimization with generic front modeling, IEEE\n% Transactions on Cybernetics, 2020, 50(3): 1106-1119.\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 [theta,fPFE] = Algorithm.ParameterSet(0.2,0.1);\n\n %% Generate random population\n Population = Problem.Initialization();\n FrontNo = NDSort(Population.objs,inf);\n zmin = min(Population.objs,[],1);\n % Calculate the fitness of each solution\n [P,A] = deal(ones(1,Problem.M));\n [App,Dis] = CalFitness(Population.objs-repmat(zmin,length(Population),1),P,A);\n Dis = sort(Dis,2);\n Crowd = Dis(:,1) + 0.1*Dis(:,2);\n\n %% Optimization\n while Algorithm.NotTerminated(Population)\n MatingPool = TournamentSelection(2,Problem.N,FrontNo,-theta*App-(1-theta)*Crowd);\n Offspring = OperatorGA(Problem,Population(MatingPool));\n zmin = min([zmin;Offspring.objs],[],1);\n if ~mod(ceil(Problem.FE/Problem.N),ceil(fPFE*ceil(Problem.maxFE/Problem.N))) || fPFE == 0\n [P,A] = GFM(Population(FrontNo==1).objs-repmat(zmin,sum(FrontNo==1),1));\n end\n [Population,FrontNo,App,Crowd] = EnvironmentalSelection([Population,Offspring],P,A,zmin,theta,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/GFM-MOEA/GFMMOEA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.49091644436187626}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Max manipulability index ALONG A LINE.\n% Use stomp like to optimize along a surface/line\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction experiment1B\nclose all;\nglobal robot\nglobal parameters\nglobal hfigures\n\n%STOMP PARAMETERS\n%conversion from cost to Prob factor\nparameters.lambda = .4;\nparameters.lambda_obstacles = .2;\n%height of the obstacle\nparameters.yo = 2.5;\n%cost function starts at this distance\n%must be below 0.3 for the 4 DOF robot\nparameters.epsilon = 0.2;\n%multiply noise by this facto\n%parameters.noise_k = 5;\n%parameters.noise_sigma_null_space = 0.01;\nparameters.alpha=0.02;\nparameters.time_step=0.01;\n\n%number of waypoints\nparameters.N = 12;\n%number of particles\nparameters.K = 5;\nparameters.n_repeat = 30;\nparameters.experiment_name = 'experiment1B_K5_N30.mat';\n\nparameters.animate = 0;\n\nparameters.obstacles = [];\n\n\n%LINE 1\nx1 = -1.5;\ny1 = .5; %m\nx2 = 0;\ny2 = 2; %m\nphi = 3*pi/4; \np0 = [x1 y1 0]';\npf = [x2 y2 0]';\nT0 = build_T_4dof(p0, phi);\nparameters.obstacles{1}.line = [p0 pf];\nparameters.obstacles{1}.T0 = T0;\n\n%repeat the experiment E times\nrandom_manips=[];\nGout = [];\nfor i=1:parameters.n_repeat\n close all\n [pk, final_manip] = stomp_null_space(robot);\n Gout{i}=pk;\n random_manips = [random_manips; final_manip];\n save(parameters.experiment_name)\nend\n\n\n\nfunction T = build_T_4dof(p, phi)\nT = [cos(phi) -sin(phi) 0 p(1);\n sin(phi) cos(phi) 0 p(2);\n 0 0 1 p(3);\n 0 0 0 1];\n \n function T = build_T_sawyer(p, phi)\nT = [1 -sin(phi) 0 p(1);\n 0 cos(phi) 0 p(2);\n 0 0 1 p(3);\n 0 0 0 1];\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/lib/SCO_v0.5/backup/experiment1/experiment1B_K5_N30.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.4909152004504857}} {"text": "classdef prtKernelRbfFixed < prtKernel\n\n\n\n\n\n\n\n \n properties (SetAccess = private)\n name = 'RBF Kernel'; % RBF Kernel\n nameAbbreviation = 'RBF'; % RBF\n end\n \n properties\n sigma = 1; % The inverse kernel width\n x0 = 0;\n end \n \n methods (Hidden = true)\n \n function nDimensions = nDimensions(self)\n nDimensions = 1;\n end\n \n end\n methods (Access = protected, Hidden = true)\n function self = trainAction(self,ds)\n self.internalDataSet = ds;\n self.isTrained = true;\n end\n \n function dsOut = runAction(self,ds)\n if ~self.isTrained\n error('prtKernelRbf:run','Attempt to run an untrained kernel; use kernel.train(ds) to train');\n end\n if self.internalDataSet.nObservations == 0\n dsOut = prtDataSetClass;\n else\n gram = prtKernelRbf.kernelFn(ds.getObservations,self.x0,self.sigma);\n dsOut = ds.setObservations(gram);\n end\n end\n end\n \n methods\n function self = prtKernelRbfFixed(varargin)\n self = prtUtilAssignStringValuePairs(self,varargin{:});\n end\n \n function self = set.sigma(self,value)\n if ~prtUtilIsPositiveScalar(value)\n assert(isnumeric(value) && all(value>0) && isvector(value),'sigma must be a positive numeric vector')\n if isempty(self.internalDataSet) || self.internalDataSet.nObservations==0\n error('prtKernelRbf:set','Value of sigma must be a positive scalar');\n else\n assert(self.internalDataSet.nObservations==numel(value),'When setting sigma to be an array of values the internalDataSet must be set and the number of observations and the length of sigma must match');\n end\n end\n self.sigma = value(:);\n end\n end\n \n methods(Hidden = true)\n function varargout = plot(obj)\n x = obj.internalDataSet.getObservations;\n \n if size(x,2) <= 3\n if size(x,2) == 1 && obj.internalDataSet.isLabeled\n xy = cat(2,x,obj.internalDataSet.getTargets);\n h = prtPlotUtilScatter(xy, {}, obj.plotOptions.symbol, obj.plotOptions.markerFaceColor, obj.plotOptions.color, obj.plotOptions.symbolLineWidth, obj.plotOptions.symbolSize);\n else\n h = prtPlotUtilScatter(x, {}, obj.plotOptions.symbol, obj.plotOptions.markerFaceColor, obj.plotOptions.color, obj.plotOptions.symbolLineWidth, obj.plotOptions.symbolSize);\n end\n else\n h = nan;\n end\n \n varargout = {};\n if nargout\n varargout = {h};\n end\n end\n end\n \n methods (Static, Hidden = true)\n function gram = kernelFn(x,y,sigma)\n [n1, d] = size(x);\n [n2, nin] = size(y);\n % if d ~= nin\n % error('size(x,2) must equal size(y,2)');\n % end\n % keyboard\n %dist2 = prtDistanceLNorm(x,y,2); \n dist2 = repmat(sum((x.^2), 2), [1 n2]) + repmat(sum((y.^2),2), [1 n1]).' - 2*x*(y.');\n \n if numel(sigma) == 1\n gram = exp(-dist2/(sigma.^2));\n else\n gram = exp(-bsxfun(@rdivide,dist2,(sigma.^2)'));\n end\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/kernels/prtKernelRbfFixed.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.49091518993519423}} {"text": "function mono_between_next_grlex_test ( )\n\n%*****************************************************************************80\n%\n%% MONO_BETWEEN_NEXT_GRLEX_TEST tests MONO_BETWEEN_NEXT_GRLEX.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 November 2013\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MONO_BETWEEN_NEXT_GRLEX_TEST\\n' );\n fprintf ( 1, ' MONO_BETWEEN_NEXT_GRLEX can list the monomials\\n' );\n fprintf ( 1, ' in M variables, of total degree N between N1 and N2,\\n' );\n fprintf ( 1, ' one at a time, in graded lexicographic order.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' We start the process with (0,0,...,0,N1).\\n' );\n fprintf ( 1, ' The process ends with (N2,0,...,0,0)\\n' );\n\n n1 = 2;\n n2 = 3;\n m = 3;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Let M = %d\\n', m );\n fprintf ( 1, ' N1 = %d\\n', n1 );\n fprintf ( 1, ' N2 = %d\\n', n2 );\n fprintf ( 1, '\\n' );\n\n x = [ 0, 0, n1 ];\n i = 1;\n\n while ( 1 )\n\n fprintf ( 1, ' %2d:', i );\n for j = 1 : m\n fprintf ( 1, ' %1d', x(j) );\n end\n fprintf ( 1, '\\n' );\n\n if ( x(1) == n2 )\n break\n end\n\n x = mono_between_next_grlex ( m, n1, n2, x );\n i = i + 1;\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/monomial/mono_between_next_grlex_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.49091518651597393}} {"text": "function rx = rxIn(rx);\n% \n% rx = rxIn(rx);\n%\n% For mrRx, nudge the prescription 'in' (along the vector pointing from \n% the middle of the last slice toward the middle of the first slice) a\n% certain delta according to the value of the nudge slider.\n%\n% ras, 08/05.\nif ieNotDefined('rx')\n cfig = findobj('Tag','rxControlFig');\n rx = get(cfig,'UserData');\nend\n\n%%%%%get params\nnudgeVal = get(rx.ui.nudge.sliderHandle,'Value')/6; % make a small nudge\n\n%%%%%compute a vector pointing 'in'\n% middle X, Y coords\nmidX = rx.rxDims(2)/2;\nmidY = rx.rxDims(1)/2;\n\n% cols of coords are: middle of last slice, middle of first slice\ncoords(:,1) = [midX; midY; rx.rxDims(3)];\ncoords(:,2) = [midX; midY; 1];\n\n% convert coords into volume coordinate space\nvolCoords = rx2vol(rx,coords);\n\n% get vector as diff. b/w these two points\nvec = diff(volCoords');\n\n%%%%%modify translation accordingly\n[trans rot scale skew] = affineDecompose(rx.xform);\ntrans = trans + nudgeVal.*vec;\nnewXform = affineBuild(trans,rot,scale,skew);\nrx = rxSetXform(rx,newXform);\n\nreturn\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAnatomy/mrRx/rxIn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4909151830967535}} {"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": "function value = r8vec_insignificant ( n, r, s )\n\n%*****************************************************************************80\n%\n%% R8VEC_INSIGNIFICANT determines if an R8VEC is insignificant.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 November 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the dimension of the vectors.\n%\n% Input, real R(N), the vector to be compared against.\n%\n% Input, real S(N), the vector to be compared.\n%\n% Output, logical R8VEC_INSIGNIFICANT, is TRUE if S is insignificant\n% compared to R.\n%\n value = 1;\n\n for i = 1 : n\n\n t = r(i) + s(i);\n tol = eps * abs ( r(i) );\n\n if ( tol < abs ( r(i) - t ) )\n value = 0;\n exit;\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8vec_insignificant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.7662936324115011, "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 [gKern, gVarmeans, gVarcovars] = linard2VardistPsi0Gradient(linard2Kern, vardist, covGrad)\n\n% LINARD2VARDISTPSI0GRADIENT description.\n\n% VARGPLVM\n \nA = linard2Kern.inputScales;\ngKern = covGrad*sum((vardist.means.*vardist.means) + vardist.covars,1); \n \ngVarmeans = 2*(vardist.means*sparse(diag(A))); \n%gVarmeans1 = 2*(repmat(A,size(vardist.means,1),1).*vardist.means); \n\ngVarcovars = ones(size(vardist.means,1),1)*A; \n\ngVarmeans = covGrad*gVarmeans(:)'; \ngVarcovars = covGrad*gVarcovars(:)';\n\n\n", "meta": {"author": "SheffieldML", "repo": "vargplvm", "sha": "480201fde5ac84ff36e4a9f06d3fafeafa8ef06d", "save_path": "github-repos/MATLAB/SheffieldML-vargplvm", "path": "github-repos/MATLAB/SheffieldML-vargplvm/vargplvm-480201fde5ac84ff36e4a9f06d3fafeafa8ef06d/vargplvm/matlab/linard2VardistPsi0Gradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4908544188732087}} {"text": "%==============================================================================\n% This code is part of the VAMPIRE app for the Matlab-based toolbox\n% FAIR - Flexible Algorithms for Image Registration. \n% For details see \n% - https://github.com/C4IR/VAMPIRE.m \n%==============================================================================\n%\n% 2D Example for Multilevel Mass-Preserving Image Registration using VAMPIRE\n% \n% \t- data synthetic 2D Gaussian blobs (level 3:8, full\n% resolution: 256x256)\n% - viewer viewImage2D\n% - interpolation splineInter\n% - distance SSD\n% - pre-registration none\n% - regularizer mfHyperElastic\n% - optimizer Gauss-Newton with ArmijoBacktrack linesearch\n\nsetup2DGaussianData;\n\n% prepare the plot\nFAIRplots('clear')\nDshow = @(T,R,omega,m) viewImage2D(128+(T-R)/2,omega,m,'colormap',gray(256));\nFAIRplots('set','Dshow',Dshow);\n\n% initialize the regularizer for the non-parametric part\nalpha = 100;\nalphaLength = 1;\nalphaArea = 0;\nalphaVolume = 1;\n[reg,regOptn] = regularizer('reset', 'regularizer', 'mfHyperElastic', ...\n 'alpha',alpha, 'alphaLength', alphaLength, 'alphaArea', alphaArea, ...\n 'alphaVolume', alphaVolume);\n\n% finally: run the Mass-Preserving Non-Parametric Image Registration\nNPIRpara = optPara('NPIR-GN');\nNPIRpara.lineSearch = @ArmijoDiffeomorphic;\nNPIRpara.solver = @VAMPIREsolveGN_PCG;\n\n[yc,wc,his] = MLIR(ML, 'NPIRobj', @VAMPIRENPIRobjFctn, ...\n 'parametric', false, 'NPIRpara', NPIRpara, 'minLevel', 5);\n\n% [reg,regOptn] = regularizer('reset','regularizer','mfElastic',...\n% 'alpha',alpha,'alphaLength',alphaLength,'alphaArea',alphaArea,...\n% 'alphaVolume',alphaVolume);\n% \n% % finally: run the Non-Parametric Image Registration\n% [yc,wc,his] = MLIR(ML, 'NPIRobj', @NPIRobjFctn, ...\n% 'parametric', false, 'minLevel', 4);\n\n%% Plot Results\n% Compute resulting image: dataT(yc) * det(D(yc))\nTopt = reshape(linearInter(dataT,omega,center(yc,m)) .* geometry(yc,m,'Jac','omega',omega), m);\nfigure;\nsubplot(2,2,1);\nviewImage2D(dataT,omega,m,'colormap', 'gray(256)');\nhold on; plotGrid(center(yc, m), omega, m, 'spacing', [5 5]); axis off; hold off;\ntitle('Template (T) & Grid')\nsubplot(2,2,2);\nviewImage2D(dataR,omega,m,'colormap', 'gray(256)'); axis off;\ntitle('Reference (R)')\nsubplot(2,2,3);\nviewImage2D(Topt,omega,m,'colormap', 'gray(256)'); axis off;\ntitle('VAMPIRE result (Topt)')\nsubplot(2,2,4);\nviewImage2D(abs(Topt-dataR),omega,m,'colormap', 'gray(256)'); axis off;\ntitle('Absolute difference image of R and Topt');", "meta": {"author": "C4IR", "repo": "FAIR.m", "sha": "975edebd37b833ae76696792870de5c05efcb9cb", "save_path": "github-repos/MATLAB/C4IR-FAIR.m", "path": "github-repos/MATLAB/C4IR-FAIR.m/FAIR.m-975edebd37b833ae76696792870de5c05efcb9cb/add-ons/VAMPIRE/examples/EV_2DGaussian_VAMPIRE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4908544144837849}} {"text": "%%**********************************************************************\n%% HSDNTpred: Compute (dX,dy,dZ) for NT direction.\n%%\n%% compute SVD of Xchol*Zchol via eigenvalue decompostion of\n%% Zchol * X * Zchol' = V * diag(sv2) * V'.\n%% compute W satisfying W*Z*W = X.\n%% W = G'*G, where G = diag(sqrt(sv)) * (invZchol*V)'\n%%\n%% SDPT3: version 3.1\n%% Copyright (c) 1997 by\n%% K.C. Toh, M.J. Todd, R.H. Tutuncu\n%% Last Modified: 16 Sep 2004\n%%**********************************************************************\n\nfunction [par,dX,dy,dZ,coeff,L,hRd] = ...\n HSDNTpred(blk,At,par,rp,Rd,sigmu,X,Z,Zchol,invZchol)\n\nglobal schurfun schurfun_par\n%%\n%% compute NT scaling matrix\n%%\n[par.W,par.G,par.sv,par.gamx,par.gamz,par.dd,par.ee,par.ff] = ...\n NTscaling(blk,X,Z,Zchol,invZchol);\n%%\n%% compute schur matrix\n%%\nm = par.m;\nschur = sparse(m+2,m+2);\nUU = []; EE = [];\n%%\nfor p = 1:size(blk,1)\n pblk = blk(p,:);\n if strcmp(pblk{1},'l')\n [schur,UU,EE] = schurmat_lblk(blk,At,par,schur,UU,EE,p,par.dd);\n elseif strcmp(pblk{1},'q');\n [schur,UU,EE] = schurmat_qblk(blk,At,par,schur,UU,EE,p,par.dd,par.ee);\n elseif strcmp(pblk{1},'s')\n if isempty(schurfun{p})\n schur = schurmat_sblk(blk,At,par,schur,p,par.W);\n elseif ischar(schurfun{p})\n if ~isempty(par.permZ{p})\n Wp = par.W{p}(par.permZ{p},par.permZ{p});\n else\n Wp = par.W{p};\n end\n schurtmp = feval(schurfun{p},Wp,Wp,schurfun_par(p,:));\n schur = schur + schurtmp;\n end\n end\nend\n%%\n%% compute rhs\n%%\n[rhs,EinvRc,hRd] = HSDNTrhsfun(blk,At,par,X,Z,rp,Rd,sigmu);\n%%\n%% solve linear system\n%%\npar.addschur = par.kap/par.tau;\nschur(m+1,m+1) = schur(m+1,m+1) + par.kap/par.tau;\nschur(m+2,m+2) = schur(m+2,m+2) + par.addschur;\n[xx,coeff,L] = HSDlinsysolve(par,schur,UU,EE,par.Umat,rhs);\n%%\n%% compute (dX,dZ)\n%%\n[par,dX,dy,dZ] = HSDNTdirfun(blk,At,par,Rd,EinvRc,xx);\n%%**********************************************************************\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/sdpt3/HSDSolver/HSDNTpred.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.49085137228325576}} {"text": "function prediction = BasicCifarNet(varargin)\n%BASICCIFARNET Returns a simple network for CIFAR10\n% M = models.BasicCifarNet() returns a model inspired by:\n%\n% LeCun et al., \"Gradient-Based Learning Applied to Document\n% Recognition\", Proceedings of the IEEE, 1998.\n%\n% models.BasicCifarNet(..., 'option', value, ...) accepts the following\n% options:\n%\n% `input`:: default input\n% Specifies an input (images) layer for the network. If unspecified, a\n% new one is created.\n%\n% `numClasses`:: 10\n% Number of output classes.\n%\n% `batchNorm`:: true\n% Whether to use batch normalization.\n%\n% Any other options will be passed to models.ConvBlock(), and can be used\n% to change the activation function, weight initialization, etc.\n%\n% Suggested SGD training options are also returned in the struct M.meta.\n\n % parse options. unknown arguments will be passed to ConvBlock (e.g.\n % activation).\n opts.input = Input('name', 'images', 'gpu', true) ; % default input layer\n opts.numClasses = 10 ;\n opts.batchNorm = true ; % whether to use batch normalization\n [opts, convBlockArgs] = vl_argparse(opts, varargin, 'nonrecursive') ;\n \n % get conv block generator with the given options. default activation is\n % ReLU, with pre-activation batch normalization (can be overriden).\n conv = models.ConvBlock('batchNorm', opts.batchNorm, ...\n 'preActivationBatchNorm', true, convBlockArgs{:}) ;\n \n % build network\n images = opts.input ;\n \n x = conv(images, 'size', [5, 5, 3, 32], 'pad', 2, 'weightScale', 0.01) ;\n x = vl_nnpool(x, 3, 'stride', 2, 'method', 'max', 'pad', 1) ;\n \n x = conv(x, 'size', [5, 5, 32, 32], 'pad', 2, 'weightScale', 0.05) ;\n x = vl_nnpool(x, 3, 'stride', 2, 'method', 'avg', 'pad', 1) ;\n \n x = conv(x, 'size', [5, 5, 32, 64], 'pad', 2, 'weightScale', 0.05) ;\n x = vl_nnpool(x, 3, 'stride', 2, 'method', 'avg', 'pad', 1) ;\n \n x = conv(x, 'size', [4, 4, 64, 64], 'weightScale', 0.05) ;\n \n prediction = conv(x, 'size', [1, 1, 64, opts.numClasses], 'weightScale', 0.05, ...\n 'batchNorm', false, 'activation', 'none') ;\n \n \n % default training options for this network\n defaults.batchSize = 128 ;\n defaults.weightDecay = 0.0005 ;\n if ~opts.batchNorm\n defaults.learningRate = 0.01 ;\n defaults.numEpochs = 100 ;\n else\n defaults.learningRate = 0.1 ;\n defaults.numEpochs = 40 ;\n end\n defaults.imageSize = [32, 32, 3] ;\n prediction.meta = defaults ;\n \nend\n", "meta": {"author": "ShuaiBai623", "repo": "MFT", "sha": "8762f8cdf494ce0b1a1c3d431660c5c8fd91744a", "save_path": "github-repos/MATLAB/ShuaiBai623-MFT", "path": "github-repos/MATLAB/ShuaiBai623-MFT/MFT-8762f8cdf494ce0b1a1c3d431660c5c8fd91744a/external_libs/autonn/matlab/+models/BasicCifarNet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059707450325, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4907584565824485}} {"text": "function y = previewsong(frequencies, durations, gap, Fs)\n% PREVIEWSONG plays the output of song() on the host PC.\n%\n% PREVIEWSONG converts frequency domain data in the\n% form of a frequency vector and a duration vector\n% into a single time domain vector and plays it over\n% the PC speaker using the sound command.\n%\n% frequencies - Vector of frequencies.\n% durations - Vector of times.\n% gap - Pause between notes. Default 0.01.\n% Fs - Sample rate. Default 8192.\n%\n% Example:\n% [sng.tune, sng.rhythm, sng.message, sng.stats] = song('random');\n% previewsong(sng.tune, sng.rhythm);\n\n if nargin < 4, Fs = 8192; end\n if nargin < 3, gap = 0.01; end\n if nargin < 2, durations = 1; end\n if nargin < 1, frequencies = 261.6256; end\n\n if length(durations) < length(frequencies)\n for i=length(durations)+1:length(frequencies)\n durations(i) = 0;\n end\n end\n\n if gap\n paddedFrequencies = [];\n paddedDurations = [];\n for i=1:length(frequencies)\n paddedFrequencies = [paddedFrequencies frequencies(i) 0]; %#ok\n paddedDurations = [paddedDurations durations(i) gap]; %#ok\n end\n else\n paddedFrequencies = frequencies;\n paddedDurations = durations;\n end\n\n deltaT = 1.0/Fs;\n\n startTime = 0;\n y = [];\n for i=1:length(paddedFrequencies)\n% timeIntervals = 0 : deltaT : paddedDurations(i);\n timeIntervals = startTime : deltaT : startTime+paddedDurations(i);\n startTime = timeIntervals(1)+deltaT;\n yCurrent = sin(2*pi*paddedFrequencies(i)*timeIntervals);\n y = [y yCurrent]; %#ok\n end\n\n sound(y, Fs);\n\nreturn % end of previewsong()\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/20415-xpc-target-driver-authoring-tool-tutorial/previewsong.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4907584444785335}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% PARAMETERS Returns a data structure containing the parameters of the\n% ABB IRB1600iD.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Authors:Daniel Vivancos Unica\n% Jose David Martinez Exposito\n% Maria Jose Martinez Liza\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 .\n\n\nfunction robot = parameters()\n\nrobot.name= 'ABB_IRB1600ID';\n\n%Path where everything is stored for this robot\nrobot.path = 'robots/abb/IRB1600ID';\n\nrobot.DH.theta= '[q(1) q(2)-pi/2 q(3) q(4) q(5) q(6)+pi]';\nrobot.DH.d='[0.4865 0 0 0.640 0 0.2]';\nrobot.DH.a='[0.15 0.7 0.11 0 0 0]';\nrobot.DH.alpha= '[-pi/2 0 -pi/2 pi/2 -pi/2 0]';\nrobot.J=[];\n\n\nrobot.inversekinematic_fn = 'inversekinematic_irb1600id(robot, T)';\n\n%number of degrees of freedom\nrobot.DOF = 6;\n\n%rotational: 0, translational: 1\nrobot.kind=['R' 'R' 'R' 'R' 'R' 'R'];\n\n%minimum and maximum rotation angle in rad\nrobot.maxangle =[-pi pi; %Axis 1, minimum, maximum\n deg2rad(-90) deg2rad(150); %Axis 2, minimum, maximum\n deg2rad(-238) deg2rad(79); %Axis 3\n deg2rad(-155) deg2rad(155); %Axis 4\n deg2rad(-90) deg2rad(135); %Axis 5\n deg2rad(-200) deg2rad(200)]; %Axis 6\n\n%maximum absolute speed of each joint rad/s or m/s\nrobot.velmax = [deg2rad(180); %Axis 1, rad/s\n deg2rad(180); %Axis 2, rad/s\n deg2rad(180); %Axis 3, rad/s\n deg2rad(320); %Axis 4, rad/s\n deg2rad(380); %Axis 5, rad/s\n deg2rad(460)];%Axis 6, rad/s\nrobot.accelmax=robot.velmax/0.1; % 0.1 is here an acceleration time\n \n % end effectors maximum velocity\nrobot.linear_velmax = 2.5; %m/s\n\n%base reference system\nrobot.T0 = eye(4);\n\n%INITIALIZATION OF VARIABLES REQUIRED FOR THE SIMULATION\n%position, velocity and acceleration\nrobot=init_sim_variables(robot);\n\n% GRAPHICS\nrobot.graphical.has_graphics=1;\nrobot.graphical.color = [255 102 51]./255;\n%for transparency\nrobot.graphical.draw_transparent=0;\n%draw DH systems\nrobot.graphical.draw_axes=1;\n%DH system length and Font size, standard is 1/10. Select 2/20, 3/30 for\n%bigger robots\nrobot.graphical.axes_scale=1;\n%adjust for a default view of the robot\nrobot.axis=[-2 2 -2 2 0 2.2];\n%read graphics files\nrobot = read_graphics(robot);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%DYNAMICS\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nrobot.has_dynamics=1;\n\n%consider friction in the computations\nrobot.dynamics.friction=0;\n\n%link masses (kg)\n%Tenemos que repartir 250kg (peso total robot IRB1600ID entre los 6 eslabones) \n%Utilizando como material Aluminio, los datos obtenidos del programa Inventor seran:\n\nrobot.dynamics.masses=[0 109.440 28.242 31.079 6.936 1.430 0.249];\n%COM of each link with respect to own reference system\nrobot.dynamics.r_com=[0.052 -0.012 0.343; %(rx, ry, rz) link 1\n 0.150 0.791 -0.183;%(rx, ry, rz) link 2\n 1.172\t 0.140\t 0.017; %(rx, ry, rz) link 3\n 1.296 0.063 0.561; %(rx, ry, rz) link 4\n 1.296 0.870 0.027; %(rx, ry, rz) link 5\n 0 1.296 0.966];%(rx, ry, rz) link 6\n\n%Inertia matrices of each link with respect to its D-H reference system.\n% Ixx\tIyy\tIzz\tIxy\tIyz\tIxz, for each row\nrobot.dynamics.Inertia=[0 0\t 0 \t0\t0\t0;\n 2.305 2.696\t3.802\t0\t0\t0;\n .0700\t1.765\t1.784\t0\t0\t0;\n 0.267 0.324\t0.332\t0\t0\t0;\n 0.297\t0.290\t.023\t0\t0\t0;\n .008\t.002\t.008\t0 0\t0;\n 0 0 0 0 0 0];\n%Los momentos de Inercia y los centros de gravedad quedan corregidos de los\n%obtenidos del programa Inventor para ser ajustados al sistema de\n%coordenadas designado en nuestro robot.\n\n\nrobot.motors=load_motors([5 5 5 4 4 4]);\n%Speed reductor at each joint\nrobot.motors.G=[300 300 300 300 300 300];\n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/robots/ABB/IRB1600ID/parameters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4907584384265757}} {"text": "function X = skew(x)\n\nX=[0 -x(3) x(2) ; x(3) 0 -x(1) ; -x(2) x(1) 0 ];\n\nend", "meta": {"author": "ayonga", "repo": "frost-dev", "sha": "e5dc0624d834520872bfa588dd3eda5643da71de", "save_path": "github-repos/MATLAB/ayonga-frost-dev", "path": "github-repos/MATLAB/ayonga-frost-dev/frost-dev-e5dc0624d834520872bfa588dd3eda5643da71de/example/atlas/skew.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.6187804267137442, "lm_q1q2_score": 0.49075843285095705}} {"text": "function [node,elem,bdFlag,HB] = uniformbisect3(node,elem,bdFlag,HB)\n%% UNIFORMBISECT3 uniformly bisect a 3-D triangulation. \n%\n% [node,elem] = uniformbisect3(node,elem) divides each tetrahedron into 8 small\n% tetrahedrons using longest vertex bisection.\n%\n% [node,elem,bdFlag,HB] = uniformbisect3(node,elem,bdFlag,HB) update HB and\n% boundary conditions.\n%\n% Example\n%\n% node = [-1,-1,-1; 1,-1,-1; 1,1,-1; -1,1,-1; -1,-1,1; 1,-1,1; 1,1,1; -1,1,1]; \n% elem = [1,2,3,7; 1,6,2,7; 1,5,6,7; 1,8,5,7; 1,4,8,7; 1,3,4,7];\n% elem = label3(node,elem);\n% figure(1); subplot(1,3,1); \n% set(gcf,'Units','normal'); set(gcf,'Position',[0.25,0.25,0.5,0.3]);\n% showmesh3(node,elem,[],'FaceAlpha',0.35); view([210 8]);\n% [node,elem] = uniformbisect3(node,elem);\n% figure(1); subplot(1,3,2);\n% showmesh3(node,elem,[],'FaceAlpha',0.35); view([210 8]);\n% bdFlag = setboundary3(node,elem,'Dirichlet');\n% [node,elem,bdFlag] = uniformbisect3(node,elem,bdFlag);\n% figure(1); subplot(1,3,3);\n% showmesh3(node,elem,[],'FaceAlpha',0.35); view([210 8]);\n%\n% See also uniformbisect, uniformrefine, bisect, bisect3\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nif ~exist('bdFlag','var')\n bdFlag =[]; \nend\nif ~exist('HB','var')\n HB = []; \nend\n[node,elem,bdFlag,HB] = bisect3(node,elem,'all',bdFlag,HB);\n[node,elem,bdFlag,HB] = bisect3(node,elem,'all',bdFlag,HB);\n[node,elem,bdFlag,HB] = bisect3(node,elem,'all',bdFlag,HB);", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/mesh/uniformbisect3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.49074470833149375}} {"text": "function [nm] = A2nm(A)\n% Convert length from angstroms to nanometers. \n% Chad A. Greene 2012\nnm = A*0.1;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35258-unit-converters/unit_converters/A2nm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.4907447041694754}} {"text": "classdef ZDT5 < PROBLEM\n% \n% Benchmark MOP proposed by Zitzler, Deb, and Thiele\n\n%------------------------------- Reference --------------------------------\n% E. Zitzler, K. Deb, and L. Thiele, Comparison of multiobjective\n% evolutionary algorithms: Empirical results, Evolutionary computation,\n% 2000, 8(2): 173-195.\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 = 2;\n if isempty(obj.D); obj.D = 80; end\n obj.D = ceil(max(obj.D-30,1)/5)*5 + 30;\n obj.encoding = 4 + zeros(1,obj.D);\n end\n %% Calculate objective values\n function PopObj = CalObj(obj,PopDec)\n u = zeros(size(PopDec,1),1+(size(PopDec,2)-30)/5);\n u(:,1) = sum(PopDec(:,1:30),2);\n for i = 2 : size(u,2)\n u(:,i) = sum(PopDec(:,(i-2)*5+31:(i-2)*5+35),2);\n end\n v = zeros(size(u));\n v(u<5) = 2 + u(u<5);\n v(u==5) = 1;\n PopObj(:,1) = 1 + u(:,1);\n g = sum(v(:,2:end),2);\n h = 1./PopObj(:,1);\n PopObj(:,2) = g.*h;\n end\n %% Generate points on the Pareto front\n function R = GetOptimum(obj,N)\n R(:,1) = 1 : 31;\n R(:,2) = (obj.D-30)./5./R(:,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/ZDT/ZDT5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.49074469541436355}} {"text": "%GETNEXTCLUSTERS Takes in a cluster graph and returns the indices\n% of the nodes between which the next message should be passed.\n%\n% [i j] = GetNextClusters(P,Messages,oldMessages,m,useSmart)\n%\n% INPUT\n% P - our cluster graph\n% Messages - the current values of all messages in P\n% oldMessages - the previous values of all messages in P. Thus, \n% oldMessages(i,j) contains the value that Messages(i,j) contained \n% immediately before it was updated to its current value\n% m - the index of the message we are passing (ie, m=0 indicates we have\n% passed 0 messages prior to this one. m=5 means we've passed 5 messages\n% useSmart - indicates whether we should use the Naive or Smart message\n% passing order\n%\n%\n% Output [i j]\n% i = the origin of the m+1th message\n% j = the destination of the m+1th message\n%\n% Copyright (C) Daphne Koller, Stanford University, 2012\n\nfunction [i j] = GetNextClusters(P,Messages,oldMessages,m,useSmart)\n\nif(~exist('useSmart','var')||~useSmart)\n [i j] = NaiveGetNextClusters(P,m);\nelse\n [i j] = SmartGetNextClusters(P,Messages,oldMessages,m);\nend\n", "meta": {"author": "anhncs", "repo": "Probabilistic-Graphical-Models", "sha": "7fd4ef255db59ecbfe1a134cadbc4be5ca839894", "save_path": "github-repos/MATLAB/anhncs-Probabilistic-Graphical-Models", "path": "github-repos/MATLAB/anhncs-Probabilistic-Graphical-Models/Probabilistic-Graphical-Models-7fd4ef255db59ecbfe1a134cadbc4be5ca839894/5.Approximate Inference/GetNextClusters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679928, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.49074468665925153}} {"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 [A, B, C, D, tau, kappa, epsilon] = theta2abcd(theta, idx, R, L )\n% Transform DCM parameters from vectorized to structured format\n% \n% This is a protected method of the tapas_Huge class. It cannot be called\n% from outside the class.\n% \n\n% Author: Yu Yao (yao@biomed.ee.ethz.ch)\n% Copyright (C) 2019 Translational Neuromodeling Unit\n% Institute for Biomedical Engineering,\n% University of Zurich and ETH Zurich.\n% \n% This file is part of TAPAS, which is released under the terms of the GNU\n% General Public Licence (GPL), version 3. For further details, see\n% .\n% \n% This software is provided \"as is\", without warranty of any kind, express\n% or implied, including, but not limited to the warranties of\n% merchantability, fitness for a particular purpose and non-infringement.\n% \n% This software is intended for research only. Do not use for clinical\n% purpose. Please note that this toolbox is under active development.\n% Considerable changes may occur in future releases. For support please\n% refer to:\n% https://github.com/translationalneuromodeling/tapas/issues\n% \n\n\n\ntmp = zeros(idx.P_f, 1);\ntmp([idx.clustering; idx.homogenous]) = theta;\n% hemodynamic parameters\niEd = numel(tmp);\nepsilon = tmp(iEd); % ratio of intra- and extravascular signal\niEd = iEd - 1;\nkappa = tmp(iEd-R+1:iEd); % decay of vasodilatory signal\niEd = iEd - R;\ntau = tmp(iEd-R+1:iEd); % transit time\niEd = iEd - R;\n\n% connectivity parameters\niSt = 0;\nA = reshape(tmp(iSt+1:iSt+R^2), R, R);\niSt = iSt + R^2;\nB = reshape(tmp(iSt+1:iSt+R^2*L), R, R, L);\niSt = iSt + R^2*L;\nC = reshape(tmp(iSt+1:iSt+R*L), R, L);\niSt = iSt + R*L;\n% nonlinear connections\nif iEd - iSt == R^3\n D = reshape(tmp(iSt+1:iEd), R, R, R);\nelse\n D = zeros(R, R, 0);\nend\n\nend\n\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/huge/@tapas_Huge/theta2abcd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.490735791705475}} {"text": "function M_hat = run_mc(params)\n M = params.M;\n Idx = params.Idx;\n Ms = sparse(M);\n [~,~,VALS] = find(Ms);\n Known = logical(Idx);\n [U,S,V,hist] = ScGrassMC(Known, VALS, 2,...\n 'tol', 1.e-6,...\n 'maxit',100,...\n 'grad_type','scaled',...\n 'beta_type','P-R',...\n 'sigma_type','approx',... %'tol_reschg', tol_reschg,...\n 'verbose', 1);\n M_hat = (U*S*V');\nend\n", "meta": {"author": "andrewssobral", "repo": "mctc4bmi", "sha": "fbcbcd25654b818646387c3d6a64304fb60e12dd", "save_path": "github-repos/MATLAB/andrewssobral-mctc4bmi", "path": "github-repos/MATLAB/andrewssobral-mctc4bmi/mctc4bmi-fbcbcd25654b818646387c3d6a64304fb60e12dd/algs_mc/ScGrassMC/run_mc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49069869411081857}} {"text": "\n\nclear all; close all;\nN=0:4\nX=fftshift(N)\nY=fftshift(fftshift(N))\nZ=ifftshift(fftshift(N))\n\n", "meta": {"author": "HuangCongQing", "repo": "Algorithms_MathModels", "sha": "e15b0e9053b11f08b5ce1e3492c4acb444409c8b", "save_path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels", "path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels/Algorithms_MathModels-e15b0e9053b11f08b5ce1e3492c4acb444409c8b/\u300aMATLAB\u56fe\u50cf\u5904\u7406\u300b\u6e90\u6587\u4ef6/\u672c\u4e66\u6e90\u6587\u4ef6/chap8/chap8_8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49069868877525163}} {"text": "function camAAr2c = projICP(camAAr2c)\n\n global VMap;\n global NMap;\n global XYZcamBilateral;\n global NcamBilateral;\n global K;\n\n global NMapCam;\n global VMapCam;\n global Vku;\n\n for iterID = 1:10\n\n %% data association\n\n % transform the point cloud \n\n VMapCam = AngleAxisRotatePoint(camAAr2c, VMap) + repmat(camAAr2c(4:6)',1,size(VMap,2));\n NMapCam = AngleAxisRotatePoint(camAAr2c, NMap);\n\n % projective association\n\n px = round(K(1,1)*(VMapCam(1,:)./VMapCam(3,:)) + K(1,3));\n py = round(K(2,2)*(VMapCam(2,:)./VMapCam(3,:)) + K(2,3));\n \n isValid = (1<=px & px <= 640 & 1<=py & py<= 480);\n VMapCam = VMapCam(:,isValid);\n NMapCam = NMapCam(:,isValid);\n px = px(isValid);\n py = py(isValid);\n \n ind = sub2ind([480 640],py,px);\n \n \n %{\n cla(subplot(6,3,12))\n validMap = zeros(480,640);\n validMap(ind) = 1;\n imagesc(validMap);\n axis equal;\n axis tight;\n title(sprintf('Iteration %d: init valid Map',iterID))\n %}\n \n\n isValid = XYZcamBilateral(640*480*2+ind)~=0;\n VMapCam = VMapCam(:,isValid);\n NMapCam = NMapCam(:,isValid);\n ind = ind(isValid);\n\n % outlier rejection\n\n\n diffD = (VMapCam(1,:) - XYZcamBilateral(ind)).^2 + (VMapCam(2,:) - XYZcamBilateral(640*480+ind)).^2 + (VMapCam(3,:) - XYZcamBilateral(640*480*2+ind)).^2 ;\n dotProdN = sum([NcamBilateral(ind); NcamBilateral(640*480+ind); NcamBilateral(640*480*2+ind)] .* NMapCam,1);\n\n \n\n subplot(6,3,17)\n validMap = zeros(480,640);\n validMap(ind) = diffD;\n imagesc(validMap);\n axis equal;\n axis tight;\n title(sprintf('Iteration %d: diffD',iterID))\n \n \n\n subplot(6,3,18)\n validMap = zeros(480,640);\n validMap(ind) = dotProdN;\n imagesc(validMap);\n axis equal;\n axis tight;\n title(sprintf('Iteration %d: dotProdN',iterID))\n\n \n \n \n %isValid = (diffD<0.1^2) & (dotProdN > cos(pi/3));\n isValid = (diffD<1^2);\n \n VMapCam = VMapCam(:,isValid);\n NMapCam = NMapCam(:,isValid);\n ind = ind(isValid);\n Vku = [XYZcamBilateral(ind); XYZcamBilateral(640*480+ind); XYZcamBilateral(640*480*2+ind)];\n\n \n\n subplot(6,3,15)\n validMap = zeros(480,640);\n validMap(ind) = 1;\n imagesc(validMap);\n axis equal;\n axis tight;\n title(sprintf('Iteration %d: valid Map',iterID))\n\n \n \n %% optimization\n % objective function\n E = sum(( Vku - VMapCam ) .* NMapCam,1);\n \n \n\n subplot(6,3,16)\n validMap = zeros(480,640);\n validMap(ind) = E;\n imagesc(validMap);\n axis equal;\n axis tight;\n title(sprintf('Iteration %d: Distance Map',iterID))\n\n \n \n fprintf('initial error: #inliers = %.2f(%d/%d), sum = %f, mean = %f, median = %f\\n', sum(isValid)/length(isValid), sum(isValid), length(isValid), sum(E.^2), mean(E.^2), median(E.^2));\n\n\n %options = optimset('Display','iter', 'Algorithm','levenberg-marquardt');\n options = optimset('display','off','Algorithm','levenberg-marquardt');\n [AA_gk, resnorm, residual, exitflag, output] = lsqnonlin(@residualFunction, [0 0 0 0 0 0],[],[],options);\n\n\n camAAr2c = cameraRt2AngleAxis(concatenateCameraRt(transformCameraRt(cameraAngleAxis2Rt(AA_gk)), cameraAngleAxis2Rt(camAAr2c)));\n end\n\nend\n\n\nfunction residuals = residualFunction(Tgk)\n global NMapCam;\n global VMapCam;\n global Vku;\n \n VkuTran = AngleAxisRotatePoint(Tgk, Vku) + repmat(Tgk(4:6)',1,size(Vku,2)); \n \n residuals = ( VkuTran - VMapCam ) .* NMapCam;\nend\n\n\n%{\n% for visualization\n\nfigure\nimage2show = zeros(480,640);\nimage2show(ind) = distance(1,:);\nimagesc(image2show); axis equal; axis tight;\ntitle('Vm(1) - Vd(1)')\n\nfigure\nimage2show = zeros(480,640);\nimage2show(ind) = distance(2,:);\nimagesc(image2show); axis equal; axis tight;\ntitle('Vm(2) - Vd(2)')\n\nfigure\nimage2show = zeros(480,640);\nimage2show(ind) = distance(3,:);\nimagesc(image2show); axis equal; axis tight;\ntitle('Vm(3) - Vd(3)')\n\nfigure\nimage2show = zeros(480,640);\nimage2show(ind) = sum(distance.^2,1);\nimagesc(image2show); axis equal; axis tight;\ntitle('(Vm - Vd)^2')\n\n\nfigure\nimage2show = zeros(480,640);\nimage2show(ind) = sum(distance .* NMapCam,1).^2;\nimagesc(image2show); axis equal; axis tight;\ntitle('E')\n\n\n\n%}\n\n\n% coarse to fine\n\n\n", "meta": {"author": "jianxiongxiao", "repo": "ProfXkit", "sha": "7376c50abf5ead846247774a36be026e6f24953c", "save_path": "github-repos/MATLAB/jianxiongxiao-ProfXkit", "path": "github-repos/MATLAB/jianxiongxiao-ProfXkit/ProfXkit-7376c50abf5ead846247774a36be026e6f24953c/SiftFu/SiftFu/projICP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49069868877525163}} {"text": "function I2 = undistortImage(I,K,kc)\n% function to undo lens distortion with perspective camera intrinsics K and kc\n% This is the model from Oulu university and described clearly in Bouguet's Matlab camera calibration toolbox\n% (http://www.vision.caltech.edu/bouguetj/calib_doc/). This is done using\n% Bouguet's toolbox (rect). You need to download it.\n\nif ~exist('rect.m','file')\n error('To undistort an image you need to download Bouguets Matlab camera calibration toolbox (http://www.vision.caltech.edu/bouguetj/calib_doc/) and add it to the path.')\nend\nif isa(I,'uint8')\n I = im2double(I); \nend\nfor i=1:size(I,3) \n I2(:,:,i) =rect((I(:,:,i)),eye(3),[K(1,1),K(2,2)],[K(1,3),K(2,3)],kc,K(1,2)/K(1,1),K); \nend\nI2 = uint8(I2*255);\n\n", "meta": {"author": "tobycollins", "repo": "IPPE", "sha": "3304dfa40c7cbd046ba0d540b8b1143283c83f4e", "save_path": "github-repos/MATLAB/tobycollins-IPPE", "path": "github-repos/MATLAB/tobycollins-IPPE/IPPE-3304dfa40c7cbd046ba0d540b8b1143283c83f4e/matlab/IPPE_utils/undistortImage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49069868877525163}} {"text": "function [Pt,a,b] = mci_lds_lat2par (P,M)\n% Convert latent params to params\n% FORMAT [Pt,a,b] = mci_lds_lat2par (P,M)\n%\n% P Parameters (latent)\n% M model structure\n%\n% Pt Parameters (transformed)\n% a diagonal values\n% b off-diagonal values\n%__________________________________________________________________________\n% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny\n% $Id: mci_lds_lat2par.m 6548 2015-09-11 12:39:47Z will $\n\n% Diagonal entries\ns=exp(P(1:M.d));\na=s*M.a_typical;\n\n% Off-diagonal entries\nb=P(M.d+1:end);\n \nPt=[a(:);b(:)];", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/mci/models/lds/mci_lds_lat2par.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936438, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49069868343968454}} {"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": "function rot = power(rot,n)\n% r.^n\n%\n% Syntax\n% rot = rot^(-1) % inverse rotation\n% rot = rot.^2\n% rot = rot.^[0,1,2,3]\n%\n%\n% Input\n% rot - @rotation\n%\n% Output\n% rot - @rotation\n%\n% See also\n% rotation/log \n\nrot = power@quaternion(rot,n);\n\n% change inversion\nrot.i = (1-(1-2*rot.i).^n)./2;\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/geometry/@rotation/power.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49069867810411716}} {"text": "function i4vec_permute_test ( )\n\n%*****************************************************************************80\n%\n%% I4VEC_PERMUTE_TEST tests I4VEC_PERMUTE.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 May 2015\n%\n% Author:\n%\n% John Burkardt\n%\n n = 12;\n b = 0;\n c = n;\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4VEC_PERMUTE_TEST\\n' );\n fprintf ( 1, ' I4VEC_PERMUTE reorders an integer vector\\n' );\n fprintf ( 1, ' according to a given permutation.\\n' );\n fprintf ( 1, ' Using initial random number seed = %d\\n', seed );\n\n [ a, seed ] = i4vec_uniform_ab ( n, b, c, seed );\n\n i4vec_print ( n, a, ' A, before rearrangement:' );\n\n p = perm1_uniform ( n, seed );\n\n i4vec_print ( n, p, ' Permutation vector P:' );\n\n a = i4vec_permute ( n, a, p );\n\n i4vec_print ( n, a, ' A, after rearrangement:' );\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_permute_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.4906986744138088}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% function F= GetMeyerBasedFilter(level,dBand,dataClass)\n% Generates windowing filters\n%Input: \n% level : In multilevel decomposition number of level\n% dataClass : 'single' or 'double'\n%Output: \n% F : Windowing filter at different level\n% : \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n function F= GetMeyerBasedFilter(level,dBand,filterSize,dataClass)\n\nF=cell(3,level); \n\nfor l=1:level \n\ncubeSize=filterSize(l);\n\nnumDir=dBand{level}{l}(1,1);\n \n[P,PF]=GeneratePyramidSection(cubeSize);\nSF=PF{1}+PF{2}+PF{3};\nPF{1}=SF;\nPF{2}=SF;\nPF{3}=SF;\nshift=floor(cubeSize/numDir);\nF{3,l}=cell(numDir,numDir);\n \nA=zeros(cubeSize,cubeSize,cubeSize,dataClass);\n \nfor c=1:3\n\tmRadial=ones(shift+1,cubeSize,shift+1,dataClass);\n mRadial( [1 shift+1],1:cubeSize,1: shift+1)=.5;\n mRadial(1: shift+1,1: cubeSize,[1 shift+1])=.5; \n mRadial(1,1: cubeSize,1)=1/3;\n\n l2=1;\n l1=1;\n mRadialIdx=[(l1-1)*shift+1 l1*shift+1 ;1 cubeSize ; (l2-1)*shift+1 l2*shift+1 ];\n\n F{c,l}{l2,l1}=PolarToRec(mRadialIdx,mRadial,cubeSize,P{c},PF{c} );\n A=A+F{c,l}{l2,l1};\n\n mRadial=ones(shift+1,cubeSize,shift+1,dataClass);\n mRadial( [1 shift+1],1:cubeSize,1: shift+1)=.5;\n mRadial(1: shift+1,1: cubeSize,[1 shift+1])=.5; \n\n for l2=2:numDir-1\n for l1=2:numDir-1\n mRadialIdx=[(l1-1)*shift+1 l1*shift+1 ;1 cubeSize ; (l2-1)*shift+1 l2*shift+1 ];\n \n F{c,l}{l2,l1}=PolarToRec(mRadialIdx,mRadial,cubeSize,P{c},PF{c} );\n A=A+F{c,l}{l2,l1};\n end\n end \n \n mRadial=ones(shift,cubeSize,shift+1,dataClass);\n mRadial( [1 shift],1:cubeSize,1: shift+1)=.5;\n mRadial(1: shift,1: cubeSize,[1 shift+1])=.5;\n mRadial(shift,1: cubeSize,1)=1/3;\n \n l2=1;\n l1=numDir;\n mRadialIdx=[(l1-1)*shift+1 l1*shift ;1 cubeSize ; (l2-1)*shift+1 l2*shift+1 ];\n\n F{c,l}{l2,l1}=PolarToRec(mRadialIdx,mRadial,cubeSize,P{c},PF{c} );\n A=A+F{c,l}{l2,l1};\n \n mRadial=ones(shift,cubeSize,shift+1,dataClass);\n mRadial( [1 shift],1:cubeSize,1: shift+1)=.5;\n mRadial(1: shift,1: cubeSize,[1 shift+1])=.5;\n \n for l2=2:numDir-1\n l1=numDir;\n mRadialIdx=[(l1-1)*shift+1 l1*shift ;1 cubeSize ; (l2-1)*shift+1 l2*shift+1 ];\n \n F{c,l}{l2,l1}=PolarToRec(mRadialIdx,mRadial,cubeSize,P{c},PF{c} );\n A=A+F{c,l}{l2,l1};\n end\n mRadial=ones(shift+1,cubeSize,shift+1,dataClass);\n mRadial( [1 shift+1],1:cubeSize,1: shift+1)=.5;\n mRadial(1: shift+1,1: cubeSize,[1 shift+1])=.5; \n for l2=2:numDir-1\n l1=1;\n mRadialIdx=[(l1-1)*shift+1 l1*shift+1 ;1 cubeSize ; (l2-1)*shift+1 l2*shift+1 ];\n \n F{c,l}{l2,l1}=PolarToRec(mRadialIdx,mRadial,cubeSize,P{c},PF{c} );\n A=A+F{c,l}{l2,l1};\n end \n \n mRadial=ones(shift+1,cubeSize,shift,dataClass);\n mRadial( [1 shift+1],1:cubeSize,1: shift)=.5;\n mRadial(1: shift+1,1: cubeSize,[1 shift])=.5;\n mRadial(1,1: cubeSize,shift)=1/3;\n \n l1=1;\n l2=numDir;\n mRadialIdx=[(l1-1)*shift+1 l1*shift+1 ;1 cubeSize ; (l2-1)*shift+1 l2*shift ];\n \n F{c,l}{l2,l1}=PolarToRec(mRadialIdx,mRadial,cubeSize,P{c},PF{c} );\n A=A+F{c,l}{l2,l1};\n \n mRadial=ones(shift+1,cubeSize,shift,dataClass);\n mRadial( [1 shift+1],1:cubeSize,1: shift)=.5;\n mRadial(1: shift+1,1: cubeSize,[1 shift])=.5;\n \n for l1=2:numDir-1\n l2=numDir;\n mRadialIdx=[(l1-1)*shift+1 l1*shift+1 ;1 cubeSize ; (l2-1)*shift+1 l2*shift ];\n\n F{c,l}{l2,l1}=PolarToRec(mRadialIdx,mRadial,cubeSize,P{c},PF{c} );\n A=A+F{c,l}{l2,l1};\n end\n mRadial=ones(shift+1,cubeSize,shift+1,dataClass);\n mRadial( [1 shift+1],1:cubeSize,1: shift+1)=.5;\n mRadial(1: shift+1,1: cubeSize,[1 shift+1])=.5;\n \n for l1=2:numDir-1\n l2=1;\n mRadialIdx=[(l1-1)*shift+1 l1*shift+1 ;1 cubeSize ; (l2-1)*shift+1 l2*shift+1 ];\n \n F{c,l}{l2,l1}=PolarToRec(mRadialIdx,mRadial,cubeSize,P{c},PF{c} );\n A=A+F{c,l}{l2,l1};\n end\n \n mRadial=ones(shift,cubeSize,shift,dataClass);\n mRadial( [1 shift],1:cubeSize,1: shift)=.5;\n mRadial(1: shift,1: cubeSize,[1 shift])=.5;\n mRadial( shift,1: cubeSize,shift)=1/3;\n l1=numDir;\n l2=numDir;\n mRadialIdx=[(l1-1)*shift+1 l1*shift ;1 cubeSize ; (l2-1)*shift+1 l2*shift ];\n \n F{c,l}{l2,l1}=PolarToRec(mRadialIdx,mRadial,cubeSize,P{c},PF{c} );\n A=A+F{c,l}{l2,l1};\nend\n \nfor c=1:3\n for l2=1:numDir\n for l1=1:numDir\n F{c,l}{l2,l1}=F{c,l}{l2,l1}./A;\n F{c,l}{l2,l1}=squeeze(real(fftshift(ifftn(fftshift(F{c,l}{l2,l1}))))); \n end\n end\nend\nend\nTemp=F(1,:);\nF(1,:)=F(2,:);\nF(2,:)=Temp;\n\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_TRAFO/Shearlet/3DShearTrans/GetMeyerBasedFilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.4906290775566428}} {"text": "% op_combinesubspecs.m\n% Jamie Near, McGill University 2014.\n% \n% USAGE:\n% out=op_combinesubspecs(in,mode);\n% \n% DESCRIPTION:\n% Combine the subspectra in an acquisition either by addition or\n% subtraction.\n% \n% INPUTS:\n% in = input data in matlab structure format.\n% mode = -\"diff\" adds the subspectra together (this is counter intuitive,\n% but the reason is that many \"difference editing\" sequences use phase\n% cycling of the readout ADC to achieve \"subtraction by addition\".\n% -\"summ\" performs a subtraction of the subspectra.\n%\n% OUTPUTS:\n% out = Output following combination of subspectra. \n\nfunction out=op_combinesubspecs(in,mode);\n\nif in.flags.subtracted\n error('ERROR: Subspectra have already been combined! Aborting!');\nend\nif in.flags.isFourSteps\n error('ERROR: data with four steps must first be converted using op_fourStepCombine.m! Aborting!');\nend\n\n% if ~in.flags.freqcorrected\n% disp('WARNING: Frequency correction has not yet been performed!');\n% end\n% if ~in.flags.phasecorrected\n% disp('WARNING: Phase correction has not yet been performed!');\n% end\n\n\nif mode=='diff'\n %add the spectrum along the subSpecs dimension;\n fids=sum(in.fids,in.dims.subSpecs);\n fids=fids/in.sz(in.dims.subSpecs); %divide by number of subspecs so that this is an averaging operation;\nelseif mode=='summ'\n %subtract the spectrum along the subSpecs dimension;\n fids=diff(in.fids,1,in.dims.subSpecs);\n fids=fids/in.sz(in.dims.subSpecs); %divide by nymber of subspecs so that this is an averaging operation;\nend\n\nfids=squeeze(fids);\n\n%re-calculate Specs using fft\nspecs=fftshift(ifft(fids,[],in.dims.t),in.dims.t);\n\n%change the dims variables\nif in.dims.t>in.dims.subSpecs\n dims.t=in.dims.t-1;\nelse\n dims.t=in.dims.t;\nend\nif in.dims.coils>in.dims.subSpecs\n dims.coils=in.dims.coils-1;\nelse\n dims.coils=in.dims.coils;\nend\nif in.dims.averages>in.dims.subSpecs\n dims.averages=in.dims.averages-1;\nelse\n dims.averages=in.dims.averages;\nend\ndims.subSpecs=0;\nif in.dims.extras>in.dims.subSpecs\n dims.extras=in.dims.extras-1;\nelse\n dims.extras=in.dims.extras;\nend\n\n%re-calculate the sz variable\nsz=size(fids);\n\n\n%FILLING IN DATA STRUCTURE\nout=in;\nout.fids=fids;\nout.specs=specs;\nout.sz=sz;\nout.dims=dims;\nout.subspecs=1;\nout.averages=in.averages/2;\n\n%FILLING IN THE FLAGS\nout.flags=in.flags;\nout.flags.writtentostruct=1;\nout.flags.subtracted=1;\n", "meta": {"author": "CIC-methods", "repo": "FID-A", "sha": "c24da581e376f6eed66979dcc662ec26903a2eef", "save_path": "github-repos/MATLAB/CIC-methods-FID-A", "path": "github-repos/MATLAB/CIC-methods-FID-A/FID-A-c24da581e376f6eed66979dcc662ec26903a2eef/processingTools/op_combinesubspecs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6334102705979902, "lm_q1q2_score": 0.49062907096461106}} {"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 Y = utl_picktimes(X,wnd)\n% Average the input array within the given index ranges, for each row and plane.\n% Result = utl_picktimes(Data, Windows)\n%\n% In:\n% Data : [Channels x Samples x Trials] data array\n% Windows : [Ranges x 2] array specifying the beginning and end of each range, in samples\n%\n% Out:\n% Result : averaged sub-ranges of the original data array; sized [Channels x Ranges x Trials]\n%\n% Examples:\n% % for a given 3d data array, average intervals of 20:30 samples, 50:100 samples, and 100:200 samples\n% % for each epoch and each channel\n% averages = utl_picktimes(EEG.data,[20 30;50 100;100 200])\n%\n% See also:\n% set_picktimes\n%\n% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD\n% 2010-04-20\n\n[C,S,T] = size(X);\n\nif any(wnd(:,1) > wnd(:,2))\n error('Some of the windows are malformed: %s',hlp_tostring(wnd(wnd(:,1) > wnd(:,2),:))); end\nif any(wnd(:,1)>S | wnd(:,2)<1)\n error('Some windows are entirely outside the data dimensions (%i): %s',S,hlp_tostring(wnd(wnd(1,:)>S|wnd(2,:)<1,:))); end\nif any(wnd(:)>S | wnd(:)<1)\n disp_once('WARNING: some windows passed to utl_picktimes exceed the data dimensions; windows trimmed.'); end\n\n% fix the windows, if necessary\nwnd = min(max(wnd,1),S);\nwnd(:,2) = wnd(:,2)+1;\nW = size(wnd,1);\n\n% calc offset & coverage values for first & last sample\nfo = floor(wnd(:,1));\nfc = min(fo+1,wnd(:,2)) - wnd(:,1);\nlo = ceil(wnd(:,2)-1);\nlc = wnd(:,2) - max(lo,wnd(:,1));\n% calc fully overlapped sample range, inverse length\nfor r=1:W\n full{r} = fo(r)+1:lo(r)-1; end %#ok\nilen = 1./(fc+cellfun('length',full)'+lc); \n\nY = zeros(C,W,T);\n% accumulate for every range...\nfor r=1:W \n Y(:,r,:) = (X(:,fo(r),:)*fc(r)+sum(X(:,full{r},:),2)+X(:,lo(r),:)*lc(r))*ilen(r); end\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/code/utils/utl_picktimes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.49062907096461095}} {"text": "function handles = select_plane_from_point_cloud(handles,preview_filenames,ind_preview)\n\nfig = figure;\ndcm_obj = datacursormode(fig);\n\nh = uicontrol('Position',[20 20 100 40],'String','Continue',...\n 'Callback',@continue_callback);\nh1 = uicontrol('Position',[220 20 100 40],'String','back',...\n 'Enable','off','Callback',@back_callback);\n \nfor i=1:numel(preview_filenames)\n disp(preview_filenames{i});\n done = 0;\n pc = import_point_cloud_from_file(preview_filenames{i});\n pcshow(pc);\n title(preview_filenames{i}, 'interpreter', 'none');\n \n uiwait(gcf);\n \nend\nclose(gcf);\n\n\nfunction continue_callback(objectHandle , eventData )\n if done == 0\n cur_info = getCursorInfo(dcm_obj);\n if isfield(cur_info,'Position')\n arrayPos=find(handles.active_image_numbers==ind_preview(i));\n \n [theta, alpha, minError, inliers] = ObtainPlanePoint(pc.Location,cur_info.Position);\n% [theta,alpha,minError] = tls_robust(inliers);\n handles.user_selected_planes{arrayPos}.theta = theta;\n handles.user_selected_planes{arrayPos}.alpha = alpha;\n handles.user_selected_planes{arrayPos}.e = minError;\n handles.user_selected_planes{arrayPos}.inliers = inliers;\n \n pcshow(pointCloud(inliers));\n h1.Enable = 'on';\n done = 1;\n end\n else\n h1.Enable = 'off';\n uiresume(gcbf);\n end\n \n \nend \nfunction back_callback(objectHandle , eventData )\n \n pcshow(pc);\n done = 0; \n objectHandle.Enable = 'off';\nend \n\nend", "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/src/select_plane_from_point_cloud.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.4906290697328119}} {"text": "function linplus_test25 ( )\n\n%*****************************************************************************80\n%\n%% TEST25 tests R8GB_PRINT.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 March 2009\n%\n% Author:\n%\n% John Burkardt\n%\n m = 8;\n n = 10;\n ml = 1;\n mu = 3;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST25\\n' );\n fprintf ( 1, ' For a general banded matrix,\\n' );\n fprintf ( 1, ' R8GB_PRINT prints the matrix.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Matrix rows M = %d\\n', m );\n fprintf ( 1, ' Matrix columns N = %d\\n', n );\n fprintf ( 1, ' Lower bandwidth ML = %d\\n', ml );\n fprintf ( 1, ' Upper bandwidth MU = %d\\n', mu );\n\n a = r8gb_indicator ( m, n, ml, mu );\n\n r8gb_print ( m, n, ml, mu, a, ' The R8GB matrix:' );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linplus/linplus_test25.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.4906290548839114}} {"text": "function s2de_test ( )\n\n%*****************************************************************************80\n%\n%% S2DE_TEST tests the S2DE library.\n%\n% Location:\n%\n% http://people.sc.fsu.edu/~jburkardt/m_src/stokes_2d_exact/s2de_test.m\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 February 2015\n%\n% Author:\n%\n% John Burkardt\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'S2DE_TEST\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, ' Test the S2DE library.\\n' );\n\n uvp_stokes1_test ( );\n resid_stokes1_test ( );\n gnuplot_stokes1_test ( );\n\n uvp_stokes2_test ( );\n resid_stokes2_test ( );\n gnuplot_stokes2_test ( );\n\n uvp_stokes3_test ( );\n resid_stokes3_test ( );\n gnuplot_stokes3_test ( );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'S2DE_TEST\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n timestamp ( );\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/stokes_2d_exact/s2de_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.49062905158789544}} {"text": "\n% create a sub network that takes in waveforms and produces fourier\n% coefficients\n\nfunction layer = genNetworkSTFT2LogSpec(stftLayer, useLog, logConst)\nlayer = stftLayer;\n\nlayer{end+1} = PowerNode(stftLayer{end}.dim(1));\nif useLog\n if nargin<3\n logConst = 0.00;\n end\n layer{end+1} = LogarithmNode(layer{end}.dim(1), logConst);\nend\n\nlayer = ConnectLinearGraph(layer);\nlayer = FinishLayer_obj(layer);\n\nend\n", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/prototypes/genNetworkSTFT2LogSpec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.4905732725072078}} {"text": "function blas1_z_test06 ( )\n\n%*****************************************************************************80\n%\n%% TEST06 tests ZAXPY.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 May 2006\n%\n% Author:\n%\n% John Burkardt\n%\n n = 5;\n\n x = [ ...\n 2.0 -1.0 * i, ...\n -4.0 -2.0 * i, ...\n 3.0 1.0 * i, ...\n 2.0 2.0 * i, ...\n -1.0 -1.0 * i ];\n y = [ ...\n -1.0, 0.0 * i, ...\n 0.0, -3.0 * i, ...\n 4.0, 0.0 * i, ...\n -3.0, 4.0 * i, ...\n -2.0, 0.0 * i ];\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST06\\n' );\n fprintf ( 1, ' ZAXPY adds a multiple of one complex vector to another.\\n' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X = \\n' );\n fprintf ( 1, '\\n' );\n for j = 1 : n\n fprintf ( 1, ' %6d %10f %10f\\n', j, real ( x(j) ), imag ( x(j) ) );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Y = \\n' );\n fprintf ( 1, '\\n' );\n for j = 1 : n\n fprintf ( 1, ' %6d %10f %10f\\n', j, real ( y(j) ), imag ( y(j) ) );\n end\n\n s = 0.50 - 1.00 * i;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The scalar multiplier is: ( %f %f )\\n', ...\n real ( s ), imag ( s ) );\n\n y = zaxpy ( n, s, x, 1, y, 1 );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' A * X + Y = \\n' );\n fprintf ( 1, '\\n' );\n for j = 1 : n\n fprintf ( 1, ' %6d %10f %10f\\n', j, real ( y(j) ), imag ( y(j) ) );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/blas1_z/blas1_z_test06.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.49057326746169194}} {"text": "function [volCc,dims] = mrAnatGetBrainVolume(brainMask)\n%\n% [volCc,dims] = mrAnatGetbrainVolume([brainMask=uigetfile])\n%\n% Returns the brain volume (in cubic centimeters) for the specified brain\n% mask. Optionally also returns the left-right, anterior-posterior and\n% superior-inferior dimensions (in centimeters) of the brain.\n%\n% If you don't have a brain mask, use mrAnatExtractBrain. \n%\n% 2008.08.14 RFD wrote it.\n% 2008.09.09 RFD fixed x,y bug in dims- the first two dims were flipped.\n\nif(~exist('brainMask','var')||isempty(brainMask))\n [f,p] = uigetfile({'*.nii.gz';'*.*'},'Select a brain mask NIFTI file...');\n if(isnumeric(f)), disp('User canceled.'); return; end\n brainMask = fullfile(p,f); \nend\n\nif(ischar(brainMask))\n % It's a nifti file\n brainMask = niftiRead(brainMask);\nend\n\nmm = brainMask.pixdim(1:3);\nccPerPixel = prod(mm)/1000;\nvolCc = numel(find(brainMask.data)) * ccPerPixel;\n\nif(nargout>1)\n tmp = sum(brainMask.data,3);\n y = find(sum(tmp,1)); \n y = [y(1) y(end)];\n x = find(sum(tmp,2)); \n x = [x(1) x(end)];\n tmp = squeeze(sum(brainMask.data,1));\n z = find(sum(tmp,1)); \n z = [z(1) z(end)];\n dims = [diff(x)*mm(1) diff(y)*mm(2) diff(z)*mm(3)];\n dims = dims./10;\nend\n\nreturn;\n\n\nbd = '/biac3/wandell4/data/reading_longitude/dti_y1';\nd = dir(fullfile(bd,'*04*'));\nn = 0;\nfor(ii=1:numel(d))\n f = fullfile(bd,d(ii).name,'t1','t1_mask.nii.gz');\n if(exist(f,'file'))\n n = n+1;\n [volCc(n),dims(n,:)] = mrAnatGetBrainVolume(f);\n sc{n} = d(ii).name;\n end\nend\n\n[behData,colNames] = dtiGetBehavioralData(sc);\n\nsexInd = strmatch('Sex (1=male)',colNames);\nboys = behData(:,sexInd)==1;\nfprintf('boys = %0.1fcc (%0.2f), girls = %0.1fcc (%0.2f)\\n', mean(volCc(boys)), std(volCc(boys)), mean(volCc(~boys)), std(volCc(~boys)));\n\nbrInd = strmatch('Basic reading (W-J)',colNames);\nnecrosisControls = ~boys & behData(:,brInd)>=90;\nmn = mean(volCc(necrosisControls));\nsd = std(volCc(necrosisControls));\n\n[sVol, sDims] = mrAnatGetBrainVolume('/biac1/wandell/data/radiationNecrosis/dti/al060406/t1/t1_mask.nii.gz');\n% Compute the percentile:\n[hcnt,hcent] = hist(volCc(necrosisControls),50);\npctile = sum(hcnt(find(sVol>hcent)))/sum(hcnt)*100;\nfprintf('Controls: mean = %0.0fcc (%0.1f); S = %0.0fcc (%0.0f %%tile)\\n', mn, sd, sVol, pctile);\n\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAnatomy/VolumeUtilities/mrAnatGetBrainVolume.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.4905732550793743}} {"text": "% normaliseiris - performs normalisation of the iris region by\n% unwraping the circular region into a rectangular block of\n% constant dimensions.\n%\n% Usage: \n% [polar_array, polar_noise] = normaliseiris(image, x_iris, y_iris, r_iris,...\n% x_pupil, y_pupil, r_pupil,eyeimage_filename, radpixels, angulardiv)\n%\n% Arguments:\n% image - the input eye image to extract iris data from\n% x_iris - the x coordinate of the circle defining the iris\n% boundary\n% y_iris - the y coordinate of the circle defining the iris\n% boundary\n% r_iris - the radius of the circle defining the iris\n% boundary\n% x_pupil - the x coordinate of the circle defining the pupil\n% boundary\n% y_pupil - the y coordinate of the circle defining the pupil\n% boundary\n% r_pupil - the radius of the circle defining the pupil\n% boundary\n% eyeimage_filename - original filename of the input eye image\n% radpixels - radial resolution, defines vertical dimension of\n% normalised representation\n% angulardiv - angular resolution, defines horizontal dimension\n% of normalised representation\n%\n% Output:\n% polar_array\n% polar_noise\n%\n% Author: \n% Libor Masek\n% masekl01@csse.uwa.edu.au\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% November 2003\n\nfunction [polar_array, polar_noise] = normaliseiris(image, x_iris, y_iris, r_iris,...\nx_pupil, y_pupil, r_pupil,eyeimage_filename, radpixels, angulardiv, method)\n\nglobal DIAGPATH\n\nradiuspixels = radpixels + 2;\nangledivisions = angulardiv-1;\n\nr = 0:(radiuspixels-1);\n\ntheta = 0:2*pi/angledivisions:2*pi;\n\nx_iris = double(x_iris);\ny_iris = double(y_iris);\nr_iris = double(r_iris);\n\nx_pupil = double(x_pupil);\ny_pupil = double(y_pupil);\nr_pupil = double(r_pupil);\n\n% calculate displacement of pupil center from the iris center\nox = x_pupil - x_iris;\noy = y_pupil - y_iris;\n\nif ox <= 0\n sgn = -1;\nelseif ox > 0\n sgn = 1;\nend\n\nif ox==0 && oy > 0\n \n sgn = 1;\n \nend\n\nr = double(r);\ntheta = double(theta);\n\na = ones(1,angledivisions+1)* (ox^2 + oy^2);\n\n% need to do something for ox = 0\nif ox == 0\n phi = pi/2;\nelse\n phi = atan(oy/ox);\nend\n\nb = sgn.*cos(pi - phi - theta);\n\n% calculate radius around the iris as a function of the angle\nr = (sqrt(a).*b) + ( sqrt( a.*(b.^2) - (a - (r_iris^2))));\n\nr = r - r_pupil;\n\nrmat = ones(1,radiuspixels)'*r;\n\nrmat = rmat.* (ones(angledivisions+1,1)*[0:1/(radiuspixels-1):1])';\nrmat = rmat + r_pupil;\n\n\n% exclude values at the boundary of the pupil iris border, and the iris scelra border\n% as these may not correspond to areas in the iris region and will introduce noise.\n%\n% ie don't take the outside rings as iris data.\nrmat = rmat(2:(radiuspixels-1), :);\n\n% calculate cartesian location of each data point around the circular iris\n% region\nxcosmat = ones(radiuspixels-2,1)*cos(theta);\nxsinmat = ones(radiuspixels-2,1)*sin(theta);\n\nxo = rmat.*xcosmat; \nyo = rmat.*xsinmat;\n\nxo = x_pupil+xo;\nyo = y_pupil-yo;\n\n% extract intensity values into the normalised polar representation through\n% interpolation\n[x,y] = meshgrid(1:size(image,2),1:size(image,1)); \npolar_array = interp2(x,y,image,xo,yo);\n\n% create noise array with location of NaNs in polar_array\npolar_noise = zeros(size(polar_array));\ncoords = find(isnan(polar_array));\npolar_noise(coords) = 1;\n\npolar_array = double(polar_array)./255;\n\n\n% start diagnostics, writing out eye image with rings overlayed\n\n% get rid of outling points in order to write out the circular pattern\ncoords = find(xo > size(image,2));\nxo(coords) = size(image,2);\ncoords = find(xo < 1);\nxo(coords) = 1;\n\ncoords = find(yo > size(image,1));\nyo(coords) = size(image,1);\ncoords = find(yo<1);\nyo(coords) = 1;\n\nxo = round(xo);\nyo = round(yo);\n\nxo = int32(xo);\nyo = int32(yo);\n\nind1 = sub2ind(size(image),double(yo),double(xo));\n\nimage = uint8(image);\n\nimage(ind1) = 255;\n%get pixel coords for circle around iris\n[x,y] = circlecoords([x_iris,y_iris],r_iris,size(image));\nind2 = sub2ind(size(image),double(y),double(x));\n%get pixel coords for circle around pupil\n[xp,yp] = circlecoords([x_pupil,y_pupil],r_pupil,size(image));\nind1 = sub2ind(size(image),double(yp),double(xp));\n\nimage(ind2) = 255;\nimage(ind1) = 255;\n\n\n% % write out rings overlaying original iris image\n% w = cd;\n% % cd(DIAGPATH);\n% \n% imwrite(image,[eyeimage_filename,'_method',num2str(method),'-normal.jpg'],'jpg');\n% \n% cd(w);\n% \n% % end diagnostics\n\n%replace NaNs before performing feature encoding\ncoords = find(isnan(polar_array));\npolar_array2 = polar_array;\npolar_array2(coords) = 0.5;\navg = sum(sum(polar_array2)) / (size(polar_array,1)*size(polar_array,2));\npolar_array(coords) = avg;", "meta": {"author": "Qingbao", "repo": "iris", "sha": "bb6b58b58fc0b517f53f6a6084066af127c13c47", "save_path": "github-repos/MATLAB/Qingbao-iris", "path": "github-repos/MATLAB/Qingbao-iris/iris-bb6b58b58fc0b517f53f6a6084066af127c13c47/Daugman/normaliseiris.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587159, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4905588404234398}} {"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": "function test_bug3417\n\n% WALLTIME 00:20:00\n% MEM 3gb\n% DEPENDENCY\n\n% ... works fine on his computer, which has a 2012 version of FieldTrip and Matlab 2013a.\n% But when we try to run either a later version of Fieldtrip (e.g. 2015) or a later version\n% of Matlab (e.g. 2017b), we get the following bug:\n%\n% Error using findcluster (line 50)\n% invalid dimension of spatdimneighbstructmat\n\n% figure 4\n\n%% SL - one sample t\n\nload(dccnpath('/home/common/matlab/fieldtrip/data/test/bug3417.mat'))\n\nfreqs=14; % or 21\ntimes=81;\n\ncond1=permute(SL_Fig4,[3,1,2]);\ncond1=cond1(:,1:freqs,:);\n\ncond2=cond1;\ncond2(:,:,:)=0;\n\ndata1.globspctrm=cond1;\ndata2.globspctrm=cond2;\n\n[subj,~,freq] = size(data1.globspctrm);\nnsubj = subj;\n\ncfg.statistic = 'depsamplesT';\ncfg.design = zeros(2,2*nsubj);\ncfg.design(1,:)=[ones(1,nsubj) ones(1,nsubj)+1];\ncfg.design(2,:)=[1:nsubj 1:nsubj];\ncfg.ivar = 1;\ncfg.uvar = 2;\n\ndata1.label = {'Positive'};\ndata2.label = {'Negative'};\ndata1.dimord = 'rpt_freq_time'; % does clustering in 2 dimensions (freq, time)\ndata2.dimord = 'rpt_freq_time';\ndata1.freq = [1:freqs];\ndata2.freq = [1:freqs];\ndata1.time =[1:times];\ndata2.time= [1:times];\n\n% fix the invalid data structure, see ft_datatype_freq\ndata1.dimord = 'rpt_chan_freq_time';\ndata2.dimord = 'rpt_chan_freq_time';\ndata1.globspctrm = reshape(data1.globspctrm, [nsubj 1 freqs times]);\ndata2.globspctrm = reshape(data2.globspctrm, [nsubj 1 freqs times]);\ndata1.label = {'TheSame'};\ndata2.label = {'TheSame'};\n\ncfg.parameter = 'globspctrm'; % 'avg', 'cohspctrm'\ncfg.method = 'montecarlo'; % 'montecarlo', 'analytic' , 'stats', 'crossvalidate'\n\ncfg.neighbours = [];\ncfg.channel = 'all';\ncfg.correctm = 'cluster'; % 'no', 'max', 'cluster', 'bonferroni', 'holm', 'hochberg', 'fdr' (default = 'no')\n\ncfg.clusterstatistc = 'wcm'; % 'wcm', 'maxsum', 'maxsize'\ncfg.clusterthreshold = 'parametric'; % 'parametric', 'nonparametric_individual', 'nonparametric_common'\ncfg.numrandomization = 1000;\ncfg.clusteralpha = 0.05;\ncfg.tail = 0;\n\nstats = ft_freqstatistics(cfg,data1,data2);\n\nfigure;\n\nsubplot(2,3,1)\ntres=squeeze(mean(cond1,1));\nimagesc(tres)\ncolorbar\ntitle('Adult SL: Mean')\nylabel('Frequencies')\nxlabel('Time')\n\nsubplot(2,3,4)\ntres=squeeze(stats.stat)\nimagesc(tres)\ncolorbar\ntitle('SL: t matrix')\nylabel('Frequencies')\nxlabel('Time')\n\nsubplot(2,3,5)\nPositive_cluster=squeeze(stats.posclusterslabelmat);\nPositive_cluster(Positive_cluster > 1) = 0; % keep just cluster 1\nimagesc(Positive_cluster)\ntitle(['Positive cluster: p=' num2str(stats.posclusters(1, 1).prob)])\ncolorbar\nylabel('Frequencies')\nxlabel('Time')\n\nsubplot(2,3,6)\nNegative_cluster=squeeze(stats.negclusterslabelmat);\nNegative_cluster(Negative_cluster > 1) = 0; % keep just cluster 1\nimagesc(Negative_cluster)\ntitle(['Negative cluster: p=' num2str(stats.negclusters(1, 1).prob)])\ncolorbar\nylabel('Frequencies')\nxlabel('Time')\n\n\n%% JA - one sample t\n\nload(dccnpath('/home/common/matlab/fieldtrip/data/test/bug3417.mat'))\n\nfreqs=14; % or 21\ntimes=81;\n\ncond1=permute(JA_Fig4,[3,1,2]);\ncond1=cond1(:,1:freqs,:);\n\ndata1.globspctrm=cond1;\ndata2.globspctrm=cond2;\n\n\n[subj,~,freq] = size(data1.globspctrm);\nnsubj = subj;\n\ncfg.statistic = 'depsamplesT';\ncfg.design = zeros(2,2*nsubj);\ncfg.design(1,:)=[ones(1,nsubj) ones(1,nsubj)+1];\ncfg.design(2,:)=[1:nsubj 1:nsubj];\ncfg.ivar = 1;\ncfg.uvar = 2;\n\ndata1.label = {'Positive'};\ndata2.label = {'Negative'};\ndata1.dimord = 'rpt_freq_time'; % does clustering in 2 dimensions (freq, time)\ndata2.dimord = 'rpt_freq_time';\ndata1.freq = [1:freqs];\ndata2.freq = [1:freqs];\ndata1.time =[1:times];\ndata2.time= [1:times];\n\n% fix the invalid data structure, see ft_datatype_freq\ndata1.dimord = 'rpt_chan_freq_time';\ndata2.dimord = 'rpt_chan_freq_time';\ndata1.globspctrm = reshape(data1.globspctrm, [nsubj 1 freqs times]);\ndata2.globspctrm = reshape(data2.globspctrm, [nsubj 1 freqs times]);\ndata1.label = {'TheSame'};\ndata2.label = {'TheSame'};\n\ncfg.parameter = 'globspctrm'; % 'avg', 'cohspctrm'\ncfg.method = 'montecarlo'; % 'montecarlo', 'analytic' , 'stats', 'crossvalidate'\n\ncfg.neighbours = [];\ncfg.channel = 'all';\ncfg.correctm = 'cluster'; % 'no', 'max', 'cluster', 'bonferroni', 'holm', 'hochberg', 'fdr' (default = 'no')\n\ncfg.clusterstatistc = 'wcm'; % 'wcm', 'maxsum', 'maxsize'\ncfg.clusterthreshold = 'parametric'; % 'parametric', 'nonparametric_individual', 'nonparametric_common'\ncfg.numrandomization = 1000;\ncfg.clusteralpha = 0.05;\ncfg.tail = 0;\n\nstats = ft_freqstatistics(cfg,data1,data2)\n\nfigure;\n\nsubplot(2,3,1)\ntres=squeeze(mean(cond1,1));\nimagesc(tres)\ncolorbar\ntitle('Adult SL: Mean')\nylabel('Frequencies')\nxlabel('Time')\n\nsubplot(2,3,4)\ntres=squeeze(stats.stat)\nimagesc(tres)\ncolorbar\ntitle('SL: t matrix')\nylabel('Frequencies')\nxlabel('Time')\n\nsubplot(2,3,5)\nPositive_cluster=squeeze(stats.posclusterslabelmat);\nPositive_cluster(Positive_cluster > 1) = 0; % keep just cluster 1\nimagesc(Positive_cluster)\ntitle(['Positive cluster: p=' num2str(stats.posclusters(1, 1).prob)])\ncolorbar\nylabel('Frequencies')\nxlabel('Time')\n\nsubplot(2,3,6)\nNegative_cluster=squeeze(stats.negclusterslabelmat);\nNegative_cluster(Negative_cluster > 1) = 0; % keep just cluster 1\nimagesc(Negative_cluster)\ntitle(['Negative cluster: p=' num2str(stats.negclusters(1, 1).prob)])\ncolorbar\nylabel('Frequencies')\nxlabel('Time')\n\n%% SJ vs. AJ\n\nload(dccnpath('/home/common/matlab/fieldtrip/data/test/bug3417.mat'))\n\nfreqs=14; % or 21\ntimes=81;\n\ncond1=permute(SL_Fig4,[3,1,2]);\ncond2=permute(JA_Fig4,[3,1,2]);\n\ncond1=cond1(:,1:freqs,:);\ncond2=cond2(:,1:freqs,:);\n\ndata1.globspctrm=cond1;\ndata2.globspctrm=cond2;\n\n\n[subj,~,freq] = size(data1.globspctrm);\nnsubj = subj;\n\ncfg.statistic = 'depsamplesT';\ncfg.design = zeros(2,2*nsubj);\ncfg.design(1,:)=[ones(1,nsubj) ones(1,nsubj)+1];\ncfg.design(2,:)=[1:nsubj 1:nsubj];\ncfg.ivar = 1;\ncfg.uvar = 2;\n\ndata1.label = {'Positive'};\ndata2.label = {'Negative'};\ndata1.dimord = 'rpt_freq_time'; % does clustering in 2 dimensions (freq, time)\ndata2.dimord = 'rpt_freq_time';\ndata1.freq = [1:freqs];\ndata2.freq = [1:freqs];\ndata1.time =[1:times];\ndata2.time= [1:times];\n\n% fix the invalid data structure, see ft_datatype_freq\ndata1.dimord = 'rpt_chan_freq_time';\ndata2.dimord = 'rpt_chan_freq_time';\ndata1.globspctrm = reshape(data1.globspctrm, [nsubj 1 freqs times]);\ndata2.globspctrm = reshape(data2.globspctrm, [nsubj 1 freqs times]);\ndata1.label = {'TheSame'};\ndata2.label = {'TheSame'};\n\ncfg.parameter = 'globspctrm'; % 'avg', 'cohspctrm'\ncfg.method = 'montecarlo'; % 'montecarlo', 'analytic' , 'stats', 'crossvalidate'\n\ncfg.neighbours = [];\ncfg.channel = 'all';\ncfg.correctm = 'cluster'; % 'no', 'max', 'cluster', 'bonferroni', 'holm', 'hochberg', 'fdr' (default = 'no')\n\ncfg.clusterstatistc = 'wcm'; % 'wcm', 'maxsum', 'maxsize'\ncfg.clusterthreshold = 'parametric'; % 'parametric', 'nonparametric_individual', 'nonparametric_common'\ncfg.numrandomization = 1000;\ncfg.clusteralpha = 0.05;\ncfg.tail = 0;\n\nstats = ft_freqstatistics(cfg,data1,data2)\n\nfigure;\n\nsubplot(2,3,1)\ntres=squeeze(mean(cond1,1));\nimagesc(tres)\ncolorbar\ntitle('Adult SL: Mean')\nylabel('Frequencies')\nxlabel('Time')\n\nsubplot(2,3,2)\ntres=squeeze(mean(cond2,1));\nimagesc(tres)\ncolorbar\ntitle('Adult JA: Mean')\nylabel('Frequencies')\nxlabel('Time')\n\nsubplot(2,3,4)\ntres=squeeze(stats.stat)\nimagesc(tres)\ncolorbar\ntitle('SL vs. JA: t matrix')\nylabel('Frequencies')\nxlabel('Time')\n\nsubplot(2,3,5)\nPositive_cluster=squeeze(stats.posclusterslabelmat);\nPositive_cluster(Positive_cluster > 1) = 0; % keep just cluster 1\nimagesc(Positive_cluster)\ntitle(['SL > JA cluster: p=' num2str(stats.posclusters(1, 1).prob)])\ncolorbar\nylabel('Frequencies')\nxlabel('Time')\n\nsubplot(2,3,6)\nNegative_cluster=squeeze(stats.negclusterslabelmat);\nNegative_cluster(Negative_cluster > 1) = 0; % keep just cluster 1\nimagesc(Negative_cluster)\ntitle(['SL < JA cluster: p=' num2str(stats.negclusters(1, 1).prob)])\ncolorbar\nylabel('Frequencies')\nxlabel('Time')\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_bug3417.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.737158174177441, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.49051282767302273}} {"text": "function plot_data_against_probabilities(sv,type,specs)\n\nif nargin<3\n \n specs=[3,3];\n \n if nargin<2\n \n type='state';\n \n end\n \nend\n\n% myLimits=[-sqrt(eps),1+sqrt(eps)];\n\n[f,the_regimes,endog,data,tex]=load_filters(sv);\n\nswitch type\n \n case 'state'\n \n probs=f.smoothed_state_probabilities;\n \n case 'regime'\n \n probs=f.smoothed_regime_probabilities;\n \n otherwise\n \n error('second input must be either \"state\" or \"regime\"')\n \nend\n\nr0=specs(1);\n\nc0=specs(2);\n\nall_regimes=fieldnames(probs);\n\nall_regimes(strcmp(all_regimes,'const_1'))=[];\n\nfor iv=1:numel(endog)\n \n vn=endog{iv};\n \n utils.plot.multiple(@plotfuncr,all_regimes,...\n [vn,' against smoothed ',type,' probabilities'],r0,c0);\n \n if ~isempty(tex)\n \n [~,h]=sup_label(tex.(vn),'t');\n \n set(h,'fontsize',12)\n \n end\n\nend\n\n\n function [mytex,leg]=plotfuncr(vname)\n \n dd=data.(vn)(probs.(vname).date_numbers);\n \n [AX,H1,H2]=plotyy(probs.(vname),dd,'linewidth',2);\n \n axis(AX,'tight')\n \n if isempty(tex)\n \n mytex=vname;\n \n else\n \n mytex=tex.(vname);\n \n end\n \n if strcmp(type,'regime')\n \n vname(1:numel('regime'))=[];\n \n vname=strrep(vname,'_','');\n \n mytex=sprintf('%s(%s)',mytex,the_regimes{str2double(vname)});\n \n end\n \n leg='';\n \n end\n\nend", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/examples/VariousModels/TaoZha/Tutorials/SVAR/plot_data_against_probabilities.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.49051282487952697}} {"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 [kg] = slug2kg(slug)\n% Convert units of mass from slugs to kilograms. \n% Chad A. Greene 2012\nkg = slug*14.5939;", "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/slug2kg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.49051281230369204}} {"text": "clear; close all; clc;\n\nn = 150;\nxx = linspace(-4,4,n);\nmy_polynomial = [1, -2, -3, 4];\nyy = polyval(my_polynomial, xx);\n\nn_step = 150;\n\nnewVid = VideoWriter('pic1', 'MPEG-4'); % New\nnewVid.FrameRate = 30;\nnewVid.Quality = 100;\nopen(newVid);\n\nfigure('position',[490, 110, 900, 650],'color','w');\nfor i_step = 1:n_step\n yy2plot = (yy - zeros(1, n)) * i_step / n_step + zeros(1, n);\n plot2DPlane(-4,4,-6,6,false);\n hold on;\n \n if i_step == 1\n \n plot(xx, zeros(1,n),'linewidth',2);\n xlim([-3, 4])\n ylim([-6, 6])\n grid on;\n xlabel('$$x$$','interpreter','latex');\n ylabel('$$y = f(x)$$','interpreter','latex');\n title('$$y=f(x)=x^3-2x^2-3x+4$$','interpreter','latex')\n\n for i = 1:29 % \uccab \uc7a5\uba74\uc5d0\uc11c 1.5\ucd08 \ub300\uae30\ud560 \uc218 \uc788\ub3c4\ub85d\n \n writeVideo(newVid, getframe(gcf))\n end\n drawnow;\n cla;\n end\n plot2DPlane(-4,4,-6,6,false);\n\n plot(xx, yy2plot,'linewidth',2);\n xlim([-3, 4])\n ylim([-6, 6])\n grid on;\n xlabel('$$x$$','interpreter','latex');\n ylabel('$$y = f(x)$$','interpreter','latex');\n title('$$y=f(x)=x^3-2x^2-3x+4$$','interpreter','latex')\n drawnow;\n\n writeVideo(newVid, getframe(gcf))\n \n if i_step < n_step\n cla;\n end\nend\n\nfor i = 1:30 % \ub9c8\uc9c0\ub9c9 \uc7a5\uba74\uc5d0\uc11c 1.5\ucd08 \ub354 \ub300\uae30\ud560 \uc218 \uc788\ub3c4\ub85d\n writeVideo(newVid, getframe(gcf))\nend\n\nclose(newVid)\n", "meta": {"author": "angeloyeo", "repo": "gongdols", "sha": "7be9fbd988dec6edab1dc881cb22d63e6f69398d", "save_path": "github-repos/MATLAB/angeloyeo-gongdols", "path": "github-repos/MATLAB/angeloyeo-gongdols/gongdols-7be9fbd988dec6edab1dc881cb22d63e6f69398d/\uace0\ub824\ub300\ud559\uad50\ud2b9\uac15/function_as_a_mapping.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.49049367145856904}} {"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 [circle, labels] = imEnclosingCircle(img, varargin)\n% Minimal enclosing circle of a region.\n%\n% CIRC = imEnclosingCircle(IMG)\n% Computes the minimal enclosing circle around a binary region, or\n% around each labeled region in the input image.\n%\n%\n% CIRC = imEnclosingCircle(IMG, SPACING);\n% CIRC = imEnclosingCircle(IMG, SPACING, ORIGIN);\n% Specifies the spatial calibration of image. Both SPACING and ORIGIN are\n% 1-by-2 row vectors. SPACING = [SX SY] contains the size of a pixel.\n% ORIGIN = [OX OY] contains the center position of the top-left pixel of\n% image. \n% If no calibration is specified, spacing = [1 1] and origin = [1 1] are\n% used. If only the sapcing is specified, the origin is set to [0 0].\n%\n% CIRC = imEnclosingCircle(..., LABELS)\n% Specify the labels for which the enclosing circle needs to be computed.\n% The result is a N-by-3 array with as many rows as the number of labels.\n%\n%\n% Example\n% % Draw a commplex region together with its enclosing circle\n% img = imread('circles.png');\n% imshow(img); hold on;\n% circ = imEnclosingCircle(img);\n% drawCircle(circ)\n%\n% % Compute and display the equivalent ellipses of several regions\n% img = imread('rice.png');\n% img2 = img - imopen(img, ones(30, 30));\n% lbl = bwlabel(img2 > 50, 4);\n% circles = imEnclosingCircle(lbl);\n% imshow(img); hold on;\n% drawCircle(circles, 'linewidth', 2, 'color', 'g');\n%\n% See also\n% drawCircle, enclosingCircle\n% imInscribedCircle, imInertiaEllipse, imInertiaEllipse\n% \n% References\n% Based on a file from Yazan Ahed (yash78@gmail.com)\n% which was rewritten from a Java applet by Shripad Thite:\n% http://heyoka.cs.uiuc.edu/~thite/mincircle/\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inrae.fr\n% Created: 2012-07-08, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2012 INRA - Cepia Software Platform.\n\n\n%% Process input arguments\n\n% default values\nspacing = [1 1];\norigin = [1 1];\ncalib = false;\n\n% extract spacing\nif ~isempty(varargin) && sum(size(varargin{1}) == [1 2]) == 2\n spacing = varargin{1};\n varargin(1) = [];\n calib = true;\n origin = [0 0];\nend\n\n% extract origin\nif ~isempty(varargin) && sum(size(varargin{1}) == [1 2]) == 2\n origin = varargin{1};\nend\n\n% check if labels are specified\nlabels = [];\nif ~isempty(varargin) && size(varargin{1}, 2) == 1\n labels = varargin{1};\nend\n\n\n%% Initialisations\n\n% extract the set of labels, without the background\nif isempty(labels)\n labels = imFindLabels(img);\nend\nnLabels = length(labels);\n\n% allocate memory for result\ncircle = zeros(nLabels, 3);\n\n\n%% Iterate over labels\n\nfor i = 1:nLabels\n % extract points of the current region\n [y, x] = find(img==labels(i));\n\n % works on convex hull (faster), or on original points if the hull\n % could not be computed\n try \n inds = convhull(x, y);\n pts = [x(inds) y(inds)];\n catch %#ok\n pts = [x y];\n end\n \n % works on pixel corners rather than on pixel centers\n x = pts(:,1);\n y = pts(:,2);\n pts = [x-0.5 y-0.5 ; x+0.5 y-0.5 ; x-0.5 y+0.5 ; x+0.5 y+0.5];\n \n % convex hull again, to remove duplicates\n inds = convhull(pts(:,1), pts(:,2));\n pts = pts(inds, :);\n \n % transform to physical space if needed\n if calib\n pts(:,1) = (pts(:,1)-1) * spacing(1) + origin(1);\n pts(:,2) = (pts(:,2)-1) * spacing(2) + origin(2);\n end\n \n circle(i,:) = recurseCircle(size(pts, 1), pts, 1, zeros(3, 2));\nend\n\n\nfunction circ = recurseCircle(n, p, m, b)\n% n: number of points given\n% m: an argument used by the function. Always use 1 for m.\n% bnry: an argument (3x2 array) used by the function to set the points that \n% determines the circle boundary. You have to be careful when choosing this\n% array's values. I think the values should be somewhere outside your points\n% boundary. For my case, for example, I know the (x,y) I have will be something\n% in between (-5,-5) and (5,5), so I use bnry as:\n% [-10 -10\n% -10 -10\n% -10 -10]\n\n\nif m == 4\n circ = createCircle(b(1,:), b(2,:), b(3,:));\n return;\nend\n\ncirc = [Inf Inf 0];\n\nif m == 2\n circ = [b(1,1:2) 0];\nelseif m == 3\n c = (b(1,:) + b(2,:))/2;\n circ = [c distancePoints(b(1,:), c)];\nend\n\n\nfor i = 1:n\n if distancePoints(p(i,:), circ(1:2)) > circ(3)\n if sum(b(:,1)==p(i,1) & b(:,2)==p(i,2)) == 0\n b(m,:) = p(i,:);\n circ = recurseCircle(i, p, m+1, b);\n end\n end\nend\n\n\nfunction dist = distancePoints(p1, p2)\n\ndist = hypot(p2(:,1) - p1(:,1), p2(:,2) - p1(:,2));\n", "meta": {"author": "mattools", "repo": "matImage", "sha": "94d892c7beac0db32daadf2646ce37f58e894caf", "save_path": "github-repos/MATLAB/mattools-matImage", "path": "github-repos/MATLAB/mattools-matImage/matImage-94d892c7beac0db32daadf2646ce37f58e894caf/matImage/imMeasures/imEnclosingCircle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.4904936621783899}} {"text": "function [minM, maxM] = getMinMaxIM(IM,NHOOD)\n% function [minM, maxM] = getMinMaxIM(IM,NHOOD)\n%\n% This function returns min and max for the local neighborhood NHOOD\n%\n% APA, 04/26/2012\n\n\n% ---- No reflection required if our NHOOD is symmetric ------\n\n% % NHOOD is reflected across its origin in order for IMDILATE\n% % to return the local maxima of I in NHOOD if it is asymmetric. A symmetric NHOOD\n% % is naturally unaffected by this reflection.\n% reflectH = NHOOD(:);\n% reflectH = flipud(reflectH);\n% reflectH = reshape(reflectH, size(NHOOD));\n% maxMat = imdilate(IM,reflectH);\n\nmaxM = imdilate(IM,NHOOD);\n\n% IMERODE returns the local minima of IM in NHOOD.\nminM = imerode(IM,NHOOD); \n\nend", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Utilities/getMinMaxIM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.4904936591179338}} {"text": "function [Xgp Ygp]=projectToGroundPlane(Xi, Yi, sceneInfo)\n% \n% (C) Anton Andriyenko, 2012\n%\n% The code may be used free of charge for non-commercial and\n% educational purposes, the only requirement is that this text is\n% preserved within the derivative work. For any other purpose you\n% must contact the authors for permission. This code may not be\n% redistributed without written permission from the authors.\n\n[F N]=size(Xi);\nXgp=zeros(size(Xi));\nYgp=zeros(size(Xi));\n\nfor t=1:F\n extar=find(Xi(t,:));\n for id=extar\n [Xgp(t,id) Ygp(t,id) zw]=imageToWorld(Xi(t,id), Yi(t,id), sceneInfo.camPar);\n end\nend\n\nend\n", "meta": {"author": "VisDrone", "repo": "DroneCrowd", "sha": "3d25637f93f9476b4c949b6b9362287635b1a8c3", "save_path": "github-repos/MATLAB/VisDrone-DroneCrowd", "path": "github-repos/MATLAB/VisDrone-DroneCrowd/DroneCrowd-3d25637f93f9476b4c949b6b9362287635b1a8c3/STNNet/DroneCrowd-MOT-toolkit/trackers/GOG/utils/projectToGroundPlane.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.4904936544778443}} {"text": "function mpe = find_mpe(engine, local_evidence)\n% FIND_MPE Find the most probable explanation of the data \n% function mpe = find_mpe(engine, local_evidence\n%\n% local_evidence{i}(j) = Pr(observation at node i | S(i)=j)\n%\n% This finds the marginally most likely value for each hidden node.\n% It may give inconsistent results if there are ties.\n\n[mpe, niter] = bp_mpe_mrf2(engine.mrf2.adj_mat, engine.mrf2.pot, local_evidence, ...\n\t\t\t 'max_iter', engine.max_iter, 'momentum', engine.momentum, ...\n\t\t\t 'tol', engine.tol);\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/inference/static/@belprop_mrf2_inf_engine/find_mpe.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4904551250729538}} {"text": "function Fitness = CalFitness(C,Population)\n% Calculate the fitness of each solution in terms of a single level\n\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 PopObj = Population.objs;\n PopCon = Population.cons;\n if any(isnan(PopObj(:,1))) % Lower level\n PopObj = PopObj(:,2);\n PopCon = PopCon(:,C+1:end);\n else % Upper level\n PopObj = PopObj(:,1);\n PopCon = PopCon(:,1:C);\n end\n if isempty(PopCon)\n PopCon = zeros(size(PopObj,1),1);\n else\n PopCon = sum(max(0,PopCon),2);\n end\n Feasible = PopCon <= 0;\n Fitness = Feasible.*PopObj + ~Feasible.*(PopCon+1e10);\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/NBLEA/CalFitness.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.49045511887346077}} {"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 optodedistance = ft_nirs_optodedistance(datain)\n% FT_NIRS_OPTODEDISTANCE computes distances between pairs of optodes.\n%\n% Use as\n% distance = ft_nirs_optodedistance(indata)\n% where indata is nirs data.\n%\n% See also FT_NIRS_REFERENCECHANNELSUBTRACTION\n\n% You are using the FieldTrip NIRS toolbox developed and maintained by\n% Artinis Medical Systems (http://www.artinis.com). For more information\n% on FieldTrip, see http://www.fieldtriptoolbox.org\n%\n% This work is licensed under a Creative Commons Attribution-ShareAlike 4.0\n% International License. To view a copy of this license, visit\n% http://creativecommons.org/licenses/by-sa/4.0/ or send a letter to\n% Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.\n%\n% Creative Commons Attribution-ShareAlike 4.0 International License:\n% -----------------------------------\n% You are free to:\n%\n% Share - copy and redistribute the material in any medium or format\n% Adapt - remix, transform, and build upon the material\n% for any purpose, even commercially.\n%\n% The licensor cannot revoke these freedoms as long as you follow the\n% license terms.\n%\n% Under the following terms:\n%\n% Attribution - You must give appropriate credit, provide a link to\n% the license, and indicate if changes were made. You\n% may do so in any reasonable manner, but not in any way\n% that suggests the licensor endorses you or your use.\n%\n% ShareAlike - If you remix, transform, or build upon the material,\n% you must distribute your contributions under the same\n% license as the original.\n%\n% No additional restrictions - You may not apply legal terms or\n% technological measures that legally\n% restrict others from doing anything the\n% license permits.\n%\n% -----------------------------------\n%\n% This toolbox is not to be used for medical or clinical purposes.\n%\n% Copyright (c) 2016 by Artinis Medical Systems.\n% Contact: askforinfo@artinis.com\n%\n% Main programmer:\n% Marc van Wanrooij, DCN, http://www.neural-code.com\n% J\u00f6rn M. Horschig, Artinis Medical Systems BV, http://www.artinis.com\n% $Id$\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% the initial part deals with parsing the input options and data\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% ensure that the input data is raw NIRS-data, this will also do\n% backward-compatibility conversions of old data that for example was\n% read from an old *.mat file\ndatain = ft_checkdata(datain, 'datatype', 'raw', 'senstype', 'nirs');\n\n%% Relevant parameters\nlabel\t= datain.label; % transformed channel label, combination Receiver and Transmitter\nolabel\t= datain.opto.optolabel; % optode label\nopos\t= datain.opto.optopos; % optode positions\n\nnpos\t= numel(label);\n\nxf\t\t= opos(:,1);\nyf\t\t= opos(:,2);\n\n%% determine distance between Receiver and Transmitter optodes\noptodedistance\t\t\t\t= NaN(npos,1);\n\nfor posIdx=1:npos\n str\t= label{posIdx};\n c = textscan(str, '%s%s%s', 'Delimiter', {'-', ' '});\n \n chanRstr = c{1};\n chanTstr = c{2};\n \n idxR\t\t= match_str(olabel,chanRstr); \n idxT\t\t= match_str(olabel,chanTstr);\n \n optodedistance(posIdx)\t= sqrt( (xf(idxR)-xf(idxT)).^2+(yf(idxR)-yf(idxT)).^2 ); % Pythagorean theorem\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/artinis/private/ft_nirs_optodedistance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4903808603362428}} {"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": "%\n% Overview: Test ECGBeatFitter program for mean ECG beat extraction and\n% parameter optimization. The script does the following:\n% 1. Reads the ECG data in the sample_ecg_datam file in the 'Physionet-Cardiovascular-Signal-Toolbox/Tools/ECG_Analysis_Tools/MV/testdata/' subfolder.\n% 2. Estimates the average ECG beat for the first fifteen seconds. \n% 3. The ECGBeatFitter algorithm is used to estimate the parameters of\n% Gaussian functions that accurately estimate the shape of the average ECG\n% beat. The number of Gaussians is specified by selecting points along the\n% average beat in the ECGBeatFitter GUI.\n% 4. The output of the script are the parameters for the Gaussians stored in the following variables:\n% \n% ai: contains the amplitudes of the Gaussians.\n% bi: contains the standard deviations of the Gaussians.\n% tetai: contains the phase of each Gaussian function.\n%\n% 5. These parameters may be estimated for each of the x, y and z\n% components of a VCG and substituted into the generate_resp_modulated_ecg\n% function in the Physionet-Cardiovascular-Signal-Toolbox to generate an artificial \n% VCG with a morphology similar to VCG used for estimating the parameters. \n% The Dower transform may be applied to generate 12 lead ECG from the VCG.\n%\n%\n% ORIGINAL SOURCE AND AUTHORS: \n% Open Source ECG Toolbox, version 1.0, November 2006\n% Released under the GNU General Public License\n% Copyright (C) 2006 Reza Sameni\n% Sharif University of Technology, Tehran, Iran -- LIS-INPG, Grenoble, France\n% reza.sameni@gmail.com\n% editted by Ismail Sadiq on 11/29/2020.\n\n% This program is free software; you can redistribute it and/or modify it\n% under the terms of the GNU General Public License as published by the\n% Free Software Foundation; either version 2 of the License, or (at your\n% option) any later version.\n% This program is distributed in the hope that it will be useful, but\n% WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\n% Public License for more details. You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\nclc\nclear\nclose all;\n\n% Load test ecg data\naddpath(genpath('../../../../../PhysioNet-Cardiovascular-Signal-Toolbox-master/')); % add all dependencies from cardiovascular signal toolbox\nsig = load('./testdata/mvm/sample_ecg_datam');\nsiginfo = readheader('./testdata/mvm/sample_ecg_datam.hea');\nfs = siginfo.freq;\necg = (sig.val - siginfo.adczero)./siginfo.gain; data=ecg(1:15000);% Adjust signal according to gain and dc offset\nclear siginfo sig ecg;\n\nt = (0:length(data)-1)/fs;\n\nf = 1; % approximate R-peak frequency\n\nbsline = LPFilter(data,.7/fs); % baseline wander removal (may be replaced by other approaches)\n%bsline = BaseLineKF(data,.5/fs); % baseline wander removal (may be replaced by other approaches)\n\ndata1 = data-bsline;\n\n%//////////////////////////////////////////////////////////////////////////\n% Making the data noisy\nSNR = 20;\nSignalPower = mean(data1.^2);\nNoisePower = SignalPower / 10^(SNR/10);\nx = data1 + sqrt(NoisePower)*randn(size(data1));\n%//////////////////////////////////////////////////////////////////////////\n\npeaks = PeakDetection(x,f/fs); % peak detection\n\n[phase, phasepos] = PhaseCalculation(peaks); % phase calculation\n\nteta = 0; % desired phase shift\npphase = PhaseShifting(phase,teta); % phase shifting\n\nbins = round(fs/3); % number of phase bins\n[ECGmean,ECGsd,meanphase] = MeanECGExtraction(x,pphase,bins,1); % mean ECG extraction \n\nOptimalParams = ECGBeatFitter(ECGmean,ECGsd,meanphase); % ECG beat fitter GUI\n\n% display the optimal parameters\nL = length(OptimalParams)/3;\nai = OptimalParams(1:L)\nbi = OptimalParams(L+1:2*L)\ntetai = OptimalParams(2*L+1:3*L)\n\n", "meta": {"author": "cliffordlab", "repo": "PhysioNet-Cardiovascular-Signal-Toolbox", "sha": "eec46e75e0b95c379ecb68cb0ebee0c4c9f54605", "save_path": "github-repos/MATLAB/cliffordlab-PhysioNet-Cardiovascular-Signal-Toolbox", "path": "github-repos/MATLAB/cliffordlab-PhysioNet-Cardiovascular-Signal-Toolbox/PhysioNet-Cardiovascular-Signal-Toolbox-eec46e75e0b95c379ecb68cb0ebee0c4c9f54605/Tools/ECG_Analysis_Tools/MV/Demos/demo_ECGBeatFitter.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 out = sampleInSeconds(stimList,ISI,varargin)\n% out = sampleInSeconds(stimList,ISI,varargin)\n% input: stimList, output: stimlist sampled in .1 seconds\n% OR sampled at your specified frequency\n\nscale = ceil(ISI*10);\n\nif nargin > 2\n scale = round(ISI/varargin{1});\nend\n\nnumstim = size(stimList,1);\n\nout = zeros(numstim*scale,1);\n\nfor i = 0:numstim-1\n\n out(i*scale+1,1) = stimList(i+1,1);\n\nend\n\nreturn\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/OptimizeDesign11/core_functions/sampleInSeconds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.49019262949559766}} {"text": "% Figure 7.21 Feedback Control of Dynamic Systems, 5e\n% Franklin, Powell, Emami\n%\n% Script to generate fig. 7.21.\nclf;\nnum=1;\nden=[1 0 0 0 0];\nrlocus(num,den);\ntitle('Fig. 7.21 Symmetric root locus for satellite system')\ngrid;\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/9907-feedback-control-of-dynamic-systems-fifth-ed/fig7_21.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.4901926213655584}} {"text": "function calpak_test337 ( )\n\n%*****************************************************************************80\n%\n%% CALPAK_TEST337 tests MONTH_EG_LUNAR.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 26 March 2013\n%\n% Author:\n%\n% John Burkardt\n%\n n_test = 2;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CALPAK_TEST337\\n' );\n fprintf ( 1, ' For the Egyptian Lunar calendar,\\n' );\n fprintf ( 1, ' MONTH_LENGTH_EG_LUNAR returns month lengths.\\n' );\n\n y_test(1) = 1;\n y_test(2) = 2;\n\n for i_test = 1 : n_test\n\n y = y_test(i_test);\n sy = y_to_s_eg_lunar ( y );\n months = year_length_months_eg_lunar ( y );\n days = year_length_eg_lunar ( y );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' %d\\n', y );\n fprintf ( 1, ' %s\\n', sy );\n fprintf ( 1, ' Year length in months = %d\\n', months );\n fprintf ( 1, ' Year length in days = %d\\n', days );\n fprintf ( 1, '\\n' );\n\n for m = 1 : months\n month_name = month_to_month_name_eg_lunar ( m );\n fprintf ( 1, ' %10s %2d\\n', month_name, month_length_eg_lunar ( y, m ) );\n end\n\n end\n \n return\nend", "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/calpak_test337.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.49019261730053865}} {"text": "function c = horzcat(varargin)\n% function C=horzcat(A,B);\n%\n% DESCRIPTION\n% Horizontal concatenation of polynomial objects.\n%\n% INPUTS\n% A,B: polynomials\n%\n% OUTPUTS\n% C: horizontal concatenation of input matrices.\n%\n% SYNTAX\n% [A B]\n% Horizontal concatenation of polynomial matrices A and B.\n% A and B must have the same number of rows.\n% [A1 A2 A3 ...]\n% Horizontal concatenation of several polynomial matrices.\n% C = horzcat(A1,A2,...);\n% Function-call form of horizontal concatenation.\n%\n% See also vertcat\n\n% 6/8/2002: PJS Initial Coding\n\nif nargin==1\n c = varargin{1};\nelse\n % Promote a to polynomial\n a = polynomial(varargin{1});\n [nra,nca] = size(a);\n \n % Promote b to polynomial\n b = polynomial(varargin{2});\n [nrb,ncb] = size(b);\n \n if isempty(b);\n c = a;\n elseif isempty(a);\n c = b;\n elseif nra==nrb\n % Get Dimensions\n nta = size(a.degmat,1);\n nva = length(a.varname);\n ntb = size(b.degmat,1);\n nvb = length(b.varname);\n \n if nva==0 && nvb==0\n % Combine constant terms\n ar = combine(a);\n coef1 = reshape(ar.coefficient,[nra nca]);\n br = combine(b);\n coef2 = reshape(br.coefficient,[nrb ncb]);\n \n % Stack Coefficients and Form Polynomial\n coefficient = [coef1 coef2];\n c = polynomial(coefficient);\n else\n % Form Degmat, Varname, and Matdim\n adeg = a.degmat;\n bdeg = b.degmat;\n degmat = blkdiag(adeg,bdeg);\n varname = [a.varname(:); b.varname(:)];\n matdim = [nra nca+ncb];\n \n % Stack up Coefficients\n coef1 = [a.coefficient zeros(nta,nra*ncb)];\n coef2 = [zeros(ntb,nrb*nca) b.coefficient];\n coefficient = [coef1; coef2];\n \n % Form Polynomial and combine terms\n chkval = 0; % skip validity check\n c = polynomial(coefficient,degmat,varname,matdim,chkval);\n c = combine(c);\n end\n else\n error('All columns must have the same row dimension')\n end\n \n if nargin>2\n c = horzcat(c,varargin{3:end});\n end\nend\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/SOSTOOLS.300/SOSTOOLS.300/multipoly/@polynomial/horzcat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.49019261667871916}} {"text": "function varargout = lap(varargin)\n%LAP Laplacian of a CHEBFUN2.\n% L = LAP(F) returns a CHEBFUN2 representing the Laplacian of F.\n%\n% This is shorthand for LAPLACIAN(F).\n%\n% See also CHEBFUN2/LAPLACIAN.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Call SEPARABLEAPPROX/LAP:\n[varargout{1:nargout}] = lap@separableApprox(varargin{:});\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebfun2/lap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.4901926154350796}} {"text": " function ob = Ginterp1(mask, varargin)\n%function ob = Ginterp1(mask, options)\n%|\n%| Construct Ginterp1 object for 1D image registration.\n%| This method does not have an adjoint.\n%|\n%| See Ginterp1_test() below for example usage.\n%|\n%| in\n%|\tmask\tsize(image)\tlogical array of object support.\n%|\n%| options\n%|\t'interp1_arg'\t{}\targuments to interp1 for 'forward' operation\n%|\n%| out\n%|\tob [nd np]\tnp = sum(mask(:)), so it is already \"masked\"\n%|\t\t\tnd = numel(interp1_arg{2})\n%|\n%| Copyright 2013-12-05, Jeff Fessler, University of Michigan\n\nif nargin == 1 && streq(mask, 'test'), Ginterp1_test, return, end\nif nargin < 1, ir_usage, end\n\narg.mask = mask;\n\n% option defaults\narg.interp1_x = [];\narg.interp1_xq = [];\narg.interp1_arg = {'linear', 0};\n\n% options specified by name/value pairs\narg = vararg_pair(arg, varargin);\n\nif isempty(arg.interp1_x) || isempty(arg.interp1_xq)\n\tfail '\"interp1_arg\" and \"interp1_x\" required'\nend\n\narg.ndim = ndims(mask);\nif arg.ndim == 2 && size(mask,2) == 1\n\targ.ndim = 1;\nelse\n\tfail 'only 1D mask allowed'\nend\n\nif streq(arg.interp1_arg{1}, 'linear')\n\tabs_arg = {'abs', @(ob) ob}; % linear interpolation uses nonnegative coefficients\nelse\n\tabs_arg = {}; % unknown\nend\n\narg.fun_forw = @(arg, x) ...\n\tinterp1(arg.interp1_x, x, arg.interp1_xq, arg.interp1_arg{:});\narg.fun_back = @(arg, y) fail('interp adjoint not done');\n\n% build object\nidim = size(mask);\nif numel(idim) == 2 && idim(2) == 1\n\tidim = idim(1); % 1d\nend\nob = fatrix2('mask', mask, 'arg', arg, ...\n\t'idim', idim, 'odim', numel(arg.interp1_xq), ...\n\tabs_arg{:}, 'forw', arg.fun_forw, 'back', arg.fun_back);\n\n\n% Ginterp1_test()\nfunction Ginterp1_test\n\nnx = 8;\nmask = true(nx,1);\nmask(1) = false;\nxq = linspace(0,nx+1, 101);\n\nA = Ginterp1(mask, 'interp1_x', 1:nx, 'interp1_xq', xq);\n\nif 0 % todo\n\tfatrix2_tests(A, 'complex', 0, 'halt', 0, ...\n\t\t'check1', false, 'full', false) % because of bad adjoint\n%\ttest_adjoint(A, 'complex', 1);\nelse\n\twarn 'adjoint not tested'\nend\n\nim plc 1 2\nAf = full(A);\nim(1, Af'), axis xy, axis normal\n\nim subplot 2\nx = [1:nx]' .* mask;\ny = A * x;\n\nplot(1:nx, x, 'o', xq, y, '.-')\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/systems/Ginterp1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.49019261199187986}} {"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": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% PARAMETERS Returns a data structure containing the parameters of the\n% KUKA KR30 L16 2\n%\n% Author: Arturo Gil. Universidad Miguel Hern\ufffdndez de Elche. \n% email: arturo.gil@umh.es date: 08/01/2012\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 robot = parameters()\n \nrobot.DH.theta= '[-q(1) q(2)-pi/2 q(3) q(4) q(5) q(6)]';\nrobot.DH.d='[0.815 0 0 1.545 0 0.158]';\nrobot.DH.a='[0.350 1.2 0.145 0 0 0]';\nrobot.DH.alpha= '[-pi/2 0 -pi/2 pi/2 -pi/2 0]';\n\nrobot.J=[];\nrobot.name= 'KUKA_KR30_L16_2';\n\nrobot.inversekinematic_fn = 'inversekinematic_kuka_kr_30_L16_2(robot, T)';\n\n%number of degrees of freedom\nrobot.DOF = 6;\n\n%rotational: 0, translational: 1\nrobot.kind=['R' 'R' 'R' 'R' 'R' 'R'];\n\n%minimum and maximum rotation angle in rad\nrobot.maxangle =[deg2rad(-185) deg2rad(185); %Axis 1, minimum, maximum\n deg2rad(-135) deg2rad(35); %Axis 2, minimum, maximum\n deg2rad(-120) deg2rad(158); %Axis 3\n deg2rad(-350) deg2rad(350); %Axis 4\n deg2rad(-130) deg2rad(130); %Axis 5\n deg2rad(-350) deg2rad(350)]; %Axis 6\n\n%maximum absolute speed of each joint rad/s or m/s\nrobot.velmax = [deg2rad(100); %Axis 1, rad/s\n deg2rad(80); %Axis 2, rad/s\n deg2rad(80); %Axis 3, rad/s\n deg2rad(230); %Axis 4, rad/s\n deg2rad(165); %Axis 5, rad/s\n deg2rad(249)];%Axis 6, rad/s\n% end effectors maximum velocity\nrobot.linear_velmax = 2.0; %m/s\nrobot.accelmax=robot.velmax/0.1; % 0.1 is here an acceleration time\n%base reference system\nrobot.T0 = eye(4);\n\n%INITIALIZATION OF VARIABLES REQUIRED FOR THE SIMULATION\n%position, velocity and acceleration\nrobot=init_sim_variables(robot);\n\n% GRAPHICS\nrobot.graphical.has_graphics=1;\nrobot.graphical.color = [200 20 40]./255;\n%for transparency\nrobot.graphical.draw_transparent=0;\n%draw DH systems\nrobot.graphical.draw_axes=1;\n%DH system length and Font size, standard is 1/10. Select 2/20, 3/30 for\n%bigger robots\nrobot.graphical.axes_scale=1;\n%adjust for a default view of the robot\nrobot.axis=[-2 2 -2 2 0 2.5];\n%read graphics files\nrobot = read_graphics(robot);\n\n%DYNAMICS\nrobot.has_dynamics=0;", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/robots/KUKA/KR30_L16_2/parameters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4900302477199527}} {"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": "function [B, elapse] = BRE_compress(A, model)\n% This is a wrapper function of Binary Reconstructive Embedding testing.\n%\n%\tUsage:\n%\t[B,elapse] = BRE_compress(A, model)\n%\n%\t A: Rows of vectors of data points. Each row is sample point\n% model: The model generated by BRE_learn.\n%\n%\t B: The binary code of the input data A. Each row is sample point\n% elapse: The coding time (testing time).\n%\n%\n%\n% version 2.0 --Nov/2016 \n% version 1.0 --Jan/2013 \n%\n% Written by Yue Lin (linyue29@gmail.com)\n% Deng Cai (dengcai AT gmail DOT com) \n% \n\n\ntmp_T = tic;\n\nKtest = A*model.X';\nH_query = zeros(size(A,1),size(model.W,2));\nfor b = 1:size(model.W,2)\n H_query(:,b) = Ktest(:,model.hash_inds(:,b))*model.W(:,b);\nend\nB = (H_query>0);\n\nelapse = toc(tmp_T);\nend\n", "meta": {"author": "ZJULearning", "repo": "MatlabFunc", "sha": "97504df0f597c1980ab76ddc0c9c5d669043c6c9", "save_path": "github-repos/MATLAB/ZJULearning-MatlabFunc", "path": "github-repos/MATLAB/ZJULearning-MatlabFunc/MatlabFunc-97504df0f597c1980ab76ddc0c9c5d669043c6c9/ANNS/Hashing/Unsupervised/BRE_compress.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.49003024072901796}} {"text": "function images = rmfilter_energy(images, display)\n\n% simlpe energy filter: \n% (1) subtract background intenstity\n% (2) rectify\n% (3) divide by maximum \n% (max = greatest absolute distance from background) \n\ntry\n % look up min, max, and bk from screen calibration\n Cmap.min = min(display.stimRgbRange);\n Cmap.max = max(display.stimRgbRange);\n Cmap.bk = display.backColorIndex;\ncatch\n % if not found assume them from image matrix\n Cmap.min = min(images(:));\n Cmap.max = max(images(:));\n Cmap.bk = round(mean(images(:)));\nend\n\nimages = double(images);\nimages = images - Cmap.bk;\nimages = sqrt(images.^2);\nmaxEnergy = double(max(Cmap.max - Cmap.bk, Cmap.bk - Cmap.min));\nmaxEnergy = double(maxEnergy);\nimages = images / maxEnergy;\n\nend", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Analysis/retinotopyModel/FilterDefinitions/rmfilter_energy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4899644731945312}} {"text": "function node_num = grid_q4_node_num ( nelemx, nelemy )\n\n%*****************************************************************************80\n%\n%% GRID_Q4_NODE_NUM counts the nodes in a grid of Q4 elements.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 February 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NELEMX, NELEMY, the number of elements along the\n% X and Y directions. The number of elements generated will be\n% NELEMX * NELEMY.\n%\n% Output, integer NODE_NUM, the number of nodes in the grid.\n%\n node_num = ( nelemx + 1 ) * ( nelemy + 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/fem2d_pack/grid_q4_node_num.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.4899644693989791}} {"text": "function lagrange_interp_1d_test ( )\n\n%*****************************************************************************80\n%\n%% LAGRANGE_INTERP_1D_TEST tests the LAGRANGE_INTERP_1D library.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 August 2012\n%\n% Author:\n%\n% John Burkardt\n%\n addpath ( '../r8lib' )\n addpath ( '../test_interp_1d' )\n\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LAGRANGE_INTERP_1D_TEST:\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, ' Test the LAGRANGE_INTERP_1D library.\\n' );\n fprintf ( 1, ' The R8LIB library is needed.\\n' );\n fprintf ( 1, ' The test needs the TEST_INTERP_1D library.\\n' );\n\n prob_num = p00_prob_num ( );\n for prob = 1 : prob_num\n for nd = [ 4, 8, 16, 32, 64, 256 ]\n lagrange_interp_1d_test02 ( prob, nd );\n end\n end\n\n prob_num = p00_prob_num ( );\n for prob = 1 : prob_num\n for nd = [ 4, 8, 16, 32, 64, 256 ]\n lagrange_interp_1d_test03 ( prob, nd );\n end\n end\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LAGRANGE_INTERP_1D_TEST:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n rmpath ( '../r8lib' )\n rmpath ( '../test_interp_1d' )\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/lagrange_interp_1d/lagrange_interp_1d_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.4899644656034269}} {"text": "classdef PESAII < ALGORITHM\n% \n% Pareto envelope-based selection algorithm II\n% div --- 10 --- The number of divisions in each objective\n\n%------------------------------- Reference --------------------------------\n% D. W. Corne, N. R. Jerram, J. D. Knowles, and M. J. Oates, PESA-II:\n% Region-based selection in evolutionary multiobjective optimization,\n% Proceedings of the Annual Conference on Genetic and Evolutionary\n% Computation, 2001, 283-290.\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 div = Algorithm.ParameterSet(10);\n\n %% Generate random population\n Population = Problem.Initialization();\n\n %% Optimization\n while Algorithm.NotTerminated(Population)\n MatingPool = MatingSelection(Population.objs,Problem.N,div);\n Offspring = OperatorGA(Problem,Population(MatingPool));\n Population = EnvironmentalSelection([Population,Offspring],Problem.N,div);\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/PESA-II/PESAII.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4899644580123224}} {"text": "function test_bug3192\n\n% WALLTIME 00:10:00\n% MEM 2gb\n% DEPENDENCY ft_plot_mesh ft_plot_box ft_plot_headmodel ft_plot_dipole ft_plot_headshape\n\n% one color for all vertex\ncfg = [];\ncfg.sourcemodel.xgrid = -20:5:20;\ncfg.sourcemodel.ygrid = -20:5:20;\ncfg.sourcemodel.zgrid = -20:5:20;\ngrid = ft_prepare_sourcemodel(cfg);\nfigure, ft_plot_mesh(grid, 'vertexcolor', 'blue', 'facecolor', 'brain', 'edgecolor', 'skull')\n\n% different colors for each vertex\nc = [];\ntemp = {'r','b'};\nfor iPos=1:length(grid.pos), c = [c temp{mod(iPos,2)+1}]; end\nfigure, ft_plot_mesh(grid, 'vertexcolor', c)\n\nfigure, ft_plot_box([-1 1 2 3], 'facecolor', 'brain')\n\n% ft_plot_sens, _vol, _headshape, and _dipole just forward to ft_plot_mesh\nelecs = [];\nelecs.elecpos = [23 42 -31; 69 52 1; 61 67 26; 52 65 45];\nelecs.label = {'1' '2' '3' '4'};\nfigure, ft_plot_sens(elecs, 'edgecolor', 'red')\n\nload(dccnpath('/home/common/matlab/fieldtrip/template/headmodel/standard_singleshell.mat'))\nfigure, ft_plot_headmodel(vol, 'edgecolor', 'blue', 'vertexcolor', 'red', 'facecolor', 'brain')\n\nvol.pos = [23 42 -31; 69 52 1; 61 67 26; 52 65 45];\nfigure, ft_plot_headshape(vol, 'edgecolor', 'blue', 'vertexcolor', 'red', 'facecolor', 'brain')\n\nfigure, ft_plot_dipole([1 2 3], [1 2 3], 'color', 'brain')\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_bug3192.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.6619228891883799, "lm_q1q2_score": 0.4899383446364469}} {"text": "function images = loadMNISTImages(filename)\n%loadMNISTImages returns a 28x28x[number of MNIST images] matrix containing\n%the raw MNIST images\n\nfp = fopen(filename, 'rb');\nassert(fp ~= -1, ['Could not open ', filename, '']);\n\nmagic = fread(fp, 1, 'int32', 0, 'ieee-be');\nassert(magic == 2051, ['Bad magic number in ', filename, '']);\n\nnumImages = fread(fp, 1, 'int32', 0, 'ieee-be');\nnumRows = fread(fp, 1, 'int32', 0, 'ieee-be');\nnumCols = fread(fp, 1, 'int32', 0, 'ieee-be');\n\nimages = fread(fp, inf, 'unsigned char=>unsigned char');\nimages = reshape(images, numCols, numRows, numImages);\nimages = permute(images,[2 1 3]);\n\nfclose(fp);\n\n% Reshape to #pixels x #examples\nimages = reshape(images, size(images, 1) * size(images, 2), size(images, 3));\n% Convert to double and rescale to [0,1]\nimages = double(images) / 255;\n\nend\n", "meta": {"author": "xuzhenqi", "repo": "cnn", "sha": "3b505ad0fc3bbb0cc5331d109702b6921fef2cb2", "save_path": "github-repos/MATLAB/xuzhenqi-cnn", "path": "github-repos/MATLAB/xuzhenqi-cnn/cnn-3b505ad0fc3bbb0cc5331d109702b6921fef2cb2/Dataset/MNIST/loadMNISTImages.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.48993833741493464}} {"text": "function [A,idxList]=quickSort(A,byCol,gtCompareFunc)\n%%QUICKSORT Sort an array, a matrix, or a cell array in ascending order\n% using a non-recursive implementation of the quicksort\n% algorithm. The quicksort algorithm tends to have better average\n% performance than other techniques, being O(n*log(n)) averge and\n% best case, with a small multiplicative constant, but has O(n^2)\n% worst case performance, which is worse than heapsort. A custom\n% comparison function can be used so that one can, for example,\n% sort strings or other things. Changing the direction of the\n% comparison function (from greater than to less than) changes\n% the sorting order from ascending to descending. Note that\n% quickSort is not a stable sorting algorithm, meaning that the\n% order of items having the same value might change.\n%\n%INPUTS: A An array, 2D matrix, or linear cell array that is to be sorted.\n% When given a matrix, the comparison function gtCompareFunc must\n% be provided so that it is clear how the columns are compared\n% (or the rows if byCol is false).\n% byCol A boolean value indicating whether sorting should be performed\n% by row or by column. This must be specified when a matrix is\n% passed as as a linear array could be confused with a matrix\n% with just one row/column. The default if this parameter is\n% omitted and the input is 1-dimensional is whatever would sort\n% over the 1D array. If the input is 2D, then the default is\n% true. This parameter is not used when cell arrays are passed\n% (an empty matrix can be passed for this) as only linear cell\n% arrays are supported, so no ambiguity between 1D and 2D inputs\n% would exist.\n%gtCompareFunc A function handle that performs a greather-than comparison\n% of two entries in A. This lets one define custom comparison\n% operations. Providing a less-than comparison for this will\n% cause the list to be sorted in descending order rather than\n% ascending order. When sorting an array or matrix, the\n% the function handle takes inputs of the form\n% gtCompareFunc(A(:,i),A(:,j)) if byCol=true and with\n% reversed row and column indices if byCol=false. When\n% comparing cell arrays, it must handle inputs of the form\n% gtCompareFunc(A{i},A{j}). The default if this parameter is\n% omitted is @(x1,x2)(x1>x2);\n%\n%OUTPUTS: A The sorted array/ matrix/ cell array. If gtCompareFunc\n% performs a greater-than comparison, then it is in increasing\n% order. Otherwise it is in decreasing order.\n% idxList The indices of the original elements with respect to the sorted\n% order. For example, if the input A is an array, then\n% A(idxList) on the input A will give the sorted output A.\n%\n%The quicksort algorithm is based on the description given in Chapter 7 of\n%[1]. However, it has been modified to eliminate the recursion.\n%\n%Note that sorting large matrices can be slow as each element (so an entire\n%row/ column) is copied during the search. Thus, if one is just sorting\n%according to a particular row, it makes sense ot get the idxList for that\n%one row and then use it to sort everything else.\n%\n%REFERENCES:\n%[1] T. H. Cormen, C. E. Leiserson, R. L. Rivest, and C. Stein,\n% Introduction to Algorithms, 2nd ed. Cambridge, MA: The MIT Press,\n% 2001.\n%\n%December 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n %If an empty matrix is passed, return an empty matrix.\n if(isempty(A))\n idxList=[];\n return;\n end\n\n if(nargin<2||isempty(byCol))\n %If the input is 1-dimensional, then make the byCol parameter go\n %over whichever dimension would sort it. Otherwise, make it go over\n %columns.\n if(size(A,1)==1)\n byCol=true;\n elseif(size(A,2)==1)\n byCol=false;\n else\n byCol=true;\n end\n end\n\n if(nargin<3||isempty(gtCompareFunc))\n gtCompareFunc=@(x1,x2)(x1>x2);\n end\n\n isACellArray=isa(A,'cell');\n if(~isACellArray)\n %If A is supposed to be sorted by row.\n if(byCol==false)\n A=A';\n end\n \n numPoints=size(A,2);\n else\n numPoints=length(A);\n end\n \n %The index list is not used in the algorithm for sorting; it is just\n %computed in case the user wants it as a return variable.\n idxList=1:numPoints;\n \n %stack(:,i) holds the lower and upper bounds of the partiion being\n %sorted at the ith level. The upper bound on the stack space in\n %the worst-case scenario is where every single point visited\n %creates two partitions. However, since each time it splits, it\n %deletes itself, the limit on the memory is ceil(numPoints/2) and\n %not numPoints.\n stack=zeros(2,ceil(numPoints/2));\n\n p=1;\n r=numPoints;\n stackIdx=1;\n stack(:,stackIdx)=[p;r];\n while(stackIdx>0)\n %Pop the p and r values off of the stack.\n p=stack(1,stackIdx);\n r=stack(2,stackIdx);\n stackIdx=stackIdx-1;\n\n %Partition the array, getting the correct location of the pivor\n %element.\n if(~isACellArray)\n [q,A,idxList]=partition(A,idxList,p,r,gtCompareFunc);\n else\n [q,A,idxList]=partitionCell(A,idxList,p,r,gtCompareFunc);\n end\n\n %If there are elements on the left side, then push them onto\n %the stack.\n if(p ai(eqtn)\n% --> ai(eqtn,vbl)\n% --> ai(eqtn,vbl,chain_name,state)\n% --> a(eqtn)\n% --> a(eqtn,vbl)\n% --> a(eqtn,vbl,chain_name,state)\n% - **eqtn** [integer]: integer\n% - **vbl** [integer|char]: integer or variable name\n% - **i** [integer]: lag\n% - **chain_name** [char]: name of the markov chain\n% - **state** [integer]: state number\n%\n% - The lag coefficients are labelled a0, a1, a2,...,ak, for a model with k\n% lags. Obviously, a0 denotes the contemporaneous coefficients.\n%\n% - The constant terms labelled c_1_1, c_2_2,...,c_n_n, for a model with n\n% endogenous variables.\n%\n% - The standard deviations labelled s_1_1, s_2_2,...,s_n_n, for a\n% model with n endogenous variables.\n%\n% Example:\n%\n% See also:\n\nif nargin==0||isempty(markov_chains)\n\n markov_chains=struct('name',{},...\n 'states_expected_duration',{},...\n 'controlled_parameters',{});\n \nend\n\n% syntax is coef(eqtn,vname,lag)\n%-------------------------------\nlin_restr={\n % first equation or \"FFR\" equation\n %----------------------------------\n 'a1(1,pi)=0'\n 'a2(1,pi)=0'\n 'a1(1,ygap)=0'\n 'a2(1,ygap)=0'\n 'a2(1,FFR)=0'\n % second equation or \"pi\" equation\n %----------------------------------\n 'a0(2,FFR)=0'\n 'a1(2,FFR)=0'\n 'a2(2,FFR)=0'\n 'a1(2,ygap)=0'\n 'a2(2,ygap)=0'\n % third equation or \"ygap\" equation\n %-----------------------------------\n 'a1(3,FFR)=0'\n 'a2(3,FFR)=0'\n 'a1(3,pi)=0'\n 'a2(3,pi)=0'\n 'a0(3,pi)+a0(3,FFR)=0'\n };\nnonlin_restr={\n 'a0(3,FFR)>=0'\n 'a1(1,FFR)>=0'\n 'a1(1,FFR)<=1'\n };\n\nend", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/examples/VariousModels/TaoZha/Tutorials/SVAR/+deprecated/create_restrictions_and_markov_chains0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.489927805039744}} {"text": "classdef IDTLZ1 < PROBLEM\n% \n% Inverted DTLZ1\n\n%------------------------------- Reference --------------------------------\n% H. Jain and K. Deb, An evolutionary many-objective optimization algorithm\n% using reference-point based non-dominated sorting approach, part II:\n% Handling constraints and extending to an adaptive approach, IEEE\n% Transactions on Evolutionary Computation, 2014, 18(4): 602-622.\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 if isempty(obj.M); obj.M = 3; end\n if isempty(obj.D); obj.D = obj.M+4; end\n obj.lower = zeros(1,obj.D);\n obj.upper = ones(1,obj.D);\n obj.encoding = ones(1,obj.D);\n end\n %% Calculate objective values\n function PopObj = CalObj(obj,PopDec)\n g = 100*(obj.D-obj.M+1+sum((PopDec(:,obj.M:end)-0.5).^2-cos(20.*pi.*(PopDec(:,obj.M:end)-0.5)),2));\n PopObj = (1+repmat(g,1,obj.M))/2 - 0.5*repmat(1+g,1,obj.M).*fliplr(cumprod([ones(size(PopDec,1),1),PopDec(:,1:obj.M-1)],2)).*[ones(size(PopDec,1),1),1-PopDec(:,obj.M-1:-1:1)];\n end\n %% Generate points on the Pareto front\n function R = GetOptimum(obj,N)\n R = (1-UniformPoint(N,obj.M))/2;\n end\n %% Generate the image of Pareto front\n function R = GetPF(obj)\n if obj.M == 2\n R = obj.GetOptimum(100);\n elseif obj.M == 3\n a = linspace(0,1,10)';\n R = {(1-a*a')/2,(1-a*(1-a'))/2,(1-(1-a)*ones(size(a')))/2};\n else\n R = [];\n end\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Problems/Multi-objective optimization/DTLZ/IDTLZ1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.4899277944403275}} {"text": "function I=wave_inv_transform(x,ld)\n[m n]=size(x);\n% [ld hd lr hr]=wfilters('sym8');\nt=0:(length(ld)-1);\nhd=ld; hd(end:-1:1)=cos(pi*t).*ld;\nWn=zeros(n);\nWm=zeros(m);\nz=length(ld);\n% l=ld;\n% l(end:-1:1)=ld;\n% ld=l;\nj=1;\nfor i=1:n/2\n \n if j+z-1>n\n a=j+z-1-n;\n Wn(i,1:a)=ld(z-a+1:end);\n Wn(i,j:end)=ld(1:z-a);\n else\n Wn(i,j:j+z-1)=ld;\n end\n j=j+2;\nend\nj=1;\nfor i=n/2+1:n\n \n if j+z-1>n\n a=j+z-1-n;\n Wn(i,1:a)=hd(z-a+1:end);\n Wn(i,j:end)=hd(1:z-a);\n else\n Wn(i,j:j+z-1)=hd;\n end\n j=j+2;\nend\nWn;\nj=1;\nfor i=1:m/2\n \n if j+z-1>m\n a=j+z-1-m;\n Wm(i,1:a)=ld(z-a+1:end);\n Wm(i,j:end)=ld(1:z-a);\n else\n Wm(i,j:j+z-1)=ld;\n end\n j=j+2;\n end\n j=1;\n for i=m/2+1:m\n \n if j+z-1>m\n a=j+z-1-m;\n Wm(i,1:a)=hd(z-a+1:end);\n Wm(i,j:end)=hd(1:z-a);\n else\n Wm(i,j:j+z-1)=hd;\n end\n j=j+2;\n end\n Wm;\nx=double(x);\n c=Wm'*x;\n I=c*Wn;\nend", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u53bb\u566a\u7b97\u6cd5/VideoDenoising-master/matlab files/wave_inv_transform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851918, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.489927792996723}} {"text": "close all; clear all; clc\n\naddpath('apm')\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Configuration\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% number of terms\nny = 2; % output coefficients\nnu = 1; % input coefficients\n% number of inputs\nni = 1;\n% number of outputs\nno = 1;\n% load data and parse into columns\ndata = load('data_step_test.csv');\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% generate time-series model\nsysd = apm_id(data,ni,nu,ny);\n\n% plt.figure(1)\n% plt.subplot(2,1,1)\n% plt.plot(data[:,0],ypred,'r-',LineWidth=2)\n% plt.plot(data[:,0],data[:,2],'b--',LineWidth=2)\n% plt.legend(['Predicted','Measured'],loc='best')\n% plt.ylabel('Temp (K)')\n% \n% plt.subplot(2,1,2)\n% plt.plot(data[:,0],data[:,1],'k-',LineWidth=2)\n% plt.legend(['Heater'],loc='best')\n% plt.ylabel('Heater')\n% plt.show()\n", "meta": {"author": "APMonitor", "repo": "arduino", "sha": "f36e65a70dd7122d1829883899e40e56bf6c4279", "save_path": "github-repos/MATLAB/APMonitor-arduino", "path": "github-repos/MATLAB/APMonitor-arduino/arduino-f36e65a70dd7122d1829883899e40e56bf6c4279/2_Regression/2nd_order_SISO/ARX_APM_MATLAB/empirical_id.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562643, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.48992779058422303}} {"text": "function net = cnnsetup(net, x, y)\n assert(~isOctave() || compare_versions(OCTAVE_VERSION, '3.8.0', '>='), ['Octave 3.8.0 or greater is required for CNNs as there is a bug in convolution in previous versions. See http://savannah.gnu.org/bugs/?39314. Your version is ' myOctaveVersion]);\n inputmaps = 1;\n mapsize = size(squeeze(x(:, :, 1)));\n\n for l = 1 : numel(net.layers) % layer\n if strcmp(net.layers{l}.type, 's')\n mapsize = mapsize / net.layers{l}.scale;\n assert(all(floor(mapsize)==mapsize), ['Layer ' num2str(l) ' size must be integer. Actual: ' num2str(mapsize)]);\n for j = 1 : inputmaps\n net.layers{l}.b{j} = 0;\n end\n end\n if strcmp(net.layers{l}.type, 'c')\n mapsize = mapsize - net.layers{l}.kernelsize + 1;\n fan_out = net.layers{l}.outputmaps * net.layers{l}.kernelsize ^ 2;\n for j = 1 : net.layers{l}.outputmaps % output map\n fan_in = inputmaps * net.layers{l}.kernelsize ^ 2;\n for i = 1 : inputmaps % input map\n net.layers{l}.k{i}{j} = (rand(net.layers{l}.kernelsize) - 0.5) * 2 * sqrt(6 / (fan_in + fan_out));\n end\n net.layers{l}.b{j} = 0;\n end\n inputmaps = net.layers{l}.outputmaps;\n end\n end\n % 'onum' is the number of labels, that's why it is calculated using size(y, 1). If you have 20 labels so the output of the network will be 20 neurons.\n % 'fvnum' is the number of output neurons at the last layer, the layer just before the output layer.\n % 'ffb' is the biases of the output neurons.\n % 'ffW' is the weights between the last layer and the output neurons. Note that the last layer is fully connected to the output layer, that's why the size of the weights is (onum * fvnum)\n fvnum = prod(mapsize) * inputmaps;\n onum = size(y, 1);\n\n net.ffb = zeros(onum, 1);\n net.ffW = (rand(onum, fvnum) - 0.5) * 2 * sqrt(6 / (onum + fvnum));\nend\n", "meta": {"author": "rasmusbergpalm", "repo": "DeepLearnToolbox", "sha": "5df2801f2196a2afddb7a87f800e63e153c34995", "save_path": "github-repos/MATLAB/rasmusbergpalm-DeepLearnToolbox", "path": "github-repos/MATLAB/rasmusbergpalm-DeepLearnToolbox/DeepLearnToolbox-5df2801f2196a2afddb7a87f800e63e153c34995/CNN/cnnsetup.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.4899277905842229}} {"text": "function b_sorted = comp_b_sorted(R, bF)\n\n[~,Rfp,~,Rpp] = seg_R(R);\n\n% Optimized bP\nbP_opt = -Rpp\\Rfp'*bF;\nb_sorted = [bF;bP_opt];\n\n\nend\n\n", "meta": {"author": "yorgoon", "repo": "minimum-snap-geometric-control", "sha": "efbd741223d1b38f5451f3e5ff421cb3dbf7f8ac", "save_path": "github-repos/MATLAB/yorgoon-minimum-snap-geometric-control", "path": "github-repos/MATLAB/yorgoon-minimum-snap-geometric-control/minimum-snap-geometric-control-efbd741223d1b38f5451f3e5ff421cb3dbf7f8ac/poly_optimization/comp_b_sorted.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.4899277876970148}} {"text": "function kernel = calibrate2D(obj, AtA, nCha, coil)\n% retrieve calibration kernel from 2D calibration region\n%\n% (c) Thomas Kuestner \n% ---------------------------------------------------------------------\n\nsampling = ones([obj.kernelSize,nCha],obj.measPara.precision);\n\ndummyK = zeros(obj.kernelSize(1),obj.kernelSize(2),nCha,obj.measPara.precision); \ndummyK((end+1)/2,(end+1)/2,coil) = 1;\nidxY = find(dummyK);\nsampling(idxY) = 0;\nidxA = find(sampling);\n\nAty = AtA(:,idxY); Aty = Aty(idxA); % correlation values to target point, take complete neighbourhood and not just aquired ones\nAtA = AtA(idxA,:); AtA = AtA(:,idxA); % kick out the searched point\n\nkernel = sampling*0;\n\nlambda = norm(AtA,'fro')/size(AtA,1)*obj.calibTyk;\n\ncnd = cond(AtA + eye(size(AtA))*lambda);\nif(cnd == inf)\n rawkernel = pinv(AtA + eye(size(AtA))*lambda)*Aty; % grappa weighting values\nelse\n rawkernel = (AtA + eye(size(AtA))*lambda)\\Aty; % grappa weighting values \nend\nkernel(idxA) = rawkernel; \n\nend", "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/@FOCUSS/calibrate2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.4898816716504239}} {"text": "% rovXYZ 3 x N vectors, inillh 3 x N vectors\n% output 3 x N vectors\nfunction dNED=posdiff_v001(rovXYZ, inillh)\n% for blh2xyz, input N x 3, output N x 3;\nstartXYZ= blh2xyz(inillh');\nstartCen=llh2dcm_v000(inillh(1:2),[0,1]);\ndXYZ = rovXYZ-startXYZ';\ndNED = startCen*dXYZ;", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/ekfmonoslam/geodetic/posdiff_v001.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.48988166755271456}} {"text": "report_this_filefun(mfilename('fullpath'));\n\n\nl=storedcat(:,3) > mati+ 2.5/365 & storedcat(:,3) < mati+ 3/365 + 7/365;\nb=storedcat.subset(l);\n\ncd /home2/stefan/srisk/\n\nload lat\nload lon\nlon = -lon;\n\n\nle = length(lat);\nY0 = zeros(le,1);\n\n\nfor i = 1:length(b)\n di2 = deg2km((distance(lat,lon,repmat(b(i,2),le,1),repmat(b(i,1),le,1))));\n R = di2;\n r = sqrt(R.^2 + 5.57^2);\n M = b(i,6);\n Y = -0.136 + 0.229*(M-6) - 0.778 * log10(r) ;\n Y = 10.^Y;\n c = [Y , Y0];\n mapga = max(c');\n Y0 = mapga';\nend\n\nmapga = mapga';\n\ncd /home2/stefan/srisk/\n\nsave hpga2 mapga -ascii\n\ndo = [' ! /home2/stefan/srisk/myriskobs2 ' num2str(max(mapga)/2.4,2) ' ' num2str(max(mapga)/10,2) ]; eval(do)\n\n% do = [' ! /home2/stefan/srisk/myriskobs 0.04 0.008' ]; eval(do)\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/deleteme/obs_pga.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4898713124822658}} {"text": "% exampleTextureCalc1.m\n%\n% Example script for texture calculation\n%\n% APA, 05/23/2016\n\nglobal planC\n\n%% EXAMPLE 1: Patch-wise texture\nscanNum = 1;\nstructNum = 3;\ndescript = 'CTV texture';\npatchUnit = 'vox'; % or 'cm'\npatchSizeV = [1 1 1];\ncategory = 1; % Haralick texture\ndirctn = 1; % 1: 3d neighbors , 2: 2d neighbors\nnumGrLevels = 16; % 32, 64, 256 etc..\nenergyFlg = 1; % or 0\nentropyFlg = 1; % or 0\nsumAvgFlg = 1; % or 0\nhomogFlg = 1; % or 0\ncontrastFlg = 1; % or 0\ncorrFlg = 1; % or 0\nclustShadFlg = 1; % or 0\nclustPromFlg = 1; % or 0\nharalCorrFlg = 1; % or 0\nflagsV = [energyFlg, entropyFlg, sumAvgFlg, corrFlg, homogFlg, ...\n contrastFlg, clustShadFlg, clustPromFlg, haralCorrFlg];\nplanC = createTextureMaps(scanNum,structNum,descript,...\n patchUnit,patchSizeV,category,dirctn,numGrLevels,flagsV,planC);\n\n\n%% EXAMPLE 2: Texture for the entire structure\nglobal planC\nindexS = planC{end};\nscanNum = 1;\nstructNum = 4;\nnumGrLevels = 16;\ndirctn = 1; % 2: 2d neighbors\ncooccurType = 1; % 2: build separate cooccurrence for each direction\n\n% Quantize the volume of interest\n[rasterSegments, planC, isError] = getRasterSegments(structNum,planC);\n[mask3M, uniqueSlices] = rasterToMask(rasterSegments, scanNum, planC);\nscanArray3M = getScanArray(planC{indexS.scan}(scanNum));\nSUVvals3M = mask3M.*double(scanArray3M(:,:,uniqueSlices));\n[minr, maxr, minc, maxc, mins, maxs]= compute_boundingbox(mask3M);\nmaskBoundingBox3M = mask3M(minr:maxr,minc:maxc,mins:maxs);\nvolToEval = SUVvals3M(minr:maxr,minc:maxc,mins:maxs);\nvolToEval(maskBoundingBox3M==0) = NaN;\nquantizedM = imquantize_cerr(volToEval,numGrLevels);\n\n% Buiild cooccurrence matrix\noffsetsM = getOffsets(dirctn);\ncooccurM = calcCooccur(quantizedM, offsetsM, numGrLevels, cooccurType);\n\n% Reduce cooccurrence matrix to scalar features\nglcmFlagS.energy = 1;\nglcmFlagS.jointEntropy = 1;\nglcmFlagS.jointMax = 1;\nglcmFlagS.jointAvg = 1;\nglcmFlagS.jointVar = 1;\nglcmFlagS.contrast = 1;\nglcmFlagS.invDiffMoment = 1;\nglcmFlagS.sumAvg = 1;\nglcmFlagS.corr = 1;\nglcmFlagS.clustShade = 1;\nglcmFlagS.clustProm = 1;\nglcmFlagS.haralickCorr = 1;\nglcmFlagS.invDiffMomNorm = 1;\nglcmFlagS.invDiff = 1;\nglcmFlagS.invDiffNorm = 1;\nglcmFlagS.invVar = 1;\nglcmFlagS.dissimilarity = 1;\nglcmFlagS.diffEntropy = 1;\nglcmFlagS.diffVar = 1;\nglcmFlagS.diffAvg = 1;\nglcmFlagS.sumVar = 1;\nglcmFlagS.sumEntropy = 1;\nglcmFlagS.clustTendency = 1;\nglcmFlagS.autoCorr = 1;\nglcmFlagS.invDiffMomNorm = 1;\nglcmFlagS.firstInfCorr = 1;\nglcmFlagS.secondInfCorr = 1;\n\nfeatureS = cooccurToScalarFeatures(cooccurM, glcmFlagS);\n\n\n%% Dominant orientation\nglobal planC\nindexS = planC{end};\n\nscanNum = 1;\nstructNum = 6;\npatchSizeV = [3 3 3];\n\n[rasterSegments, planC, isError] = getRasterSegments(structNum,planC);\n[mask3M, uniqueSlices] = rasterToMask(rasterSegments, scanNum, planC);\nscanArray3M = getScanArray(planC{indexS.scan}(scanNum));\n\nSUVvals3M = mask3M.*double(scanArray3M(:,:,uniqueSlices));\n[minr, maxr, minc, maxc, mins, maxs]= compute_boundingbox(mask3M);\nmaskBoundingBox3M = mask3M(minr:maxr,minc:maxc,mins:maxs);\nvolToEval = SUVvals3M(minr:maxr,minc:maxc,mins:maxs);\nvolToEval(maskBoundingBox3M==0) = NaN;\n\n% volToEval = scanArray3M; % for ITK comparison\n\nposition = [400 400 300 50];\nwaitFig = figure('name','Creating Texture Maps','numbertitle','off',...\n 'MenuBar','none','ToolBar','none','position',position);\nwaitAx = axes('parent',waitFig,'position',[0.1 0.3 0.8 0.4],...\n 'nextplot','add','XTick',[],'YTick',[],'yLim',[0 1],'xLim',[0 1]);\nwaitH = patch([0 0 0 0], [0 1 1 0], [0.1 0.9 0.1],...\n 'parent', waitAx);\n\ndomOrient3M = calcDominantOrientation(volToEval, patchSizeV, waitH);\n\nvol3M = zeros(size(volToEval));\nvol3M(:,30:60,5) = 1;\nvol3M(30:62,:,5) = 1;\ndom3M = calcDominantOrientation(vol3M, patchSizeV, waitH);\n\nclose(waitFig)\n\n\n%% Law's texture\nglobal planC\nindexS = planC{end};\n\nscanNum = 1;\nstructNum = 1;\npatchSizeV = [3 3 3];\n\n[rasterSegments, planC, isError] = getRasterSegments(structNum,planC);\n[mask3M, uniqueSlices] = rasterToMask(rasterSegments, scanNum, planC);\nscanArray3M = getScanArray(planC{indexS.scan}(scanNum));\n\nSUVvals3M = mask3M.*double(scanArray3M(:,:,uniqueSlices));\n[minr, maxr, minc, maxc, mins, maxs]= compute_boundingbox(mask3M);\nmaskBoundingBox3M = mask3M(minr:maxr,minc:maxc,mins:maxs);\nvolToEval = SUVvals3M(minr:maxr,minc:maxc,mins:maxs);\n%volToEval(maskBoundingBox3M==0) = NaN;\nvolToEval(maskBoundingBox3M==0) = nanmean(volToEval(:));\nmeanVol = nanmean(volToEval(:));\nif exist('padarray.m','file')\n paddedVolM = padarray(volToEval,[5 5 5],meanVol,'both');\nelse\n paddedVolM = padarray_oct(volToEval,[5 5 5],meanVol,'both');\nend\nlawsMasksS = getLawsMasks();\n\nfieldNamesC = fieldnames(lawsMasksS);\nnumFeatures = length(fieldNamesC);\nfeaturesM = zeros(sum(maskBoundingBox3M(:)),numFeatures);\nfor i = 1:numFeatures \n disp(i)\n text3M = convn(paddedVolM,lawsMasksS.(fieldNamesC{i}),'same');\n text3M = text3M(6:end-5,6:end-5,6:end-5);\n featuresM(:,i) = text3M(maskBoundingBox3M);\nend\n\n% Haralick textures\n\nfeaturesM = zeros(sum(maskBoundingBox3M(:)),0);\nfor patchSiz = 1:3\n \n%patchSizeV = [2 2 2];\npatchSizeV = [patchSiz patchSiz 0];\n\n%numGrLevels = 16;\nfor numGrLevels = [8 16 32]\noffsetsM = getOffsets(2);\n\n[rasterSegments, planC, isError] = getRasterSegments(structNum,planC);\n[mask3M, uniqueSlices] = rasterToMask(rasterSegments, scanNum, planC);\nscanArray3M = getScanArray(planC{indexS.scan}(scanNum));\n\nSUVvals3M = mask3M.*double(scanArray3M(:,:,uniqueSlices));\n[minr, maxr, minc, maxc, mins, maxs]= compute_boundingbox(mask3M);\nmaskBoundingBox3M = mask3M(minr:maxr,minc:maxc,mins:maxs);\nvolToEval = SUVvals3M(minr:maxr,minc:maxc,mins:maxs);\nvolToEval(maskBoundingBox3M==0) = NaN;\n\n% Haralick texture\nenergyFlg = 1; % or 0\nentropyFlg = 1; % or 0\nsumAvgFlg = 1; % or 0\nhomogFlg = 1; % or 0\ncontrastFlg = 1; % or 0\ncorrFlg = 1; % or 0\nclustShadFlg = 1; % or 0\nclustPromFlg = 1; % or 0\nharalCorrFlg = 1; % or 0\nflagsV = [energyFlg, entropyFlg, sumAvgFlg, corrFlg, homogFlg, ...\n contrastFlg, clustShadFlg, clustPromFlg, haralCorrFlg];\nwaitH = NaN;\n[energy3M,entropy3M,sumAvg3M,corr3M,invDiffMom3M,contrast3M, ...\n clustShade3M,clustPromin3M,haralCorr3M] = textureByPatchCombineCooccur(volToEval,...\n numGrLevels,patchSizeV,offsetsM,flagsV,waitH);\n\nfeaturesM(:,end+1) = energy3M(maskBoundingBox3M);\nfeaturesM(:,end+1) = entropy3M(maskBoundingBox3M);\nfeaturesM(:,end+1) = sumAvg3M(maskBoundingBox3M);\nfeaturesM(:,end+1) = corr3M(maskBoundingBox3M);\nfeaturesM(:,end+1) = invDiffMom3M(maskBoundingBox3M);\nfeaturesM(:,end+1) = contrast3M(maskBoundingBox3M);\nfeaturesM(:,end+1) = clustShade3M(maskBoundingBox3M);\nfeaturesM(:,end+1) = clustPromin3M(maskBoundingBox3M);\nfeaturesM(:,end+1) = haralCorr3M(maskBoundingBox3M);\n\nend\nend\n\n\n\n[coeff,score,latVar] = pca(featuresM,'NumComponents',20);\nfigure, plot(cumsum(latVar)./sum(latVar)*100,'linewidth',2)\nxlabel('Number of components','fontsize',20)\nylabel('Explained variance','fontsize',20)\nset(gca,'fontsize',20)\n\nfigure, \nfor i = 1:4\n comp1M = zeros(size(maskBoundingBox3M));\n comp1M(maskBoundingBox3M) = score(:,3);\n comp1M = volToEval; \n subplot(2,2,i), imagesc(comp1M(:,:,i)), title(['slice: ',num2str(i)]) \n axis equal, colormap('gray')\n axis off\nend\n\ncomp1M = NaN*ones(size(maskBoundingBox3M));\ncomp1M(maskBoundingBox3M) = score(:,2);\nfigure, hist(comp1M(:),30)\ntitle('Component 2','fontsize',20)\n\n\n%% Neighborhood Gray Tone Difference Matrix (NGTDM)\nglobal planC\nindexS = planC{end};\n\n% L:\\Ziad\\HUH_from_Maria\\ASTRO_AAPM\\Included_after_AAPM\\mat_cropped\\HUH2\n\nscanNum = 1;\nstructNum = 27;\npatchRadiusV = [1 1 1];\nnumGrLevels = 16;\n\n[rasterSegments, planC, isError] = getRasterSegments(structNum,planC);\n[mask3M, uniqueSlices] = rasterToMask(rasterSegments, scanNum, planC);\nscanArray3M = getScanArray(planC{indexS.scan}(scanNum));\n\nSUVvals3M = mask3M.*double(scanArray3M(:,:,uniqueSlices));\n[minr, maxr, minc, maxc, mins, maxs]= compute_boundingbox(mask3M);\nmaskBoundingBox3M = mask3M(minr:maxr,minc:maxc,mins:maxs);\nvolToEval = SUVvals3M(minr:maxr,minc:maxc,mins:maxs);\nvolToEval(maskBoundingBox3M==0) = NaN;\nquantizedM = imquantize_cerr(volToEval,numGrLevels);\n\nhWait = NaN;\n[s,p] = calcNGTDM(quantizedM,patchRadiusV,numGrLevels,hWait);\n\nif exist('padarray.m','file')\n paddedM = padarray(quantizedM,[1 1 1],0,'both');\n paddedMaskM = padarray(maskBoundingBox3M,[1 1 1],0,'both');\nelse\n paddedM = padarray_oct(quantizedM,[1 1 1],0,'both');\n paddedMaskM = padarray_oct(maskBoundingBox3M,[1 1 1],0,'both');\nend\n[rV,cV,sV] = find3d(paddedMaskM);\nmask_rcs = [rV(:),cV(:),sV(:)];\n[NGTDM,vox_occurances_NGD26] = compute_3D_NGTDM_full_vol(paddedM,numGrLevels,mask_rcs);\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/heterogenity_metrics/exampleTextureCalc1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.6757646075489391, "lm_q1q2_score": 0.4898416857374413}} {"text": "function[] = Param_Space(Cat)\n\n \nrdc= ReasenbergDeclusterClass(Cat, ....\n 'AutoShowPlots',false,'DelayProcessing',true,'InteractiveMode',false);\n\nlTaumin = 1;\nlTaumax = 10;\nlP = .95;\nlXk = .4;\nlXmeff = 3;\nlRfact = 10;\nlErr = 2;\nlDerr = 5;\n\nrdc.taumin = lTaumin;\nrdc.taumax = lTaumax;\nrdc.P = lP;\nrdc.xk = lXk;\nrdc.xmeff = lXmeff;\nrdc.rfact = lRfact;\nrdc.err = lErr;\nrdc.derr = lDerr;\n\n%% loop for P\n\nresFileOut = 'decResP';\nparmFileOut = 'decParmP';\nP_Sim = .8:.01:1;\nnumSim = length(P_Sim);\n\n\nfor simNum = 1:numSim\n rdc.P = P_sim(simNum);\n [declusCat] = rdc.ReasenbergDeclus();\n decResult(simNum) = {declusCat};\n save(resFileOut,'decResult');\n\n monteParms(simNum) = {[rdc.taumin;rdc.taumax;rdc.P;rdc.xk;rdc.xmeff;rdc.rfact;rdc.err;rdc.derr]};\n save(parmFileOut,'monteParms');\n disp(num2str(simNum));\nend\n\nrdc.P = lTauP;\n\n%% loop for Taumin\n\nresFileOut = 'decResTmin';\nparmFileOut = 'decParmTmin';\nT_Sim = .2:.1:5;\nnumSim = length(T_Sim);\n\n\nfor simNum = 1:numSim\n rdc.taumin = T_Sim(simNum);\n [declusCat] = rdc.ReasenbergDeclus();\n decResult(simNum) = {declusCat};\n save(resFileOut,'decResult');\n\n monteParms(simNum) = {[rdc.taumin;rdc.taumax;rdc.P;rdc.xk;rdc.xmeff;rdc.rfact;rdc.err;rdc.derr]};\n save(parmFileOut,'monteParms');\n disp(num2str(simNum));\nend\n\nrdc.taumin = lTaumin;\n\n%% loop for Taumax\n\nresFileOut = 'decResTmax';\nparmFileOut = 'decParmTmax';\nT_Sim = 1:1:20;\nnumSim = length(T_Sim);\n\n\nfor simNum = 1:numSim\n rdc.taumax = T_Sim(simNum);\n [declusCat] = rdc.ReasenbergDeclus();\n decResult(simNum) = {declusCat};\n save(resFileOut,'decResult');\n\n monteParms(simNum) = {[rdc.taumin;rdc.taumax;rdc.P;rdc.xk;rdc.xmeff;rdc.rfact;rdc.err;rdc.derr]};\n save(parmFileOut,'monteParms');\n disp(num2str(simNum));\nend\nrdc.taumax = lTaumax;\n\n%% loop for rFact\n\nresFileOut = 'decRes_rFact';\nparmFileOut = 'decParm_rFact';\nR_Sim = 0:1:40;\nnumSim = length(R_Sim);\n\n\nfor simNum = 1:numSim\n rdc.rfact = R_Sim(simNum);\n [declusCat] = rdc.ReasenbergDeclus();\n decResult(simNum) = {declusCat};\n save(resFileOut,'decResult');\n\n monteParms(simNum) = {[rdc.taumin;rdc.taumax;rdc.P;rdc.xk;rdc.xmeff;rdc.rfact;rdc.err;rdc.derr]};\n save(parmFileOut,'monteParms');\n disp(num2str(simNum));\nend\n\n%% loop for xK\n\nresFileOut = 'decRes_xk';\nparmFileOut = 'decParm_xk';\nXk_Sim = 0:.1:1;\nnumSim = length(Xk_Sim);\n\n\nfor simNum = 1:numSim\n rdc.xk = Xk_Sim(simNum);\n [declusCat] = rdc.ReasenbergDeclus();\n decResult(simNum) = {declusCat};\n save(resFileOut,'decResult');\n\n monteParms(simNum) = {[rdc.taumin;rdc.taumax;rdc.P;rdc.xk;rdc.xmeff;rdc.rfact;rdc.err;rdc.derr]};\n save(parmFileOut,'monteParms');\n disp(num2str(simNum));\nend\n\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/thomas/decluster/reasen/Param_Space.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.6757646140788308, "lm_q1q2_score": 0.4898416824378476}} {"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 [y, extra, invhess] = glmevfwd(net, x, t, x_test, invhess)\n%GLMEVFWD Forward propagation with evidence for GLM\n%\n%\tDescription\n%\tY = GLMEVFWD(NET, X, T, X_TEST) takes a network data structure NET\n%\ttogether with the input X and target T training data and input test\n%\tdata X_TEST. It returns the normal forward propagation through the\n%\tnetwork Y together with a matrix EXTRA which consists of error bars\n%\t(variance) for a regression problem or moderated outputs for a\n%\tclassification problem.\n%\n%\tThe optional argument (and return value) INVHESS is the inverse of\n%\tthe network Hessian computed on the training data inputs and targets.\n%\tPassing it in avoids recomputing it, which can be a significant\n%\tsaving for large training sets.\n%\n%\tSee also\n%\tFEVBAYES\n%\n\n%\tCopyright (c) Ian T Nabney (1996-2001)\n\n[y, a] = glmfwd(net, x_test);\nif nargin == 4\n [extra, invhess] = fevbayes(net, y, a, x, t, x_test);\nelse\n [extra, invhess] = fevbayes(net, y, a, x, t, x_test, invhess);\nend\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/netlab3.3/glmevfwd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.4898270583875157}} {"text": "function [spectogram_y_lims, s, f] = cutSpectogramFrequency(s,f, handles)\n\n upper_freq = find(f>=handles.data.settings.HighFreq*1000,1);\n if isempty(upper_freq)\n upper_freq = length(f);\n end\n lower_freq = find(f>=handles.data.settings.LowFreq*1000,1);\n\n % Extract the region within the frequency range\n f = f(lower_freq:upper_freq,:); \n s = s(lower_freq:upper_freq,:); \n spectogram_y_lims = [ min(f), max(f)];\nend\n\n", "meta": {"author": "DrCoffey", "repo": "DeepSqueak", "sha": "c62f2c7bb86a9d77ae177248abe7d234857edf53", "save_path": "github-repos/MATLAB/DrCoffey-DeepSqueak", "path": "github-repos/MATLAB/DrCoffey-DeepSqueak/DeepSqueak-c62f2c7bb86a9d77ae177248abe7d234857edf53/Functions/cutSpectogramFrequency.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.4898270503592005}} {"text": "function [IDX, maxIdxArray] = Cluster(data, MinPts, epsilon, PtsNumThr, IS_SHOW)\nif size(data, 2) ~= 2\n data = data';\nend\nif size(data, 2) ~= 2\n error('Input for Cluster() is wrong!');\nend\nIDX = [];\nmaxIdxArray = [];\nif nargin == 4\n IS_SHOW = 0;\nend\nif size(data, 1) < PtsNumThr %%%%%% too few points!\n return;\nend\n[ IDX, isNoise] =DBSCAN(data,epsilon,MinPts);\nif IS_SHOW\n figure;\n hold on; \n box on; \n xlabel('X(meter)'); \n ylabel('Y(meter)'); \n PlotClusterinResult(data, IDX);\n title(['DBSCAN Clustering (\\epsilon = ' num2str(epsilon) ', MinPts = ' num2str(MinPts) ')']);\nend\nScanData = CalScanData(IDX);\nif isempty(ScanData)\n IDX = []; \n maxIdxArray = []; \n return; \nend\n[maxVal, idxOrder]= max(ScanData(2, :));\nif maxVal < PtsNumThr\n return;\nend\nmaxIdxArray = find(IDX == ScanData(1, idxOrder));\nend\n\n", "meta": {"author": "DrGabor", "repo": "LiDAR", "sha": "707ca635db955cf00d833578ad1236f0790cdf98", "save_path": "github-repos/MATLAB/DrGabor-LiDAR", "path": "github-repos/MATLAB/DrGabor-LiDAR/LiDAR-707ca635db955cf00d833578ad1236f0790cdf98/iGPR/Cluster.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754471, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.48982705035920043}} {"text": "function F = coeffs2spherefunv( X, Y, Z )\n%COEFFS2SPHEREFUNV Convert componentwise matrices of 2D Fourier \n% coefficients to a spherefunv. \n% \n% F = coeffs2spherefunv( X, Y, Z ) returns a spherefunv object F that has \n% matrices of 2D Fourier coefficients X, Y, and Z for each component. \n% \n% See also SPHEREFUN/COEFFS2SPHEREFUN \n\n% Copyright 2019 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nU = spherefun.coeffs2spherefun(X); \nV = spherefun.coeffs2spherefun(Y); \nW = spherefun.coeffs2spherefun(Z); \nF = spherefunv(U, V, W); \nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@spherefunv/coeffs2spherefunv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.4898270431189679}} {"text": "function [xyTV,xyLV,xyBV,xyRV] = dividePolygon(xV,yV,xc,yc)\n% function [xyTV,xyLV,xyBV,xyRV] = dividePolygon(xV,yV,xc,yc)\n%\n% This function divides the passed polygon into Top, Left, Bottom and Right\n% parts.\n%\n% APA, 08/23/2012\n\n\n%xV = planC{indexS.structures}(2).contour(71).segments.points(:,1);\n%yV = planC{indexS.structures}(2).contour(71).segments.points(:,2);\n\nif nargin < 3\n xc = mean(xV);\n yc = mean(yV);\nend\ntheta1 = 45*pi/180;\nx1 = xc+100*cos(theta1);\ny1 = yc+100*sin(theta1);\ntheta2 = 135*pi/180;\nx2 = xc+100*cos(theta2);\ny2 = yc+100*sin(theta2);\n\n% Get 45 degree cut\nxyTLV = cutpolygon([xV(:) yV(:)], [[xc; x1],[yc;y1]], 'B');\nxyBRV = cutpolygon([xV(:) yV(:)], [[xc; x1],[yc;y1]], 'T');\n\n% Top part\nxyTV = cutpolygon([xyTLV(:,1) xyTLV(:,2)], [[xc; x2],[yc;y2]], 'B');\n\n% Left part\nxyLV = cutpolygon([xyTLV(:,1) xyTLV(:,2)], [[xc; x2],[yc;y2]], 'T');\n\n% Bottom part\nxyBV = cutpolygon([xyBRV(:,1) xyBRV(:,2)], [[xc; x2],[yc;y2]], 'T');\n\n% Right part\nxyRV = cutpolygon([xyBRV(:,1) xyBRV(:,2)], [[xc; x2],[yc;y2]], 'B');\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Utilities/dividePolygon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.4898270409682509}} {"text": "function cCell = cqtSparse2Cell(cSparse,M,cDC,cNyq)\n\nbins = size(M,1)/2 - 1;\ncCell = cell(1,bins+2);\ncCell{bins+2} = cNyq;\n\nM = M(1:bins+1);\nstep = 1;\ncSparse = full(cSparse);\ndistinctHops = log2(M(bins+1)/M(2))+1;\ncurNumCoef = M(bins+1);\n\nfor ii=1:distinctHops\n idx = (M == curNumCoef); \n temp = cSparse(idx,1:step:end).';\n temp = num2cell(temp,1);\n cCell(idx) = temp;\n step = step*2;\n curNumCoef = curNumCoef / 2;\nend\n\ncCell{1} = cDC;", "meta": {"author": "nesl", "repo": "asvspoof2019", "sha": "8b780369f7273345c22d979192119198bbf3db13", "save_path": "github-repos/MATLAB/nesl-asvspoof2019", "path": "github-repos/MATLAB/nesl-asvspoof2019/asvspoof2019-8b780369f7273345c22d979192119198bbf3db13/baseline/CQCC_v1.0/CQT_toolbox_2013/cqtSparse2Cell.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.4898270380294519}} {"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": "function F = fit_metric_field(DiffDir, arange,brange, Q)\n\n% fit_metric_field - fit a field of tensor\n%\n% F = fit_metric_field(DiffDir, arange,brange, Q);\n%\n% F is a (Q,Q,2,2) field of 2x2 SDP matrices.\n% DiffDir(x,h) is the directional value of the metric at x in direction h. \n%\n% Copyright (c) 2014 Gabriel Peyre\n\n\nF = zeros(Q,Q,2,2);\nalist = linspace(arange(1), arange(2), Q);\nblist = linspace(brange(1), brange(2), Q);\nfor i=1:Q\n % progressbar(i,Q);\n for j=1:Q \n ab = [alist(i) blist(j)];\n M = fit_metric(@(h)DiffDir(ab,h));\n F(i,j,:,:) = reshape(M, [1 1 2 2]);\n end\nend\n\nend", "meta": {"author": "gpeyre", "repo": "2015-SIGGRAPH-convolutional-ot", "sha": "484b83c5ee396f3d998f67ed35652249b5e29e81", "save_path": "github-repos/MATLAB/gpeyre-2015-SIGGRAPH-convolutional-ot", "path": "github-repos/MATLAB/gpeyre-2015-SIGGRAPH-convolutional-ot/2015-SIGGRAPH-convolutional-ot-484b83c5ee396f3d998f67ed35652249b5e29e81/code/colors_functions/fit_metric_field.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.48955300967576076}} {"text": "function out = riverplot_line(x, y, color, thickness, steepness, varargin)\n% out = riverplot_line(x, y, color, thickness, steepness, varargin)\n%\n% Draw sigmoidal line from 2-coord point x to 2-coord point y\n% x = [xcoord ycoord] for left-hand point\n% y = [xcoord ycoord] for right-hand point\n%\n% x = rect1.topright\n% y = rect2.topleft\n\n% Programmers' notes:\n% 8/21/2017 Stephan Geuter\n% changed steepnes treatment computation. Steepness coefficient is now used\n% in sigmoid function to control steepnes and curvature at tangets (box\n% edges). shift in xstartpoints is removed. Makes ribbons smoother.\n%\n%\n\n\n% x, y inputs can be [x,y,z] coordinate triplets or clusters.\nif isstruct(x), x = x.mm_center(1:2); end\nif isstruct(y), y = y.mm_center(1:2); end\n\n% make middle points with sigmoid function\n\nxdiff = y(1) - x(1); % difference in x position\nydiff = y(2) - x(2);\n\n% xstartpoints = [x(1) + xdiff * steepness(1) y(1) - xdiff * steepness(1)]';\nxstartpoints = [x(1) y(1)]';\n\n\n% sigmoid reference curve\n% sigmoid = inline('p(1) .* ( 1 ./ (1 + p(2)*exp(-p(3)*x)) )','p','x');\nsigmoid = @(p,x) (p(1) .* ( 1 ./ (1 + p(2)*exp(-p(3)*x)) ));\nxx = linspace(-5, 5, 50); % generate 50 points with standard sigmoid \n% % Range determines steepness bounds, larger range\n% = more steep\nyy = sigmoid([1 1 1+steepness(1)], xx)'; % add steepness coefficient to have ribbons meet the box edges\n\n\nxmidpoints = linspace(xstartpoints(1), xstartpoints(end), 50)';\nymidpoints = x(2) + yy * ydiff;\n\nxcoords = [x(1); xstartpoints(1); xmidpoints; xstartpoints(end); y(1)];\nycoords = [x(2); x(2); ymidpoints; y(2); y(2)];\n\n% % make x, y bend percents\n% if length(steepness) == 1\n% steepness = repmat(steepness, 1, 2);\n% end\n% \n% % make 4 coords, adding 2 middle points, so we can bend\n% xdiff = y(1) - x(1); % difference in x position\n% xmidpoints = [x(1) + xdiff * steepness(1) x(1) + xdiff * .5 y(1) - xdiff * steepness(1)]';\n% \n% xcoords = [x(1); xmidpoints; y(1)];\n% \n% ydiff = (y(2) - x(2)) ./ 2;\n% ycoords = [x(2); x(2); x(2) + ydiff; y(2); y(2)];\n\n% plot(xcoords, ycoords, 'go');\n% \n% if any(steepness)\n% \n% %[p,sse,fit] = nonlin_fit(ycoords, xcoords - mean(xcoords), 'start',[1 1 1]);\n% \n% sigmoid = inline('p(1) .* ( 1 ./ (1 + p(2)*exp(-p(3)*x)) )','p','x');\n% xcoords2 = linspace(xcoords(1), xcoords(end), 100); \n% \n% ycoords2 = sigmoid([1 1 1], xcoords2 - mean(xcoords2));\n% ycoords2 = ycoords(1) + ydiff * ycoords2;\n% \n% plot(xcoords2, ycoords2, 'rx');\n\n% % bow out: curved line\n% n = length(xcoords);\n% \n% nsamples = [];\n% if length(varargin) > 0\n% nsamples = varargin{1};\n% end\n% \n% if isempty(nsamples)\n% nsamples = 10 * n;\n% end\n% \n% t = 1:n;\n% ts = 1:((n-1)/(nsamples-1)):n; % spline grid\n% \n% xcoords = spline(t, xcoords, ts);\n% ycoords = spline(t, ycoords, ts);\n% \n% end\n\n h = plot(xcoords, ycoords,'Color',color,'LineWidth',thickness);\n\n out.h = h;\n out.xcoords = xcoords;\n out.ycoords = ycoords;\n\nend % function", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Visualization_functions/riverplot/riverplot_line.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.48955300967576076}} {"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/\u53bb\u566a\u7b97\u6cd5/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 output=SSMultibandKamath02(signal,fs,IS)\n\n% OUTPUT=SSMULTIBANDKAMATH02(S,FS,IS)\n% Multi-band Spectral subtraction [Kamath2002]\n% subtraction with adjusting subtraction factor. the adjustment is\n% according to local a postriori SNR and the frequency band.\n% S is the noisy signal, FS is the sampling frequency and IS is the initial\n% silence (noise only) length in seconds (default value is .25 sec)\n%\n% April-04\n% Esfandiar Zavarehei\n\nif (nargin<3 | isstruct(IS))\n IS=.25; %seconds\nend\nW=fix(.025*fs); %Window length is 25 ms\nnfft=W;\nSP=.4; %Shift percentage is 40% (10ms) %Overlap-Add method works good with this value(.4)\nwnd=hamming(W);\n\n% IGNORE THIS SECTION FOR CAMPATIBALITY WITH ANOTHER PROGRAM FROM HERE.....\nif (nargin>=3 & isstruct(IS))%This option is for compatibility with another programme\n W=IS.windowsize\n SP=IS.shiftsize/W;\n nfft=IS.nfft;\n wnd=IS.window;\n if isfield(IS,'IS')\n IS=IS.IS;\n else\n IS=.25;\n end\nend\n% .......IGNORE THIS SECTION FOR CAMPATIBALITY WITH ANOTHER PROGRAM T0 HERE\n\nNIS=fix((IS*fs-W)/(SP*W) +1);%number of initial silence segments\nGamma=2;%Magnitude Power (1 for magnitude spectral subtraction 2 for power spectrum subtraction)\n\ny=segment(signal,W,SP,wnd);\nY=fft(y,nfft);\nYPhase=angle(Y(1:fix(end/2)+1,:)); %Noisy Speech Phase\nY=abs(Y(1:fix(end/2)+1,:)).^Gamma;%Specrogram\nnumberOfFrames=size(Y,2);\nFreqResol=size(Y,1);\n\nN=mean(Y(:,1:NIS)')'; %initial Noise Power Spectrum mean\n\nNoiseCounter=0;\nNoiseLength=9;%This is a smoothing factor for the noise updating\n\nBeta=.03;\nminalpha=1;\nmaxalpha=5;\nminSNR=-5;\nmaxSNR=20;\nalphaSlope=(minalpha-maxalpha)/(maxSNR-minSNR);\nalphaShift=maxalpha-alphaSlope*minSNR;\n\nBN=Beta*N;\n\n%Delta is a frequency dependent coefficient\nDelta=1.5*ones(size(BN));\nDelta(1:fix((-2000+fs/2)*FreqResol*2/fs))=2.5; %if the frequency is lower than FS/2 - 2KHz\nDelta(1:fix(1000*FreqResol*2/fs))=1; %if the frequency is lower than 1KHz\n\n\nfor i=1:numberOfFrames\n [NoiseFlag, SpeechFlag, NoiseCounter, Dist]=vad(Y(:,i).^(1/Gamma),N.^(1/Gamma),NoiseCounter); %Magnitude Spectrum Distance VAD\n if SpeechFlag==0\n N=(NoiseLength*N+Y(:,i))/(NoiseLength+1); %Update and smooth noise\n BN=Beta*N;\n end\n \n SNR=10*log(Y(:,i)./N);\n alpha=alphaSlope*SNR+alphaShift;\n alpha=max(min(alpha,maxalpha),minalpha);\n \n D=Y(:,i)-(Delta.*alpha.*N); %Nonlinear (Non-uniform) Power Specrum Subtraction\n \n X(:,i)=max(D,BN); %if BY>D X=BY else X=D which sets very small values of subtraction result to an attenuated \n %version of the input power spectrum.\nend\n\noutput=OverlapAdd2(X.^(1/Gamma),YPhase,W,SP*W);\n\n\n\nfunction ReconstructedSignal=OverlapAdd2(XNEW,yphase,windowLen,ShiftLen);\n\n%Y=OverlapAdd(X,A,W,S);\n%Y is the signal reconstructed signal from its spectrogram. X is a matrix\n%with each column being the fft of a segment of signal. A is the phase\n%angle of the spectrum which should have the same dimension as X. if it is\n%not given the phase angle of X is used which in the case of real values is\n%zero (assuming that its the magnitude). W is the window length of time\n%domain segments if not given the length is assumed to be twice as long as\n%fft window length. S is the shift length of the segmentation process ( for\n%example in the case of non overlapping signals it is equal to W and in the\n%case of %50 overlap is equal to W/2. if not givven W/2 is used. Y is the\n%reconstructed time domain signal.\n%Sep-04\n%Esfandiar Zavarehei\n\nif nargin<2\n yphase=angle(XNEW);\nend\nif nargin<3\n windowLen=size(XNEW,1)*2;\nend\nif nargin<4\n ShiftLen=windowLen/2;\nend\nif fix(ShiftLen)~=ShiftLen\n ShiftLen=fix(ShiftLen);\n disp('The shift length have to be an integer as it is the number of samples.')\n disp(['shift length is fixed to ' num2str(ShiftLen)])\nend\n\n[FreqRes FrameNum]=size(XNEW);\n\nSpec=XNEW.*exp(j*yphase);\n\nif mod(windowLen,2) %if FreqResol is odd\n Spec=[Spec;flipud(conj(Spec(2:end,:)))];\nelse\n Spec=[Spec;flipud(conj(Spec(2:end-1,:)))];\nend\nsig=zeros((FrameNum-1)*ShiftLen+windowLen,1);\nweight=sig;\nfor i=1:FrameNum\n start=(i-1)*ShiftLen+1;\n spec=Spec(:,i);\n sig(start:start+windowLen-1)=sig(start:start+windowLen-1)+real(ifft(spec,windowLen));\nend\nReconstructedSignal=sig;\n\nfunction [NoiseFlag, SpeechFlag, NoiseCounter, Dist]=vad(signal,noise,NoiseCounter,NoiseMargin,Hangover)\n\n%[NOISEFLAG, SPEECHFLAG, NOISECOUNTER, DIST]=vad(SIGNAL,NOISE,NOISECOUNTER,NOISEMARGIN,HANGOVER)\n%Spectral Distance Voice Activity Detector\n%SIGNAL is the the current frames magnitude spectrum which is to labeld as\n%noise or speech, NOISE is noise magnitude spectrum template (estimation),\n%NOISECOUNTER is the number of imediate previous noise frames, NOISEMARGIN\n%(default 3)is the spectral distance threshold. HANGOVER ( default 8 )is\n%the number of noise segments after which the SPEECHFLAG is reset (goes to\n%zero). NOISEFLAG is set to one if the the segment is labeld as noise\n%NOISECOUNTER returns the number of previous noise segments, this value is\n%reset (to zero) whenever a speech segment is detected. DIST is the\n%spectral distance. \n%Saeed Vaseghi\n%edited by Esfandiar Zavarehei\n%Sep-04\n\nif nargin<4\n NoiseMargin=3;\nend\nif nargin<5\n Hangover=8;\nend\nif nargin<3\n NoiseCounter=0;\nend\n \nFreqResol=length(signal);\n\nSpectralDist= 20*(log10(signal)-log10(noise));\nSpectralDist(find(SpectralDist<0))=0;\n\nDist=mean(SpectralDist); \nif (Dist < NoiseMargin) \n NoiseFlag=1; \n NoiseCounter=NoiseCounter+1;\nelse\n NoiseFlag=0;\n NoiseCounter=0;\nend\n\n% Detect noise only periods and attenuate the signal \nif (NoiseCounter > Hangover) \n SpeechFlag=0; \nelse \n SpeechFlag=1; \nend \n\nfunction Seg=segment(signal,W,SP,Window)\n\n% SEGMENT chops a signal to overlapping windowed segments\n% A= SEGMENT(X,W,SP,WIN) returns a matrix which its columns are segmented\n% and windowed frames of the input one dimentional signal, X. W is the\n% number of samples per window, default value W=256. SP is the shift\n% percentage, default value SP=0.4. WIN is the window that is multiplied by\n% each segment and its length should be W. the default window is hamming\n% window.\n% 06-Sep-04\n% Esfandiar Zavarehei\n\nif nargin<3\n SP=.4;\nend\nif nargin<2\n W=256;\nend\nif nargin<4\n Window=hamming(W);\nend\nWindow=Window(:); %make it a column vector\n\nL=length(signal);\nSP=fix(W.*SP);\nN=fix((L-W)/SP +1); %number of segments\n\nIndex=(repmat(1:W,N,1)+repmat((0:(N-1))'*SP,1,W))';\nhw=repmat(Window,1,N);\nSeg=signal(Index).*hw;\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/7674-multi-band-spectral-subtraction/SSMultibandKamath02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079208, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.48952866205771395}} {"text": "% NTF | bcuNCP | Non-negative CP Decomposition by block-coordinate update (Xu and Yin, 2012)\n% process_video('NTF', 'bcuNCP', 'dataset/demo.avi', 'output/bcuNCP.avi');\n\n% Compute a simple NTF model of 10 components\nA = double(T);\nR = 10; % tensor rank\nopts.maxit = 1000; % max number of iterations\nopts.tol = 1e-4; % stopping tolerance\nM = ncp(T,R,opts);\nL = double(full(M));\nS = (A - L);\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/ntf/bcuNCP/run_alg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.48952865624226916}} {"text": "function plotValdata(valdata, fignum)\n\n\ncthresh = (0.001:0.001:0.5);\nerr = zeros(size(cthresh));\nnregions = zeros(size(cthresh));\nfor f = 1:numel(valdata)\n for k = 1:numel(cthresh)\n [tmp, minind] = min(abs(valdata(f).mergeCost-cthresh(k)));\n err(k) = err(k) + valdata(f).segError(minind)/numel(valdata);\n nregions(k) = nregions(k) + valdata(f).nregions(minind)/numel(valdata);\n end\nend\nfigure(fignum), subplot(2,2,1), hold off, plot(cthresh, err), title('bias vs. err')\nfigure(fignum), subplot(2,2,2), plot(err, nregions), title('conf: err vs. nregions')\n\nrthresh = (5:5:1000);\nerr = zeros(size(rthresh));\nnregions = zeros(size(rthresh));\nfor f = 1:numel(valdata)\n for k = 1:numel(rthresh)\n [tmp, minind] = min(abs(valdata(f).nregions-rthresh(k)));\n err(k) = err(k) + valdata(f).segError(minind)/numel(valdata);\n nregions(k) = nregions(k) + valdata(f).nregions(minind)/numel(valdata);\n end\nend\nfigure(fignum), subplot(2,2,3), plot(rthresh, err), title('minregion vs. err')\nfigure(fignum), subplot(2,2,4), plot(err, nregions), title('minreg: err vs. nregions')", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/src/iccv07Final/src/display/plotValdata.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.48952865624226916}} {"text": "function [fhat,xhat,fcount,retcode] = csminit(fcn,x0,f0,g0,badg,H0,varargin)\n% [fhat,xhat,fcount,retcode] = csminit(fcn,x0,f0,g0,badg,H0,...\n% P1,P2,P3,P4,P5,P6,P7,P8)\n% retcodes: 0, normal step. 5, largest step still improves too fast.\n% 4,2 back and forth adjustment of stepsize didn't finish. 3, smallest\n% stepsize still improves too slow. 6, no improvement found. 1, zero\n% gradient.\n%---------------------\n% Modified 7/22/96 to omit variable-length P list, for efficiency and compilation.\n% Places where the number of P's need to be altered or the code could be returned to\n% its old form are marked with ARGLIST comments.\n%\n% Fixed 7/17/93 to use inverse-hessian instead of hessian itself in bfgs\n% update.\n%\n% Fixed 7/19/93 to flip eigenvalues of H to get better performance when\n% it's not psd.\n%\n%tailstr = ')';\n%for i=nargin-6:-1:1\n% tailstr=[ ',P' num2str(i) tailstr];\n%end\n%ANGLE = .03;\nANGLE = .005;\n%THETA = .03;\nTHETA = .3; %(0 1e12\n % disp('Bad, small gradient problem.')\n % dx = dx*FCHANGE/dxnorm;\n % end\n %else\n % Gauss-Newton step;\n %---------- Start of 7/19/93 mod ---------------\n %[v d] = eig(H0);\n %toc\n %d=max(1e-10,abs(diag(d)));\n %d=abs(diag(d));\n %dx = -(v.*(ones(size(v,1),1)*d'))*(v'*g);\n% toc\n dx = -H0*g;\n% toc\n dxnorm = norm(dx);\n if dxnorm > 1e12\n disp('Near-singular H problem.')\n dx = dx*FCHANGE/dxnorm;\n end\n dfhat = dx'*g0;\n %end\n %\n %\n if ~badg\n % test for alignment of dx with gradient and fix if necessary\n a = -dfhat/(gnorm*dxnorm);\n if a1\n dxtest=x0+dx'*lambda;\n else\n dxtest=x0+dx*lambda;\n end\n % home\n f = feval(fcn,dxtest,varargin{:});\n %ARGLIST\n %f = feval(fcn,dxtest,P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12,P13);\n % f = feval(fcn,x0+dx*lambda,P1,P2,P3,P4,P5,P6,P7,P8);\n disp(sprintf('lambda = %10.5g; f = %20.7f',lambda,f ))\n %debug\n %disp(sprintf('Improvement too great? f0-f: %g, criterion: %g',f0-f,-(1-THETA)*dfhat*lambda))\n if f 0) & (f0-f > -(1-THETA)*dfhat*lambda) );\n if shrinkSignal & ( (lambda>lambdaPeak) | (lambda<0) )\n if (lambda>0) & ((~shrink) | (lambda/factor <= lambdaPeak))\n shrink=1;\n factor=factor^.6;\n while lambda/factor <= lambdaPeak\n factor=factor^.6;\n end\n %if (abs(lambda)*(factor-1)*dxnorm < MINDX) | (abs(lambda)*(factor-1) < MINLAMB)\n if abs(factor-1)lambdaPeak)\n lambdaMax=lambda;\n end\n lambda=lambda/factor;\n if abs(lambda) < MINLAMB\n if (lambda > 0) & (f0 <= fhat)\n % try going against gradient, which may be inaccurate\n lambda = -lambda*factor^6\n else\n if lambda < 0\n retcode = 6;\n else\n retcode = 3;\n end\n done = 1;\n end\n end\n elseif (growSignal & lambda>0) | (shrinkSignal & ((lambda <= lambdaPeak) & (lambda>0)))\n if shrink\n shrink=0;\n factor = factor^.6;\n %if ( abs(lambda)*(factor-1)*dxnorm< MINDX ) | ( abs(lambda)*(factor-1)< MINLAMB)\n if abs(factor-1)0)\n fPeak=f;\n lambdaPeak=lambda;\n if lambdaMax<=lambdaPeak\n lambdaMax=lambdaPeak*factor*factor;\n end\n end\n lambda=lambda*factor;\n if abs(lambda) > 1e20;\n retcode = 5;\n done =1;\n end\n else\n done=1;\n if factor < 1.2\n retcode=7;\n else\n retcode=0;\n end\n end\n end\nend\ndisp(sprintf('Norm of dx %10.5g', dxnorm))\n", "meta": {"author": "naffe15", "repo": "BVAR_", "sha": "4c935f440a2e98475ead4f873ebdfd03378a0eee", "save_path": "github-repos/MATLAB/naffe15-BVAR_", "path": "github-repos/MATLAB/naffe15-BVAR_/BVAR_-4c935f440a2e98475ead4f873ebdfd03378a0eee/cmintools/csminit.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": "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 [collapsed peakidx] = hlp_collapseFrequencies(data,collapsefun,freqidx,tindex,fspacing)\n%\n% Collapse matrix across frequencies. If tindex is provided, then collapse\n% across frequencies for the given timeindex.\n%\n% Input:\n% data: col vector or matrix of dimension [nfreqs ntimes].\n% If matrix, collapse separately for each timepoint\n%\n% collapsefun: The method to use for collapsing across frequencies\n% none: no collapse\n% integrate: numerical integration using trapz\n% mean: average\n% max: maximum\n% absmax: maximum of absolute value\n% peak: 1-dimensional peak. Returns 0 if no\n% peak is found\n%\n% freqidx: (opt) vector of frequency indices to collapse across\n% If empty or omitted, use all freqs\n%\n% ttindex: (opt) vector of timepoint(s) or single timepoint\n% If empty or omitted, use all times\n%\n% fspacing: (opt) Frequency spacing for integration. Default: 1\n%\n% Out:\n% collapsed: Row vector or single containing collapsed data for\n% each time point\n%\n% peakidx: If peak or max is used, return frequency index of\n% peak location\n%\n% References:\n%\n% [1] Mullen T (2010) The Source Information Flow Toolbox (SIFT):\n% Theoretical Handbook and User Manual.\n% Available at: http://www.sccn.ucsd.edu/wiki/Sift/\n% \n% \n% Author: Tim Mullen 2010, SCCN/INC, UCSD. \n% Email: tim@sccn.ucsd.edu\n\n% This function is part of the Source Information Flow Toolbox (SIFT)\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n% handle defaults\nif nargin < 5\n fspacing = 1; end\nif nargin < 4\n tindex = []; end\nif nargin < 3\n freqidx = []; end\n\npeakidx = [];\n\nsz = size(data);\nif length(sz)>2\n error('data cannot have more than 2 dimensions');\nend\n\nif isempty(freqidx)\n freqidx = 1:sz(1); end\nif isempty(tindex)\n tindex = 1:sz(2); end\n\n% select the desired data range\ndata = data(freqidx,tindex);\nsz = size(data);\n\nif all(sz==1)\n collapsed = data;\n return;\nend\n\n% ensure we have a column vector (we always collapse for each col)\nif any(sz==1), data = data(:); end\n\nswitch lower(collapsefun)\n case 'none'\n collapsed = data;\n case 'integrate'\n collapsed = trapz(data)*fspacing;\n case 'mean' \n collapsed = mean(data);\n case 'max'\n [collapsed peakidx] = max(data);\n case 'peak'\n w = warning;\n warning('off','all');\n collapsed = zeros(1,size(data,2));\n peakidx = nan(size(collapsed));\n for t=1:size(data,2)\n val = [];\n try, [val idx] = findpeaks(data(:,t),'npeaks',1); catch, end\n \n if isempty(val)\n collapsed(t) = 0;\n peakidx(t) = nan;\n else\n collapsed(t) = val;\n peakidx(t) = idx;\n end\n end\n warning(w);\n case 'absmax'\n [collapsed peakidx] = max(abs(data));\n case 'minmax'\n [collapsed peakidx] = max(abs(data));\n for k=1:size(peakidx,2)\n collapsed(k) = data(peakidx(k),k); \n end\nend\n\nif isempty(collapsed)\n collapsed = 0;\n peakidx = nan;\nend\n\n\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/hlp/hlp_collapseFrequencies.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.48952371921127097}} {"text": "function Problem = ITERmake_CON_MAT(Problem, Constraints, Objectives, Spec)\n\ndisp(' ')\nnxny = input('Number of instances of swept variables [7]: ');\nif isempty(nxny); nxny = 7; end\nnxny = round(nxny);\nif nxny < 3; return; end\ndisp(' ')\n\ntic;\nnPPreqs = Spec.nPPrequirements;\nConstraints.current_active_cons = Constraints.active_cons(1:nPPreqs);\nif length(Constraints.active_cons)>nPPreqs\n Constraints.current_active_nonlcons = Constraints.active_cons(nPPreqs+1:end);\n Constraints.activeNonLLabels = Constraints.conLabels(nPPreqs+1:end);\n Constraints.activeNonLLabels = Constraints.activeNonLLabels(Constraints.current_active_nonlcons);\nelse\n Constraints.current_active_nonlcons = [];\n Constraints.activeNonLLabels = [];\nend\n\nConstraints.activePPLabels = Constraints.conLabels(1:nPPreqs);\nConstraints.activePPLabels = Constraints.activePPLabels(Constraints.current_active_cons);\n\nConstraints.nactiveMar = nnz(Constraints.current_active_cons);\nConstraints.nactivenonL = nnz(Constraints.current_active_nonlcons);\n\nConstraints.colors = [0 0 1\n 0 1 0\n 1 0 0\n 0 1 1\n 1 0 1];\nwhile length(Constraints.colors) ii %make a carpet plot and store it\n action = ['Generating plot ' XLabels{ii} ' versus ' XLabels{jj} '...'];\n disp(action);\n [Matrix(ii,jj).X,Matrix(ii,jj).Y,Matrix(ii,jj).ObjStack,...\n Matrix(ii,jj).MarStack,Matrix(ii,jj).feasible,...\n Matrix(ii,jj).feasCompObj]=...\n carpet_plot_vals(ii,jj,...\n x0,lb,ub,Problem, Constraints, Objectives, Spec, nxny,...\n ticker, nsubplots);\n ticker = ticker+1;\n progressbar(ticker/nsubplots);\n elseif jj < ii %just do a reflection\n Matrix(ii,jj).Y = Matrix(jj,ii).X;\n Matrix(ii,jj).X = Matrix(jj,ii).Y;\n Matrix(ii,jj).ObjStack = Matrix(jj,ii).ObjStack;\n Matrix(ii,jj).MarStack = Matrix(jj,ii).MarStack;\n Matrix(ii,jj).feasible = Matrix(jj,ii).feasible;\n end \n end\n end\nend\nprogressbar(1);\nsave\ndisp('Workspace saved to matlab.mat')\nTstamp = num2str(fix(clock),'%02d');\nfname = ['Autosaves\\CarpetMatrixData' Tstamp '.mat'];\nsave(fname)\ntoc; \nbeep;pause(.5);beep;pause(.5);beep;pause(.5);\nbeep;pause(.1);beep;pause(.1);beep;\nHaxes = CMATplot_the_carpet...\n (Matrix, Constraints,Objectives,x0,200,lb,ub,XLabels);\ntoc;\nProblem = CMATpick_point(Problem,Constraints,Spec,Objectives,Haxes);\nif get_yes_or_no('Save result to History.xls? [Y]/N: ',true)\n ITERsave_hist(Problem,Constraints,Objectives,Spec,'Visualizer');\nend\nend\n \nfunction [XX,YY,ObjStack,MarsStack,feasible,feasCompObj]=...\n carpet_plot_vals(Xyind,Xxind,x0,lb,ub,...\n Problem, Constraints, Objectives, Spec, nxny,...\n ticker, nsubplots)\n% nx = 9; ny = 8;\nnx = nxny;\nny = nxny;\n\nxx = linspace3(lb(Xxind),x0(Xxind),ub(Xxind),nx);\nyy = linspace3(lb(Xyind),x0(Xyind),ub(Xyind),ny);\n\n[YY,XX]=meshgrid(yy,xx);\n\nObjStack = NaN(nx,ny,1+Objectives.nObj);\nMarsStack = NaN(nx,ny,Constraints.nactiveMar+Constraints.nactivenonL);\n\nwaitbar1tot = nx*ny-1;\nwaitbar1prog = 0;\nprogressbar([],0)\nfor ii = 1:length(xx)\n for jj = 1:length(yy)\n\n X = x0;\n X(Xxind) = xx(ii);\n X(Xyind) = yy(jj);\n if all(X==x0) %skip evaluating the seed point\n ObjStack(ii,jj,:) = ...\n [Objectives.ObjectiveValue0; Objectives.ObjVals0(:)];\n MarsStack(ii,jj,:) = -Constraints.C0(:);\n else\n C = EVALnonlcons(X,Problem,Constraints,Spec);\n MarsStack(ii,jj,:) = -C(:);\n [ObjectiveValue, ObjVals] = EVALobjective...\n (X,Problem,Objectives,Spec,Constraints,'single');\n ObjStack(ii,jj,:) = [ObjectiveValue; ObjVals(:)];\n waitbar1prog = waitbar1prog+1;\n frac2 = waitbar1prog/waitbar1tot;\n progressbar((ticker+frac2)/nsubplots,frac2)\n end\n end\nend\nfeasible = all(MarsStack>=0,3);\nfeasCompObj = ObjStack(:,:,1);\nfeasCompObj(~feasible) = NaN;\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/41725-core-conceptual-optimization-of-rotorcraft-environment/CORE_v0p7 - for upload may 2013/CORE/ITERmake_CON_MAT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.48952371921127097}} {"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": "function ti = treeinfo(X, y, treeopts, tstopts)\n%TREEINFO Collects decision tree information based on tree walking.\n%\n% ti = treeinfo(X, y, treeopts, tstopts)\n% \n% It creates CART according to data set [X, y] and \n% optional parameters in treeopts, performs \n% tree pruning (if required) according to optional \n% parameters in tstopts, and implements tree walking \n% to collect all necessary information for genfis4.\n% treeopts and tstopts should be either empty matrix or\n% cell array containing one or more optional \n% parameter name/value pairs.\n% \n% The result is a structure ti containing the following fields:\n% - structure array \"node\" with fields \"variable\" (integer-valued scalar), \n% \"cutpoint\" (float scalar), and \"sample\" (index-valued vector);\n% - structure array \"leaf\" with field \"sample\" (index-valued vector);\n% - structure array \"branch\" with fields \"nodes\" (integer-valued vector),\n% and \"ineqs\" (vector of \"1\" or \"-1\" values).\n% \n% It requires Statistics Toolbox realizing CART algorithm.\n% \n% Example:\n% load fisheriris;\n% treeopts = {'minparent', 5, 'prune', 'off'};\n% tstopts = {'crossvalidation', meas, species};\n% ti = treeinfo(meas, species, treeopts, tstopts);\n \n% Per Konstantin A. Sidelnikov, 2009.\n\n% Check inputs\nerror(nargchk(2, 4, nargin));\n\nif (nargin < 4) || isempty(tstopts)\n tstopts = {};\nend\nif (nargin < 3) || isempty(treeopts)\n treeopts = {};\nend \n\n% Create a decision tree using CART algorithm\nt = classregtree(X, y, treeopts{:});\n% If necessary, perfom optimal tree pruning\nif ~isempty(tstopts)\n [~, ~, ~, bestlevel] = t.test(tstopts{:});\n t = t.prune('level', bestlevel); \nend\n% Get indices of nodes and leaves (terminal nodes)\nindn = find(t.isbranch());\nindl = find(~t.isbranch());\n% Get overall numbers of nodes and leaves\nnumn = length(indn);\nnuml = length(indl);\n% Allocate memory for structure array,\n% which stores information about each branch nodes:\n% cut variable number, cut point, and observations from \n% the original data that satisfy the conditions for the node\nnode(numn).variable = [];\nnode(numn).cutpoint = [];\nnode(numn).sample = [];\n% Allocate memory for structure array,\n% which stores information about each leaves:\n% observations from the original data that \n% satisfy the conditions for the leaf\nleaf(numl).sample = [];\n% Allocate memory for structure array,\n% which stores information about each branches:\n% group of nodes that form a path to the leaf, and\n% types of inequalities that are satisfied to reach the leaf\nbranch(numl).nodes = [];\nbranch(numl).ineqs = [];\n% Implement tree walking\ntreewalk(1, [], [], 1 : length(y));\n% Collect tree information\nti = struct('node', node, 'leaf', leaf, 'branch', branch);\n\n function treewalk(n, nodes, ineqs, sample)\n % This nested function implements tree walking\n % based on recursive algorithm in reference and \n % collects tree information using data sharing.\n \n % Reference: Cormen T.H., Leiserson C.E., Rivest R.L.,\n % Introduction to Algorithms (1st ed.), \n % MIT Press and McGraw-Hill, 1990.\n \n % Get numbers of the child nodes\n kids = t.children(n); \n if all(kids) % branch node\n % Get cut variable and cut point\n var = t.var(n);\n cut = t.cutpoint(n);\n % Save cut variable, cut point, and observations\n k = find(n == indn, 1, 'first');\n node(k).variable = var;\n node(k).cutpoint = cut;\n node(k).sample = sample;\n % Form new subsample and continue walking to the left child\n s = sample(X(sample, var) < cut); \n treewalk(kids(1), [nodes, k], [ineqs, -1], s);\n % Form new subsample and continue walking to the right child\n s = sample(X(sample, var) >= cut);\n treewalk(kids(2), [nodes, k], [ineqs, 1], s);\n else % leaf\n % Save leaf and branch information\n k = find(n == indl, 1, 'first'); \n leaf(k).sample = sample; \n branch(k).nodes = nodes;\n branch(k).ineqs = ineqs;\n end\n end\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/28393-fuzzy-cart/fcart/treeinfo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.4895237106023206}} {"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 [x,value] = steepestDescent(fun,x,varargin)\n% find maximum with steepest descent\n%\n% Input\n% fun - @S2Fun, @SO3Fun\n% x - initial seed @vector3d, @rotation\n%\n% Output\n% x - local maxima\n% value - function values\n%\n% Options\n% maxIter - \n% resolution -\n\n% prepare stepsize computation by Armijo search\nmaxIter = get_option(varargin,'maxIter',30);\nres = get_option(varargin,'resolution',0.05*degree);\nomega = 1.25.^(-30:1:10) * degree;\nomega(omega abbort\n if all(id == 1), break; end\n %fprintf('.')\nend\n\n% [o2,v1,v2] = unique(ori)\n% v = accumarray(v2,1)\n%id = v>5;\n%o2 = o2(id);\n%v = v(id)\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/tools/optimization_tools/steepestDescent.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4894740190387448}} {"text": "function [llh] = tapas_sem_prosa_llh(y, u, theta, ptheta)\n%% Computes the likelihood of the data.\n%\n% Input \n%\n% y -- Observed behavioral data. A structure with fields 't' times and 'a' \n% action\n% u -- Experimental input. A structure with fields: 'tt' trial type, either\n% prosaccade or antisaccade\n% theta -- Model parameters\n% ptheta -- Priors\n%\n% Output\n%\n% llh -- Log likelilhood\n%\n% aponteeduardo@gmail.com\n% copyright (C) 2015\n%\n\n% Compute the likelihood of antisaccades and prosaccades\n\nllh = zeros(1, numel(theta));\n\nit = y.i;\n\nmethod = ptheta.method;\nptrans = ptheta.ptrans;\n\nfor i = 1:numel(theta)\n llh(i) = sum(tapas_sem_prosa_cllh(y.t(~it), y.a(~it), u.tt(~it), ...\n ptrans(theta{i}), method, 1), 1);\nend\n\n\nend\n\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/sem/matlab/tapas_sem_prosa_llh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4894740135094812}} {"text": "function result = blur(im,levels,filt)\n% Blurs an image by blurring and subsampling repeatedly, followed by\n% upsampling and blurring.\n%\n% result=blur(im,[levels],[filt])\n%\n% im - input image.\n% levels - number of times to blur and subsample (default is 1).\n% filt - blurring 1d filter to be applied separably to the rows and\n% cols of im (default ='binom5').\n%\n% HISTORY:\n%\n% DJH '96\n% update 12/97 to conform to Eero's updated pyrTools\n%\n% I don't think we should use this any more. Why not just use Matlab's\n% convolution or blurring or filtering? (BW)\n% Because this is routine *much* faster than convolution. (RFD)\n%\n% 2007.05.03 RFD: fixed non-double class support.\n\n% warning('This function calls very old mex files that might not work. Try imblur instead.');\n\nif ~exist('levels','var'), levels=1; end\nif ~exist('filt','var'), filt = 'binom5'; end\nif ischar(filt), filt = namedFilter(filt); end \n\n% ras 03/07: enforce double-precision data type\n% (the compiled corrDn functions need double)\nif ~isa(im, 'double'), type = class(im); im = double(im); end\ntmp = blurDn(im,levels,filt);\n\n% save upBlurDEBUG tmp levels filt\nresult = upBlur(tmp,levels,filt);\n\n% Make sure its the same size as the input image\nresult = result((1:size(im,1)),(1:size(im,2)));\n\nif exist('type', 'var')\n\t% we had a non-double matrix, convert back\n\tresult = feval(type, result);\nend\n\nreturn;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/external/pyrTools/blur.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4894740135094812}} {"text": "function centroid = findBallFcn(greenBall1, thresh, imageType, axH)\n\n% Copyright 2011 The MathWorks, Inc.\n\nerror(nargchk(3, 4, nargin, 'struct'));\n\nif isempty(greenBall1)\n return;\nend\nif ischar(greenBall1)\n greenBall1 = imread(greenBall1);\nend\n\n%% Find Green Object\n% This script reads in an image file and then attempts to find a green\n% object in the image. It is designed to find one green ball and highlight\n% that ball on the original image\n\n%% Extract each color\n% Next we using indexing to extract three 2D matrices from the 3D image\n% data corresponding to the red, green, and blue components of the image.\n\nr = greenBall1(:, :, 1);\ng = greenBall1(:, :, 2);\nb = greenBall1(:, :, 3);\n\n%% Calculate Green\n% Then we perform an arithmetic operation on the matrices as a whole to try\n% to create one matrix that represents an intensity of green.\n\njustGreen = g - r/2 - b/2;\n\n%% Threshold the image\n% Now we can set a threshold to separate the parts of the image that we\n% consider to be green from the rest.\n\nif nargin == 4\n bw = justGreen > thresh;\nelse\n bw = justGreen > 80;\nend\n\n%% Remove small groups\n% We can use special functions provided by the Image Processing toolbox to\n% quickly perform common image processing tasks. Here we are using\n% BWAREAOPEN to remove groups of pixels less than 30.\n\nball1 = bwareaopen(bw, 30);\n\n%% Find center\n% Now we are using REGIONPROPS to extract the centroid of the group of\n% pixels representing the ball.\n\ns = regionprops(ball1, {'centroid','area'});\nif isempty(s)\n centroid = [];\nelse\n [maxArea, id] = max([s.Area]); %#ok\n centroid = s(id).Centroid;\nend\nswitch imageType\n case 'video'\n imshow(greenBall1, 'Parent', axH);\n if ~isempty(centroid)\n line(centroid(1), centroid(2), 'Parent', axH, 'Color', 'w', 'Marker', 'p', 'MarkerSize', 20, 'MarkerFaceColor', 'r')\n end\n case 'bw'\n imshow(ball1, 'Parent', axH);\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/30973-demo-files-for-algorithm-development-with-matlab-webinar/DemoFiles/WebcamGUI/findBallFcn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.48944097367999295}} {"text": "function test_suite=test_montecarlo_phase_stat\n% tests for test_phase_stat\n%\n% # For CoSMoMVPA's copyright information and license terms, #\n% # see the COPYING file distributed with CoSMoMVPA. #\n try % assignment of 'localfunctions' is necessary in Matlab >= 2016\n test_functions=localfunctions();\n catch % no problem; early Matlab versions can use initTestSuite fine\n end\n initTestSuite;\n\nfunction r=randint()\n r=ceil(rand()*10+10);\n\nfunction test_phase_stat_basics\n ds=generate_random_phase_dataset(40+randint(),'small');\n nsamples=size(ds.samples,1);\n\n methods={'param','nonparam_nan','nonparam',''};\n outputs={'pbi','pos','pop'};\n\n for k=1:numel(outputs)\n method=methods{k};\n for j=1:numel(outputs)\n output=outputs{j};\n\n opt=struct();\n opt.niter=randint();\n opt.progress=false;\n\n opt.permuter_func=@(iter) deterministic_permute(nsamples,...\n opt.niter,iter);\n opt.output=output;\n opt.seed=randint();\n\n is_parametric=false;\n extreme_tail_is_nan=true;\n switch method\n case 'param'\n opt.zscore='parametric';\n is_parametric=true;\n\n case 'nonparam_nan'\n opt.zscore='non_parametric';\n\n case 'nonparam'\n opt.extreme_tail_set_nan=false;\n extreme_tail_is_nan=false;\n\n case ''\n % deafults,ok\n\n otherwise\n assert(false);\n end\n\n expected_samples=compute_expected_samples(ds,output,...\n opt.niter,opt.permuter_func,...\n is_parametric,...\n extreme_tail_is_nan);\n result=cosmo_montecarlo_phase_stat(ds,opt);\n\n assertElementsAlmostEqual(expected_samples,result.samples,...\n 'absolute',1e-5);\n end\n end\n\n\n\n\nfunction test_random_data_nonparam_uniformity\n% when getting phase stats for random data, z-scores must follow some sort\n% of z-like distribution\n ds=generate_random_phase_dataset(40+randint(),'big');\n nsamples=size(ds.samples,1);\n\n methods={'nonparam_nan','nonparam',''};\n outputs={'pbi','pos','pop'};\n for k=1:numel(outputs)\n method=methods{k};\n for j=1:numel(outputs)\n output=outputs{j};\n\n opt=struct();\n opt.niter=50+randint();\n opt.output=output;\n opt.seed=[];\n opt.permuter_func=@(unused)nondeterministic_permute(nsamples);\n opt.progress=false;\n\n if ~isempty(method)\n opt.zscore='non_parametric';\n opt.extreme_tail_set_nan=~strcmp(method,'nonparam');\n end\n\n\n stat_ds=cosmo_montecarlo_phase_stat(ds,opt);\n samples=stat_ds.samples;\n nan_msk=isnan(samples);\n assert(mean(nan_msk)<.2); % not too many nans\n\n z_sorted=sort(samples(~nan_msk));\n n_z=numel(z_sorted);\n\n p_uniform=(.5:n_z)/n_z;\n z_uniform=cosmo_norminv(p_uniform);\n\n r2=var(z_sorted);\n r2_resid=var(z_sorted-z_uniform);\n F=r2/r2_resid;\n assert(F>10);\n end\n end\n\nfunction ds=generate_random_phase_dataset(nsamples_per_class,size_str)\n ds=cosmo_synthetic_dataset('ntargets',2,...\n 'nchunks',nsamples_per_class,...\n 'size',size_str,...\n 'seed',0);\n sz=size(ds.samples);\n ds.samples=randn(sz)+1i*randn(sz);\n ds.sa.chunks(:)=1:sz(1);\n\n\nfunction samples=compute_expected_samples(ds,output,...\n niter,permuter_func,...\n is_parametric,...\n extreme_tail_is_nan)\n\n stat_orig=cosmo_phase_stat(ds,'output',output);\n [nsamples,nfeatures]=size(ds.samples);\n\n stat_null_cell=cell(niter,1);\n for iter=1:niter\n rp=permuter_func(iter);\n ds_null=ds;\n ds_null.sa.targets=ds.sa.targets(rp);\n stat=cosmo_phase_stat(ds_null,'output',output);\n stat_null_cell{iter}=stat;\n end\n\n stat_null=cosmo_stack(stat_null_cell);\n\n if is_parametric\n mu=mean(stat_null.samples,1);\n sd=std(stat_null.samples,[],1);\n\n samples=(stat_orig.samples-mu)./sd;\n else\n count_gt=sum(bsxfun(@gt,stat_orig.samples,stat_null.samples),1);\n count_lt=sum(bsxfun(@lt,stat_orig.samples,stat_null.samples),1);\n\n msk_gt=count_gt>niter/2;\n msk_lt=count_lt>niter/2;\n\n p=zeros(1,nfeatures)+.5;\n p(msk_gt)=count_gt(msk_gt)/(1+niter);\n p(msk_lt)=1-count_lt(msk_lt)/(1+niter);\n\n min_p=1/(1+niter)+1e-10;\n\n assert(all(p>=min_p-2e-10));\n assert(all((1-p)>=(min_p-2e-10)));\n\n if extreme_tail_is_nan\n p(count_gt==niter | count_lt==niter)=NaN;\n end\n\n samples=cosmo_norminv(p);\n end\n\n\nfunction func=get_determistic_permute_func(ntargets,niter)\n func=@(iter) deterministic_permute(ntargets,niter,iter);\n\nfunction targets_idxs=deterministic_permute(ntargets,niter,iter)\n persistent cached_rand_vec;\n persistent cached_args;\n\n args={ntargets,niter};\n\n if ~isequal(args,cached_args)\n cached_rand_vec=cosmo_rand(ntargets,1,'seed',ntargets*niter);\n\n cached_args=args;\n end\n\n rand_vals=cached_rand_vec+iter/niter;\n msk=rand_vals>1;\n rand_vals(msk)=rand_vals(msk)-1;\n\n [unused,targets_idxs]=sort(rand_vals,1);\n\nfunction target_idxs=nondeterministic_permute(ntargets)\n rand_vals=randn(ntargets,1);\n [unused,target_idxs]=sort(rand_vals);\n\n\n\nfunction test_monte_carlo_phase_stat_seed\n ds=generate_random_phase_dataset(20,'tiny');\n\n opt=struct();\n opt.niter=10+randint();\n opt.output='pbi';\n opt.progress=false;\n\n\n % different results with empty seeed\n opt.seed=[];\n r1=cosmo_montecarlo_phase_stat(ds,opt);\n attempt=10;\n while attempt>0\n attempt=attempt-1;\n assert(attempt>0,'results are always the same');\n r2=cosmo_montecarlo_phase_stat(ds,opt);\n if ~isequal(r1.samples,r2.samples)\n break;\n end\n end\n\n % fixed seed, same result\n opt.seed=randint();\n r1=cosmo_montecarlo_phase_stat(ds,opt);\n r2=cosmo_montecarlo_phase_stat(ds,opt);\n assertElementsAlmostEqual(r1.samples,r2.samples);\n\n % different seed, different result\n attempt=10;\n while attempt>0\n opt.seed=opt.seed+1;\n attempt=attempt-1;\n assert(attempt>0,'results are always the same');\n r2=cosmo_montecarlo_phase_stat(ds,opt);\n if ~isequal(r1.samples,r2.samples)\n break;\n end\n end\n\n\n\n\nfunction test_montecarlo_phase_stat_exceptions()\n func=@cosmo_montecarlo_phase_stat;\n aet=@(x,varargin)assertExceptionThrown(@()...\n func(x,varargin{:}),'');\n extra_args=cosmo_structjoin({'progress',false,...\n 'niter',3,...\n 'output','pbi'});\n aet_arg=@(x,varargin)aet(x,extra_args,varargin{:});\n\n % valid\n ds=generate_random_phase_dataset(5,'tiny');\n func(ds,extra_args); % ok\n\n % unbalanced targets\n bad_ds=ds;\n i=find(ds.sa.targets==2,1,'first');\n bad_ds.sa.targets(i)=1;\n aet_arg(bad_ds);\n\n % invalid output\n aet_arg(ds,'output','foo');\n\n % valid zscore\n func(ds,extra_args,'zscore','parametric');\n func(ds,extra_args,'zscore','non_parametric');\n\n % invalid zscore\n aet_arg(ds,'zscore','nonparametric');\n aet_arg(ds,'zscore','foo');\n\n % invalid niter\n aet_arg(ds,'niter',.3);\n aet_arg(ds,'niter',-3);\n aet_arg(ds,'niter',[2 2]);\n aet_arg(ds,'niter','f');\n\n\n % valid output\n func(ds,extra_args,'output','pbi');\n func(ds,extra_args,'output','pos');\n func(ds,extra_args,'output','pop');\n\n % invalid output\n aet_arg(ds,'output','foo');\n aet_arg(ds,'output',2);\n\n % missing fields\n aet(ds,rmfield(extra_args,'niter'));\n aet(ds,rmfield(extra_args,'output'));\n\n % valid extreme_tail_set_nan\n func(ds,extra_args,'extreme_tail_set_nan',true);\n func(ds,extra_args,'extreme_tail_set_nan',false);\n\n % invalid func(ds,extra_args,'extreme_tail_set_nan',true);\n aet(ds,extra_args,'extreme_tail_set_nan',2);\n aet(ds,extra_args,'extreme_tail_set_nan','foo');\n\nfunction test_unit_length_exception\n ds=cosmo_synthetic_dataset('nchunks',10);\n sample_size=size(ds.samples);\n ds.sa.chunks(:)=1:sample_size(1);\n\n rand_func=single(randn(sample_size));\n\n ds.samples=rand_func() + 1i*rand_func();\n\n opt=struct();\n opt.output='pos';\n opt.niter=100;\n opt.progress=false;\n\n % should not raise an exception\n cosmo_montecarlo_phase_stat(ds,opt);\n", "meta": {"author": "CoSMoMVPA", "repo": "CoSMoMVPA", "sha": "5de75a1b4bef89b082d39d69e2b99d7f894ad717", "save_path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA", "path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA/CoSMoMVPA-5de75a1b4bef89b082d39d69e2b99d7f894ad717/tests/test_montecarlo_phase_stat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.48944097052375934}} {"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 a = i4mat_flip_rows ( m, n, a )\n\n%*****************************************************************************80\n%\n%% I4MAT_FLIP_ROWS swaps the rows of an I4MAT.\n%\n% Discussion:\n%\n% An I4MAT is an integer matrix.\n%\n% To \"flip\" the rows of an IMAT is to start with something like\n%\n% 11 12 13 14 15\n% 21 22 23 24 25\n% 31 32 33 34 35\n% 41 42 43 44 45\n% 51 52 53 54 55\n%\n% and return\n%\n% 51 52 53 54 55\n% 41 42 43 44 45\n% 31 32 33 34 35\n% 21 22 23 24 25\n% 11 12 13 14 15\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 June 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns.\n%\n% Input, integer A[M,N], the matrix whose rows are to be flipped.\n%\n% Output, integer A[M,N], the flipped matrix.\n%\n for i = 1 : floor ( m / 2 )\n b(1, 1:n) = a( i,1:n);\n a( i,1:n) = a(m+1-i,1:n);\n a(m+1-i,1:n) = b(1, 1: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/i4mat_flip_rows.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878696277512, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.4893996501904748}} {"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 Y = acosh(X)\n %ACOSH Symbolic inverse hyperbolic cosine.\n \n \n % Convert inputs to SymExpression\n % X = SymExpression(X);\n \n % construct the operation string\n sstr = ['ArcCosh[' X.s ']'];\n \n % create a new object with the evaluated string\n Y = SymExpression(sstr);\nend\n", "meta": {"author": "ayonga", "repo": "frost-dev", "sha": "e5dc0624d834520872bfa588dd3eda5643da71de", "save_path": "github-repos/MATLAB/ayonga-frost-dev", "path": "github-repos/MATLAB/ayonga-frost-dev/frost-dev-e5dc0624d834520872bfa588dd3eda5643da71de/matlab/symbolic/@SymExpression/acosh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4893996404525869}} {"text": "% This function compute the modulation spectrum of speech. The modulation\n% spectrum can be derived from several types of feature trajectories: 1)\n% log spectrogram; 2) log Mel filterbanks; 3) MFCC. Note that it is\n% different from another definition of modulation spectrum that derived\n% from the evelop of band-passed time domain signal. \n% Inputs:\n% wav: the time domain signal\n% para: a structure that controls various options in the function\n% Outputs:\n% modu: the modulation spectrum (complex valued) of feature blocks\n% moduAvg: the average modulation spectrum (magnitude) of the input signal\n%\n% Author: Xiao Xiong\n% Created: 1 Dec 2014\n% Last Modified: 5 Dec 2014\n%\nfunction [modu, moduAvg] = compute_modulation_stft(wav, para)\ntype = para.type;\nfs = para.fs;\nwin_size = para.win_size;\nwin_shift = para.win_shift;\n\nspec = wav2abs(wav, fs);\n\nif type == 1 % compute from spectrum\n data = log(spec);\nelseif type == 2 % compute from Mel filterbanks\n data = log(abs2Mel(spec, fs));\nelseif type == 3 % compute from static MFCC \n data = fbank2mfcc(log(abs2Mel(spec, fs)));\nend\n\n% Perform optional normalization to the data\nif isfield(para, 'norm')\n switch para.norm\n case 'CMN'\n data = CMN(data);\n case 'MVN'\n data = MVN(data);\n otherwise\n fprintf('Unknown normalization %s\\n', para.norm);\n end\nend\n\n[nFr, dim] = size(data);\n\nnBlockMax = ceil( (nFr-win_size)/win_shift ) + 1;\nmodu = []; moduAvg = [];\nnBlock = 0;\nfor i=1:win_shift:nFr\n j = min(nFr, i+win_size-1);\n if j-i+1 < win_size/2 % if the remaining frames is not enough for half of the window size, discard it. \n break;\n end\n nBlock = nBlock + 1;\n modu(:,:,nBlock) = fft(data(i:j,:), win_size);\n last_block_size = (j-i)+1;\nend\n\nif size(modu,3)==0\n return;\nend\n\nmodu = modu(1:win_size/2+1,:,:);\n\nmoduAvg = sum(abs(modu(:,:,1:end-1)),3) + abs(modu(:,:,end)) * last_block_size/win_size;\nmoduAvg = moduAvg / (size(modu,3)-1+last_block_size/win_size);\n\nend\n", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/signal/feature/compute_modulation_stft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4893996344918333}} {"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": "% determine searching area\nactive_pixel = (sum(neuron_bk.A(:,IDs), 2)>0);\n\n% update spatial/temporal components of the merged neuron\ndata = neuron_bk.A(active_pixel, IDs)*neuron_bk.C_raw(IDs, :);\nci = neuron_bk.C_raw(IDs(1), :);\nfor miter=1:10\n ai = data*ci'/(ci*ci');\n ci = ai'*data/(ai'*ai);\nend\n\nsn = GetSn(ci);\nneuron.A(active_pixel, IDs(1)) = ai*sn;\nneuron.C_raw(IDs(1), :) = ci/sn;\nneuron.S(IDs(1), :) = ci/sn; \nnewIDs(IDs(1)) = IDs(1);\n% remove merged elements\nind_del(IDs(2:end)) = true;\n\n%% show merged shape and trace \naxes(ax_merged); \nneuron.image(neuron.A(:, IDs(1))); \naxis equal off tight; \nset(gca, 'xlim', get(ax_selected, 'xlim')); \nset(gca, 'ylim', get(ax_selected, 'ylim')); \n\naxes(ax_merged_trace); \nplot(ci, 'k', 'linewidth', 2); \n\n%% clear IDs; \nIDs_last = IDs; \nIDs = []; ", "meta": {"author": "zhoupc", "repo": "CNMF_E", "sha": "ccca6f9db7d1d15b7dd1266eb9b29e417f92e79f", "save_path": "github-repos/MATLAB/zhoupc-CNMF_E", "path": "github-repos/MATLAB/zhoupc-CNMF_E/CNMF_E-ccca6f9db7d1d15b7dd1266eb9b29e417f92e79f/scripts/cnmfe_manual_merge_merge_neurons.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.48935585053098624}} {"text": "function grad = B_MVDR_spatialCov(X, curr_layer, beamform_layer, after_power_layer)\n\n% X is the multichannel complex spectrum inputs\n[D,C,T,N] = size(X);\n% weight is the beamforming weight\nweight = reshape(curr_layer.a, D,C,N);\nlambda = curr_layer.lambda;\nphi_s = curr_layer.phi_s;\nphi_n = curr_layer.phi_n;\n\nif isfield(curr_layer, 'noiseCovL2')\n noiseCovL2 = curr_layer.noiseCovL2;\nelse\n noiseCovL2 = 0; % add noiseCovRegularization*\\lambda*I to noise covariance, where \\lambda is the maximum eigenvalue\nend\n\n% Y is the beamforming's output\nY = beamform_layer.a;\n% future_grad is the gradient of the power specturm of beamformed signal\nfuture_grad = after_power_layer.grad;\n\nif N>1\n [validMask, variableLength] = getValidFrameMask(curr_layer);\n future_gradUtt = ExtractVariableLengthTrajectory(future_grad, validMask);\n YUtt = ExtractVariableLengthTrajectory(Y, validMask);\n X = reshape(X, D*C, T, N);\n XUtt = ExtractVariableLengthTrajectory(X, validMask);\n for i=1:N\n grad{i} = GetGradUtt(reshape(XUtt{i},D,C,size(XUtt{i},2)),YUtt{i},phi_s(:,:,:,:,i), phi_n(:,:,:,:,i), ...\n weight(:,:,i), lambda(:,:,:,:,i), future_gradUtt{i}, noiseCovL2);\n end\n grad = cell2mat_gpu(grad);\n grad = permute(grad, [1 3 2]);\nelse\n grad = GetGradUtt(X,Y,phi_s, phi_n, weight, lambda, future_grad, noiseCovL2);\nend\n\nend\n\n%%\nfunction grad = GetGradUtt(X,Y,phi_s, phi_n, weight, lambda, future_grad, noiseCovL2)\n[D,C,T,N] = size(X);\nu = zeros(C,1);\nu(1) = 1;\nfor f=1:D\n x = squeeze(X(f,:,:));\n xx = x*x';\n ww = weight(f,:).' * conj(weight(f,:));\n phi_n_inv = inv(phi_n{1,1,f});\n yy = abs(Y(f,:).*conj(Y(f,:)));\n dyyy = sum(future_grad(f,:).*yy);\n dyxx = bsxfun(@times, x, future_grad(f,:)) * x';\n \n if 1\n grad_phi_s(:,:,f) = 2 * phi_n_inv * dyxx * weight(f,:).' * u' / lambda{1,1,f} -2 * dyyy * phi_n_inv / lambda{1,1,f};\n grad_phi_n(:,:,f) = - 2* phi_n_inv * dyxx * ww + 2 * dyyy * phi_n_inv * phi_s{1,1,f} * phi_n_inv / lambda{1,1,f};\n elseif 0 % no lambda\n grad_phi_s(:,:,f) = 2 * phi_n_inv * dyxx * weight(f,:).' * u';\n grad_phi_n(:,:,f) = - 2* phi_n_inv * dyxx * ww;\n else % only lambda\n grad_phi_s(:,:,f) = -2 * dyyy * phi_n_inv / lambda{1,1,f};\n grad_phi_n(:,:,f) = 2 * dyyy * phi_n_inv * phi_s{1,1,f} * phi_n_inv / lambda{1,1,f};\n end\nend\n\ngrad = conj([reshape(grad_phi_s,C*C*D,1); reshape(grad_phi_n,C*C*D,1)]);\nend\n\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_MVDR_spatialCov_old.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.4893558505309862}} {"text": "\n%% load\nload cnt_ssvep;\nCNT = cnt_ssvep;\n\n% cnt variables\n% cnt.t : time information \n% cnt.fs : sampling frequency\n% cnt.y_dec : class information (e.g., up = 1, left = 2, right = 3, down = 4)\n% cnt.y_logic : logical format of class inforamtion \n% cnt_y_class : class name (e.g., up, left, right, and down)\n% cnt.class : number of class \n% cnt.chan : number of electrodes\n% cnt. x : raw eeg signals\n\n% revised 2017.11.11 - Oyeon Kwon (oy_kwon@korea.ac.kr)\n%% Initialization\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ntime = 4;\nfreq = [5, 7, 9, 11];\nfs = CNT.fs;\ninterval = [0 4000]; %\nmarker = {'1','up';'2', 'left';'3', 'right';'4', 'down'};\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% CCA - Analysis\nSMT = prep_segmentation(CNT, {'interval', interval});\n\nnumTrials = size(SMT.x, 2);\ncount= numTrials;\n\nfor i = 1: size(SMT.x, 2)\n cca_result = ssvep_cca_analysis(squeeze(SMT.x(:,i,:)),{'marker',marker;'freq', freq;'fs', fs;'time',time});\n [~, ind] = max(cca_result);\n if SMT.y_dec(i) ~= ind\n count = count -1;\n end\nend\nfprintf('Accuracy: %.2f%%\\n', count/numTrials);\nAccuracy = count/numTrials;\n\n\n\n\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/Examples/old/example_SSVEP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4893558505309861}} {"text": "classdef IncrementalSequence < handle\n \n properties (GetAccess = public, SetAccess = protected)\n value\n end\n \n properties (Access = public)\n alpha\n initialValue\n finalValue\n end\n \n properties (Access = protected)\n x0\n x1\n nSteps\n end\n \n methods (Access = protected, Abstract)\n \n generateAlphaSequence(obj)\n \n end\n \n methods (Access = public)\n \n function update(obj,i)\n obj.value = (1-obj.alpha(i))*obj.initialValue + obj.alpha(i)*obj.finalValue;\n end\n \n end\n \n methods (Access = protected)\n \n function init(obj,x0,x1,nSteps,a0,a1)\n obj.x0 = x0;\n obj.x1 = x1;\n obj.nSteps = nSteps;\n obj.initialValue = a0;\n obj.finalValue = a1;\n end\n \n end\n \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/Topology Optimization/IncrementalScheme/IncrementalSequence/IncrementalSequence.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.48931483519985147}} {"text": "function [N] = lbf2N(lbf)\n% Convert force from pounds to newtons. \n% Chad A. Greene 2012\nN = lbf*4.4482216152605;", "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/lbf2N.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.48931482523744874}} {"text": "seed = 107; \nrng(seed); \nL = 20;\nN = 6; \nT = 3000; \nW = zeros(N,1,L); \nfor ni = 0:N-1\n W(ni+1,1,(mod(1:L,N+1)-1)==ni)=1;\nend\nH = (rand(1,T)<.005);\nH(3*L) = 1;\nimagesc(squeeze(W));shg\nSimpleWHPlot(W,H); \n%%\nset(gca, 'xscale', 'log', 'ytick', [], 'color', 'none')\nset(gca,'color','none','tickdir','out','ticklength', [0.025, 0.025])\nsavedir = 'C:\\Users\\emackev\\Dropbox (MIT)\\SeqNMF\\Figures';\nsaveTitle = 'L1Example'; \npapersize = [4 2];\n\n\n[W,H] = seqNMF(helper.reconstruct(W,H)+.0*rand(N,T), 'K', 3, 'L', 2*L,...\n 'lambdaL1H', 10, 'lambda', .001, 'maxiter', 150);\nSimpleWHPlot(W,H,[],0)\nset(gcf, 'papersize', papersize, 'paperposition', [0 0 papersize]);%, 'color', 'none')\nsaveas(gcf, fullfile(savedir, [saveTitle '_L1H1.pdf'])); \n\n[W,H] = seqNMF(helper.reconstruct(W,H)+.0*rand(N,T), 'K', 3, 'L', 2*L,...\n 'lambdaL1W', 100, 'lambda', .001, 'maxiter', 150);\nSimpleWHPlot(W,H,[],0)\nset(gcf, 'papersize', papersize, 'paperposition', [0 0 papersize]);%, 'color', 'none')\nsaveas(gcf, fullfile(savedir, [saveTitle '_L1W1.pdf'])); \n\n", "meta": {"author": "FeeLab", "repo": "seqNMF", "sha": "229b9b19ac3a34b8378945ec7f9e331e004bb777", "save_path": "github-repos/MATLAB/FeeLab-seqNMF", "path": "github-repos/MATLAB/FeeLab-seqNMF/seqNMF-229b9b19ac3a34b8378945ec7f9e331e004bb777/misc_elm/L1SparsityTest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083132, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.48929306097695957}} {"text": "% Estimate sinusoid parameters using peak picking or LS solutions\n%\n% Octave compatible\n% \n% Description\n% Model a given waveform using sinusoids whose parameters are estimated\n% using various methods. Depending on the combinations of the options:\n% fharmonic, fquasiharm, fadapted and use_ls, the methods below are available:\n% | fharmonic | fquasiharm | fadapted | use_ls\n% Peak Peaking [1] false false false false\n% Peak Peaking [1] true false false false\n% Peak Peaking [1] true true false false\n% HM [2] ** true false false true (default)\n% QHM (partly [3]*) true true false true\n% aHM [5] true false true true\n% (iQHM [3] to come)\n% (aQHM [4] to come)\n%\n% ** This is a full-band HM, this is NOT the Harmonic+Noise Model (HNM)\n% * Note that [3] is NOT fully implemented. The QHM estimation is available,\n% but NOT the iterative algorithm presented in [3].\n%\n% The analysis instants need to be always provided through the f0s argument.\n%\n% The window length is always odd so as the sample at the middle of the\n% window correspond to the sample of the analysis instant.\n%\n% Inputs\n% wav : The waveform\n% fs : [Hz] The sampling frequency\n% f0s : [s, Hz] [Nx2] A temporal vector with time instants and fundamental\n% frequency f0 estimated at the given time instants.\n% The sinusoid parameters are always estimated at these time instants.\n% For the Peak Peaking method, the f0 (second column) can be omitted.\n% [opt] : Additional options (see code below)\n%\n% Outputs\n% frames : N structures containing the estimated sinusoid parameters and extra\n% information (e.g. window length, the f0 used).\n% For each frame, the sinusoid parameters are in a matrix with format:\n% [5xK] for each column: the frequency [Hz], the linear amplitude,\n% the instantaneous phase [rad], the harmonic number of each\n% sinusoidal component and a boolean specifying if the sinusoidal\n% parameters are from a spectral peak or through sampling.\n% The DC is ALWAYS included at the beginning of the matrix.\n% syn : if asked, the resynthesized waveform using an Overlap-Add method.\n% opt : The options structure which might have been altered for consistency\n% purpose.\n%\n% Example\n% Please se the HOWTO_sinusoidal example\n%\n% References\n% [1] McAulay, R., Quatieri, T.: Speech analysis/Synthesis based on a sinusoidal\n% representation, IEEE Transactions on Acoustics, Speech and Signal\n% Processing 34(4):744-754, 1986.\n% [2] Stylianou, Y.: Harmonic plus Noise Models for Speech combined with\n% Statistical Methods, for Speech and Speaker Modification, TelecomParis,\n% PhD Thesis, 1996.\n% [3] Pantazis, Y., Rosec, O., Stylianou, Y.: Iterative Estimation of Sinusoidal\n% Signal Parameters, Signal Processing Letters, IEEE 17(5):461-464, 2010.\n% [4] Pantazis, Y., Rosec, O., Stylianou, Y.: Adaptive AM-FM Signal Decomposition\n% With Application to Speech Analysis, IEEE Transactions on Audio, Speech,\n% and Language Processing 19(2):290-300, 2010.\n% [5] Degottex, G., Stylianou, Y.: Analysis and Synthesis of Speech using an\n% Adaptive Full-band Harmonic Model, IEEE Transactions on Acoustics, Speech\n% and Language Processing, 21(10):2085-2095, 2013.\n% \n% Copyright (c) 2012 University of Crete - Computer Science Department\n% \n% License\n% This file is under the LGPL license, you can\n% redistribute it and/or modify it under the terms of the GNU Lesser General \n% Public License as published by the Free Software Foundation, either version 3 \n% of the License, or (at your option) any later version. This file is\n% distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; \n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n% PARTICULAR PURPOSE. See the GNU Lesser General Public License for more\n% details.\n%\n% This function is part of the Covarep project: http://covarep.github.io/covarep\n%\n% Author\n% Gilles Degottex \n%\n\nfunction [frames, syn, opt] = sin_analysis(wav, fs, f0s, opt)\n\n if nargin<4\n % Options\n\n % Window\n opt.win_durf0sync = true;\n opt.win_durnbper = 3; % Number of period per window (def. 3)\n % (used only if win_durf0sync==true)\n opt.win_dur = 30/1000; % [s] Duration of the analysis window\n % (used only if win_durf0sync==false)\n opt.win_fn = @blackman; % Window type\n opt.win_dropoutside=true; % Drop windows which are partly outside of\n % the signal (and thus drop the \n % corresponding analysis instants).\n\n % Partials estimation\n opt.fharmonic = true; % Use harmonic or quasi-harmonic frequencies\n opt.fquasiharm= false;% Use quasi-harmonic frequencies\n % It is possible to estimate the parameters using\n % the QHM model. HOWEVER, the iterative algorithm\n % in [3] is not implemented yet !\n opt.fadapted = false; % Adapt the frequency basis to the f0 curve\n % (currently, works only with LS solution)\n\n % For LS solution [2-5]\n opt.use_ls = true; % Use the Least Square solution (LS) [2,3]\n % Otherwise, use Peak Picking (PP) [1]\n opt.win_ls_marg = 0.1;% For the LS solution, add 10% to the\n % theoretical minimum window length to ensure the\n % stability of the LS solution\n\n % For Peak Picking [1]\n opt.normstr = 'sum(win)'; % Normalize the window using the given\n % expression.\n % Among the available terms, the following exist\n % win, winlen and dftlen \n opt.dftlen = []; % Force the DFT to a given length\n % if empty, the DFT length is adapted to the \n % window length + the oversampling factor below.\n % (ignored when using the LS solution)\n opt.osf = 2; % Frequency OverSampling Factor, according to:\n % dftlen=2^(nextpow2(winlen)+opt.osf)\n opt.frames_keepspec = false; % Keep the halfspec\n opt.funique = true;% Keep only unique frequencies\n % Considered only if harmonic=false\n\n % Resynthesis\n opt.resyn = false; % Do OverLap-Add (OLA) resynthesis\n \n opt.debug = 1;\n\n opt.fmapin{1} = {{'wav', 'fs'}, 'snd'};\n opt.fmapin{2} = {{'f0s'}, 'yin'};\n opt.fmapout{1} = {{'frames'}, 'mat'};\n end\n if nargin==0; frames=opt; return; end\n\n if opt.debug>0; disp('Sinusoidal Analysis'); end\n if opt.fquasiharm; opt.fharmonic=true; end\n if opt.use_ls; opt.fharmonic=true; end % Currently, the LS solution is only possible with a harmonic model\n% if ~opt.use_ls && opt.fharmonic==true; opt.fquasiharm=true; end % commented: otherwise we can't do harmonic PP\n if ~opt.use_ls && opt.fquasiharm==true; opt.fharmonic=true; end\n if size(f0s,2)>1 && any(f0s(:,2)<=0); error('If a fundamental frequency is specified, it cannot be zero.'); end\n if opt.fharmonic\n if size(f0s,2)<2; error('An input f0 curve is necessary for harmonic model'); end\n opt.win_durf0sync=true;\n end\n if opt.fadapted\n if size(f0s,2)<2; error('An input f0 curve is necessary for adaptivity'); end\n if ~opt.use_ls; error('Adaptivity with peak picking is not possible. Should use LS solution.'); end\n end\n if nargout<2; opt.resyn=false; end\n if opt.debug>0; disp(opt); end\n\n wav = wav(:);\n if opt.resyn\n syn = zeros(size(wav));\n wins = zeros(size(wav));\n else\n syn = [];\n end \n\n T = f0s(:,1); % Get analysis time instants\n\n if opt.fadapted\n times = (0:length(wav)-1)'/fs;\n % Sample the first harmonic all along the signal\n f1 = interp1(f0s(:,1), f0s(:,2), times, 'spline');\n f1 = interp1_extrapbounds(f1); % Check if bounds are defined, and replace nan values\n % Compute the fundamental phase\n p1 = filter(1, [1 -1], 2*pi*f1/fs);\n % p1 = 2*pi*cumtrapz(f1)/fs; % Create Bad conditionned matrices !\n end\n\n % Use a constant winlen if winlen is not pitch sync\n if ~opt.win_durf0sync\n if size(f0s,2)>1\n f0m = exp(median(log(f0s(:,2))));\n winlen = round(opt.win_durnbper*fs/f0m/2)*2+1;\n else\n winlen = round(opt.win_dur*fs/2)*2+1;\n end\n win = opt.win_fn(winlen);\n if ~isempty(opt.normstr)\n eval(['d = ' opt.normstr ';']);\n win = win./d;\n end\n if ~isempty(opt.dftlen); dftlen=opt.dftlen;\n else dftlen=2^(nextpow2(winlen)+opt.osf); end\n W = delay2spec((winlen-1)/2, dftlen);\n end\n\n if opt.debug>0; pb = progressbar(length(T)); end\n for ind=1:length(T)\n\n % Be sure the analysis instant is on the sample of the window center\n T(ind) = round(T(ind)*fs)/fs;\n fr.t = T(ind);\n\n if opt.win_durf0sync\n f0 = f0s(ind,2);\n fr.f0 = f0;\n\n if opt.fadapted; winlen = get_optimal_winlen(f0s, fs, ind, opt);\n else winlen = round(opt.win_durnbper*fs/f0/2)*2+1; end\n win = opt.win_fn(winlen);\n\n if ~isempty(opt.dftlen); dftlen=opt.dftlen;\n else dftlen=2^(nextpow2(winlen)+opt.osf); end\n W = delay2spec((winlen-1)/2, dftlen);\n end\n\n fr.winlen = winlen;\n fr.dftlen = dftlen;\n\n winids = -(winlen-1)/2:(winlen-1)/2; % Indices relative to the center\n idscenter = round(T(ind)*fs)+1;\n ids = idscenter + winids; % Indices of the window in the signal\n\n if opt.win_dropoutside\n if ids(1)<1 || ids(end)>length(wav);\n T(ind) = NaN;\n continue;\n end\n iddx = (1:winlen);\n idsb = ids;\n wavsel = wav(ids);\n else\n iddx = find(ids>=1 & ids<=length(wav)); % Valid indices of the window\n idsb = ids(iddx); % Indices of the win in the sig bounded by the sig limits\n wavsel = zeros(winlen,1);\n wavsel(iddx) = wav(idsb);\n end\n\n if opt.use_ls\n % Use Least Squares (LS) solution [2]\n if opt.fadapted\n % Adapt the frequency basis to the f0 curve\n Ho = floor(((fs/2)-max(f1(idsb))/2)/max(f1(idsb)));\n\n % Use interpolated phase (through interpolated frequencies)\n if length(idsb) unconstrained sinusoids\n fr.sins = spec_getsins(S, fs);\n\n if opt.funique\n [~, idx] = unique(fr.sins(1,:));\n fr.sins = fr.sins(:,idx);\n end\n end\n\n if opt.frames_keepspec; fr.S=spec2hspec(S); end\n end\n\n if opt.resyn\n y = sin2sig(fr.sins, fs, winlen);\n y = 2*y;\n fr.SNR = mag2db(std(wavsel)/std(wavsel-y));\n syn(idsb) = syn(idsb) + y(iddx).*win(iddx);\n wins(idsb) = wins(idsb) + win(iddx);\n end\n\n if ind==1\n frames(length(T)) = fr; % pre-allocate with correct fieldnames\n end\n frames(ind)=fr;\n\n if 0 && T(ind)>0.3\n hold off;\n plot(wavsel, 'k');\n hold on;\n plot(y, 'b');\n keyboard\n end\n\n if 0\n % Compute the spectrum and compansate the window delay\n % TODO Check the behavior of the harmonic structure with the aDFT.\n win = win./sum(win);\n S = fft(wavsel.*win, dftlen);\n F = fs*(0:length(S)-1)/length(S);\n hold off;\n plot(F, ld(S), 'k');\n hold on;\n stem(fr.sins(1,:), ld(fr.sins(2,:)), 'xr');\n xlim([0 fs/2]);\n% ylim([-140 40]);\n% keyboard\n pause\n end\n\n if 0 && opt.debug>1 && T(ind)>0.3\n V3clear();\n V3spec(S, fs, 'k');\n V3part(frames(end).sins, fs);\n keyboard\n end\n\n if opt.debug>0; pb = progressbar(pb, ind); end\n end\n if opt.debug>0; pb = progressbar(pb, length(T)); end\n\n % Drop the necessary frames\n idx = find(~isnan(T));\n if length(idx)0\n disp([' Some windows were outside of the signal. ' num2str(length(T)-length(idx)) ' frames dropped. (use opt.win_dropoutside=false if you want to keep all windows and zero-pad the necessary ones at signal boundaries).']);\n end\n T = T(idx);\n frames = frames(idx);\n\n if opt.resyn\n idx = find(wins>0);\n syn(idx) = syn(idx)./wins(idx);\n if opt.debug>0; disp(['Mean SNR=' num2str(mean([frames.SNR]))]); end\n end\n \n if opt.debug>1\n Hmax = 0;\n for ind=1:numel(frames)\n Hmax = max(Hmax,size(frames(ind).sins,2));\n end\n harmstruct = NaN*ones(numel(frames), Hmax);\n for ind=1:numel(frames)\n M = min(length(frames(ind).sins(1,:)),Hmax);\n harmstruct(ind,1:M) = frames(ind).sins(1,1:M);\n end\n hold off;\n [mf0, winlen, dftlen] = spec_info(fs, f0s);\n [X, Fs, Ts] = spectrogram(wav, blackman(winlen), round(0.9*winlen), dftlen, fs);\n imagesc(Ts, Fs, lin2db(X));\n axis xy;\n hold on;\n plot([0 (length(wav)-1)/fs], 0.5*fs*[1 1], '--k');\n plot(T, harmstruct, 'k');\n keyboard\n end\n\nreturn\n\n", "meta": {"author": "covarep", "repo": "covarep", "sha": "5a2be5d6b776f14a0b275c69fde90eb13849e60d", "save_path": "github-repos/MATLAB/covarep-covarep", "path": "github-repos/MATLAB/covarep-covarep/covarep-5a2be5d6b776f14a0b275c69fde90eb13849e60d/sinusoidal/sin_analysis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4892930501997894}} {"text": "function [imr,xa,ya]=rectifyhomog(ims,roc,k0,mode)\n%RECTIFYHOMOG Apply rectifying homographies to an image set\n%\n% Usage: figure(101); % Initial figure for rectiied image display\n% rectifyhomog(ims,roc,k0,'ga'); % plot in individual figures\n%\n% Inputs:\n% ims{nc} cell array of input images (colour or monochrome)\n% roc(3,3,nc) rotation matrices from world coordinates to camera coordinates\n% k0 camera matrix or focal length in pixels optionally divided by the image width [0.8]\n% mode mode string\n% g show images on separate figures\n% G tile images onto a single figure [default if no output arguments]\n% k clip to original image dimensions\n% l do not link axes\n% v k0 contains diffent values for each camera\n% a orient to average camera orientation\n% [z make optical axis perpendicular to camera plane]\n% [x align x axis with camera displacements]\n% Outputs:\n% imr{nc}(my,mx,nc) output images (uint8)\n% xa{nc}(mx) x axis for each image\n% ya{nc}(my) y axis for each image\n\n% Copyright (C) Mike Brookes 2012\n% Version: $Id: rectifyhomog.m 1642 2012-03-16 16:22:26Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif ~iscell(ims)\n ims={ims};\nend\nnc=numel(ims); % number of images\nif ~((nc==1 && isequal(size(roc),[3 3])) || isequal(size(roc),[3 3 nc]))\n error('roc should have dimensions [3,3,%d]',nc);\nend\nif nargin<4 || ~numel(mode)\n mode='';\nend\nif nargin<3 || ~numel(k0)\n k0=0.8;\nend\nif nargin<2 || ~numel(roc)\n roc=repmat(eye(3),[1 1 nc]);\nend\n\n% sort out options\n\nvv=any(mode=='v'); % different k0 for each camera\nnk=numel(k0)/(1+vv*(nc-1)); % number of k parameters per camera\nswitch nk\n case {1,3}\n k0=reshape(k0,[1 nk 1+vv*(nc-1)]);\n case 9\n k0=reshape(k0,[3 3 1+vv*(nc-1)]);\n otherwise\n error('k0 must have 1, 3 or 9 values per camera');\nend\nncr=1+(nargout>0)*(nc-1); % numer of output images\nif any(mode=='g')\n gmode=1;\nelseif any(mode=='G') || ~nargout\n gmode=2;\nelse\n gmode=0;\nend\nif gmode>0\n fig0=gcf; % initialize the figure\nend\nif any(mode=='k')\n modeh='kxt';\nelse\n modeh='t';\nend\n\n% determine a global camera rotation\n\nif any(mode=='a')\n qrc=zeros(4,nc); % calculate the mean camera orientation\n for i=1:nc\n qrc(:,i)=rotro2qr(roc(:,:,i));\n end\n rocmean=rotqr2ro(rotqrmean(qrc));\nelse\n rocmean=eye(3);\nend\n\n% now do image transformations\n\nimr=cell(ncr,1);\nxa=imr;\nya=imr;\naxh=zeros(nc,1);\nsplx=ceil(sqrt(nc));\nsply=ceil(nc/splx);\nfor i=1:nc\n k0i=k0(:,:,1+vv*(i-1)); % camera parameters\n if numel(k0i)<9\n imsz=size(ims{i});\n fe=k0(1);\n if fe<0.1*imsz(2) % focal length is a fraction of the width\n fe=k0*imsz(2);\n end\n if numel(k0i)<3\n xy0=(imsz(2:-1:1)+1)/2;\n else\n xy0=k0i(2:3);\n end\n k0=eye(3);\n k0(1:4:5)=fe;\n k0(7:8)=xy0;\n end\n j=min(i,ncr);\n rocall=rocmean*roc(:,:,i)';\n titl=sprintf('%d: pan-tilt-roll = %.1f\u00b0, %.1f\u00b0, %.1f\u00b0',i,-rotro2eu('yxz',rocall)*180/pi);\n [imr{j},xa{j},ya{j}]=imagehomog(uint8(ims{i}),k0*rocall/k0,modeh); % apply inverse of rotation matrix\n if gmode>0\n if gmode>1\n subplot(sply,splx,i);\n else\n figure(fig0+i-1);\n end\n imagesc(xa{j},ya{j},imr{j});\n axis image\n title(titl);\n axh(i)=gca;\n end\nend\nif gmode>0 && nc>1\n if ~any(mode=='l')\n linkaxes(axh);\n end\n figure(fig0);\nend\n", "meta": {"author": "covarep", "repo": "covarep", "sha": "5a2be5d6b776f14a0b275c69fde90eb13849e60d", "save_path": "github-repos/MATLAB/covarep-covarep", "path": "github-repos/MATLAB/covarep-covarep/covarep-5a2be5d6b776f14a0b275c69fde90eb13849e60d/external/voicebox/rectifyhomog.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.6187804478040616, "lm_q1q2_score": 0.48916470458910893}} {"text": "function [fix_up,fix_down] = presolve_fixvariables(A,b,c,lb,ub,monotinicity)\n\n% These are optimally (or w.l.o.g) set to upper bound\nnot_in_obj = find(c<=0);\n% Setting to 1 makes Ax=0,1);\n% and they enter via a psd matrix in all sdp constraints\nsdp_positive = monotinicity(not_in_obj) == -1;\n% these variables satisffy all constraints\ncan_fix = not_in_obj(find(constrained_blow & sdp_positive));\n% these variables are still not fixed\nstill_on = find(lb==0 & ub==1);\n% so we can fix these\nfix_up = intersect(can_fix,still_on);\n\n% These are optimally (or w.l.o.g) set to lower bound\nnot_in_obj = find(c>=0);\n% Setting to 1 makes Ax=0,1);\n% and they enter via a psd matrix in all sdp constraints\nsdp_positive = monotinicity(not_in_obj) == 1;\n% these variables satisffy all constraints\ncan_fix = not_in_obj(find(constrained_blow & sdp_positive));\n% these variables are still not fixed\nstill_on = find(lb==0 & ub==1);\n% so we can fix these\nfix_down = intersect(can_fix,still_on);\n\n", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/modules/global/presolve_fixvariables.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397348, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4891646995814854}} {"text": "Iref=(im2double(imread('test.jpg')));\ntau=[0.2,0.3,0.1,0.2,200,100];\n% tau=[0,0,0,0,50,100];\nIt=Iref;\nfor i=1:3\nIt(:,:,i)=warpImg(Iref(:,:,i),tau);\nend\n\nimshow([Iref,It])\n\ntic\n[ImTrans,tau] = align(It,Iref, zeros(6,1),2);\ntoc;\nimshow([It,Iref,ImTrans,10*abs(ImTrans-Iref)])", "meta": {"author": "csjcai", "repo": "RealSR", "sha": "f8c724ad8363b6f51c1ccfe8ccd9a08f9c845e7c", "save_path": "github-repos/MATLAB/csjcai-RealSR", "path": "github-repos/MATLAB/csjcai-RealSR/RealSR-f8c724ad8363b6f51c1ccfe8ccd9a08f9c845e7c/Alignment/Opt_reg/demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4891646934740853}} {"text": "function net=initWeight(net,opts)\nnum=numel(net.layers);\nfor layer=1:num\n if(strcmp(net.layers{layer}.type,'conv'))\n [h,w,in,out]=size(net.layers{layer}.weights{1});\n net.layers{layer}.weights={init_weight(opts, h, w, in, out, 'single'),ones(out, 1, 'single')*opts.initBias};\n end\nend\nend\n", "meta": {"author": "zqs1022", "repo": "interpretableCNN", "sha": "6d7d1a6aaf0f1b2b03a3b54d4ac4803b3f1ce823", "save_path": "github-repos/MATLAB/zqs1022-interpretableCNN", "path": "github-repos/MATLAB/zqs1022-interpretableCNN/interpretableCNN-6d7d1a6aaf0f1b2b03a3b54d4ac4803b3f1ce823/code/tool/nets/initWeight.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4891646934740853}} {"text": "function modelConstrained = addCouplingConstraint(model, rxnList, c, d, ineqSense)\n% Constrains one (weighted) sum of fluxes to be above a lower bound.\n% Appends to existing inequality constraints if they are present\n%\n% USAGE:\n%\n% modelConstrained = constrainRxnListAboveBound(model, rxnList, c, d, ineqSense)\n%\n% INPUTS:\n% model: model structure\n% rxnList: cell array of reaction names\n%\n% OPTIONAL INPUTS:\n% c: `k x 1` vector :math:`c*v \\geq d`\n% d: `n x 1` vector :math:`c*v \\geq d`\n% ineqSense: `k x 1` inequality sense {'L','G'}\n%\n% OUTPUT:\n% modelConstrained: constrained model:\n%\n% * S - Stoichiometric matrix\n% * b - Right hand side = dx/dt\n% * C - Inequality constraint matrix\n% * d - Inequality constraint right hand side\n% :math:`[S; C] * v {=, \\leq, \\geq } [dxdt, d]` \n\n% EXAMPLE:\n%\n% rxnList = {'PCHOLP_hs_f', 'PLA2_2_f', 'SMS_f','PCHOLP_hs_b', 'PLA2_2_b', 'SMS_b'};\n% c = [1, 1, 1, 1, 1, 1];\n% d = 10;\n% ineqSense = 'G';\n% modelConstrained = constrainRxnListAboveBound(modelIrrev, rxnList, C, d, ineqSense);\n\nmodelConstrained = addCOBRAConstraints(model, rxnList ,d ,'c',c,'dsense',ineqSense);\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/coupling/addCouplingConstraint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4891646934740853}} {"text": "close all; clear all\n\nimgname = 'trace-without-GP';\noutfile = fullfile(pwd,'/simresults/20-01-15-out-GP-without-GP.mat');\nkplot = 558;\n\nimgname = 'trace-with-GP';\noutfile = fullfile(pwd,'/simresults/20-01-15-out-GP-with-GP-optimized.mat');\nkplot = 412\n\nload(outfile)\n\n\n[trackdata, x0, th0, w] = RaceTrack.loadTrack_02();\ntrack = RaceTrack(trackdata, x0, th0, w);\n\ntrackAnim = SingleTrackAnimation(track, out.mu_x_pred_opt, out.var_x_pred_opt, out.u_pred_opt, out.x_ref);\ntrackAnim.initTrackAnimation();\ndrawnow;\n\n% k = find(~isnan(out.xhat(1,:)), 1, 'last' ) - 1;\n\ntrackAnim.mu_x_pred_opt = out.mu_x_pred_opt;\ntrackAnim.var_x_pred_opt = out.var_x_pred_opt;\ntrackAnim.u_pred_opt = out.u_pred_opt;\ntrackAnim.x_ref = out.x_ref;\ntrackAnim.updateTrackAnimation(kplot); % 558\n\n\ndelete(trackAnim.h_car)\ndelete(trackAnim.h_x_ref)\ndelete(trackAnim.h_mu_x_pred_opt)\ncellfun( @(h) delete(h), trackAnim.h_var_x_pred_opt )\nlegend('off')\ntitle('')\nfp.savefig(imgname,'format','epsc')\n\n\n\n\n\n%% CHECK RELAXED BARRIER FUNCTION PLOT\n\n\nx = -0.5:0.001:0.5;\n% Relaxied barrier function for (x<=lambda)\ngamma = 10000;\nlambda = -0.2;\ny = 0.5*(sqrt((4+gamma*(lambda-x).^2)/gamma) - (lambda-x)); \nfigure('Color','w'); hold on; %grid on;\nplot(x,y,'LineWidth',2)\nylim([0,0.1])\nxlim([-0.4,0])\nset(gca,'YTickLabel',[]);\nset(gca,'XTickLabel',[]);\n%%%%\nlambda = -0.2;\nx = -0.6:0.001:(lambda-eps);\ny = 0.1*-log(lambda-x);\nfigure('Color','w'); hold on; %grid on;\nplot(x,y,'LineWidth',2)\nxlim([-0.6,0])\n\n", "meta": {"author": "lucasrm25", "repo": "Gaussian-Process-based-Model-Predictive-Control", "sha": "ef00c0df1ff25fb75f6f9c3d9099d47c9cfe1078", "save_path": "github-repos/MATLAB/lucasrm25-Gaussian-Process-based-Model-Predictive-Control", "path": "github-repos/MATLAB/lucasrm25-Gaussian-Process-based-Model-Predictive-Control/Gaussian-Process-based-Model-Predictive-Control-ef00c0df1ff25fb75f6f9c3d9099d47c9cfe1078/test-files/genFigs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4891646934740853}} {"text": "function y = log_sum_exp( x, dim )\n\n%LOG_SUM_EXP log(sum(exp(x))).\n% LOG_SUM_EXP(X) = LOG(SUM(EXP(X)).\n%\n% When used in a CVX model, LOG_SUM_EXP(X) causes CVX's successive\n% approximation method to be invoked, producing results exact to within\n% the tolerance of the solver. This is in contrast to LOGSUMEXP_SDP,\n% which uses a single SDP-representable global approximation.\n%\n% If X is a matrix, LOGSUMEXP_SDP(X) will perform its computations\n% along each column of X. If X is an N-D array, LOGSUMEXP_SDP(X)\n% will perform its computations along the first dimension of size\n% other than 1. LOGSUMEXP_SDP(X,DIM) will perform its computations\n% along dimension DIM.\n%\n% Disciplined convex programming information:\n% LOG_SUM_EXP(X) is convex and nondecreasing in X; therefore, X\n% must be convex (or affine).\n\nnarginchk(1,2);\nif ~isreal( x ),\n error( 'Argument must be real.' );\nend\ny = exp( x );\nif nargin == 1,\n y = sum( y );\nelse\n y = sum( y, dim );\nend\ny = log( y );\n\n% Copyright 2005-2016 CVX Research, Inc. \n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/functions/log_sum_exp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4891646934740853}} {"text": "% CRTP.m - Create an initial population\n%\n% This function creates a binary population of given size and structure.\n%\n% Syntax: [Chrom Lind BaseV] = crtbp(Nind, Lind, Base)\n%\n% Input Parameters:\n%\n%\t\tNind\t- Either a scalar containing the number of individuals\n%\t\t\t in the new population or a row vector of length two\n%\t\t\t containing the number of individuals and their length.\n%\n%\t\tLind\t- A scalar containing the length of the individual\n%\t\t\t chromosomes.\n%\n%\t\tBase\t- A scalar containing the base of the chromosome \n%\t\t\t elements or a row vector containing the base(s) \n%\t\t\t of the loci of the chromosomes.\n%\n% Output Parameters:\n%\n%\t\tChrom\t- A matrix containing the random valued chromosomes \n%\t\t\t row wise.\n%\n%\t\tLind\t- A scalar containing the length of the chromosome.\n%\n%\t\tBaseV\t- A row vector containing the base of the \n%\t\t\t chromosome loci.\n\n% Author: Andrew Chipperfield\n% Date:\t19-Jan-94\n\nfunction [Chrom, Lind, BaseV] = crtbp(Nind, Lind, Base)\nnargs = nargin ;\n\n% Check parameter consistency\n\nif nargs >= 1, [mN, nN] = size(Nind) ; end\nif nargs >= 2, [mL, nL] = size(Lind) ; end\nif nargs == 3, [mB, nB] = size(Base) ; end\n\nif nN == 2\n if (nargs == 1) \n Lind = Nind(2) ; Nind = Nind(1) ; BaseV = crtbase(Lind) ;\n elseif (nargs == 2 & nL == 1) \n BaseV = crtbase(Nind(2),Lind) ; Lind = Nind(2) ; Nind = Nind(1) ; \n elseif (nargs == 2 & nL > 1) \n if Lind ~= length(Lind), error('Lind and Base disagree'); end\n BaseV = Lind ; Lind = Nind(2) ; Nind = Nind(1) ; \n end\nelseif nN == 1\n if nargs == 2\n if nL == 1, BaseV = crtbase(Lind) ;\n else, BaseV = Lind ; Lind = nL ; end\n elseif nargs == 3\n if nB == 1, BaseV = crtbase(Lind,Base) ; \n elseif nB ~= Lind, error('Lind and Base disagree') ; \n else BaseV = Base ; end\n end\nelse\n error('Input parameters inconsistent') ;\nend\n\n% Create a structure of random chromosomes in row wise order, dimensions\n% Nind by Lind. The base of each chromosomes loci is given by the value\n% of the corresponding element of the row vector base.\n\nChrom = floor(rand(Nind,Lind).*BaseV(ones(Nind,1),:)) ;\n\n\n% End of file \n\u001a", "meta": {"author": "vonsylvia", "repo": "MATLAB_Algorithm_with_cases", "sha": "646e51a377568889f48b8fdebbc44f0a2514048a", "save_path": "github-repos/MATLAB/vonsylvia-MATLAB_Algorithm_with_cases", "path": "github-repos/MATLAB/vonsylvia-MATLAB_Algorithm_with_cases/MATLAB_Algorithm_with_cases-646e51a377568889f48b8fdebbc44f0a2514048a/\u652f\u6301\u5411\u91cf\u673a\u5206\u7c7b\u2014\u2014\u57fa\u4e8e\u4e73\u817a\u7ec4\u7ec7\u7535\u963b\u6297\u7279\u6027\u7684\u4e73\u817a\u764c\u8bca\u65ad/libsvm-mat-2[1].89-3[FarutoUltimate3.0Mcode]/implement[by faruto]/myprivate/gatbx[Sheffield]/crtbp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4891646934740853}} {"text": "function pred = FDDL_pred(Y, D, CoefM, opts) % GC\n vgamma = opts.gamma;\n opts.max_iter = 100;\n [X, ~] = lasso_fista(Y, D, zeros(size(D,2), size(Y,2)), vgamma, opts);\n C = size(CoefM,2);\n % w = 0.5;\n E = zeros(C, size(Y,2));\n for c = 1: C \n Dc = get_block_col(D, c, opts.D_range);\n Xc = get_block_row(X, c, opts.D_range);\n R1 = Y - Dc*Xc;\n E1 = sum(R1.^2);\n R2 = X - repmat(CoefM(:, c), 1, size(Y,2));\n E2 = sum(R2.^2);\n E(c,:) = E1 + opts.weight*E2;\n end \n [~, pred] = min(E);\nend ", "meta": {"author": "tiepvupsu", "repo": "DICTOL", "sha": "1a0361aa35c32d70525d06910d0e9b87997ff246", "save_path": "github-repos/MATLAB/tiepvupsu-DICTOL", "path": "github-repos/MATLAB/tiepvupsu-DICTOL/DICTOL-1a0361aa35c32d70525d06910d0e9b87997ff246/LRSDL_FDDL/FDDL_pred.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48916468736668506}} {"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 [L,dL] = vpbndloss(theta,vp,thetabnd,TolCon)\n%VPLOSS Variational parameter loss function for soft optimization bounds.\n\ncompute_grad = nargout > 1; % Compute gradient only if requested\n\nK = vp.K;\nD = vp.D;\n\nif vp.optimize_mu\n mu = theta(1:K*D);\n idx_start = K*D;\nelse\n mu = vp.mu(:)';\n idx_start = 0;\nend\nif vp.optimize_sigma\n lnsigma = theta(idx_start+(1:K));\n idx_start = idx_start + K;\nelse\n lnsigma = log(vp.sigma(:));\nend\nif vp.optimize_lambda\n lnlambda = theta(idx_start+(1:D));\nelse\n lnlambda = log(vp.lambda(:));\nend\nif vp.optimize_weights\n eta = theta(end-K+1:end); \nelse\n eta = [];\nend\n\nlnscale = bsxfun(@plus,lnsigma(:)',lnlambda(:));\ntheta_ext = [];\nif vp.optimize_mu; theta_ext = [theta_ext; mu(:)]; end\nif vp.optimize_sigma || vp.optimize_lambda; theta_ext = [theta_ext; lnscale(:)]; end\nif vp.optimize_weights; theta_ext = [theta_ext; eta(:)]; end\n\nif compute_grad\n [L,dL] = softbndloss(theta_ext,thetabnd.lb(:),thetabnd.ub(:),TolCon);\n if vp.optimize_mu\n dmu = dL(1:D*K);\n idx_start = D*K;\n else\n dmu = [];\n idx_start = 0;\n end\n if vp.optimize_sigma || vp.optimize_lambda\n dlnscale = reshape(dL((1:D*K)+idx_start),[D,K]);\n if vp.optimize_sigma\n dsigma = sum(dlnscale,1);\n else\n dsigma = [];\n end\n if vp.optimize_lambda\n dlambda = sum(dlnscale,2);\n else\n dlambda = [];\n end\n else\n dsigma = []; dlambda = [];\n end\n if vp.optimize_weights\n deta = dL(end-K+1:end); \n else\n deta = [];\n end\n dL = [dmu(:); dsigma(:); dlambda(:); deta(:)];\nelse\n L = softbndloss(theta_ext,thetabnd.lb(:),thetabnd.ub(:),TolCon);\nend\n\nend", "meta": {"author": "acerbilab", "repo": "vbmc", "sha": "54ba2cdd6c11d2595b9613557da14573abbb7b92", "save_path": "github-repos/MATLAB/acerbilab-vbmc", "path": "github-repos/MATLAB/acerbilab-vbmc/vbmc-54ba2cdd6c11d2595b9613557da14573abbb7b92/misc/vpbndloss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.4890325729319968}} {"text": "function refPh = referencePhase(sessions,roiName,viewType,dataType,fileNameSuffix)\n\n% function refPh = referencePhase(sessions,ROIname,[viewType],[dataType],[fileNameSuffix])\n%\n% Loops through sessions, averaging across scans to compute\n% the average response phase. Uses the output of analyzeSessions so\n% you have to run that first on the same sessions and ROI.\n%\n% datadr: top level data directory, e.g., datadr = /usr/local/mri/mrLoadRet2/'\n%\n% sessions: struct array with subdir and referenceScans fields, e.g.,\n% sessions(1).subdir = '121897';\n% sessions(1).referenceScans = [1:10];\n% where the referenceScans field lists all the scans in that session that\n% will be included in the calculation of the referencePhase. This\n% might include only one scan per session or it might include all of the scans\n% to get the grand mean.\n%\n% roiName: name of the ROI\n%\n% fileNameSuffix: specifies data file output from analyzeSessions.\n% Default is:\n% fileNameSuffix = ''; \n% so that the default filename is: roiName.mat\n%\n% djh, 2/2/2001\n\nmrGlobals\n\nif ~exist('viewType','var')\n viewType = 'Inplane';\nend\nif ~exist('dataType','var')\n dataType = 'Original';\nend\nif ~exist('fileNameSuffix','var')\n fileNameSuffix = '';\nend\n\n% Loop through sessions\nrepeats = [];\nfor s = 1:length(sessions)\n\tHOMEDIR = sessions(s).path;\n loadSession(HOMEDIR); %changed from loadsession to loadSession (BZL)\n \n % Open hidden view of the chosen viewType (either 'Inplane' or 'Gray')\n switch viewType\n case 'Inplane'\n view = initHiddenInplane;\n case 'Gray'\n view = initHiddenGray;\n otherwise\n error('analyzeSessions: supports only Inplane and Gray views.');\n end\n \n % Select chosen data type\n view = selectDataType(view,existDataType(dataType));\n \n fileName = [roiName,fileNameSuffix];\n load(fullfile(dataDir(view),'Analysis',fileName));\n % Loop through scans\n for scan=sessions(s).referenceScans\n amp = analysis.amps(scan);\n ph = analysis.phs(scan);\n repeats = [repeats, amp*exp(j*ph)];\n end\nend\nmeanRef = mean(repeats(isfinite(repeats)));\nrefPh = angle(meanRef);\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Analysis/BlockAnalysis/computeReferencePhase.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.48903257293199665}} {"text": "function showCollectionStatistics(collections, legendString, ...\n collectionColors, collectionMarkers)\n% Displays the items in collectionStats uusing scatter plots\n\n%% Plot median versus SDR overall channel deviation\nbaseTitle = 'Median versus SDR overall channel deviation';\nfigure ('Name', baseTitle, 'Color', [1, 1, 1]);\nhold on\nfor k = 1:length(collections)\n stats = collections{k}.statistics;\n s = collections{k}.statisticsIndex;\n plot(stats(:, s.medDev), stats(:, s.rSDDev), ...\n 'Color', collectionColors(k, :), ...\n 'Marker', collectionMarkers{k}, 'LineStyle', 'none', ...\n 'MarkerSize', 12, 'LineWidth', 2);\nend\nxlabel('Median overall channel deviation');\nylabel('Robust SD overall channel deviation');\ntitle(baseTitle, 'interpreter', 'none')\nfor k = 1:length(collections)\n stats = collections{k}.statistics;\n s = collections{k}.statisticsIndex;\n medDev = median(stats(:, s.medDev));\n rSDDev = median(stats(:, s.rSDDev));\n plot(medDev, rSDDev, 'Color', collectionColors(k, :), ...\n 'Marker', collectionMarkers{k}, 'MarkerSize', 14, 'LineWidth', 3);\nend\nlegend(legendString, 'Location', 'NorthEast')\nbox on\nhold off\n\n%% Plot median versus SDR window channel deviation\nbaseTitle = 'Median versus SDR window channel deviation';\nfigure ('Name', baseTitle, 'Color', [1, 1, 1]);\nhold on\nfor k = 1:length(collections)\n stats = collections{k}.statistics;\n s = collections{k}.statisticsIndex;\n plot(stats(:, s.medWinDev), stats(:, s.rSDWinDev), ...\n 'Color', collectionColors(k, :), ...\n 'Marker', collectionMarkers{k}, 'LineStyle', 'none', ...\n 'MarkerSize', 12, 'LineWidth', 2);\nend\nxlabel('Median window channel deviation');\nylabel('Robust SD window channel deviation');\ntitle(baseTitle, 'interpreter', 'none')\nfor k = 1:length(collections)\n stats = collections{k}.statistics;\n s = collections{k}.statisticsIndex;\n medDev = median(stats(:, s.medWinDev));\n rSDDev = median(stats(:, s.rSDWinDev));\n plot(medDev, rSDDev, 'Color', collectionColors(k, :), ...\n 'Marker', collectionMarkers{k}, 'MarkerSize', 14, 'LineWidth', 3);\nend\nlegend(legendString, 'Location', 'NorthEast')\nbox on\nhold off\n\n%% Plot median maximum correlation versus median window channel deviation\nbaseTitle = 'Median max correlation versus median window channel deviation';\nfigure ('Name', baseTitle, 'Color', [1, 1, 1]);\nhold on\nfor k = 1:length(collections)\n stats = collections{k}.statistics;\n s = collections{k}.statisticsIndex;\n plot(stats(:, s.medCor), stats(:, s.medWinDev), ...\n 'Color', collectionColors(k, :), ...\n 'Marker', collectionMarkers{k}, 'LineStyle', 'none', ...\n 'MarkerSize', 12, 'LineWidth', 2);\nend\nxlabel('Median maximum correlation');\nylabel('Median window channel deviation');\ntitle(baseTitle, 'interpreter', 'none')\nfor k = 1:length(collections)\n stats = collections{k}.statistics;\n s = collections{k}.statisticsIndex;\n medDev = median(stats(:, s.medWinDev));\n medCor = median(stats(:, s.medCor));\n plot(medCor, medDev, 'Color', collectionColors(k, :), ...\n 'Marker', collectionMarkers{k}, 'MarkerSize', 14, 'LineWidth', 3);\nend\nlegend(legendString, 'Location', 'NorthEast')\nbox on\nhold off\n\n%% Plot median maximum correlation versus window channel deviation ratio\nbaseTitle = 'Median max correlation versus window channel deviation ratio';\nfigure ('Name', baseTitle, 'Color', [1, 1, 1]);\nhold on\nfor k = 1:length(collections)\n stats = collections{k}.statistics;\n s = collections{k}.statisticsIndex;\n devRatio = stats(:, s.rSDWinDev)./stats(:, s.medWinDev);\n plot(stats(:, s.medCor), devRatio, ...\n 'Color', collectionColors(k, :), ...\n 'Marker', collectionMarkers{k}, 'LineStyle', 'none', ...\n 'MarkerSize', 12, 'LineWidth', 2);\nend\nxlabel('Median maximum correlation');\nylabel('Window channel deviation ratio');\ntitle(baseTitle, 'interpreter', 'none')\nfor k = 1:length(collections)\n stats = collections{k}.statistics;\n s = collections{k}.statisticsIndex;\n medRatio = median(stats(:, s.rSDWinDev)./stats(:, s.medWinDev));\n medCor = median(stats(:, s.medCor));\n plot(medCor, medRatio, 'Color', collectionColors(k, :), ...\n 'Marker', collectionMarkers{k}, 'MarkerSize', 14, 'LineWidth', 3);\nend\nlegend(legendString, 'Location', 'NorthEast')\nbox on\nhold off\n\n%% Plot average maximum correlation versus median window channel deviation\nbaseTitle = 'Average max correlation versus median window channel deviation';\nfigure ('Name', baseTitle, 'Color', [1, 1, 1]);\nhold on\nfor k = 1:length(collections)\n stats = collections{k}.statistics;\n s = collections{k}.statisticsIndex;\n plot(stats(:, s.aveCor), stats(:, s.medWinDev), ...\n 'Color', collectionColors(k, :), ...\n 'Marker', collectionMarkers{k}, 'LineStyle', 'none', ...\n 'MarkerSize', 12, 'LineWidth', 2);\nend\nxlabel('Average maximum correlation');\nylabel('Median window channel deviation');\ntitle(baseTitle, 'interpreter', 'none')\nfor k = 1:length(collections)\n stats = collections{k}.statistics;\n s = collections{k}.statisticsIndex;\n medDev = median(stats(:, s.medWinDev));\n aveCor = median(stats(:, s.aveCor));\n plot(aveCor, medDev, 'Color', collectionColors(k, :), ...\n 'Marker', collectionMarkers{k}, 'MarkerSize', 14, 'LineWidth', 3);\nend\nlegend(legendString, 'Location', 'NorthEast')\nbox on\nhold off\n\n%% Plot average maximum correlation versus window channel deviation ratio\nbaseTitle = 'Average max correlation versus window channel deviation ratio';\nfigure ('Name', baseTitle, 'Color', [1, 1, 1]);\nhold on\nfor k = 1:length(collections)\n stats = collections{k}.statistics;\n s = collections{k}.statisticsIndex;\n devRatio = stats(:, s.rSDWinDev)./stats(:, s.medWinDev);\n plot(stats(:, s.aveCor), devRatio, ...\n 'Color', collectionColors(k, :), ...\n 'Marker', collectionMarkers{k}, 'LineStyle', 'none', ...\n 'MarkerSize', 12, 'LineWidth', 2);\nend\nxlabel('Average maximum correlation');\nylabel('Window channel deviation ratio');\ntitle(baseTitle, 'interpreter', 'none')\nfor k = 1:length(collections)\n stats = collections{k}.statistics;\n s = collections{k}.statisticsIndex;\n medRatio = median(stats(:, s.rSDWinDev)./stats(:, s.medWinDev));\n aveCor = median(stats(:, s.aveCor));\n plot(aveCor, medRatio, 'Color', collectionColors(k, :), ...\n 'Marker', collectionMarkers{k}, 'MarkerSize', 14, 'LineWidth', 3);\nend\nlegend(legendString, 'Location', 'NorthEast')\nbox on\nhold off\n\n\n%% Plot median versus SDR overall HF noise\nbaseTitle = 'Median versus SDR overall HF noise';\nfigure ('Name', baseTitle, 'Color', [1, 1, 1]);\nhold on\nfor k = 1:length(collections)\n stats = collections{k}.statistics;\n s = collections{k}.statisticsIndex;\n plot(stats(:, s.medHF), stats(:, s.rSDHF), ...\n 'Color', collectionColors(k, :), ...\n 'Marker', collectionMarkers{k}, 'LineStyle', 'none', ...\n 'MarkerSize', 12, 'LineWidth', 2);\nend\nxlabel('Median overall HF noise');\nylabel('Robust SD overall HF noise');\ntitle(baseTitle, 'interpreter', 'none')\nfor k = 1:length(collections)\n stats = collections{k}.statistics;\n s = collections{k}.statisticsIndex;\n medHF = median(stats(:, s.medHF));\n rSDHF = median(stats(:, s.rSDHF));\n plot(medHF, rSDHF, 'Color', collectionColors(k, :), ...\n 'Marker', collectionMarkers{k}, 'MarkerSize', 14, 'LineWidth', 3);\nend\nlegend(legendString, 'Location', 'NorthEast')\nbox on\nhold off\n\n%% Plot median versus SDR window HF noise\nbaseTitle = 'Median versus SDR window HF noise';\nfigure ('Name', baseTitle, 'Color', [1, 1, 1]);\nhold on\nfor k = 1:length(collections)\n stats = collections{k}.statistics;\n s = collections{k}.statisticsIndex;\n plot(stats(:, s.medWinHF), stats(:, s.rSDWinHF), ...\n 'Color', collectionColors(k, :), ...\n 'Marker', collectionMarkers{k}, 'LineStyle', 'none', ...\n 'MarkerSize', 12, 'LineWidth', 2);\nend\nxlabel('Median window HF noise');\nylabel('Robust SD window HF noise');\ntitle(baseTitle, 'interpreter', 'none')\nfor k = 1:length(collections)\n stats = collections{k}.statistics;\n s = collections{k}.statisticsIndex;\n medHF = median(stats(:, s.medWinHF));\n rSDHF = median(stats(:, s.rSDWinHF));\n plot(medHF, rSDHF, 'Color', collectionColors(k, :), ...\n 'Marker', collectionMarkers{k}, 'MarkerSize', 14, 'LineWidth', 3);\nend\nlegend(legendString, 'Location', 'NorthEast')\nbox on\nhold off\n\n%% Plot median maximum correlation versus median window HF noise\nbaseTitle = 'Median max correlation versus median window HF noise';\nfigure ('Name', baseTitle, 'Color', [1, 1, 1]);\nhold on\nfor k = 1:length(collections)\n stats = collections{k}.statistics;\n s = collections{k}.statisticsIndex;\n plot(stats(:, s.medCor), stats(:, s.medWinHF), ...\n 'Color', collectionColors(k, :), ...\n 'Marker', collectionMarkers{k}, 'LineStyle', 'none', ...\n 'MarkerSize', 12, 'LineWidth', 2);\nend\nxlabel('Median maximum correlation');\nylabel('Median window channel HF noise');\ntitle(baseTitle, 'interpreter', 'none')\nfor k = 1:length(collections)\n stats = collections{k}.statistics;\n s = collections{k}.statisticsIndex;\n medHF = median(stats(:, s.medWinHF));\n medCor = median(stats(:, s.medCor));\n plot(medCor, medHF, 'Color', collectionColors(k, :), ...\n 'Marker', collectionMarkers{k}, 'MarkerSize', 14, 'LineWidth', 3);\nend\nlegend(legendString, 'Location', 'NorthEast')\nbox on\nhold off\n\n%% Plot median maximum correlation versus window channel HF noise ratio\nbaseTitle = 'Median max correlation versus window channel HF noise ratio';\nfigure ('Name', baseTitle, 'Color', [1, 1, 1]);\nhold on\nfor k = 1:length(collections)\n stats = collections{k}.statistics;\n s = collections{k}.statisticsIndex;\n HFRatio = stats(:, s.rSDWinHF)./stats(:, s.medWinHF);\n plot(stats(:, s.medCor), HFRatio, ...\n 'Color', collectionColors(k, :), ...\n 'Marker', collectionMarkers{k}, 'LineStyle', 'none', ...\n 'MarkerSize', 12, 'LineWidth', 2);\nend\nxlabel('Median maximum correlation');\nylabel('Window channel HF noise ratio');\ntitle(baseTitle, 'interpreter', 'none')\nfor k = 1:length(collections)\n stats = collections{k}.statistics;\n s = collections{k}.statisticsIndex;\n medRatio = median(stats(:, s.rSDWinHF)./stats(:, s.medWinHF));\n medCor = median(stats(:, s.medCor));\n plot(medCor, medRatio, 'Color', collectionColors(k, :), ...\n 'Marker', collectionMarkers{k}, 'MarkerSize', 14, 'LineWidth', 3);\nend\nlegend(legendString, 'Location', 'NorthEast')\nbox on\nhold off\n\n%% Plot average maximum correlation versus median window channel HF noise\nbaseTitle = 'Average max correlation versus median window channel HF noise';\nfigure ('Name', baseTitle, 'Color', [1, 1, 1]);\nhold on\nfor k = 1:length(collections)\n stats = collections{k}.statistics;\n s = collections{k}.statisticsIndex;\n plot(stats(:, s.aveCor), stats(:, s.medWinHF), ...\n 'Color', collectionColors(k, :), ...\n 'Marker', collectionMarkers{k}, 'LineStyle', 'none', ...\n 'MarkerSize', 12, 'LineWidth', 2);\nend\nxlabel('Average maximum correlation');\nylabel('Median window channel HF noise');\ntitle(baseTitle, 'interpreter', 'none')\nfor k = 1:length(collections)\n stats = collections{k}.statistics;\n s = collections{k}.statisticsIndex;\n medHF = median(stats(:, s.medWinHF));\n aveCor = median(stats(:, s.aveCor));\n plot(aveCor, medHF, 'Color', collectionColors(k, :), ...\n 'Marker', collectionMarkers{k}, 'MarkerSize', 14, 'LineWidth', 3);\nend\nlegend(legendString, 'Location', 'NorthEast')\nbox on\nhold off\n\n%% Plot average maximum correlation versus window channel HF noise ratio\nbaseTitle = 'Average max correlation versus window channel HF noise ratio';\nfigure ('Name', baseTitle, 'Color', [1, 1, 1]);\nhold on\nfor k = 1:length(collections)\n stats = collections{k}.statistics;\n s = collections{k}.statisticsIndex;\n HFRatio = stats(:, s.rSDWinHF)./stats(:, s.medWinHF);\n plot(stats(:, s.aveCor), HFRatio, ...\n 'Color', collectionColors(k, :), ...\n 'Marker', collectionMarkers{k}, 'LineStyle', 'none', ...\n 'MarkerSize', 12, 'LineWidth', 2);\nend\nxlabel('Average maximum correlation');\nylabel('Window channel HF noise ratio');\ntitle(baseTitle, 'interpreter', 'none')\nfor k = 1:length(collections)\n stats = collections{k}.statistics;\n s = collections{k}.statisticsIndex;\n medRatio = median(stats(:, s.rSDWinHF)./stats(:, s.medWinHF));\n aveCor = median(stats(:, s.aveCor));\n plot(aveCor, medRatio, 'Color', collectionColors(k, :), ...\n 'Marker', collectionMarkers{k}, 'MarkerSize', 14, 'LineWidth', 3);\nend\nlegend(legendString, 'Location', 'NorthEast')\nbox on\nhold off\n", "meta": {"author": "VisLab", "repo": "EEG-Clean-Tools", "sha": "9ac9ea0c21d44b57f9e9f93b62ca727c7b75c73e", "save_path": "github-repos/MATLAB/VisLab-EEG-Clean-Tools", "path": "github-repos/MATLAB/VisLab-EEG-Clean-Tools/EEG-Clean-Tools-9ac9ea0c21d44b57f9e9f93b62ca727c7b75c73e/PrepPipeline/reporting/showCollectionStatistics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.48903256578810855}} {"text": "% Author: Guanghan Ning, Feb 2017\nclear all;\nclc;\nclose all;\naddpath('../utils_eval_lsp/');\naddpath('../eval_LSP/');\nmat_folder_path = '../dataset_lsp/results_cropped/quantitative/';\nimg_folder_path = '../../dataset/LEEDS/lsp_dataset/images/';\n\nscale_in_cpp = load('../scale_in_cpp_LSP.mat');\nscale_in_cpp = scale_in_cpp.output_scale;\n\npred = zeros(2, 14, 1000);\nnum_test_imgs = 1000;\n\nfor img_id = 1:num_test_imgs\n\n base_name = strcat('im', num2str(img_id + 1000));\n img_path = strcat(img_folder_path, '/', base_name, '.jpg');\n img_info = imfinfo(img_path);\n org_img_size = [img_info.Width, img_info.Height];\n\n [x_preds_raw, y_preds_raw] = load_pred_result(mat_folder_path, base_name);\n\n for joint_id = 1:14 %joint_id in our joint order\n\n % Convert joint to lsp-defined order for evaluation\n id = convert_joint_order(joint_id); % id in LSP order\n\n % Convert predictions from 256 to image-size for evaluation\n pred_point_raw = [x_preds_raw(joint_id), y_preds_raw(joint_id)];\n [x_pred, y_pred]= convert_scale_cropped(pred_point_raw, org_img_size, scale_in_cpp(img_id));\n\n pred(1, id, img_id) = x_pred;\n pred(2, id, img_id) = y_pred;\n end\nend\nsave('../eval_LSP/pred/ning17iccv/pred_keypoints_lsp.mat','pred');\n\n%% Call Official evaluatePCKh() function to process the evaluation\nevaluatePCK(33,'PC', true); % 33 is my model index, using person-centric (PC)\n", "meta": {"author": "Guanghan", "repo": "GNet-pose", "sha": "c70e0fc65b290e68a16ca3040a70300f9c2bee44", "save_path": "github-repos/MATLAB/Guanghan-GNet-pose", "path": "github-repos/MATLAB/Guanghan-GNet-pose/GNet-pose-c70e0fc65b290e68a16ca3040a70300f9c2bee44/testing/eval_LSP/test_evaluation_lsp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.48901157243957705}} {"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 [positions, time] = tracker(video_path, img_files, pos, target_sz, ...\n\tpadding, kernel, lambda, output_sigma_factor, interp_factor, cell_size, ...\n\tfeatures, show_visualization)\n%TRACKER Kernelized/Dual Correlation Filter (KCF/DCF) tracking.\n% This function implements the pipeline for tracking with the KCF (by\n% choosing a non-linear kernel) and DCF (by choosing a linear kernel).\n%\n% It is meant to be called by the interface function RUN_TRACKER, which\n% sets up the parameters and loads the video information.\n%\n% Parameters:\n% VIDEO_PATH is the location of the image files (must end with a slash\n% '/' or '\\').\n% IMG_FILES is a cell array of image file names.\n% POS and TARGET_SZ are the initial position and size of the target\n% (both in format [rows, columns]).\n% PADDING is the additional tracked region, for context, relative to \n% the target size.\n% KERNEL is a struct describing the kernel. The field TYPE must be one\n% of 'gaussian', 'polynomial' or 'linear'. The optional fields SIGMA,\n% POLY_A and POLY_B are the parameters for the Gaussian and Polynomial\n% kernels.\n% OUTPUT_SIGMA_FACTOR is the spatial bandwidth of the regression\n% target, relative to the target size.\n% INTERP_FACTOR is the adaptation rate of the tracker.\n% CELL_SIZE is the number of pixels per cell (must be 1 if using raw\n% pixels).\n% FEATURES is a struct describing the used features (see GET_FEATURES).\n% SHOW_VISUALIZATION will show an interactive video if set to true.\n%\n% Outputs:\n% POSITIONS is an Nx2 matrix of target positions over time (in the\n% format [rows, columns]).\n% TIME is the tracker execution time, without video loading/rendering.\n%\n% Joao F. Henriques, 2014\n\n\n\t%if the target is large, lower the resolution, we don't need that much\n\t%detail\n\tresize_image = (sqrt(prod(target_sz)) >= 100); %diagonal size >= threshold\n\tif resize_image,\n\t\tpos = floor(pos / 2);\n\t\ttarget_sz = floor(target_sz / 2);\n\tend\n\n\n\t%window size, taking padding into account\n\twindow_sz = floor(target_sz * (1 + padding));\n\t\n% \t%we could choose a size that is a power of two, for better FFT\n% \t%performance. in practice it is slower, due to the larger window size.\n% \twindow_sz = 2 .^ nextpow2(window_sz);\n\n\t\n\t%create regression labels, gaussian shaped, with a bandwidth\n\t%proportional to target size\n \n \n\toutput_sigma = sqrt(prod(target_sz)) * output_sigma_factor / cell_size;\n if isfield(features, 'deep') && features.deep\n yf = fft2(gaussian_shaped_labels(output_sigma, ceil(window_sz / cell_size)));\n% sz = ceil(window_sz/cell_size)-1+4-4;\n% yf = fft2(gaussian_shaped_labels(output_sigma, sz));\n\n else\n yf = fft2(gaussian_shaped_labels(output_sigma, floor(window_sz / cell_size)));\n end\n\n\t%store pre-computed cosine window\n\tcos_window = hann(size(yf,1)) * hann(size(yf,2))';\t\n\t\n\t\n\tif show_visualization, %create video interface\n\t\tupdate_visualization = show_video(img_files, video_path, resize_image);\n\tend\n\t\n\t\n\t%note: variables ending with 'f' are in the Fourier domain.\n\n\ttime = 0; %to calculate FPS\n\tpositions = zeros(numel(img_files), 2); %to calculate precision\n\n\tfor frame = 1:numel(img_files),\n\t\t%load image\n\t\tim = imread([video_path img_files{frame}]);\n if ~isfield(features, 'deep')\n if size(im,3) > 1,\n im = rgb2gray(im);\n end\n end\n \n\t\tif resize_image,\n\t\t\tim = imresize(im, 0.5);\n\t\tend\n\n\t\ttic()\n\n\t\tif frame > 1,\n\t\t\t%obtain a subwindow for detection at the position from last\n\t\t\t%frame, and convert to Fourier domain (its size is unchanged)\n\t\t\tpatch = get_subwindow(im, pos, window_sz);\n\t\t\tzf = fft2(get_features(patch, features, cell_size, cos_window));\n\t\t\t\n\t\t\t%calculate response of the classifier at all shifts\n\t\t\tswitch kernel.type\n\t\t\tcase 'gaussian',\n\t\t\t\tkzf = gaussian_correlation(zf, model_xf, kernel.sigma);\n\t\t\tcase 'polynomial',\n\t\t\t\tkzf = polynomial_correlation(zf, model_xf, kernel.poly_a, kernel.poly_b);\n\t\t\tcase 'linear',\n\t\t\t\tkzf = linear_correlation(zf, model_xf);\n\t\t\tend\n\t\t\tresponse = real(ifft2(model_alphaf .* kzf)); %equation for fast detection\n\n\t\t\t%target location is at the maximum response. we must take into\n\t\t\t%account the fact that, if the target doesn't move, the peak\n\t\t\t%will appear at the top-left corner, not at the center (this is\n\t\t\t%discussed in the paper). the responses wrap around cyclically.\n\t\t\t[vert_delta, horiz_delta] = find(response == max(response(:)), 1);\n\t\t\tif vert_delta > size(zf,1) / 2, %wrap around to negative half-space of vertical axis\n\t\t\t\tvert_delta = vert_delta - size(zf,1);\n\t\t\tend\n\t\t\tif horiz_delta > size(zf,2) / 2, %same for horizontal axis\n\t\t\t\thoriz_delta = horiz_delta - size(zf,2);\n\t\t\tend\n\t\t\tpos = pos + cell_size * [vert_delta - 1, horiz_delta - 1];\n\t\tend\n\n\t\t%obtain a subwindow for training at newly estimated target position\n\t\tpatch = get_subwindow(im, pos, window_sz);\n\t\txf = fft2(get_features(patch, features, cell_size, cos_window));\n\n\t\t%Kernel Ridge Regression, calculate alphas (in Fourier domain)\n\t\tswitch kernel.type\n\t\tcase 'gaussian',\n\t\t\tkf = gaussian_correlation(xf, xf, kernel.sigma);\n\t\tcase 'polynomial',\n\t\t\tkf = polynomial_correlation(xf, xf, kernel.poly_a, kernel.poly_b);\n\t\tcase 'linear',\n\t\t\tkf = linear_correlation(xf, xf);\n\t\tend\n\t\talphaf = yf ./ (kf + lambda); %equation for fast training\n\n\t\tif frame == 1, %first frame, train with a single image\n\t\t\tmodel_alphaf = alphaf;\n\t\t\tmodel_xf = xf;\n\t\telse\n\t\t\t%subsequent frames, interpolate model\n\t\t\tmodel_alphaf = (1 - interp_factor) * model_alphaf + interp_factor * alphaf;\n\t\t\tmodel_xf = (1 - interp_factor) * model_xf + interp_factor * xf;\n\t\tend\n\n\t\t%save position and timing\n\t\tpositions(frame,:) = pos;\n\t\ttime = time + toc();\n\n\t\t%visualization\n\t\tif show_visualization,\n\t\t\tbox = [pos([2,1]) - target_sz([2,1])/2, target_sz([2,1])];\n\t\t\tstop = update_visualization(frame, box);\n\t\t\tif stop, break, end %user pressed Esc, stop early\n\t\t\t\n\t\t\tdrawnow\n% \t\t\tpause(0.05) %uncomment to run slower\n\t\tend\n\t\t\n\tend\n\n\tif resize_image,\n\t\tpositions = positions * 2;\n\tend\nend\n\n", "meta": {"author": "scott89", "repo": "KCF", "sha": "012d6b3401d3871001e6fd8a5722ab3c2e0843ad", "save_path": "github-repos/MATLAB/scott89-KCF", "path": "github-repos/MATLAB/scott89-KCF/KCF-012d6b3401d3871001e6fd8a5722ab3c2e0843ad/tracker.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933403143929, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4890115645651267}} {"text": "function m=ccwarpf(f,n,s)\n%CCWARPF Warp cepstral coefficients M=(F,N,S) \n% f(1) is the original sample freq, f(2) is the new sample freq\n% n(1) is the original number of coefficients, n(2) is the new number\n% s is a string: s(1),s(2) =l for linear, m for mel frequency, use capitals if c0 included\n\n\n% Copyright (C) Mike Brookes 1998\n% Version: $Id: ccwarpf.m,v 1.4 2007/05/04 07:01:38 dmb Exp $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif nargin<3\n s='ll';\nend\nif length(f)<2\n f(2)=1;\nend\nif length(n)<2\n n(2)=n(1);\nend\nz=s<'a';\ns=s+32*z;\nif all(s=='l')\n k=1:n(2)-z(2);\n ff=((1:n(1)).'-z(1))*f(2)/f(1);\n fa=2*sin(ff*pi).*ff/pi;\n fb=ff.^2;\n ka=1-2*rem(k,2);\n kb=k.^2;\n r1=ones(n(1),1);\n c1=ones(1,n(2)-z(2));\n a=fa(:,c1).*ka(r1,:);\n b=fb(:,c1)-kb(r1,:);\n f0=find(fix(ff)==ff);\n if length(f0)\n a(f0,:)=ff(f0,c1)==k(ones(length(f0),1),:);\n b(f0,:)=1;\n end\n m=a./b;\n if z(2)\n m=[[1; 0.5*fa(2:n(1))./fb(2:n(1))] m];\n end\nend\n\n\n\n", "meta": {"author": "decouples", "repo": "Matlab_deep_learning", "sha": "1b823b82686080e32b03e1f1a4648896bd6e3c44", "save_path": "github-repos/MATLAB/decouples-Matlab_deep_learning", "path": "github-repos/MATLAB/decouples-Matlab_deep_learning/Matlab_deep_learning-1b823b82686080e32b03e1f1a4648896bd6e3c44/\u7b2c 19 \u7ae0 \u57fa\u4e8e\u8bed\u97f3\u8bc6\u522b\u7684\u4fe1\u53f7\u706f\u56fe\u50cf\u6a21\u62df\u63a7\u5236\u6280\u672f/voicebox/ccwarpf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4890115619403097}} {"text": "function Seqs_SDC = Generate_SDC(Seqs_Long, rate)\n\nSeqs_SDC = Seqs_Long;\n\nparfor n = 1:length(Seqs_Long)\n Start_new = Seqs_Long(n).Start + ...\n rand*(Seqs_Long(n).Stop - Seqs_Long(n).Start)*(1-rate);\n \n Stop_new = Start_new + rate*(Seqs_Long(n).Stop - Seqs_Long(n).Start);\n \n Seqs_SDC(n).Start = Start_new;\n Seqs_SDC(n).Stop = Stop_new;\n \n ind = find(Seqs_SDC(n).Time>=Start_new && Seqs_SDC(n).Time<=Stop_new);\n Seqs_SDC(n).Time = Seqs_SDC(n).Time(ind);\n Seqs_SDC(n).Mark = Seqs_SDC(n).Mark(ind);\n if ~isempty(Seqs_SDC(n).Feature)\n Seqs_SDC(n).Feature = Seqs_SDC(n).Feature(ind,:);\n end\nend", "meta": {"author": "HongtengXu", "repo": "Hawkes-Process-Toolkit", "sha": "2548a41c7418b8edef3261ab4479cee4e8eaf071", "save_path": "github-repos/MATLAB/HongtengXu-Hawkes-Process-Toolkit", "path": "github-repos/MATLAB/HongtengXu-Hawkes-Process-Toolkit/Hawkes-Process-Toolkit-2548a41c7418b8edef3261ab4479cee4e8eaf071/Data/Generate_SDC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.48901155669067586}} {"text": "%% Create PNG image with alpha transparency\n%\n% The sample shows how to create an RGBA image and store it as a PNG file.\n% It also demonstrates how to set custom PNG compression parameters.\n%\n% Sources:\n%\n% * \n%\n\n%%\n% create image with alpha channel\nsz = [480 640];\nimg = create_rgba_image(sz);\nwhos img\n\n%%\n% write to PNG file with alpha data\nfname = fullfile(tempdir(), 'alpha.png');\nif true\n cv.imwrite(fname, img, 'PngCompression',9, 'PngStrategy','RLE');\nelse\n imwrite(img(:,:,1:3), fname, 'Alpha',img(:,:,4))\nend\nimfinfo(fname)\n\n%%\n% show image (over checkerboard image as background to better see transparency)\nbg = create_checkerboard_image(sz);\nfigure('Menubar','none', 'Color','k', 'Name','RGBA')\nif ~mexopencv.isOctave()\n imshow(bg, 'InitialMagnification',100, 'Border','tight')\nelse\n image(bg), axis image off\n set(gca, 'Units','normalized', 'Position',[0 0 1 1])\nend\nimage('CData',img(:,:,1:3), 'AlphaData',img(:,:,4))\n\n%%\n% Helper functions\n\nfunction img = create_rgba_image(sz)\n %CREATE_RGBA_IMAGE Create image with transparency, with a gradient effect\n\n nrows = sz(1);\n ncols = sz(2);\n img = zeros(nrows, ncols, 4, 'uint8');\n [I,J] = ndgrid(1:nrows, 1:ncols);\n img(:,:,1) = uint8(255 * (nrows-I+1)/nrows); % red\n img(:,:,2) = uint8(255 * (ncols-J+1)/ncols); % green\n img(:,:,3) = uint8(255); % blue\n img(:,:,4) = uint8(0.8 * sum(img(:,:,[1 2]),3)); % alpha\nend\n\nfunction img = create_checkerboard_image(sz)\n %CREATE_CHECKERBOARD_IMAGE Create checkerboard image\n\n % n should evenly divide both width and height\n if true\n n = 40; %HACK: hardcoded for 640x480\n else\n n = gcd(sz(1), sz(2));\n end\n s = sz / n;\n assert(isequal(s, fix(s)));\n img = kron(bsxfun(@xor, mod(1:s(1),2).', mod(1:s(2),2)), ones(n));\n img = repmat(max(img, 0.75), [1 1 3]);\n img = uint8(255 * img);\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/rgba_png_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.48899064759507027}} {"text": "% TEST_HANNING_STANDALONE Test case for HANNING_STANDALONE\n%\n% See also\n% HANNING (Signal Processing Toolbox)\n\nclassdef test_hanning_standalone < matlab.unittest.TestCase\n methods (Test)\n function testBasic(testcase)\n maxLength = 8191;\n for window_length = 1:maxLength % lasts a few seconds\n hanning_old = hanning(window_length); % requires DSP toolbox\n hanning_new = hanning_standalone(window_length);\n testcase.assertEqual(all(hanning_old==hanning_new));\n end\n end\n end\nend", "meta": {"author": "scatnet", "repo": "scatnet", "sha": "59d935afa20359845282a3518134e24244862c1f", "save_path": "github-repos/MATLAB/scatnet-scatnet", "path": "github-repos/MATLAB/scatnet-scatnet/scatnet-59d935afa20359845282a3518134e24244862c1f/unittest/scatutils/test_hanning_standalone.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 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": "%%********************************************************\n%%\n%% [A,B] = qapread('~/ZXY/PAL/QAP/qapdata/nug12.dat'); \n%%\n%% SDPNAL: \n%% Copyright (c) 2008 by\n%% Xinyuan Zhao, Defeng Sun, and Kim-Chuan Toh \n%%********************************************************\n\n function [A,B] = qapread(fname); \n\n fid = fopen(fname,'r');\n if (fid == -1); error('file cannot be opened'); end\n\n [datavec,count] = fscanf(fid,'%c');\n fclose('all'); \n linefeeds = findstr(datavec,char(10));\n datavec(linefeeds) = blanks(length(linefeeds)); \n datavec = sscanf(datavec,'%f'); \n\n n = datavec(1); n2 = n*n; \n aa = datavec(2:n2+1); \n bb = datavec(n2+2:2*n2+1); \n \n A = reshape(aa,n,n);\n B = reshape(bb,n,n); \n%%********************************************************\n", "meta": {"author": "intellhave", "repo": "SDRSAC", "sha": "b081721e9dfd7843d75aa12f30025b2bd7c8f024", "save_path": "github-repos/MATLAB/intellhave-SDRSAC", "path": "github-repos/MATLAB/intellhave-SDRSAC/SDRSAC-b081721e9dfd7843d75aa12f30025b2bd7c8f024/solvers/SDPNAL+v1.0/util/qapread.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.48893164203042233}} {"text": "%INTLAB long toolbox (rudimentary, slow but correct)\n%\n%Long constructors\n% long - Long constructor\n% long2dble - Long to double\n% long2intval - Long to intval\n% vertcat - Vertical concatenation [ ; ]\n% subsasgn - Subscripted assignment A(2:4) = 1\n% subsref - Subscripted reference r = A(3)\n%\n%Display of long numbers\n% display - Command window display for long\n% disp - Display function for pop-up windows in debugger\n%\n%Long arithmetic operations\n% plus - Plus +\n% uplus - Unary plus +\n% minus - Minus -\n% uminus - Unary minus -\n% mtimes - Elementwise multiply *\n% times - Elementwise multiply .*\n% mrdivide - Elementwise right division /\n% mldivide - Elementwise left division \\\n% rdivide - Elementwise right division ./\n% ldivide - Elementwise left division .\\\n% mpower - Elementwise power ^\n% power - Elementwise power .^\n% longshift - Shift by r bits\n%\n%Other long operations\n% min - minimum\n% max - maximum\n% abs - absolute value\n% mid - midpoint\n% rad - radius\n% diam - diameter\n% inf - infimum\n% sup - supremum\n%\n%Long comparisons\n% eq - equal ==\n% ne - not equal ~=\n% le - less equal <=\n% lt - less than <\n% ge - greater equal >=\n% gt - greater than >\n%\n%Utility routines\n%\n% isempty - Long is empty in Matlab sense, i.e. []\n% isnan - True for Not a Number\n% end - determine last index\n%\n%Structural operations\n% length - Length\n% size - Size\n%\n%Other long operations\n% longprecision- Sets/gets current precision\n% addlongerror - Add error to long number\n%\n%Some sample functions\n% exp - Exponential\n% longpi - Long computation of Pi\n%\n%Initialization of INTLAB long package and system variables\n% longinit - Initialization and definition of defaults\n%\n%Demonstration, samples\n% demolong - Some examples for using INTLAB long package\n%\n\n% written 12/30/98 S.M. Rump\n%\n% Copyright (c) Siegfried M. Rump, head of the Institute for Reliable Computing, \n% Hamburg University of Technology\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/Contents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.4889316333613757}} {"text": "% SCRIPT TEST THE DIRECT DYNAMICS OF A 3 DOF PLANAR ROBOT ROBOT\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\nclose all\n\nfprintf('\\nTHE SIMULATION PRESENTS THE ROBOT AT AN INITIAL POSITION WHEN NO TORQUES ARE APPLIED\\n')\n\n%load robot parameters\nrobot=load_robot('example', '3dofplanar');\n\n%simulate for 50 seconds, change this depending on your computer speed and\n%the total time that you want to simulate\ntotal_simulation_time = 10; \n\n%initial position and joint speed\nq0 = [0 0 0]';\nqd0 = [0 0 0]';\n\ndrawrobot3d(robot, q0);\nadjust_view(robot);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% The student should try different combinations of the following parameters:\n% g: the direction of the gravity vector. In this case, if we select g=[0 0 9.81]'; \n% the movement of the arm is not affected by the gravity, since it\n% moves in a plane perpendicular to the gravity vector.\n% tau: the torques applied to each joint. The student should observe the effects of selecting\n% tau = [0 0 0]' or different values in combination with the\n% direction of the vector g.\n% robot.dynamics.friction = 0 selects no friction at the joints, whereas\n% robot.dynamics.friction = 1 considers that there exists friction. This\n% friction is modelled by robot.motors.Viscous (viscous friction) and\n% robot.motors.Coulomb (Coulomb friction). The student should observe\n% that selecting g=[0 9.81 0]' and tau = [0 0 0]' and\n% robot.dynamics.friction = 0 turns into an infinite triple pendulum\n% movement. In addition, selecting selecting g=[0 9.81 0]' and tau = [0 0 0]' and\n% robot.dynamics.friction = 1 simulates the case in which the triple\n% pendulum converges to a steady solution with the three links\n% hanging along the Y direction.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%you may redefine the gravity vector\n%in this case you may one of the next two lines, that define\n%the gravity acting along the Y axis or the Z axis, respectively.\ng=[0 -9.81 0]'; %y axis\n%g=[0 0 9.81]'; % Z axis\n\n%tau = [3 2 1]';\ntau = [0 0 0]';%no torques applied\n\n%select friction or not\nrobot.dynamics.friction = 0;\n\nfprintf('\\nCOMPUTING FORWARD DYNAMICS (this may take a while)')\n\n%this may take a while, since it requires integration\n%of the acceleration at each time step\n[t, q, qd] = forwarddynamic(robot, total_simulation_time, q0, qd0, tau, g, []);\n\n%animate it!!\nanimate(robot, q)\n\nfigure, plot(t, q), grid, title('Position vs. time')\nxlabel('time (s)'), ylabel('Position (rad)')\nlegend('q_1', 'q_2', 'q_3', 'q_4', 'q_5', 'q_6');\n\nfigure, plot(t, qd), grid, title('Speed vs. time')\nxlabel('time (s)'), ylabel('Speed (rad/s)')\nlegend('qd_1', 'qd_2', 'qd_3', 'qd_4', 'qd_5', 'qd_6');", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/demos/forwarddynamics_3DOF_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.48889360416682015}} {"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 compareMapsByFields(map1, fields1, map2, fields2)\n % create features based on field properties, compare featrues\n \n numFields1 = length(fields1);\n numFields2 = length(fields2);\n distances = zeros(numFields2, 1);\n \n matchedPoints1 = zeros(numFields1, 2);\n matchedPoints2 = zeros(numFields1, 2);\n toRemove = false(numFields1, 1); % above matched data will be truncated based on toRemove variable\n \n matchedIndices = zeros(numFields1, 1);\n\n for i = 1:numFields1\n matchedPoints1(i, :) = [fields1(i).peakX fields1(i).peakY];\n features1 = fieldFeatures(fields1(i));\n \n for j = 1:numFields2\n features2 = fieldFeatures(fields2(j));\n distances(j) = hausdorffDistance(features1, features2);\n% peakPoint = [fields2(j).peakX fields2(j).peakY];\n% distances(j) = pdist2(matchedPoints1(i, :), peakPoint);\n end\n \n [minDist, minInd] = min(distances);\n if minDist < 21 && ~any(matchedIndices == minInd)\n% if ~any(matchedIndices == minInd)\n features2 = fieldFeatures(fields2(minInd));\n \n distance = pdist2(features1, features2);\n \n matchedPoints2(i, :) = [fields2(minInd).peakX fields2(minInd).peakY];\n matchedIndices(i) = minInd;\n else\n toRemove(i) = true;\n end\n fprintf('Field %u, distance %f, matched index %u\\n', i, minDist, minInd);\n \n end\n matchedPoints1(toRemove, :) = [];\n matchedPoints2(toRemove, :) = [];\n\n if ~isempty(matchedPoints1)\n figure;\n plot.matchedPoints(map1, map2, matchedPoints1, matchedPoints2);\n else\n fprintf('No matches\\n');\n end\nend\n\nfunction features = fieldFeatures(field)\n% features = zeros(5, 1);\n\n features(1) = field.x;\n features(2) = field.y;\n% features(3) = field.x;\n% features(4) = field.y;\n% features(3) = field.area;\n% features(1) = field.size;\n features(3) = field.Perimeter;\n features(4) = field.meanRate;\n% features(3) = field.Eccentricity;\n% features(4) = field.Extent;\n% features(5) = field.area;\n features(5) = field.Orientation;\nend", "meta": {"author": "kavli-ntnu", "repo": "MINI2P_toolbox", "sha": "83311a49baea69ecf027e19390e608fd4eaeae8d", "save_path": "github-repos/MATLAB/kavli-ntnu-MINI2P_toolbox", "path": "github-repos/MATLAB/kavli-ntnu-MINI2P_toolbox/MINI2P_toolbox-83311a49baea69ecf027e19390e608fd4eaeae8d/Analysis/+analyses/compareMapsByFields.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426303, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.48889358683571915}} {"text": "function value = sweet4_condition ( )\n\n%*****************************************************************************80\n%\n%% SWEET4_CONDITION returns the L1 condition of the SWEET4 matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 February 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real VALUE, the L1 condition.\n%\n a_norm = 100.3190000000000;\n b_norm = 0.510081684645161;\n value = a_norm * b_norm;\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/sweet4_condition.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.4888563545900975}} {"text": "function y = geomean( varargin )\n\n%GEOMEAN Geometric mean.\n% GEOMEAN(X) = GEO_MEAN(X) = PROD(X).^(1/LENGTH(X)). We have replaced this\n% function with GEO_MEAN to better match our function naming conventions.\n% Please start using it instead.\n\nwarning( 'CVX:Renamed', [ ...\n 'The function \"geomean\" has been renamed \"geo_mean\". Please start\\n', ...\n 'using the new name. The old name will be removed in a future release.' ], 1 );\n\ny = geo_mean( varargin{:} );\n\n% Copyright 2005-2016 CVX Research, Inc. \n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/functions/geomean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.48885634582574805}} {"text": "function MB = storage(x)\n% return size of doubles matrix of size x in megabytes\n\nMB= prod(x)*8/1024/1024;\n\nend\n", "meta": {"author": "karpathy", "repo": "Random-Forest-Matlab", "sha": "46aa3d5be31ba25364d087d3e71cdc9bd5f4de18", "save_path": "github-repos/MATLAB/karpathy-Random-Forest-Matlab", "path": "github-repos/MATLAB/karpathy-Random-Forest-Matlab/Random-Forest-Matlab-46aa3d5be31ba25364d087d3e71cdc9bd5f4de18/lib/storage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.705785040214066, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.4888563454427844}} {"text": "clear all; close all; clc\n\n% Connect to Arduino\ntclab;\n\n% Run time in minutes\nrun_time = 10;\n\n% Number of cycles (1 cycle per 3 seconds)\nloops = round(20*run_time);\n\n% heater input\nQ1 = zeros(1,loops);\nQ2 = zeros(1,loops);\nQ1(3:end) = 100.0;\nQ1(50:end) = 0.0;\nQ1(100:end) = 80.0;\n\nQ2(25:end) = 60.0;\nQ2(75:end) = 100.0;\nQ2(125:end) = 25.0;\n\nfor i = 130:180\n if mod(i,10)==0\n Q1(i:i+10) = rand(1) * 100;\n end\n if mod(i+5,10)==0\n Q2(i:i+10) = rand(1) * 100;\n end \nend\n\n% Temperature (degC)\nT1 = ones(1,loops) * T1C(); % measured T\nT2 = ones(1,loops) * T2C(); % measured T\ntime = zeros(1,loops);\n\nstart_time = clock;\nprev_time = start_time;\n\n% dynamic plot (note: subplots needs to be declared here first)\nfigure(1)\nsubplot(2,1,1)\nhold on, grid on\nanexp1 = animatedline('LineStyle','-', 'Color', 'k', 'LineWidth', 2);\nanexp2 = animatedline('LineStyle','-', 'Color', 'b', 'LineWidth', 2);\nylabel('Temperature \\circC')\nlegend('T_1 Measured', 'T_2 Measured', ...\n 'Location', 'northwest')\nsubplot(2,1,2)\nhold on, grid on\nanQ1 = animatedline('LineStyle','-', 'Color', 'k', 'LineWidth', 2);\nanQ2 = animatedline('LineStyle','--', 'Color', 'b', 'LineWidth', 2);\nylabel('Power Level Q (%)')\nlegend('Q_1', 'Q_2', 'Location', 'northwest')\nxlabel('Time (sec)')\n\nfor ii = 1:loops\n % adjust power level\n h1(Q1(ii));\n h2(Q2(ii));\n \n % Pause Sleep time\n pause_max = 3.0;\n pause_time = pause_max - etime(clock,prev_time);\n if pause_time >= 0.0\n pause(pause_time - 0.01)\n else\n pause(0.01)\n end\n \n % Record time and change in time\n t = clock;\n dt = etime(t,prev_time);\n if ii>=2\n time(ii) = time(ii-1) + dt;\n end\n prev_time = t;\n\n % read and record from temperature controller\n T1(ii) = T1C();\n T2(ii) = T2C();\n \n % plot\n addpoints(anexp1,time(ii),T1(ii))\n addpoints(anexp2,time(ii),T2(ii))\n addpoints(anQ1,time(ii),Q1(ii))\n addpoints(anQ2,time(ii),Q2(ii))\n drawnow \nend\n\nh1(0);\nh2(0);\ndisp('Heaters off')\n% turn off heater but keep LED on if T > 50\nif (T1C() || T2C()) > 50\n led(1)\n disp(['Warning, heater temperature 1 =', num2str(T1C())])\n disp(['Warning, heater temperature 2 =', num2str(T2C())])\nelse\n led(0)\nend\n\n% save txt file with data\ndata = [time',Q1',Q2',T1',T2'];\ncsvwrite('data.txt',data);\n\n% save as csv file with headers\nfid = fopen('data.csv','w');\nfid2 = fopen('data.txt','r');\nfprintf(fid,'%s\\n',['time,Q1,Q2,TC1,TC2']);\nwhile ~feof(fid2)\n line = fgetl(fid2);\n fprintf(fid,'%s\\n',line);\nend\nfclose(fid);\nfclose(fid2);\n", "meta": {"author": "APMonitor", "repo": "arduino", "sha": "f36e65a70dd7122d1829883899e40e56bf6c4279", "save_path": "github-repos/MATLAB/APMonitor-arduino", "path": "github-repos/MATLAB/APMonitor-arduino/arduino-f36e65a70dd7122d1829883899e40e56bf6c4279/2_Regression/2nd_order_MIMO/MATLAB/generate_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.48885634173079545}} {"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": "function [outputScore] = getSophisticatedEdgeScore(edgeImg, labels, labelIndices, spSet)\n\n[~,labelCount] = size(spSet);\nk = 0.4;\ntotalSize = 0;\nedgeCount = 0;\nfor i=1:labelCount\n tmpLabel = spSet(1,i);\n locations = labelIndices{1,tmpLabel};\n [pixelSize,~] = size(locations);\n totalSize = totalSize + pixelSize;\n \n for a=1:pixelSize\n if edgeImg(locations(a,1),locations(a,2)) > 0\n edgeCount = edgeCount + 1;\n end\n end\nend\n\n\noutputScore = edgeCount / ((totalSize).^k);\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/\u8bc6\u522b\u7b97\u6cd5/Object Recognition based on super pixel/getSophisticatedEdgeScore.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.488822660301742}} {"text": "classdef TestShapeTransformer\n %TestShapeTransformer\n\n methods (Static)\n function test_1\n img1 = cv.imread(fullfile(mexopencv.root(),'test','basketball1.png'), ...\n 'Grayscale',true, 'ReduceScale',2);\n img2 = cv.imread(fullfile(mexopencv.root(),'test','basketball2.png'), ...\n 'Grayscale',true, 'ReduceScale',2);\n\n detector = cv.AKAZE();\n [keypoints1, descriptors1] = detector.detectAndCompute(img1);\n [keypoints2, descriptors2] = detector.detectAndCompute(img2);\n matcher = cv.DescriptorMatcher('BFMatcher', ...\n 'NormType',detector.defaultNorm());\n matches = matcher.match(descriptors1, descriptors2);\n pts1 = cat(1, keypoints1.pt);\n pts2 = cat(1, keypoints2.pt);\n\n for i=1:2\n if i==1\n tps = cv.ShapeTransformer('AffineTransformer', ...\n 'FullAffine',true);\n assert(isequal(tps.FullAffine, true));\n else\n tps = cv.ShapeTransformer('ThinPlateSplineShapeTransformer', ...\n 'RegularizationParameter',25000);\n assert(isequal(tps.RegularizationParameter, 25000));\n end\n\n tps.estimateTransformation(pts1, pts2, matches);\n\n [cost, pts3] = tps.applyTransformation(pts2);\n validateattributes(cost, {'numeric'}, {'scalar'});\n validateattributes(pts3, {'numeric'}, {'size',size(pts2)});\n\n img3 = tps.warpImage(img2);\n validateattributes(img3, {class(img2)}, {'size',size(img2)});\n end\n end\n end\n\nend\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/test/unit_tests/TestShapeTransformer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6224593382055109, "lm_q1q2_score": 0.48882265954650284}} {"text": "function res = dbcsme(ya,yb)\n% derivative of F respect to ya\nBa=zeros(5,5);\nBa(1,1)=1;Ba(2,2)=1;Ba(3,3)=1;Ba(4,4)=1;\nres.Ba=Ba;\n% derivative of F respect to yb\nBb=zeros(5,5);\nBb(5,3)=-1;Bb(5,5)=1;\nres.Bb=Bb;\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/27351-multiple-shooting/Ascher_Examples_2/dbcsme.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.48882264779120055}} {"text": "function cost = costFun(u)\n% cost = costFun(u)\n%\n% Cost is the integral of torque-squared.\n\ncost = u.^2; \n\nend", "meta": {"author": "MatthewPeterKelly", "repo": "OptimTraj", "sha": "c97b57fda511dacc6a6187f683428f0f3a1965f2", "save_path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj", "path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj/OptimTraj-c97b57fda511dacc6a6187f683428f0f3a1965f2/demo/simpleWalker/costFun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7853085607891888, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4888226415359294}} {"text": "%==============================================================================\n% This code is part of the Matlab-based toolbox\n% FAIR - Flexible Algorithms for Image Registration. \n% For details see \n% - https://github.com/C4IR and\n% - http://www.siam.org/books/fa06/\n% ##2\n%==============================================================================\n% \n% - data PETCT, Omega=(0,140)x(0,151), level=4:7, m=[128,128]\n% - viewer viewImage2D\n% - interpolation splineInter\n% - distance MI\n% - pre-registration rigid2D\n% - regularizer mbCurvature\n% - optimization lBFGS\n% ===============================================================================\n\nclose all, help(mfilename);\n\nsetup2DPETCTData\nimgModel('reset','imgModel','splineInter','regularizer','none','theta',1e-3);\ndistance('reset','distance','MI','nT',32,'nR',32);\ntrafo('reset','trafo','rigid2D');\nregularizer('reset','regularizer','mfCurvature','alpha',1e-1);\n\nPIRpara = optPara('lBFGS','solver','backslash');\nNPIRpara = optPara('lBFGS','solver',regularizer('get','solver'),'maxIter',40);\n\n[yc,wc,his] = MLIR(ML,'PIRobj',@PIRBFGSobjFctn,'PIRpara',PIRpara,...\n 'NPIRobj',@NPIRBFGSobjFctn,'NPIRpara',NPIRpara,...\n 'minLevel',4,'maxLevel',7,'parametric',1,'plotMLiter',0);\n\n%==============================================================================\n", "meta": {"author": "C4IR", "repo": "FAIR.m", "sha": "975edebd37b833ae76696792870de5c05efcb9cb", "save_path": "github-repos/MATLAB/C4IR-FAIR.m", "path": "github-repos/MATLAB/C4IR-FAIR.m/FAIR.m-975edebd37b833ae76696792870de5c05efcb9cb/kernel/examples/E9_PETCT_MLIRlBFGS_MI_mfCurv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.48880142892710765}} {"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": "% Display the contents of a pyramid, as returned by functions\n% 'laplacian_pyramid' or 'gaussian pyramid'\n%\n% tom.mertens@gmail.com, August 2007\n%\n\nfunction display_pyramid(pyr)\n\nL = length(pyr);\nr = size(pyr{1},1);\nc = size(pyr{1},2);\nk = size(pyr{1},3);\nR = zeros(r,2*c,k);\n\noffset = 1;\nfor l = 1:L\n I = pyr{l};\n r = size(I,1);\n c = size(I,2);\n R(1:r, offset:offset-1+c, :) = I;\n offset = offset + c;\nend\n\nif (min(R(:)) < 1e-5)\n %make negative values displayable\n a = min(R(:));\n b = max(R(:));\n R = (R - a) / (b - a);\nend \n\nfigure; imshow(R);\n", "meta": {"author": "mahmoudnafifi", "repo": "Exposure_Correction", "sha": "01300c3ff186123d405141202f8201ebd59965fa", "save_path": "github-repos/MATLAB/mahmoudnafifi-Exposure_Correction", "path": "github-repos/MATLAB/mahmoudnafifi-Exposure_Correction/Exposure_Correction-01300c3ff186123d405141202f8201ebd59965fa/exFusion/display_pyramid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879992, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.4887308583245989}} {"text": "function plaza = create_plaza(B, L)\nglobal plazalength;\ntopgap = 5;\nbottomgap = 1;\nplaza = zeros(plazalength,B+2);\nif mod(B-L,2)==0\nfor row = 1:plazalength\nplaza(row,1) = -888;\nplaza(row,2+B) = -888;\nend\nfor col = 2:B/2 - L/2 + 1\nfor row = 1:(plazalength-1)/2 - topgap * (col-1)\nplaza(row,col) = -888;\nplaza(row,B+3-col) = -888;\nend\nend\nfor col = 2:B/2 - L/2 + 1\nfor row = (plazalength+3)/2 + bottomgap*(col-1):plazalength\nplaza(row,col) = -888;\nplaza(row,B+3-col) = -888;\nend\nend\nelse\nfor row = 1:plazalength\nplaza(row,1) = -888;\nplaza(row,3+B) = -888;\nend\nfor col = 2:(B+1)/2 - L/2 + 1\nfor row = 1:(plazalength-1)/2 - topgap * (col-1)\nplaza(row,col) = -888;\nplaza(row,B+4-col) = -888;\nend\nend\nfor col = 2:(B+1)/2 - L/2 + 1\nfor row = (plazalength+3)/2 + bottomgap*(col-1):plazalength\nplaza(row,col) = -888;\nplaza(row,B+4-col) = -888;\nend\nend\nfor row = 1:plazalength\nplaza(row,2+B) = -888;\nend\nend", "meta": {"author": "Eurus-Holmes", "repo": "Mathematical_Modeling", "sha": "cb9dd53af84ffbd455ec62ab89886351e0ec98d9", "save_path": "github-repos/MATLAB/Eurus-Holmes-Mathematical_Modeling", "path": "github-repos/MATLAB/Eurus-Holmes-Mathematical_Modeling/Mathematical_Modeling-cb9dd53af84ffbd455ec62ab89886351e0ec98d9/Cellular automaton/\u5143\u80de\u81ea\u52a8\u673a/1\u670813\u65e5\u8bfe\u4ef6\uff08\u5143\u80de\u81ea\u52a8\u673a\uff09/\u7a0b\u5e8f/The Booth Tolls for Thee/create_plaza.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.48864250371995566}} {"text": "function [del,obj] = setProj(obj,proj,projtype,insert,bbox)\n % [del,obj] = setProj(obj,proj,projtype,insert)\n % kjr generic function to parse projected space options\n % returns del flag to delete overlapping elements when plotting\n % global models.\n % if insert = 1, then automatically insert the global m_proj variables\n % into the msh obj. insert is 0 by default. \n\n if nargin < 4\n insert = 0;\n end\n \n if nargin < 5\n bbox = [];\n end\n \n % process bounds of mesh (or supply your own)\n if isempty(bbox)\n lon_mi = min(obj.p(:,1)); lon_ma = max(obj.p(:,1));\n lat_mi = min(obj.p(:,2)); lat_ma = max(obj.p(:,2));\n else\n lon_mi = bbox(1,1); lon_ma = bbox(1,2);\n lat_mi = bbox(2,1); lat_ma = bbox(2,2);\n end\n lat_mea = mean(obj.p(:,2)); lon_mea = mean(obj.p(:,1));\n \n % some defaults\n rad = 100; rot = 15;\n del = 0 ;\n\n % process the projtype as a varargin type\n I = find(strcmp(projtype,'long'));\n if ~isempty(I)\n if length(projtype{I+1}) == 1\n lon_mea = projtype{I+1};\n else\n lon_mi = projtype{I+1}(1); lon_ma = projtype{I+1}(2);\n end\n end\n I = find(strcmp(projtype,'lat'));\n if ~isempty(I)\n if length(projtype{I+1}) == 1\n lat_mea = projtype{I+1};\n else\n lat_mi = projtype{I+1}(1); lat_ma = projtype{I+1}(2);\n end\n end\n I = find(strcmp(projtype,'rad'));\n if ~isempty(I)\n rad = projtype{I+1};\n end\n I = find(strcmp(projtype,'rot'));\n if ~isempty(I)\n rot = projtype{I+1};\n end\n if proj == 0\n % normal geographic coordinates\n m_proj('equi','lat',[lat_mi lat_ma],'long',[lon_mi lon_ma]) ;\n del = 1;\n else\n if ~ischar(projtype)\n projtype = projtype{1};\n end\n projtype = lower(projtype);\n if ~isempty(regexp(projtype,'ste'))\n % Special treatment of Stereographic projection\n if lat_ma < 0\n % center Antarctica\n m_proj(projtype,'lat',-90,...\n 'long',0.5*(lon_mi+lon_ma),...\n 'radius',min(lat_ma+90,180),'rot',rot);\n else\n % center Arctic\n m_proj(projtype,'lat',90,...\n 'long',0.5*(lon_mi+lon_ma),...\n 'radius',min(90-lat_mi,180),'rot',rot);\n end\n m_proj('get') ;\n elseif ~isempty(regexp(projtype,'ort')) || ...\n ~isempty(regexp(projtype,'gno')) || ...\n ~isempty(regexp(projtype,'azi')) || ...\n ~isempty(regexp(projtype,'sat'))\n m_proj(projtype,'lat',lat_mea,'long',lon_mea,...\n 'radius',rad,'rot',rot);\n m_proj('get') ;\n del = 1;\n elseif ~isempty(regexp(projtype,'obl')) \n % Oblique Mercator projection\n asp = (lon_ma-lon_mi)/(lat_ma - lat_mi);\n dir = 'hor';\n if asp > 1 \n asp = 1./asp; dir = 'ver';\n end\n m_proj(projtype,'lon',[lon_mi lon_ma],...\n 'lat',[lat_mi lat_ma],...\n 'aspect',asp,'dir',dir) ;\n m_proj('get') ;\n del = 1;\n else\n % Cylindrical, Conic or Global type projections\n del = 1;\n m_proj(projtype,'lon',[lon_mi lon_ma],...\n 'lat',[lat_mi lat_ma]) ;\n m_proj('get') ;\n end\n end\n if insert\n global MAP_PROJECTION MAP_COORDS MAP_VAR_LIST\n obj.proj = MAP_PROJECTION ; \n obj.coord = MAP_COORDS ; \n obj.mapvar = MAP_VAR_LIST ; \n end\nend\n", "meta": {"author": "CHLNDDEV", "repo": "OceanMesh2D", "sha": "56222604a5c1fe897d10c8b08cb3380ef8b43740", "save_path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D", "path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D/OceanMesh2D-56222604a5c1fe897d10c8b08cb3380ef8b43740/utilities/setProj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.4886424963261615}} {"text": "function A=posmatr(matriks)\n%fungsi ini untuk menghitung pada baris ke berapa suatu matriks mencapai\n%nilai maksimum\n[m,n,o,p]=size(matriks);\nfor j=1:p\n A(1,j)=posmax(matriks(:,j));\nend\nA;\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/32339-stochastic-dynamic-programming-for-water-reservoir/posmatr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.48864248864298165}} {"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": " function [xhat, smap, ref] = ir_mri_coil_combine(ykj, varargin)\n%function [xhat, smap, ref] = ir_mri_coil_combine(ykj, varargin)\n%|\n%| Given multiple MRI surface coil images, estimate their sensitivity maps,\n%| relative to the sqrt-sum-of-squares (SSoS) map, and then perform the\n%| \"best\" linear combination using the sensitivity maps.\n%| todo: currently ignores noise correlations\n%|\n%| This routine provides an alternative to the usual \"sqrt-sum-of-squares\"\n%| approach to combining multiple coil data. It produces a complex-valued\n%| output image that has approximately a complex gaussian distribution at\n%| each voxel. However, it does not preserve image phase information\n%| because the image phase is included in the sensitivity map phase estimates.\n%| So it might be logical to just take the real part of the output image.\n%| The output is \"approximately\" gaussian only because of random errors in\n%| the sensitivity maps estimated within.\n%|\n%| The variance is space-dependent because of coil sensitivity variations.\n%| todo: return variance map!\n%|\n%| Signal model: y_kj = s_kj f_j + noise_kj\n%|\ts_kj\tsensitivity map (relative to SSoS reference image)\n%|\tf_j\tunknown underlying object\n%|\tk: coil index\n%|\tj: voxel index\n%|\n%| in\n%|\tykj\t[(N) ncoil]\tnoisy complex images (2D or 3D) for each coil\n%|\n%| options\n%|\tbodycoil [(N)]\t\treference image (optional) (default: SSoS)\n%|\tthresh0\t\t\tzero reference image values below this fraction\n%|\t\t\t\t of peak value (default: 0.05)\n%|\tthresh1\t\t\tfraction of reference peak used for median\n%|\t\t\t\t initial value in \"background\" (default: 0.05)\n%|\n%| out\n%|\txhat\t[(N)]\t\tcoil combination image\n%|\tsmap\t[(N) ncoil]\testimated sensitivity maps\n%|\n%| Uses the 'chol' (Cholesky) option of mri_sensemap_denoise.m which is\n%| fast for medium sized images but may use much memory for large images.\n%|\n%| Copyright 2014-08-18, Jeff Fessler, University of Michigan\n\nif nargin < 1, ir_usage, end\nif nargin == 1 && streq(ykj, 'test')\n\tir_mri_coil_combine_test\nreturn\nend\n\n% defaults\narg.thresh0 = 0.05; % below this set reference image to 0\narg.thresh1 = 0.05; % below this set reference image to median\narg.bodycoil = [];\narg.chol = true;\n\narg = vararg_pair(arg, varargin);\n\ntmp = size(ykj);\nNN = tmp(1:end-1);\nncoil = tmp(end);\n\n% default reference image\nif isempty(arg.bodycoil)\n\tref = ir_mri_coil_combine_ref(ykj, arg.thresh0);\nelse\n\tref = arg.bodycoil;\nend\n\nsmap = mri_sensemap_denoise(ykj, 'thresh', arg.thresh1, ...\n\t'bodycoil', ref, 'chol', 1, 'niter', 1);\n\ncoildim = ndims(ykj);\nnumer = sum(conj(smap) .* ykj, coildim);\ndenom = sum(abs(smap).^2, coildim);\nxhat = div0(numer, denom); % LS solution at each pixel\n\n\n% ir_mri_coil_combine_ref()\nfunction ref = ir_mri_coil_combine_ref(ykj, thresh0)\ncoildim = ndims(ykj);\nref = sqrt(sum(abs(ykj).^2, coildim)); % sqrt-sum-of-squares\npeak = max(abs(ref(:)));\nref(abs(ref) < peak * thresh0) = 0; % zero low SNR pixels\n%ref = ref / peak; % normalize to 1\n\n\n% ir_mri_coil_combine_test()\n% built-in test/example\nfunction ir_mri_coil_combine_test\n\nif 1 % xtrue\n\tf.dir = [path_find_dir('mri') '/../data/mri/'];\n\tf.xtrue = [f.dir 'brainweb_t1.jpg'];\n\txtrue = single(imread(f.xtrue)');\n\txtrue = xtrue(2:end-1,2:end-1); % make it 256^2\n\txtrue = downsample2(xtrue, 4); % now 64^2\n\t[nx, ny] = size(xtrue);\n\tatrue = 2*pi * (-0.5+([1:nx]'/nx * [1:ny]/ny).^0.5); % smooth phase\n\txtrue = xtrue .* exp(1i * atrue); % phase\n%\tim clf, im('hsv', angle(xtrue), [-pi pi]), cbar, return\n\n\tim plc 3 4\n\tim(1, abs(xtrue), '$|x|$'), cbar\n\tim(2, 'hsv', angle(xtrue), [-pi pi], '$\\angle x$'), cbar\n\tmask = conv2(abs(xtrue), ones(5), 'same') > 0;\n%\tim(11, abs(xtrue) + 100*mask), return % check mask\nend\n\nif 1 % smap\n\tncoil = 4;\n\tmask4 = repmat(mask, [1 1 ncoil]);\n\tsmap = ir_mri_sensemap_sim('nx', nx, 'ny', ny, 'dx', 192/nx, ...\n\t\t'ncoil', ncoil, 'rcoil', 100);\n%\tsmap = smap(:, :, [ncoil 1:(ncoil-1)]); % phase of last coil is cooler\n\ttmp = sqrt(sum(abs(smap).^2, 3));\n\tsmap = smap / tmp(end/2,end/2); % normalize true smap for simplicity\n\tim(5, mask4 .* abs(smap), '$|s|$'), cbar\n\tim(6, 'hsv', mask4 .* angle(smap), [-pi pi], '$\\angle s$'), cbar\n\tim(12, mask .* sqrt(sum(abs(smap).^2, 3)), 's SSoS'), cbar\nend\n\nif 1 % y\n\tytrue = smap .* repmat(xtrue, [1 1 4]);\n\trng(0)\n\tsnr2sigma = @(db, yb) 10^(-db/20) * norm(yb(:)) / sqrt(numel(yb)) / sqrt(2); % for complex noise\n\tsig = snr2sigma(50, ytrue);\n%\tsig = 0; % noiseless\n\tykj = ytrue + sig * (randn(size(ytrue)) + 1i * randn(size(ytrue)));\n\tim(7, abs(ykj), '$|y|$'), cbar\n\tim(8, 'hsv', ir_unwrap(angle(ykj)), [-pi pi], '$\\angle y$'), cbar\nend\n\n\t[xhat shat ref] = ir_mri_coil_combine(ykj);\n\tssos = sqrt(sum(abs(ykj).^2, 3));\n\txhat = xhat * ir_best_scale(xhat, abs(xtrue));\n\tssos = ssos * ir_best_scale(ssos, abs(xtrue));\n\n\tpr nrms(xhat(:), col(abs(xtrue)))\n\tpr nrms(ssos(:), col(abs(xtrue)))\n%\tpr corrcoef(abs(xtrue(:)), ssos(:))\n%\tpr corrcoef(abs(xtrue(:)), real(xhat(:)))\n\n%\txhat = reale(xhat);\n%\tim(3, abs(xhat), '|x hat|'), cbar\n%\tim(4, angle(xhat), [-pi pi], '< x hat'), cbar\n\tim(3, real(xhat), 'Re($\\hat{x}$)'), cbar\n\tim(4, imag(xhat), 'Im($\\hat{x}$)'), cbar\n\tim(9, mask4 .* abs(shat), '$|\\hat{s}|$'), cbar\n\tim(10, 'hsv', mask4 .* angle(shat), [-pi pi], '$\\angle \\hat{s}$'), cbar\n\tim(11, ssos, 'x SSoS'), cbar\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/mri/ir_mri_coil_combine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.4886424836173235}} {"text": "classdef DynamicPressureTermCondition < AbstractEventTerminationCondition\n %AltitudeTermCondition Summary of this class goes here\n % Detailed explanation goes here\n \n properties\n dynP(1,1) double = 0; %km\n bodyInfo KSPTOT_BodyInfo\n end\n \n methods\n function obj = DynamicPressureTermCondition(dynP)\n obj.dynP = dynP;\n end\n \n function evtTermCondFcnHndl = getEventTermCondFuncHandle(obj) \n evtTermCondFcnHndl = @(t,y) obj.eventTermCond(t,y, obj.dynP, obj.bodyInfo);\n end\n \n function initTermCondition(obj, initialStateLogEntry)\n obj.bodyInfo = initialStateLogEntry.centralBody;\n end\n \n function name = getName(obj)\n name = sprintf('Dynamic Pressure (%.3f kPa)', obj.dynP);\n end\n \n function tf = shouldBeReinitOnRestart(obj)\n tf = true;\n end\n \n function params = getTermCondUiStruct(obj)\n params = struct();\n \n params.paramName = 'Dynamic Pressure';\n params.paramUnit = 'kPa';\n params.useParam = 'on';\n params.useStages = 'off';\n params.useTanks = 'off';\n params.useEngines = 'off';\n params.useStopwatches = 'off';\n \n params.value = obj.dynP;\n params.refStage = LaunchVehicleStage.empty(1,0);\n params.refTank = LaunchVehicleEngine.empty(1,0);\n params.refEngine = LaunchVehicleEngine.empty(1,0);\n params.refStopwatch = LaunchVehicleStopwatch.empty(1,0);\n end\n \n function optVar = getNewOptVar(obj)\n optVar = DynPressOptimizationVariable(obj);\n end\n \n function optVar = getExistingOptVar(obj)\n optVar = obj.optVar;\n end\n \n function tf = usesStage(obj, stage)\n tf = false;\n end\n \n function tf = usesEngine(obj, engine)\n tf = false;\n end\n \n function tf = usesTank(obj, tank)\n tf = false;\n end\n \n function tf = usesEngineToTankConn(obj, engineToTank)\n tf = false;\n end\n \n function tf = usesStopwatch(obj, stopwatch)\n tf = false;\n end\n end\n \n methods(Static)\n function termCond = getTermCondForParams(paramValue, stage, tank, engine, stopwatch)\n termCond = DynamicPressureTermCondition(paramValue);\n end\n end\n \n methods(Static, Access=private)\n function [value,isterminal,direction] = eventTermCond(ut,y, targetDynP, bodyInfo)\n rVectECI = y(1:3);\n vVectECI = y(4:6);\n \n altitude = norm(rVectECI) - bodyInfo.radius;\n\n if(altitude <= bodyInfo.atmohgt && altitude >= 0)\n [lat, long, ~, ~, ~, ~, ~, vVectECEF] = getLatLongAltFromInertialVect(ut, rVectECI, bodyInfo, vVectECI);\n density = getAtmoDensityAtAltitude(bodyInfo, altitude, lat, ut, long); \n elseif(altitude <= 0)\n density = 0;\n vVectECEF = [0;0;0];\n else \n density = 0;\n vVectECEF = [0;0;0];\n end\n \n vVectEcefMag = norm(vVectECEF);\n vVectEcefMagMS = vVectEcefMag*1000;\n \n dynP = density * (vVectEcefMagMS^2) / 2; %kg/m^3 * m^2 / s^2 = kg/(m*s^2)\n dynP_kPa = dynP/1000;\n \n value = dynP_kPa - targetDynP;\n isterminal = 1;\n direction = 0;\n end\n end\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_lvd/classes/Events/termConditions/@DynamicPressureTermCondition/DynamicPressureTermCondition.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4886310569221648}} {"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 [mu, varsigma] = vargplvmPosteriorMeanVarPar(model, X, varX);\n\n% VARGPLVMPOSTERIORMEANVARPAR Mean and variances of the posterior at points given by X, parallel version.\n% FORMAT\n% DESC returns the posterior mean and variance for a given set of\n% points.\n% ARG model : the model for which the posterior will be computed.\n% ARG X : variational mean in the latent space for which posterior is computed.\n% ARG varX : variational variances in the latent space for which posterior is computed (assumed zero if not present).\n% RETURN mu : the mean of the posterior distribution.\n% RETURN sigma : the variances of the posterior distributions.\n%\n% SEEALSO : vargplvmPosteriorMeanVar, gpPosteriorMeanVar, vargplvmCreate\n%\n% COPYRIGHT : Michalis K. Titsias and Neil D. Lawrence, 2009, 2011\n\n% VARGPLVM\n\n\n% do prediction by replacing the variational distribution with a delta function \n%model.K_uf = kernCompute(model.kern, model.X_u, model.vardist.means);\n%model.A = (1/model.beta)*model.K_uu + model.K_uf*model.K_uf';\n%[model.Ainv, U] = pdinv(model.A);\n%[mu1, varsigma1] = gpPosteriorMeanVar(model, vardistX.means);\n\n\n% Find exactly the mean and the variances of the predictive distribution\n% (which is not Gaussian, however its moments can be computed in closed-form)\n\nif nargin < 3\n vardistX.covars = repmat(0.0, size(X, 1), size(X, 2));%zeros(size(X, 1), size(X, 2));\nelse\n vardistX.covars = varX;\nend\nvardistX.latentDimension = size(X, 2);\nvardistX.numData = size(X, 1);\n%model.vardist.covars = 0*model.vardist.covars; \nvardistX.means = X;\n%model = vargplvmUpdateStats(model, model.X_u);\n\n\nAinv = model.P1' * model.P1; % size: NxN\n\nif ~isfield(model,'alpha')\n model.alpha = Ainv*model.Psi1'*model.m; % size: 1xD\nend\nPsi1_star = kernVardistPsi1Compute(model.kern, vardistX, model.X_u);\n\n% mean prediction \nmu = Psi1_star*model.alpha; % size: 1xD\n\nif nargout > 1\n % \n % precomputations\n vard = vardistCreate(zeros(1,model.q), model.q, 'gaussian');\n Kinvk = (model.invK_uu - (1/model.beta)*Ainv);\n %\n for i=1:size(vardistX.means,1)\n %\n vard.means = vardistX.means(i,:);\n vard.covars = vardistX.covars(i,:);\n % compute psi0 term\n Psi0_star = kernVardistPsi0Compute(model.kern, vard);\n % compute psi2 term\n Psi2_star = kernVardistPsi2Compute(model.kern, vard, model.X_u);\n \n vars = Psi0_star - sum(sum(Kinvk.*Psi2_star));\n \n % parfor j=1:model.d\n % %[model.alpha(:,j)'*(Psi2_star*model.alpha(:,j)), mu(i,j)^2]\n % varsigma(i,j) = model.alpha(:,j)'*(Psi2_star*model.alpha(:,j)) - mu(i,j)^2; \n % end\n % varsigma(i,:) = varsigma(i,:) + vars; \n %\n end\n % \n %if isfield(model, 'beta')\n % varsigma = varsigma + (1/model.beta);\n %end\n %\nend\n \n% Rescale the mean\nmu = mu.*repmat(model.scale, size(vardistX.means,1), 1);\n\n% Add the bias back in\nmu = mu + repmat(model.bias, size(vardistX.means,1), 1);\n\n% rescale the variances\nif nargout > 1\n varsigma = varsigma.*repmat(model.scale.*model.scale, size(vardistX.means,1), 1);\nend\n \n", "meta": {"author": "SheffieldML", "repo": "vargplvm", "sha": "480201fde5ac84ff36e4a9f06d3fafeafa8ef06d", "save_path": "github-repos/MATLAB/SheffieldML-vargplvm", "path": "github-repos/MATLAB/SheffieldML-vargplvm/vargplvm-480201fde5ac84ff36e4a9f06d3fafeafa8ef06d/vargplvm/matlab/vargplvmPosteriorMeanVarPar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4886310518096748}} {"text": "function [overall_peaks, overall_onsets] = co_ppg_peak_detector(ppg, fs, up)\n%CO_PPG_PEAK_DETECTOR detects PPG pulse peaks\n%\n% This has been adapted by Peter Charlton from code supplied by Christina\n% Orphanidou.\n%\n% Purpose: To detect PPG peaks.\n%\n% With grateful thanks to Christina Orphanidou and Alexander Darrell.\n%\n\n%% Pre-processing\n% remove nans\nppg.v(isnan(ppg.v)) = mean(ppg.v(~isnan(ppg.v)));\n% filter\nppgfilt.v = filtfilt(up.paramSet.CO_peak_det.PPG_smoother.coeffs, 1, ppg.v);\nppgfilt.t = ppg.t;\n\n%% Setup\n% Segmentation into 10s windows\nwin_length = 10;\noverlap = 3;\nwin_starts = ppgfilt.t(1):win_length:ppgfilt.t(end);\nwin_ends = win_starts + win_length + overlap;\nwin_ends(end) = win_ends(end) - overlap;\n% setup variables\n[overall_peaks, overall_onsets] = deal([]);\n\n%% Perform peak detection on each 10s window\nfor win_no = 1 : length(win_starts)\n \n rel_data = struct;\n \n rel_data.i = find(ppgfilt.t >= win_starts(win_no) & ppgfilt.t <= win_ends(win_no));\n rel_data.t = ppgfilt.t(rel_data.i);\n rel_data.v = ppgfilt.v(rel_data.i);\n \n %% Calculate thresholds\n thresh1=quantile(rel_data.v,up.paramSet.CO_peak_det.upctl);\n thresh2=quantile(rel_data.v,up.paramSet.CO_peak_det.lpctl);\n thresh3=thresh2+0.3*(thresh1-thresh2);\n thresh4=thresh2+0.7*(thresh1-thresh2);\n \n %% Find all peaks\n % identify peaks\n diffs_on_left_of_pt = diff(rel_data.v); diffs_on_left_of_pt = diffs_on_left_of_pt(1:(end-1)); diffs_on_left_of_pt = logical(diffs_on_left_of_pt>0);\n diffs_on_right_of_pt = diff(rel_data.v); diffs_on_right_of_pt = diffs_on_right_of_pt(2:end); level_on_right_of_pt = logical(diffs_on_right_of_pt==0); diffs_on_right_of_pt = logical(diffs_on_right_of_pt<0);\n diffs_on_second_right_of_pt = [1; diff(rel_data.v(2:end))]; diffs_on_second_right_of_pt = diffs_on_second_right_of_pt(2:end); diffs_on_second_right_of_pt = logical(diffs_on_second_right_of_pt<0);\n peaks.i = find((diffs_on_left_of_pt & diffs_on_right_of_pt) | ...\n (diffs_on_left_of_pt & level_on_right_of_pt & diffs_on_second_right_of_pt))+1;\n peaks.i = peaks.i';\n % Take maximum value in window if no peaks were found\n if isempty(peaks.i)\n peaks.i = find(max(rel_data.v) == rel_data.v);\n end\n % Extract signal values at peaks\n peaks.t = rel_data.t(peaks.i);\n peaks.v = rel_data.v(peaks.i);\n \n %% Classify peaks\n % Identify relevant peaks according to amplitude\n upperdiff = abs(peaks.v-thresh1);\n middlehighdiff = abs(peaks.v-thresh4);\n middlelowdiff = abs(peaks.v-thresh3);\n lowerdiff = abs(peaks.v-thresh2);\n upper_pks = find(upperdiff=fs/3)+1;\n PPG_PKS.i = PPG_PKS.i(good_els);\n PPG_PKS.v = PPG_PKS.v(good_els);\n PPG_PKS.t = PPG_PKS.t(good_els);\n \n %% Find troughs\n \n PPG_TRS.i = nan(length(PPG_PKS.t)-1,1);\n for s = 1 : (length(PPG_PKS.t)-1)\n start_el = PPG_PKS.i(s);\n [~, additional_el] = min(rel_data.v(PPG_PKS.i(s):PPG_PKS.i(s+1)));\n PPG_TRS.i(s) = start_el - 1 + additional_el;\n end\n PPG_TRS.v = rel_data.v(PPG_TRS.i);\n PPG_TRS.t = rel_data.t(PPG_TRS.i);\n \n temp_pk_is = rel_data.i(PPG_PKS.i(:));\n temp_on_is = rel_data.i(PPG_TRS.i(:));\n \n overall_peaks = [overall_peaks; temp_pk_is(:)]; overall_peaks = unique(overall_peaks);\n overall_onsets = [overall_onsets; temp_on_is(:)]; overall_onsets = unique(overall_onsets);\n \n clear upper lower middlehigh middlelow temp_pk_is temp_on_is PPG_TRS PPG_PKS additional_el s good_els peaks lower_pks upper_pks lowerdiff middlelowdiff middlehighdiff upperdiff ind\n \nend\n", "meta": {"author": "peterhcharlton", "repo": "RRest", "sha": "f5022e7029c5b6d6b8159b665dccc2c8f267976e", "save_path": "github-repos/MATLAB/peterhcharlton-RRest", "path": "github-repos/MATLAB/peterhcharlton-RRest/RRest-f5022e7029c5b6d6b8159b665dccc2c8f267976e/RRest_v2.0/Algorithms/extract_resp_sig/feat_based_extraction/COr_peak_detector/co_ppg_peak_detector.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.48863104669718477}} {"text": "function C=plotwmdct(coef,varargin)\n%PLOTWMDCT Plot WMDCT coefficients\n% Usage: plotwmdct(coef);\n% plotwmdct(coef,fs);\n% plotwmdct(coef,fs,dynrange);\n%\n% `plotwmdct(coef)` plots coefficients from |wmdct|.\n%\n% `plotwmdct(coef,fs)` does the same assuming a sampling rate of\n% *fs* Hz of the original signal.\n%\n% `plotwmdct(coef,fs,dynrange)` additionally limits the dynamic\n% range.\n%\n% `C=plotwmdct(...)` returns the processed image data used in the\n% plotting. Inputting this data directly to `imagesc` or similar\n% functions will create the plot. This is useful for custom\n% post-processing of the image data.\n% \n% |plotwmdct| supports all the optional parameters of |tfplot|. Please\n% see the help of |tfplot| for an exhaustive list.\n%\n% See also: wmdct, tfplot, sgram, plotdgt\n\n% AUTHOR : Peter L. S\u00f8ndergaard.\n% TESTING: NA\n% REFERENCE: NA\n\nif nargin<1\n error('%s: Too few input parameters.',upper(mfilename));\nend;\n\ndefinput.import={'ltfattranslate','tfplot'};\n\n[flags,kv,fs]=ltfatarghelper({'fs','dynrange'},definput,varargin);\n\nM=size(coef,1);\n\nyr=[.5/M, 1-.5/M];\n\nC = tfplot(coef,M,yr,'argimport',flags,kv);\n\nif nargout<1\n clear C;\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/gabor/plotwmdct.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.4884908874520522}} {"text": "function displayMobject(mObject,fieldname,note)\n% M-object information display\n% displayMobject(mObject,fieldname,note);\n\n% Designed and coded by Hideki Kawahara\n% 27/Feb./2005\n% Copyright(c) 2005, Hideki Kawahara\n% 05/Oct./2005 minor bug fix\n\nfs = mObject.samplingFrequency;\ntFrame = mObject.frameUpdateInterval;\nswitch fieldname\n case 'spectrogram'\n figure\n [nrow,ncolumn]=size(mObject.spectrogram);\n timeSpan = [0 (ncolumn-1)*tFrame];\n dBsgram = 20*log10(mObject.spectrogram);\n maxSgramdB = max(max(dBsgram));\n imagesc(timeSpan, [0 fs/2],max(dBsgram,maxSgramdB-70));\n axis('xy');\n set(gca,'fontsize',14);\n xlabel('time (ms)');\n ylabel('frequency (Hz)');\n title([note ' time span 0 ' num2str(timeSpan(2),10) ' (ms) ' datestr(now)]);\n case 'waveform'\n figure\n x = mObject.waveform;\n timeSpan = (0:length(x)-1)/fs*1000;\n plot(timeSpan,x);grid on;\n axis([timeSpan(1) timeSpan(end) 1.1*[min(x) max(x)]]);\n set(gca,'fontsize',14);\n xlabel('time (ms)');\n title([note ' time span 0 ' num2str(round(timeSpan(end)),8) ' (ms) ' datestr(now)]);\n case {'anchorFrequency', 'anchorTimeLocation'}\n figure\n [nrow,ncolumn]=size(mObject.spectrogram);\n timeSpan = [0 (ncolumn-1)*tFrame];\n dBsgram = 20*log10(mObject.spectrogram);\n maxSgramdB = max(max(dBsgram));\n imagesc(timeSpan, [0 fs/2],max(dBsgram,maxSgramdB-70));\n axis('xy');\n set(gca,'fontsize',14);\n xlabel('time (ms)');\n ylabel('frequency (Hz)');\n title([note ' time span 0 ' num2str(timeSpan(2),10) ' (ms) ' datestr(now)]);\n if length(mObject.anchorTimeLocation)>0\n hold on;\n for ii=1:length(mObject.anchorTimeLocation)\n hh = plot(mObject.anchorTimeLocation(ii)*[1 1],[0 fs/2],'w:');\n set(hh,'linewidth',2);\n if sum(mObject.anchorFrequency(ii,:)>0)>0\n nFrequency = sum(mObject.anchorFrequency(ii,:)>0);\n anchorFrequencyVector = mObject.anchorFrequency(ii,mObject.anchorFrequency(ii,:)>0); % 05/Oct./2005 HK\n for jj=1:nFrequency\n hh=plot(mObject.anchorTimeLocation(ii),anchorFrequencyVector(jj),'ok');\n set(hh,'markersize',9);\n set(hh,'linewidth',2);\n hh=plot(mObject.anchorTimeLocation(ii),anchorFrequencyVector(jj),'.w');\n set(hh,'markersize',7);\n set(hh,'linewidth',4);\n end;\n end;\n end;\n hold off;\n end;\nend;\n\n", "meta": {"author": "HidekiKawahara", "repo": "legacy_STRAIGHT", "sha": "964684981fe12cd232c5e882259dff126b3af0f2", "save_path": "github-repos/MATLAB/HidekiKawahara-legacy_STRAIGHT", "path": "github-repos/MATLAB/HidekiKawahara-legacy_STRAIGHT/legacy_STRAIGHT-964684981fe12cd232c5e882259dff126b3af0f2/morphing_src/displayMobject.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.48849088458159756}} {"text": "function test_ft_spike_rate()\n\n% MEM 1gb\n% WALLTIME 00:10:00\n% DEPENDENCY ft_spike_rate\n\nclear\nspikesPerTrial = 1;\nnTrials = 100;\nshapePar = 2;\nscalePar = 3;\ndata = [];\ntime = linspace(0,1,1000);\ndata.trial(1:nTrials) = {zeros(1,length(time))};\ndata.time(1:nTrials) = {time};\nfor iTrial = 1:nTrials \n for iUnit = 1:4\n data.trial{iTrial}(iUnit,:) = rand(1,1000)\n\npt1 = [10 10];\npt2 = [10 20];\npt3 = [20 20];\n\ntestCase.assertEqual(distancePoints(pt1, pt2), 10, 'AbsTol', .01);\ntestCase.assertEqual(distancePoints(pt2, pt3), 10, 'AbsTol', .01);\ntestCase.assertEqual(distancePoints(pt1, pt3), 10*sqrt(2), 'AbsTol', .01);\n\nfunction testSingleSingleNorm1(testCase)\n% test norm 1, equivalent to sum of absolute differences\n\npt1 = [10 10];\npt2 = [10 20];\npt3 = [20 20];\n\ntestCase.assertEqual(distancePoints(pt1, pt2, 1), 10, 'AbsTol', .01);\ntestCase.assertEqual(distancePoints(pt2, pt3, 1), 10, 'AbsTol', .01);\ntestCase.assertEqual(distancePoints(pt1, pt3, 1), 20, 'AbsTol', .01);\n\nfunction testSingleSingleMaxNorm(testCase)\n\npt1 = [10 10];\npt2 = [10 20];\npt3 = [20 20];\n\ntestCase.assertEqual(distancePoints(pt1, pt2, inf), 10, 'AbsTol', .01);\ntestCase.assertEqual(distancePoints(pt2, pt3, inf), 10, 'AbsTol', .01);\ntestCase.assertEqual(distancePoints(pt1, pt3, inf), 10, 'AbsTol', .01);\n\nfunction testSingleSingle3d(testCase)\n\npt1 = [10 10 10];\npt2 = [10 20 10];\npt3 = [20 20 10];\npt4 = [20 20 20];\n\ntestCase.assertEqual(distancePoints(pt1, pt2), 10, 'AbsTol', .01);\ntestCase.assertEqual(distancePoints(pt2, pt3), 10, 'AbsTol', .01);\ntestCase.assertEqual(distancePoints(pt1, pt3), 10*sqrt(2), 'AbsTol', .01);\ntestCase.assertEqual(distancePoints(pt1, pt4), 10*sqrt(3), 'AbsTol', .01);\n\n\nfunction testSingleSingle3dNorm1(testCase)\n% test norm 1, equivalent to sum of absolute differences\n\npt1 = [10 10 30];\npt2 = [10 20 30];\npt3 = [20 20 30];\npt4 = [20 20 40];\n\ntestCase.assertEqual(distancePoints(pt1, pt2, 1), 10, 'AbsTol', .01);\ntestCase.assertEqual(distancePoints(pt2, pt3, 1), 10, 'AbsTol', .01);\ntestCase.assertEqual(distancePoints(pt1, pt3, 1), 20, 'AbsTol', .01);\ntestCase.assertEqual(distancePoints(pt1, pt4, 1), 30, 'AbsTol', .01);\n\nfunction testSingleSingleMaxNorm3d(testCase)\n\npt1 = [10 10 10];\npt2 = [10 20 10];\npt3 = [20 20 10];\npt4 = [20 20 20];\n\ntestCase.assertEqual(distancePoints(pt1, pt2, inf), 10, 'AbsTol', .01);\ntestCase.assertEqual(distancePoints(pt2, pt3, inf), 10, 'AbsTol', .01);\ntestCase.assertEqual(distancePoints(pt1, pt3, inf), 10, 'AbsTol', .01);\ntestCase.assertEqual(distancePoints(pt1, pt4, inf), 10, 'AbsTol', .01);\n\nfunction testSingleArray(testCase)\n\npt1 = [10 10];\npt2 = [10 20];\npt3 = [20 20];\n\ntestCase.assertEqual(...\n distancePoints(pt1, [pt1; pt2; pt3]), ...\n [0 10 10*sqrt(2)], 'AbsTol', .01);\n\nfunction testArrayArray(testCase)\n\npt1 = [10 10];\npt2 = [10 20];\npt3 = [20 20];\npt4 = [20 10];\n\narray1 = [pt1;pt2;pt3];\narray2 = [pt1;pt2;pt3;pt4];\nres = [...\n 0 10 10*sqrt(2) 10;...\n 10 0 10 10*sqrt(2);...\n 10*sqrt(2) 10 0 10];\n \ntestCase.assertEqual(distancePoints(array1, array2), res, 'AbsTol', .01);\n\nfunction testArrayArrayDiag(testCase)\n\npt1 = [10 10];\npt2 = [10 20];\npt3 = [20 20];\n\narray = [pt1;pt2;pt3];\n\ntestCase.assertEqual(...\n distancePoints(array, array, 'diag'), ...\n [0;0;0], 'AbsTol', .01);\n\nfunction testArrayArray3dDiag(testCase)\n\npt1 = [10 10 30];\npt2 = [10 20 30];\npt3 = [10 20 40];\n\narray1 = [pt1;pt2;pt3];\narray2 = [pt2;pt3;pt1];\n\ntestCase.assertEqual(...\n distancePoints(array1, array2, 'diag'), ...\n [10;10;10*sqrt(2)], 'AbsTol', .01);\n\nfunction testArrayArray3dNorm1Diag(testCase)\n\npt1 = [10 10 30];\npt2 = [10 20 30];\npt3 = [10 20 40];\n\narray1 = [pt1;pt2;pt3];\narray2 = [pt2;pt3;pt1];\n\ntestCase.assertEqual(...\n distancePoints(array1, array2, 1, 'diag'), ...\n [10;10;20], 'AbsTol', .01);\n\n\nfunction testArrayArrayDiagMaxNorm(testCase)\n\npt1 = [10 10];\npt2 = [10 20];\npt3 = [20 20];\n\narray1 = [pt1;pt2;pt3];\narray2 = [pt2;pt3;pt1];\n\ntestCase.assertEqual(...\n distancePoints(array1, array2, inf, 'diag'), ...\n [10;10;10], 'AbsTol', .01);\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/tests/geom2d/test_distancePoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.48849087971059}} {"text": "function [annotation, img] = LMimscale(annotation, img, scaling, method)\n%\n% Scales one image (as in imresize) and the associated annotation.\n% The scale factor is given by 'scaling'.\n% \n% When scaling<1, the image is downsampled.\n%\n% [annotation, img] = LMimscale(annotation, img, scaling);\n%\n% or, if you are using the LabelMe struct D:\n% \n% [D(i).annotation, img] = LMimscale(D(i).annotation, img, scaling);\n%\n% Also, the scaling can be given in absolute coordinates:\n%\n% [annotation, img] = LMimscale(annotation, img, [NROWS NCOLS]);\n\n% Store the original numerical format of the image and turn it into 'double'.\n\n\nimgtype = whos('img');\nimg = single(img);\n\nif nargin < 4\n method = 'bilinear';\nend\nif length(scaling) > 1\n scalingx = scaling(2)/size(img,2);\n scalingy = scaling(1)/size(img,1);\n if isnan(scalingx)\n scalingx = scalingy;\n end\n if isnan(scalingy)\n scalingy = scalingx;\n end\nelse\n scalingx = scaling;\n scalingy = scaling;\nend\n \nif scaling ~= 1\n if nargout > 1\n % Image resampling:\n %img = imresizefast(img, scaling, method);\n img = imresize(img, scaling, method);\n end\n \n % Change the size of the polygon coordinates\n if isfield(annotation, 'object')\n Nobjects = length(annotation.object); n=0;\n for i = 1:Nobjects\n [x,y] = getLMpolygon(annotation.object(i).polygon);\n x = round(x*scalingx);\n y = round(y*scalingy);\n annotation.object(i).polygon = setLMpolygon(x,y);\n \n% Npoints = length(annotation.object(i).polygon.pt);\n% for j = 1:Npoints\n% % Scale each point:\n% x=str2num(annotation.object(i).polygon.pt(j).x);\n% y=str2num(annotation.object(i).polygon.pt(j).y);\n% \n% x = round(x*scalingx);\n% y = round(y*scalingy);\n% \n% annotation.object(i).polygon.pt(j).x = num2str(x);\n% annotation.object(i).polygon.pt(j).y = num2str(y);\n% end\n end\n end\nend\n\n% add/modify image size field\nannotation.imagesize.nrows = size(img,1);\nannotation.imagesize.ncols = size(img,2);\n\nif nargout > 1\n % return the image in its original numeric format\n img = feval(imgtype.class, img);\nend\n\nfunction img = imresizefast(img, scaling, method, init)\n\nif nargin<4\n init = 0;\nend\n\nif max(scaling) > .5\n img = imresize(img, scaling, method);\nelse\n c = size(img,3);\n for n = 1:c\n img(:,:,n) = conv2(img(:,:,n), [1 2 1; 2 4 2; 1 2 1]/16, 'same');\n end\n img = img(init+1:2:end, init+1:2:end, :);\n %img = convn(img, [1 2 1]/4, 'same'); \n %img = img(:,init+1:2:end,:);\n img = imresizefast(img, 2*scaling, method, 1-init);\nend\n\n\n\n", "meta": {"author": "CSAILVision", "repo": "LabelMeToolbox", "sha": "b8eb2179723d8c15a4331c1ea6da5c6cd64e75e2", "save_path": "github-repos/MATLAB/CSAILVision-LabelMeToolbox", "path": "github-repos/MATLAB/CSAILVision-LabelMeToolbox/LabelMeToolbox-b8eb2179723d8c15a4331c1ea6da5c6cd64e75e2/imagemanipulation/LMimscale.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6261241911813151, "lm_q1q2_score": 0.4883724237987708}} {"text": "classdef DepthAnalysisWindow < AnalysisWindow\n % DEPTHANALYSISWINDOW shows the number of events, binned per depth\n properties\n binedges double; % km\n end\n methods\n function obj=DepthAnalysisWindow(ax,binedges)\n obj@AnalysisWindow(ax);\n obj.binedges=binedges;\n end\n \n function prepare_axes(obj)\n % prepare the depth profile axes\n obj.ax.Tag = 'dvEventsWidthDepth';\n obj.ax.YDir = 'reverse';\n obj.ax.Title.String = 'Depth Profile';\n obj.ax.XLabel.String= 'Number of events';\n obj.ax.YLabel.String= 'Depth';\n end\n \n function [x,y]=calculate(obj,catalog)\n % calculate the number of events (y) for each binned depth(x)\n x = histcounts(catalog.Depth,obj.binedges);\n y=obj.binedges(1:end-1) + diff(obj.binedges)./2;\n end\n \n end\nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/DepthAnalysisWindow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4883724193197654}} {"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": "% MatrixUser, a multi-dimensional matrix analysis software package\n% https://sourceforge.net/projects/matrixuser/\n% \n% The MatrixUser is a matrix analysis software package developed under Matlab\n% Graphical User Interface Developing Environment (GUIDE). It features \n% functions that are designed and optimized for working with multi-dimensional\n% matrix under Matlab. These functions typically includes functions for \n% multi-dimensional matrix display, matrix (image stack) analysis and matrix \n% processing.\n%\n% Author:\n% Fang Liu \n% University of Wisconsin-Madison\n% Aug-30-2014\n\n\n\nfunction MU_funcFlipV(Temp,Event,handles)\nhandles=guidata(handles.MU_matrix_display);\n\nif ~isempty(handles.V.Segs)\n choice = questdlg('Segmentation mask is detected, transform operation will reset them, preceed?','Mask Reset', ...\n 'No, go save mask','Yes','No, go save mask');\n if isempty(choice)\n warndlg('Transform is cancelled.');\n return;\n end\n % Handle response\n switch choice\n case 'No, go save mask'\n warndlg('Save your mask before transform.');\n return;\n end\n \n handles.Mask=handles.Mask*0;\n handles.V.Segs=[];\nend\n\n% close 3D slicer\nglobal Figure_handles\nif isfield(Figure_handles,'MU_display2')\n slicer_display_handles=guidata(Figure_handles.MU_display2);\n if Figure_handles.MU_display == slicer_display_handles.Parent\n close(Figure_handles.MU_display2);\n end\nend\n\nhandles.TMatrix=flipdim(handles.TMatrix,1);\nhandles.Mask=flipdim(handles.Mask,1);\n\nMergeM=get(handles.Matrix_name_edit,'String');\nset(handles.Matrix_name_edit,'String',[MergeM '_fpv']);\n\n% update current display matrix\nhandles=MU_update_image(handles.Matrix_display_axes,{handles.TMatrix,handles.Mask},handles,0);\nguidata(handles.MU_matrix_display, handles);\n\nend", "meta": {"author": "leoliuf", "repo": "MRiLab", "sha": "5cdcf1f7b67759700685d3a26ffeb70e55325567", "save_path": "github-repos/MATLAB/leoliuf-MRiLab", "path": "github-repos/MATLAB/leoliuf-MRiLab/MRiLab-5cdcf1f7b67759700685d3a26ffeb70e55325567/External/MatrixUser2.2/Src/FuncLib/MU_funcFlipV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.4883296377293476}} {"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 ylag = lagmatrix( y, lags )\n n = length(y);\n N = max(lags);\n \n ylag = convmtx(y, N+1);\n ylag = ylag(1:n, lags+1);\n\nend\n\n", "meta": {"author": "BUNPC", "repo": "Homer3", "sha": "d0fac4b22d1069eaa5cba268a225eb117ddcdca1", "save_path": "github-repos/MATLAB/BUNPC-Homer3", "path": "github-repos/MATLAB/BUNPC-Homer3/Homer3-d0fac4b22d1069eaa5cba268a225eb117ddcdca1/FuncRegistry/UserFunctions/iWLS/lagmatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.48832961925087653}} {"text": "function [ y, m, d, f, ierror ] = ymdf_check_common ( y, m, d, f )\n\n%*****************************************************************************80\n%\n%% YMDF_CHECK_COMMON checks a Common YMDF date.\n%\n% Discussion:\n%\n% Certain simple errors in dates will be corrected, such as\n% \"31 September 1996\"\n% which will become\n% \"1 October 1996\".\n%\n% The routine also knows that in the Common calendar, the dates\n% 5 October 1582 through 14 October 1582 are illegal.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 December 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer Y, integer M, integer D, real F, the\n% YMDF date.\n%\n% Output, integer Y, integer M, integer D, real F, the\n% YMDF date, which may be corrected if necessary and possible.\n%\n% Output, integer IERROR, is 0 if the date is legal.\n%\n ierror = 0;\n\n [ y, m, d, ierror ] = ymd_check_common ( y, m, d );\n\n if ( ierror ~= 0 )\n return\n end\n\n [ y, m, d, f ] = frac_borrow_common ( y, m, d, f );\n\n [ y, m, d, f ] = frac_carry_common ( y, m, d, f );\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/calendar_nyt/ymdf_check_common.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484144, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.48832961558742205}} {"text": "function [fusion,params] = quality_fuser_v1(w,scores,train_vecs,test_vecs,train_ndx,test_ndx,ddim)\n% \n% Inputs:\n%\n% scores: the primary detection scores, for training\n% D-by-T matrix of T scores for D input systems\n%\n% train_vecs: K1-by-M matrix, one column-vector for each of M training\n% segments\n%\n% test_vecs: K2-by-N matrix, one column-vector for each of N training\n% segemnts\n%\n% train_ndx: 1-by-T index where train_ndx(t) is the index into train_vecs\n% for trial t. \n%\n% test_ndx: 1-by-T index where test_ndx(t) is the index into test_vecs\n% for trial t. \n% ddim: dimension of subspace for quality distandce calculation,\n% where ddim <= min(K1,K2)\n\nif nargin==0\n test_this();\n return;\nend\n\n% Check data dimensions\n[K1,M] = size(train_vecs);\n[K2,N] = size(test_vecs);\nassert(ddim 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 check = triangular_check ( a, b )\n\n%*****************************************************************************80\n%\n%% TRIANGULAR_CHECK checks the parameters of the Triangular CDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, B, the parameters of the PDF.\n% A < B.\n%\n% Output, logical CHECK, is true if the parameters are legal.\n%\n if ( b <= a )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRIANGULAR_CHECK - Fatal error!\\n' );\n fprintf ( 1, ' B <= A.\\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/triangular_check.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.4880591393152951}} {"text": "function R = getHPfilter(freq,numsamps)\n\n% freq is number of frequencies to cut off.\nbase = 1:2*pi/numsamps:2*pi\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/core_functions/getHPfilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.48805912929516143}} {"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 d = dot(obj1,obj2)\n% inner product between embeddings\n%\n% Syntax\n% d = dot(e1,e2)\n%\n% Input\n% e1,e2 - @embedding\n%\n% Output\n% d - double\n%\n \nd = 0;\nfor i = 1:length(obj1.u)\n \n id = -(1:obj1.rank(i));\n d = d + EinsteinSum(obj1.u{i},id,obj2.u{i},id);\n \nend\n\nend", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/geometry/@embedding/dot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.48801750847178366}} {"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 MatingPool = MatingSelection(Obj,RefPoint,Range)\n% The mating selection of AR-MOEA\n\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 %% Calculate the fitness of each feasible solution based on IGD-NS\n % Calculate the distance between each solution and point\n N = size(Obj,1);\n Distance = CalDistance(Obj-repmat(Range(1,:),N,1),RefPoint);%N*NR\n Convergence = min(Distance,[],2);% The minimum Angle between each solution and the reference point\n [dis,rank] = sort(Distance,1);% In columns, for reference points\n % Calculate the fitness of noncontributing solutions\n Noncontributing = true(1,N);\n Noncontributing(rank(1,:)) = false;\n METRIC = sum(dis(1,:)) + sum(Convergence(Noncontributing));\n % The sum of the minimum angles of all reference points plus the sum of the minimum angles of all non-contributing solutions\n fitness = inf(1,N);\n fitness(Noncontributing) = METRIC - Convergence(Noncontributing);\n % Calculate the fitness of contributing solutions\n for p = find(~Noncontributing)\n temp = rank(1,:) == p;\n noncontributing = false(1,N);\n noncontributing(rank(2,temp)) = true;% After removing this contribution point, the new contribution point Index\n noncontributing = noncontributing & Noncontributing;% Judge whether the new contribution point is the original non-contribution point or not\n fitness(p) = METRIC - sum(dis(1,temp)) + sum(dis(2,temp)) - sum(Convergence(noncontributing));\n % When this contribution point is removed, the METRIC adjusts\n end\n\n %% Combine the fitness of feasible solutions with the fitness of infeasible solutions\n Fitness = fitness;\n \n %% Binary tournament selection\n CV=zeros(N,1);\n MatingPool = TournamentSelection(2,ceil(N/2)*2,CV,-Fitness);\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/EDN-ARMOEA/MatingSelection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.48799700723174955}} {"text": "\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 .\nim = mksq(64, 1);\n%im = zeros(64,64);\n%im(32,:) = 1;\nf1\nidisp(im)\ndisp('create a square')\npause\n\nf2\nedge = icanny(im);\n%edge = zeros(64,64);\n%edge(32,:) = 1;\nidisp(edge);\ndisp('take Laplacian to get 4 line segments')\npause\n\nf3\nh = Hough(edge)\ndisp('now show the Hough accumulator in which 4 peaks can be seen')\nh.show()\n\nf2\nh.plot(4,'g')\nh.peaks(4)\nf1\nh.plot(4,'g')\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/houghdemo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.48794185860786277}} {"text": "function [linGrid,gridSize,xx,yy,zz] = prtPlotUtilGenerateGrid(plotMins, plotMaxs, nSamplesPerDim, includePoints)\n% [linGrid,gridSize,xx,yy,zz] = prtPlotUtilGenerateGrid(plotMins, plotMaxs, nSamplesPerDim, includePoints)\n% Internal function, \n% xxx Need Help xxx\n\n\n\n\n\n\n\nyy = [];\nzz = [];\n\nnDims = length(plotMins);\n\nif ~isnumeric(nSamplesPerDim)\n try\n nSamplesPerDim = nSamplesPerDim.nSamplesPerDim;\n catch %#ok\n error('prt:prtPlotUtilGenerateGrid','Invalid nSamplesPerDim input');\n end\nend\n\nxx = linspace(plotMins(1),plotMaxs(1),nSamplesPerDim(nDims));\nif nargin > 3 && ~isempty(includePoints)\n xx = cat(2,xx,includePoints(:,1)');\n xx = sort(xx,'ascend');\nend\n\nif nDims > 1\n yy = linspace(plotMins(2),plotMaxs(2),nSamplesPerDim(nDims));\n if nargin > 3 && ~isempty(includePoints)\n yy = cat(2,yy,includePoints(:,2)');\n yy = sort(yy,'ascend');\n end\nend\n\nif nDims > 2\n zz = linspace(plotMins(3),plotMaxs(3),nSamplesPerDim(nDims));\n if nargin > 3 && ~isempty(includePoints)\n zz = cat(2,zz,includePoints(:,3)');\n zz = sort(zz,'ascend');\n end\nend\n\nswitch nDims\n case 1\n linGrid = xx(:);\n gridSize = size(xx);\n yy = ones(size(xx));\n case 2\n [xx,yy] = meshgrid(xx,yy);\n linGrid = [xx(:),yy(:)];\n gridSize = size(xx);\n case 3\n [xx,yy,zz] = meshgrid(xx,yy,zz);\n gridSize = size(xx);\n linGrid = [xx(:), yy(:), zz(:)];\nend\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/plot/util/prtPlotUtilGenerateGrid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.4879418547856693}} {"text": "function s = collapse(t,dims,fun)\n%COLLAPSE Collapse sparse tensor along specified dimensions.\n%\n% S = COLLAPSE(T,DIMS) sums the entries of T along all dimensions\n% specified in DIMS. If DIMS is negative, then T is summed across\n% all dimensions *not* specified by -DIMS.\n%\n% S = COLLAPSE(T) is shorthand for S = COLLAPSE(T,1:ndims(T)).\n%\n% S = COLLAPSE(T,DIMS,FUN) accumulates the entries of T using the\n% accumulation function @FUN.\n%\n% Examples\n% subs = [1 1 1; 1 1 3; 2 2 4; 4 4 4]\n% vals = [10.5; 1.5; 2.5; 3.5]\n% X = sptensor(subs,vals,[4 4 4]);\n% Y = collapse(X,[2 3]) %<-- sum of entries in each mode-1 slice\n% Y = collapse(ones(X),[1 2]) %<-- nnz in each mode-3 slide\n% Y = collapse(ones(X),[1 2],@max) %<-- 1 if mode-3 has any entry\n% Y = collapse(ones(X),-3,@max); %<-- equivalent\n%\n% See also SPTENSOR, SPTENSOR/SCALE.\n%\n%MATLAB Tensor Toolbox.\n%Copyright 2015, Sandia Corporation.\n\n% This is the MATLAB Tensor Toolbox by T. Kolda, B. Bader, and others.\n% http://www.sandia.gov/~tgkolda/TensorToolbox.\n% Copyright (2015) Sandia Corporation. Under the terms of Contract\n% DE-AC04-94AL85000, there is a non-exclusive license for use of this\n% work by or on behalf of the U.S. Government. Export of this data may\n% require a license from the United States Government.\n% The full license terms can be found in the file LICENSE.txt\n\n\nif ~exist('fun', 'var')\n fun = @sum;\nend\n\nif ~exist('dims', 'var')\n dims = 1:ndims(t);\nend\n\ndims = tt_dimscheck(dims,ndims(t));\nremdims = setdiff(1:ndims(t),dims);\n\n% Check for the case where we accumulate over *all* dimensions\nif isempty(remdims)\n s = fun(t.vals);\n return;\nend\n\n% Calculate the size of the result\nnewsiz = size(t,remdims);\n\n% Check for the case where the result is just a dense vector\nif numel(remdims) == 1\n if ~isempty(t.subs)\n s = accumarray(t.subs(:,remdims), t.vals, [newsiz 1], fun);\n else\n s = zeros(newsiz,1);\n end\n return;\nend\n\n% Create the result\nif ~isempty(t.subs)\n s = sptensor(t.subs(:,remdims), t.vals, newsiz, fun);\nelse\n s = sptensor([],[],newsiz);\nend\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u5206\u7c7b\u7b97\u6cd5/DEEP-TENSOR-FACTORIZATION-FOR-HYPERSPECTRAL-IMAGE-CLASSIFICATION-master/code/tensor_toolbox_2.6/@sptensor/collapse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.4879418547856693}} {"text": "% function plot_srErrorOrigin\n% %\n% %\n% %\n% % Author: van Stiphout, Thomas, vanstiphout@sed.ethz.ch\n\nfRes=10000;\nvEdges=[-9.9:0.2:9.9];\n\n% Plot-list\nsPlotList=['mCompose.m05';...\n 'mCompose.m06';...\n 'mCompose.m07';...\n 'mCompose.m08';...\n% 'mCompose.m12';...\n 'mCompose.m13'];\n\n\nmColorLine=lines(size(sPlotList,1));\n\nfigure;\nfor i=1:size(sPlotList,1)\n if i==1\n subplot(2,1,1)\n else\n hold on;\n end\n eval(sprintf('mPlotit=%s.mResult1;',sPlotList(i,:)));\n vVal=reshape(squeeze(mPlotit(:,1,:)),...\n size(mPlotit,1)*size(mPlotit,3),1);\nvRes=reshape(squeeze(mPlotit(:,2,:)),...\n size(mPlotit,1)*size(mPlotit,3),1);\n% vSel=(vRes ].\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 [vITRS,rotMat]=ITRS2TIRS(vTIRS,TT1,TT2,xpyp)\n%%ITRS2TIRS Rotate vectors from the International terrestrial Reference\n% System (ITRS) into the Terrestrial Intermediate Reference\n% System (TIRS). The ITRS is essentially the WGS-84 coordinate\n% system: it defines locations with respect to the crust of a\n% non-rotating Earth, where the z axis passes through a fixed\n% point on the surface. On the other hand, the TIRS is nearly\n% the same except the z axis is the axis of rotation of the\n% Earth, which slowly varies over time. Note that the velocity\n% conversion does not include the (small) centrifugal effect of\n% polar motion.\n%\n%INPUTS: x The NXnumVec collection of vectors in TIRS coordinates to\n% convert (units do not matter). N can be 3, or 6. If the vectors\n% are 3D, then they are position. 6D vectors are assumed to be\n% position and velocity. Since the TIRS and ITRS co-rotate, there\n% is no Coriolis effect to add. Also, the accelerations due to the\n% wobble of the rotation axis over time are not considered. These\n% accelerations are very small. Thus, the function just rotates\n% both halves of the vector.\n% TT1, TT2 Two parts of a Julian date given in terrestrial time (TT).\n% The units of the date are days. The full date is the sum of\n% both terms. The date is broken into two parts to provide more\n% bits of precision. It does not matter how the date is split.\n% xpyp xpyp=[xp;yp] are the polar motion coordinates in radians\n% including the effects of tides and librations. If this\n% parameter is omitted or if an empty matrix is passed, the value\n% from the function getEOP will be used.\n%\n%OUTPUTS: vITRS The NXnumVec vector of values of x rotated from the ITRS\n% into the TIRS.\n% rotMat The 3X3 rotation matrix used to rotate vectors from the\n% ITRS into the TIRS.\n%\n%The conversion functions from the International Astronomical Union's\n%(IAU) Standard's of Fundamental Astronomy library are put together to get\n%the necessary rotation matrix.\n%\n%The algorithm can be compiled for use in Matlab using the \n%CompileCLibraries function.\n%\n%The algorithm is run in Matlab using the command format\n%[vITRS,rotMat]=ITRS2TIRS(vTIRS,TT1,TT2)\n%or if more parameters are known, using the format\n%[vITRS,rotMat]=ITRS2TIRS(vTIRS,TT1,TT2,xpyp);\n%\n%Different celestial coordinate systems are compared in [1].\n%\n%REFERENCES:\n%[1] D. F. Crouse, \"An Overview of Major Terrestrial, Celestial, and\n% Temporal Coordinate Systems for Target Tracking,\" Formal Report,\n% Naval Research Laboratory, no. NRL/FR/5344--16-10,279, 10 Aug. 2016,\n% 173 pages.\n%\n%March 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nerror('This function is only implemented as a mexed C or C++ function. Please run CompileCLibraries.m to compile the function for use.')\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Coordinate_Systems/Celestial_and_Terrestrial_Systems/ITRS2TIRS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4878735072309065}} {"text": "function mtrPlotRankCorrSummary(summaryFilename)\n\nsummary = load(summaryFilename);\nparamNames = {'kLength','kSmooth','kMidSD'};\nmidP = [-2 18 0.175];\nccGrid = mtrFilenames2Paramlist(summary.pdbIDFiles,paramNames);\n\nfor pp = 1:length(paramNames)\n strThreshVec = {};\n parVecs = [];\n corrVecs = [];\n ovrVecs = [];\n for tt = 1:length(summary.threshVec)\n ccGrid(:,4) = summary.rhoS(:,tt);\n ccGrid(:,5) = summary.overlapVec(:,tt);\n indGrid = ones(size(ccGrid,1),1);\n for ss = 1:length(paramNames)\n if ss ~= pp\n indGrid = indGrid & ccGrid(:,ss) == midP(ss);\n end\n end\n subGrid = ccGrid(indGrid,:);\n [foo, sortI] = sort(subGrid(:,pp));\n parVecs(:,tt) = subGrid(sortI(:),pp);\n corrVecs(:,tt) = subGrid(sortI(:),4);\n ovrVecs(:,tt) = subGrid(sortI(:),5);\n strThreshVec{tt} = ['Top ' num2str(summary.threshVec(tt))];\n end\n figure; plot(parVecs,corrVecs);\n legend(strThreshVec);\n xlabel([paramNames{pp} ' parameter']);\n ylabel('Spearman rank correlation');\n figure; plot(parVecs,ovrVecs);\n legend(strThreshVec);\n xlabel([paramNames{pp} ' parameter']);\n ylabel('Overlap');\nend\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrDiffusion/fiber/tractography/contrack/metrotrac/mtrPlotRankCorrSummary.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.48787350178917677}} {"text": "function [A, C, b, f] = HALS_2d(Y, A, C, b, f, params)\n%% Hierarchical alternating least square method for solving NMF problem\n% Y = A*C + b*f\n\n%input:\n% Y: d1 X d2 X T, raw data. It will be reshaped to (d1*d2) X T in this\n% function\n% A: (d1*d2) X K, initial value of spatial components\n% C: K X T, initial value of temporal components\n% b: (d1*d2) X nb, initial value of background spatial component\n% f: nb X T, initial value of background temporal component\n% params: parameters used in this function.\n% bSiz: blur size. A box kernel (bSiz X bSiz) will be convolved\n% with each neuron's initial spatial component, then all nonzero\n% pixels will be picked as pixels to be updated, and the rest will be\n% forced to be 0.\n% maxIter: maximum iteration of iterating HALS.\n\n% Author: Pengcheng Zhou, Columbia University, based on a python\n% implementation from Johannes Friedrich, Columbia University, 2015.\n\n%% parameters\nif isfield(params, 'maxIter'), maxIter = params.maxIter; else maxIter=5; end\nif isfield(params, 'search_method'); method=params.search_method; else method='ellipse'; end\nif and(isfield(params, 'bSiz'), strcmpi(method, 'dilate'))\n params.se = strel('disk', params.bSiz);\nend\n% search locations\nIND = determine_search_location(A, method, params);\n\n%% update spatial and temporal components neuron by neurons\n\nfor miter=1:maxIter\n %% update neurons\n Yac = Y - b*f;\n ind_del = find(std(A,0,1)==0); \n A(:, ind_del) = []; \n C(ind_del, :) = []; \n IND(:, ind_del) = []; \n % temporal\n C = HALS_temporal(Yac, A, C, 5);\n \n ind_del = find(std(C,0,2)==0); \n A(:, ind_del) = []; \n C(ind_del, :) = []; \n IND(:, ind_del) = []; \n % spatial\n A = HALS_spatial(Yac, A, C, IND, 5);\n \n %% update background\n Ybg = Y-A*C;\n % temporal\n f = HALS_temporal(Ybg, b, f, 5);\n % spatial \n b = HALS_spatial(Ybg, b, f, [], 5); \nend", "meta": {"author": "flatironinstitute", "repo": "CaImAn-MATLAB", "sha": "49b7884e93348d50df7173e1619d7499468bb1f6", "save_path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB", "path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB/CaImAn-MATLAB-49b7884e93348d50df7173e1619d7499468bb1f6/utilities/HALS_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.487829844726708}} {"text": "function v = grad(f)\n%GRAD Gradient of a BALLFUN in cartesian coordinates.\n% GRAD(F) is the gradient of the BALLFUN F expressed in\n% cartesian coordinates.\n%\n% This is shorthand for the command GRADIENT.\n%\n% See also DIV, CURL\n\n% Copyright 2019 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nv = gradient(f);\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@ballfun/grad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4878298387108655}} {"text": "function obj_val = evaluate_objective(objective_function,scores,classf, ...\n\t\t\t\t prior)\n% Returns the result of the objective function evaluated on the\n% scores.\n%\n% Inputs:\n% objective_function: a function handle to the objective function\n% to feed the scores into\n% scores: length T vector of scores to be evaluated where T is\n% the number of trials\n% classf: length T vector with entries +1 for target scores; -1 \n% for non-target scores\n% prior: the prior (given to the system that produced the scores)\n%\n% Outputs\n% obj_val: the value returned by the objective function\n\nif nargin==0\n test_this();\n return;\nend\n\n\nif ~exist('objective_function','var') || isempty(objective_function)\n objective_function = @(w,T,weights,logit_prior) cllr_obj(w,T,weights,logit_prior);\nend\n\n\nlogit_prior = logit(prior);\nprior_entropy = objective_function([0;0],[1,-1],[prior,1-prior],logit_prior);\n\nntar = length(find(classf>0));\nnnon = length(find(classf<0));\nN = nnon+ntar;\n\nweights = zeros(1,N);\n\nweights(classf>0) = prior/(ntar*prior_entropy);\nweights(classf<0) = (1-prior)/(nnon*prior_entropy);\n\n\nobj_val = objective_function(scores,classf,weights,logit_prior);\n\nend\n\nfunction test_this()\nnum_trials = 20;\nscores = randn(1,num_trials);\nclassf = [ones(1,num_trials/2),-ones(1,num_trials/2)];\nprior = 0.5;\nres = evaluate_objective(@cllr_obj,scores,classf,prior)\nend\n\n", "meta": {"author": "nesl", "repo": "asvspoof2019", "sha": "8b780369f7273345c22d979192119198bbf3db13", "save_path": "github-repos/MATLAB/nesl-asvspoof2019", "path": "github-repos/MATLAB/nesl-asvspoof2019/asvspoof2019-8b780369f7273345c22d979192119198bbf3db13/baseline/tDCF_v1/bosaris_toolkit.1.06/bosaris_toolkit/utility_funcs/Optimization_Toolkit/applications/fusion2class/evaluate_objective.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4878298387108655}} {"text": "function dcfplot(devkeyname,evalkeyname,devscrfilename,evalscrfilename,outfilename,plot_title,xmin,xmax,ymin,ymax,prior)\n% Makes a Norm_DCF plot of the dev and eval scores for a system. \n% Inputs:\n% devkeyname: The name of the file containing the Key for\n% the dev scores.\n% evalkeyname: The name of the file containing the Key for\n% the eval scores.\n% devscrfilename: The name of the file containing the Scores\n% for the dev trials.\n% evalscrfilename: The name of the file containing the\n% Scores the eval trials.\n% outfilename: The name for the PDF file that the plot will be\n% written in.\n% plot_title: A string for the plot title. (optional)\n% xmin, xmax, ymin, ymax: The boundaries of the plot. (optional)\n% prior: The effective target prior. (optional)\n\nassert(isa(devkeyname,'char'))\nassert(isa(evalkeyname,'char'))\nassert(isa(devscrfilename,'char'))\nassert(isa(evalscrfilename,'char'))\nassert(isa(outfilename,'char'))\n\nif ~exist('plot_title','var') || isempty(plot_title)\n plot_title = '';\nend\n\nif ~exist('xmin','var')\n xmin = -10;\n xmax = 0;\n ymin = 0;\n ymax = 1.2;\n prior = 0.001;\nend\n\n[dev_tar,dev_non] = get_tar_non_scores(devscrfilename,devkeyname);\n[eval_tar,eval_non] = get_tar_non_scores(evalscrfilename,evalkeyname);\n\nclose all\nplot_obj = Norm_DCF_Plot([xmin,xmax,ymin,ymax],plot_title);\nplot_obj.set_system(dev_tar,dev_non,'dev')\nplot_obj.plot_operating_point(logit(prior),'m--','new DCF point')\nplot_obj.plot_curves([0 0 0 1 1 1 0 0],{{'b--'},{'g--'},{'r--'}})\nplot_obj.set_system(eval_tar,eval_non,'eval')\nplot_obj.plot_curves([0 0 1 1 1 1 0 1],{{'r','LineWidth',2},{'b'},{'g'},{'r'},{'k*'}})\nplot_obj.display_legend()\nplot_obj.save_as_pdf(outfilename)\nend\n\nfunction [tar,non] = get_tar_non_scores(scrfilename,keyname)\nkey = Key.read(keyname);\nscr = Scores.read(scrfilename);\n[tar,non] = scr.get_tar_non(key);\nend\n", "meta": {"author": "nesl", "repo": "asvspoof2019", "sha": "8b780369f7273345c22d979192119198bbf3db13", "save_path": "github-repos/MATLAB/nesl-asvspoof2019", "path": "github-repos/MATLAB/nesl-asvspoof2019/asvspoof2019-8b780369f7273345c22d979192119198bbf3db13/baseline/tDCF_v1/bosaris_toolkit.1.06/bosaris_toolkit/plotting/dcfplot.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 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": "classdef IQR < Algorithm\n \n methods (Access = public)\n \n function obj = IQR()\n obj.name = 'IQR';\n obj.inputPort = DataType.kSignal;\n obj.outputPort = DataType.kFeature;\n end\n \n function result = compute(~,signal)\n result = iqr(signal);\n end\n \n function metrics = computeMetrics(~,input)\n n = size(input,1);\n flops = 57 * n;\n memory = n;\n outputSize = Constants.kFeatureBytes;\n metrics = Metric(flops,memory,outputSize);\n end\n end\nend\n", "meta": {"author": "avenix", "repo": "WDK", "sha": "c525222b02bd390b4758d30f1cd8b19af043108e", "save_path": "github-repos/MATLAB/avenix-WDK", "path": "github-repos/MATLAB/avenix-WDK/WDK-c525222b02bd390b4758d30f1cd8b19af043108e/ARC/algorithm/6-featureExtraction/time domain/IQR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.4878129639832843}} {"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": "% SCRIPT TEST FOR THE KINEMATIC PROBLEM FOR SERIAL ROBOTS\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% \n% qinv =\n% \n% 0 0 0 0 3.1416 3.1416 3.1416 3.1416\n% -0.0412 -0.0412 1.6597 1.6597 -1.5798 -1.5798 -0.3550 -0.3550\n% 0.0720 0.0720 3.0696 3.0696 -0.3825 -0.3825 -2.7591 -2.7591\n% 0.0000 -3.1416 3.1416 -0.0000 0.0000 3.1416 0.0000 -3.1416\n% -0.0308 0.0308 -1.5539 1.5539 -1.1793 1.1793 -0.0275 0.0275\n% -0.0000 3.1416 -3.1416 0 3.1416 -0.0000 3.1416 -0.0000\n\nfunction test_kinematics_jaco\n\nclose all\n\nfprintf('\\nTHE DEMO PRESENTS THE DIRECT AND INVERSE KINEMATIC PROBLEM')\n\n%load robot parameters. You can try different robots%\nrobot=load_robot('KINOVA', 'JACO'); \n%adjust 3D view as desired\nadjust_view(robot)\n\nq =[pi/2 -pi/2 0 0 0 0];\nq0 = q + [0.1 0.1 0.1 0.1 0.1 0.1];\n\n\nT = directkinematic(robot, q)\n\n\n%Call the inversekinematic for this robot. All the possible solutions are\n%stored at qinv. At least, one of the possible solutions should match q\nqinv = inversekinematic(robot, T, q0)\n\nT2 = directkinematic(robot, qinv)\n\nqinv(:,1)\nq\n\nT-T2\n\n\n\nfunction test_movement(robot, qinv, T)\n\nq0 = [0, 0, 0, 0, 0, 0];\nn = 5\nfor i=1:size(qinv,2)\n qq = []; \n qi = qinv(:,i);\n for j=1:6\n v = linspace(q0(j), qi(j), n);\n qq = [qq; v];\n end\n animate(robot, qq) \nend\n\n\n\nfunction test_solutions(robot, qinv, T)\nn_solutions = 8;\n\nfprintf('\\nNOW WE CAN REPRESENT THE DIFFERENT SOLUTIONS TO ACHIEVE THE SAME POSITION AND ORIENTATION\\n')\nfprintf('\\nNote that some solutions may not be feasible since some joints may be out of range.\\n')\ncorrect=zeros(1,n_solutions);\n%check that all of them are possible solutions!\nfor i=1:size(qinv,2)\n \n Ti = directkinematic(robot, qinv(:,i)) %Ti is constant for the different solutions \n \n % Note that all the solutions may not be feasible. Some of the joints may\n % be out of range. You can test this situation with test_joints\n test_joints(robot, qinv(:,i));\n \n %now draw the robot to see the solution\n drawrobot3d(robot, qinv(:,i))\n \n pause(0.5);\n \n k=sum(sum((T-Ti).^2));\n if k < 0.01 % a simple threshold to find differences in the solution\n correct(1,i)= 1; \n else\n correct(1,i)= 0; %uncorrect solution\n fprintf('\\nERROR: One of the solutions seems to be uncorrect. Sum of errors: %f', i, k);\n end\nend\n\nfprintf('\\n************** RESULTS **************')\n\n%Display a message if any of the solutions is not correct\nif sum(correct)==n_solutions\n fprintf('\\nTEST 1--> OK: Every solution in qinv yields the same position/orientation T');\nelse\n fprintf('\\nTEST 1--> ERROR: One or more of the solutions seem to be uncorrect.');\nend\n\n\nfprintf('\\n************** ****** **************\\n')\n\n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/robots/KINOVA/JACO/test_kinematics_jaco.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.4878129347279301}} {"text": "function [n maxLflag] = loadfactor(tState)\n\nif tState.omega >= 0 % if level flight or sustained turn\n n = sqrt((tState.omega*tState.V/g0)^2+1);\n maxLflag = false;\nelseif tState.omega < 0 % if instantaneous turn indicated by negative omega\n % NB: rotor itertia doesn't help an inst. turn\n n = abs(tState.omega).*tState.V/g0;\n maxLflag = true;\nelse\n disp('Ill-defined turning condition')\nend\n\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/41725-core-conceptual-optimization-of-rotorcraft-environment/CORE_v0p7 - for upload may 2013/CORE/loadfactor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.48770904112477265}} {"text": "filename='Cantilever_hexahedra_coarse';\n ptype = 'MACRO';\nmethod = 'SIMPALL';\nmaterialType = 'ISOTROPIC';\ninitial_case = 'full';\ncost = {'compliance';'perimeter'};\nweights = [1, 0.1];\nconstraint = {'volumeConstraint'};\noptimizer = 'PROJECTED GRADIENT';\nincrementFactor = 1;\ndesignVariable = 'Density';\nfilterType = 'P1';\n\nnsteps = 5;\nVfrac_final = 0.1;\nPerimeter_target = 1;\noptimality_final = 1e-3;\nconstr_final =1e-3;\n\nVfrac_initial = 1;\noptimality_initial = 1e-2;\nconstr_initial = 1e-3;\nTOL.rho_plus = 1;\nTOL.rho_minus = 0;\nTOL.E_plus = 1;\nTOL.E_minus = 1e-3;\nTOL.nu_plus = 1/3;\nTOL.nu_minus = 1/3;", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/Benchmarks/Cantilever/CantileverHexahedraCoarse_Case_2_2_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.5660185351961013, "lm_q1q2_score": 0.4876465953176267}} {"text": "%%%C-Type implementation for imu interpolation for iphone data\n%oper=new output period\n%cdef= col definitions [total, Time , x , y, z]\nfunction [ini_time]=interp_imu(INFILES, OUTFILE, cdef, oper)\n\n% fclose all;\n% clear;\n% DIRNAME='C:\\Documents and Settings\\Yigiter\\Desktop\\data\\CalibTest1\\';\n% INFILES=[[DIRNAME '07-16-00-12-acclog.bin ']; [DIRNAME '07-16-00-12-gyrolog.bin']];\n% OUTFILE=[DIRNAME 'imu.bin'];\n% cdef=[5 2 3 4 5;5 2 3 4 5];\n% oper=2;\n\n%i/o files\nnfiles=size(cdef,1);\nndat=size(cdef,2)-1;\n\ninfids=zeros(nfiles,1);\nfor (in=1:nfiles)\n infids(in,1)=fopen(INFILES(in,:),'rb');\nend\nofid=fopen(OUTFILE,'wb');\n\n\n%first data from all files\ndata=zeros(ndat,nfiles);\nfor in=1:nfiles\n vr_a=fread(infids(in),[cdef(in,1) 1],'double');\n data(:,in)=vr_a(cdef(in,2:end),1);\nend\n\n%Latest data\nct=data(1,1);\nfor in=2:nfiles\n if ct nc*scale,\n break;\n end\n for yi = 1:ceil(nr/psize),\n cy = (psize/2 + (yi-1)*psize)*scale+ 1 ;\n if cy+psize/2 > nr*scale,\n break;\n end\n \n for bini = 1:nbins,\n tmp = bincenters(bini);\n curpatch = [cos(tmp) -sin(tmp); sin(tmp) cos(tmp)]*hogpatch;\n xcurr = cx + curpatch(1,:)*scale;\n ycurr = cy + curpatch(2,:)*scale;\n h(yi,xi,bini) = patch(xcurr,ycurr,colors(bini,:),'LineStyle','none','FaceAlpha',min(1,H(yi,xi,bini)/maxv2));\n end\n \n end\nend\ntruesize(hfig);\n% im = getframe(hax);\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/spaceTime/VisualizeHogFeatures.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 [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": "function failed_old_specest_vs_oldimplementation\n\n% MEM 1gb\n% WALLTIME 00:10:00\n% DEPENDENCY\n\n% read in data from /home/common/testdata (I just my own testdata)\n% data = .....\n\n%% COHERENCE specest_mtmfft\ncfg = [];\ncfg.keeptrials = 'yes';\ncfg.foilim = [2 100];\ncfg.output = 'powandcsd';\ncfg.taper = 'dpss';\ncfg.tapsmofrq = 4;\ncfg.pad = 'maxperlen';\ncfg.calcdof = 'yes';\ncfg.keeptrials = 'no';\n% old style\ncfg.method = 'mtmfft_old';\ntic; freqold = ft_freqanalysis(cfg,data); toc\n% new style\ncfg.method = 'mtmfft';\ntic; freqnew = ft_freqanalysis(cfg,data); toc\n\n% calculate coherence\ncfg = [];\ncfg.method = 'coh';\nconnold = ft_connectivityanalysis(cfg,freqold);\nconnnew = ft_connectivityanalysis(cfg,freqnew);\n\n% plot 'a' chancomb\nfigure\nsubplot(3,1,1)\nplot(connold.freq,squeeze(connold.cohspctrm(10,:)))\naxis tight\nxlabel('frequency (Hz)')\nylabel('coh')\ntitle('old implementation')\nsubplot(3,1,2)\nplot(connnew.freq,squeeze(connnew.cohspctrm(10,:)))\naxis tight\nxlabel('frequency (Hz)')\nylabel('coh')\ntitle('new implementation')\nsubplot(3,1,3)\nhold on\nplot(connold.freq,squeeze(connold.cohspctrm(10,:)))\nplot(connnew.freq,squeeze(connnew.cohspctrm(10,:)),'r')\nlegend\naxis tight\nxlabel('frequency (Hz)')\nylabel('coh')\ntitle('both overlayed, using freq axis of new implementation')\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n\n%% POWER specest_mtmfft\ncfg = [];\ncfg.trials = 1:3;\ncfg.keeptrials = 'yes';\ncfg.foilim = [0 256/2];\ncfg.output = 'pow';\ncfg.taper = 'dpss';\ncfg.tapsmofrq = 4;\ncfg.pad = 'maxperlen';\ncfg.calcdof = 'yes';\n% old style\ncfg.method = 'mtmfft_old';\ntic; freqold = ft_freqanalysis(cfg,data); toc\n% new style\ncfg.method = 'mtmfft';\ntic; freqnew = ft_freqanalysis(cfg,data); toc\n\n% plot first trial first channel, single timepoint\nfigure\nsubplot(3,1,1)\nplot(freqold.freq,squeeze(freqold.powspctrm(1,1,:)))\naxis tight\nxlabel('frequency (Hz)')\nylabel('power')\ntitle('old implementation')\nsubplot(3,1,2)\nplot(freqnew.freq,squeeze(freqnew.powspctrm(1,1,:)))\naxis tight\nxlabel('frequency (Hz)')\nylabel('power')\ntitle('new implementation')\nsubplot(3,1,3)\nhold on\nplot(freqnew.freq,squeeze(freqold.powspctrm(1,1,:)))\nplot(freqnew.freq,squeeze(freqnew.powspctrm(1,1,:)),'r')\nlegend\naxis tight\nxlabel('frequency (Hz)')\nylabel('power')\ntitle('both overlayed, using freq axis of new implementation')\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n\n\n%% COHERENCE specest_mtmconvol\ncfg = [];\ncfg.trials = 1:2;\ncfg.keeptrials = 'no';\ncfg.keeptapers = 'no';\ncfg.channel = 'all';\ncfg.channelcmb = {'all' 'all'};\n%cfg.pad = 4.24;\ncfg.foi = 2:2:20;\ncfg.toi = data.time{1}(1):0.050:data.time{1}(end);\ncfg.output = 'powandcsd';\ncfg.taper = 'hanning';\ncfg.t_ftimwin = 4 ./ cfg.foi; %ones(length(cfg.foi),1) .* 1.5; %\ncfg.tapsmofrq = ones(length(cfg.foi),1) * 8;\ncfg.calcdof = 'yes';\ncfg.correctt_ftimwin = 'no';\n% old style\ncfg.method = 'mtmconvol_old';\ntic; freqold = ft_freqanalysis(cfg,data); toc\n% new style\ncfg.method = 'mtmconvol';\ntic; freqnew = ft_freqanalysis(cfg,data); toc\n\n% calculate coherence\ncfg = [];\ncfg.method = 'coh';\nconnold = ft_connectivityanalysis(cfg,freqold);\nconnnew = ft_connectivityanalysis(cfg,freqnew);\n\n\n\n% plot 'a' chancomb at a single timepoint\ntimepoint = 20;\nfigure\nsubplot(3,1,1)\nplot(connold.freq,squeeze(connold.cohspctrm(10,:,timepoint)))\naxis tight\nxlabel('frequency (Hz)')\nylabel('coh')\ntitle('old implementation')\nsubplot(3,1,2)\nplot(connnew.freq,squeeze(connnew.cohspctrm(10,:,timepoint)))\naxis tight\nxlabel('frequency (Hz)')\nylabel('coh')\ntitle('new implementation')\nsubplot(3,1,3)\nhold on\nplot(connold.freq,squeeze(connold.cohspctrm(10,:,timepoint)))\nplot(connnew.freq,squeeze(connnew.cohspctrm(10,:,timepoint)),'r')\nlegend\naxis tight\nxlabel('frequency (Hz)')\nylabel('coh')\ntitle('both overlayed, using freq axis of new implementation')\n\n\n\n% plot 'a' chancomb at a all timepoints\nfigure\nsubplot(3,1,1)\nimagesc(connold.time,connold.freq,squeeze(connold.cohspctrm(10,:,:)))\naxis tight\nylabel('frequency (Hz)')\nxlabel('time (s)')\ntitle('old implementation')\ncolorbar; axis xy; caxis([0 1])\nsubplot(3,1,2)\nimagesc(connnew.time,connnew.freq,squeeze(connnew.cohspctrm(10,:,:)))\naxis tight\nylabel('frequency (Hz)')\nxlabel('time (s)')\ntitle('new implementation')\ncolorbar; axis xy; caxis([0 1]);\nsubplot(3,1,3)\nhold on\nimagesc(connold.time,connold.freq,squeeze(connold.cohspctrm(10,:,:))-squeeze(connnew.cohspctrm(10,:,:)))\nlegend\naxis tight\nylabel('frequency (Hz)')\nxlabel('time (s)')\ntitle('old minus new')\ncolorbar; caxis([0 1]); axis xy\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n\n\n\n%% POWER specest_mtmconvol\ncfg = [];\ncfg.implementation = 'old';\ncfg.trials = 1:3;\ncfg.keeptrials = 'yes';\ncfg.keeptapers = 'no';\n%cfg.pad = 4.24;\ncfg.foi = 0:2:128;\ncfg.toi = data.time{1}(1):0.0050:data.time{1}(end);\ncfg.output = 'pow';\ncfg.taper = 'hanning';\ncfg.t_ftimwin = 4 ./ cfg.foi; %ones(length(cfg.foi),1) .* 1.5; %\ncfg.tapsmofrq = ones(length(cfg.foi),1) * 8;\ncfg.calcdof = 'yes';\ncfg.correctt_ftimwin = 'no';\n% new style\ncfg.method = 'mtmconvol';\ntic; freqnew = ft_freqanalysis(cfg,data); toc\n% old style\ncfg.method = 'mtmconvol_old';\ncfg.foi = freqnew.freq;\ncfg.t_ftimwin = 4 ./ cfg.foi; %ones(length(cfg.foi),1) .* 1.5; %\ntic; freqold = ft_freqanalysis(cfg,data); toc\n\n\n\n\n\n% plot first trial first channel, single timepoint\ntimepoint = 20;\nfigure\nsubplot(3,1,1)\nplot(freqold.freq,squeeze(freqold.powspctrm(1,1,:,timepoint)))\naxis tight\nxlabel('frequency (Hz)')\nylabel('power')\ntitle('old implementation')\nsubplot(3,1,2)\nplot(freqnew.freq,squeeze(freqnew.powspctrm(1,1,:,timepoint)))\naxis tight\nxlabel('frequency (Hz)')\nylabel('power')\ntitle('new implementation')\nsubplot(3,1,3)\nhold on\nplot(freqnew.freq,squeeze(freqold.powspctrm(1,1,:,timepoint)))\nplot(freqnew.freq,squeeze(freqnew.powspctrm(1,1,:,timepoint)),'r')\nlegend\naxis tight\nxlabel('frequency (Hz)')\nylabel('power')\ntitle('both overlayed, using freq axis of new implementation')\n\n\n\n% plot first trial first channel, all timepoints\nfigure\nsubplot(3,1,1)\nimagesc(freqold.time,freqold.freq,squeeze(freqold.powspctrm(1,1,:,:)))\naxis tight; axis xy; colorbar\nylabel('frequency (Hz)')\nxlabel('time (s)')\ntitle('old implementation')\nsubplot(3,1,2)\nimagesc(freqold.time,freqnew.freq,squeeze(freqnew.powspctrm(1,1,:,:)))\naxis tight; axis xy; colorbar\nylabel('frequency (Hz)')\nxlabel('time (s)')\ntitle('new implementation')\nsubplot(3,1,3)\nhold on\nimagesc(freqold.time,freqold.freq,squeeze(freqold.powspctrm(1,1,:,:)) - squeeze(freqnew.powspctrm(1,1,:,:)))\nlegend\naxis tight; axis xy; colorbar\nylabel('frequency (Hz)')\nxlabel('time (s)')\ntitle('old minus new')\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n\n\n\n\n\n%% POWER specest_wavelet\ncfg = [];\ncfg.trials = 1;\ncfg.keeptrials = 'yes';\ncfg.keeptapers = 'no';\n%cfg.pad = 4.24;\ncfg.foi = 2:1:40;\ncfg.toi = 0:0.05:4; %data.time{1}(1):(1/data.fsample):data.time{1}(end);\ncfg.output = 'pow';\ncfg.calcdof = 'yes';\ncfg.correctt_ftimwin = 'no';\n% new style\ncfg.method = 'wavelet';\ntic; freqnew = ft_freqanalysis(cfg,data); toc\n% old style\ncfg.foi = freqnew.freq;\ncfg.method = 'wltconvol_old';\ntic; freqold = ft_freqanalysis(cfg,data); toc\n\n\n\n% plot first trial first channel, single timepoint\ntimepoint = 40;\nfigure\nsubplot(3,1,1)\nplot(freqold.freq,squeeze(freqold.powspctrm(1,1,:,timepoint)))\naxis tight\nxlabel('frequency (Hz)')\nylabel('power')\ntitle('old implementation')\nsubplot(3,1,2)\nplot(freqnew.freq,squeeze(freqnew.powspctrm(1,1,:,timepoint)))\naxis tight\nxlabel('frequency (Hz)')\nylabel('power')\ntitle('new implementation')\nsubplot(3,1,3)\nhold on\nplot(freqnew.freq,squeeze(freqold.powspctrm(1,1,:,timepoint)))\nplot(freqnew.freq,squeeze(freqnew.powspctrm(1,1,:,timepoint)),'r')\nlegend\naxis tight\nxlabel('frequency (Hz)')\nylabel('power')\ntitle('both overlayed, using freq axis of new implementation')\n\n\n\n% plot first trial first channel, all timepoints\nfigure\nsubplot(3,1,1)\nimagesc(freqold.time,freqold.freq,squeeze(freqold.powspctrm(1,1,:,:)))\naxis tight; axis xy; colorbar\nylabel('frequency (Hz)')\nxlabel('time (s)')\ntitle('old implementation')\nsubplot(3,1,2)\nimagesc(freqold.time,freqnew.freq,squeeze(freqnew.powspctrm(1,1,:,:)))\naxis tight; axis xy; colorbar\nylabel('frequency (Hz)')\nxlabel('time (s)')\ntitle('new implementation')\nsubplot(3,1,3)\nhold on\nimagesc(freqold.time,freqold.freq,squeeze(freqold.powspctrm(1,1,:,:)) - squeeze(freqnew.powspctrm(1,1,:,:)))\nlegend\naxis tight; axis xy; colorbar\nylabel('frequency (Hz)')\nxlabel('time (s)')\ntitle('old minus new')\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n\n%% CSD specest_wavelet\ncfg = [];\ncfg.trials = 'all';\ncfg.keeptrials = 'yes';\ncfg.keeptapers = 'no';\n%cfg.pad = 4.24;\ncfg.foi = 2:2:40;\ncfg.toi = data.time{1}(1):(1/data.fsample):data.time{1}(end);\ncfg.output = 'powandcsd';\ncfg.calcdof = 'yes';\ncfg.correctt_ftimwin = 'no';\n% new style\ncfg.method = 'wavelet';\ntic; freqnew = ft_freqanalysis(cfg,data); toc\n% old style\ncfg.foi = freqnew.freq;\ncfg.method = 'wltconvol_old';\ntic; freqold = ft_freqanalysis(cfg,data); toc\n\n\n\n\n% plot first trial first channel, single timepoint\ntimepoint = 200;\nfigure\nsubplot(3,1,1)\nplot(freqold.freq,abs(squeeze(freqold.crsspctrm(1,1,:,timepoint))))\naxis tight\nxlabel('frequency (Hz)')\nylabel('')\ntitle('old implementation')\nsubplot(3,1,2)\nplot(freqnew.freq,abs(squeeze(freqnew.crsspctrm(1,1,:,timepoint))))\naxis tight\nxlabel('frequency (Hz)')\nylabel('')\ntitle('new implementation')\nsubplot(3,1,3)\nhold on\nplot(freqnew.freq,abs(squeeze(freqold.crsspctrm(1,1,:,timepoint))))\nplot(freqnew.freq,abs(squeeze(freqnew.crsspctrm(1,1,:,timepoint))),'r')\nlegend\naxis tight\nxlabel('frequency (Hz)')\nylabel('')\ntitle('both overlayed, using freq axis of new implementation')\n\n\n\n% plot first trial first channel, all timepoints\nfigure\nsubplot(3,1,1)\nimagesc(freqold.time,freqold.freq,abs(squeeze(freqold.crsspctrm(1,1,:,:))))\naxis tight; axis xy; colorbar\nylabel('frequency (Hz)')\nxlabel('time (s)')\ntitle('old implementation')\nsubplot(3,1,2)\nimagesc(freqold.time,freqnew.freq,abs(squeeze(freqnew.crsspctrm(1,1,:,:))))\naxis tight; axis xy; colorbar\nylabel('frequency (Hz)')\nxlabel('time (s)')\ntitle('new implementation')\nsubplot(3,1,3)\nhold on\nimagesc(freqold.time,freqold.freq,abs(squeeze(freqold.crsspctrm(1,1,:,:)) - squeeze(freqnew.crsspctrm(1,1,:,:))))\nlegend\naxis tight; axis xy; colorbar\nylabel('frequency (Hz)')\nxlabel('time (s)')\ntitle('old minus new')\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n%% COHERENCE specest_wavelet\ncfg = [];\ncfg.trials = 'all';\ncfg.keeptrials = 'yes';\ncfg.keeptapers = 'no';\ncfg.channel = 'all';\ncfg.channelcmb = {'all' 'all'};\n%cfg.pad = 4.24;\ncfg.foi = 2:2:20;\ncfg.toi = data.time{1}(1):0.050:data.time{1}(end);\ncfg.output = 'powandcsd';\ncfg.calcdof = 'yes';\n% new style\ncfg.method = 'wavelet';\ntic; freqnew = ft_freqanalysis(cfg,data); toc\n% old style\ncfg.foi = freqnew.freq;\ncfg.method = 'wltconvol_old';\ntic; freqold = ft_freqanalysis(cfg,data); toc\n\n% calculate coherence\ncfg = [];\ncfg.method = 'coh';\nconnold = ft_connectivityanalysis(cfg,freqold);\nconnnew = ft_connectivityanalysis(cfg,freqnew);\n\n\n\n% plot 'a' chancomb at a single timepoint\ntimepoint = 20;\nfigure\nsubplot(3,1,1)\nplot(connold.freq,squeeze(connold.cohspctrm(10,:,timepoint)))\naxis tight\nxlabel('frequency (Hz)')\nylabel('coh')\ntitle('old implementation')\nsubplot(3,1,2)\nplot(connnew.freq,squeeze(connnew.cohspctrm(10,:,timepoint)))\naxis tight\nxlabel('frequency (Hz)')\nylabel('coh')\ntitle('new implementation')\nsubplot(3,1,3)\nhold on\nplot(connold.freq,squeeze(connold.cohspctrm(10,:,timepoint)))\nplot(connnew.freq,squeeze(connnew.cohspctrm(10,:,timepoint)),'r')\nlegend\naxis tight\nxlabel('frequency (Hz)')\nylabel('coh')\ntitle('both overlayed, using freq axis of new implementation')\n\n\n\n% plot 'a' chancomb at a all timepoints\nfigure\nsubplot(3,1,1)\nimagesc(connold.time,connold.freq,squeeze(connold.cohspctrm(10,:,:)))\naxis tight\nylabel('frequency (Hz)')\nxlabel('time (s)')\ntitle('old implementation')\ncolorbar; axis xy; caxis([0 1])\nsubplot(3,1,2)\nimagesc(connnew.time,connnew.freq,squeeze(connnew.cohspctrm(10,:,:)))\naxis tight\nylabel('frequency (Hz)')\nxlabel('time (s)')\ntitle('new implementation')\ncolorbar; axis xy; caxis([0 1]);\nsubplot(3,1,3)\nhold on\nimagesc(connold.time,connold.freq,squeeze(connold.cohspctrm(10,:,:))-squeeze(connnew.cohspctrm(10,:,:)))\nlegend\naxis tight\nylabel('frequency (Hz)')\nxlabel('time (s)')\ntitle('old minus new')\ncolorbar; caxis([0 1]); axis xy\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n\n\n%% POWER specest_hilbert\ncfg = [];\ncfg.trials = 1:3;\ncfg.keeptrials = 'yes';\ncfg.keeptapers = 'no';\ncfg.width = 1;\ncfg.pad = 'maxperlen';\ncfg.foi = 10:2:40;\ncfg.toi = 0:0.05:4; %data.time{1}(1):(1/data.fsample):data.time{1}(end);\ncfg.output = 'pow';\ncfg.calcdof = 'yes';\ncfg.correctt_ftimwin = 'no';\n% new style\ncfg.method = 'hilbert';\ncfg.filtorder = round((3 ./ cfg.foi) .* data.fsample);\ncfg.filttype = 'fir';\ncfg.width = 5;\n\ntic; freqnew = ft_freqanalysis(cfg,data); toc\n% old style\ncfg.foi = freqnew.freq;\ncfg.method = 'mtmconvol';\ncfg.taper = 'hanning';\ncfg.t_ftimwin = 3 ./ cfg.foi; %ones(length(cfg.foi),1) .* 1.5; %\ntic; freqold = ft_freqanalysis(cfg,data); toc\n\n\n\n% plot first trial first channel, single timepoint\ntimepoint = 40;\nfigure\nsubplot(3,1,1)\nplot(freqold.freq,squeeze(freqold.powspctrm(1,1,:,timepoint)))\naxis tight\nxlabel('frequency (Hz)')\nylabel('power')\ntitle('mtmconvol')\nsubplot(3,1,2)\nplot(freqnew.freq,squeeze(freqnew.powspctrm(1,1,:,timepoint)))\naxis tight\nxlabel('frequency (Hz)')\nylabel('power')\ntitle('hilbert')\nsubplot(3,1,3)\nhold on\nplot(freqnew.freq,squeeze(freqold.powspctrm(1,1,:,timepoint)))\nplot(freqnew.freq,squeeze(freqnew.powspctrm(1,1,:,timepoint)),'r')\nlegend\naxis tight\nxlabel('frequency (Hz)')\nylabel('power')\ntitle('both overlayed, using freq axis of hilbert')\n\n\n\n% plot first trial first channel, all timepoints\nfigure\nsubplot(3,1,1)\nimagesc(freqold.time,freqold.freq,squeeze(freqold.powspctrm(1,1,:,:)))\naxis tight; axis xy; colorbar\nylabel('frequency (Hz)')\nxlabel('time (s)')\ntitle('mtmconvol')\nsubplot(3,1,2)\nimagesc(freqold.time,freqnew.freq,squeeze(freqnew.powspctrm(1,1,:,:)))\naxis tight; axis xy; colorbar\nylabel('frequency (Hz)')\nxlabel('time (s)')\ntitle('hilbert')\nsubplot(3,1,3)\nhold on\nimagesc(freqold.time,freqold.freq,squeeze(freqold.powspctrm(1,1,:,:)) - squeeze(freqnew.powspctrm(1,1,:,:)))\nlegend\naxis tight; axis xy; colorbar\nylabel('frequency (Hz)')\nxlabel('time (s)')\ntitle('old minus new')\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n%% FOURIER specest_hilbert\ncfg = [];\ncfg.trials = 1:3;\ncfg.keeptrials = 'yes';\ncfg.keeptapers = 'yes';\ncfg.width = 1;\ncfg.pad ='maxperlen';\ncfg.foi = 10:2:40;\ncfg.toi = 0:0.05:4; %data.time{1}(1):(1/data.fsample):data.time{1}(end);\ncfg.output = 'fourier';\ncfg.calcdof = 'yes';\ncfg.correctt_ftimwin = 'no';\n% new style\ncfg.method = 'hilbert';\ncfg.filtorder = round((3 ./ cfg.foi) .* data.fsample);\ncfg.filttype = 'fir';\ncfg.width = 1;\ntic; freqnew = ft_freqanalysis(cfg,data); toc\n% old style\ncfg.foi = freqnew.freq;\ncfg.method = 'mtmconvol';\ncfg.taper = 'hanning';\ncfg.t_ftimwin = 3 ./ cfg.foi; %ones(length(cfg.foi),1) .* 1.5; %\ntic; freqold = ft_freqanalysis(cfg,data); toc\n\n\n\n% plot first trial first channel, real part\nfreq = 3;\nfigure\nsubplot(3,1,1)\nplot(freqold.time,real(squeeze(freqold.fourierspctrm(1,1,freq,:))))\naxis tight\nxlabel('frequency (Hz)')\nylabel('amplitude')\ntitle('mtmconvol')\nsubplot(3,1,2)\nplot(freqnew.time,real(squeeze(freqnew.fourierspctrm(1,1,freq,:))))\naxis tight\nxlabel('frequency (Hz)')\nylabel('amplitude')\ntitle('hilbert')\nsubplot(3,1,3)\nhold on\nplot(freqnew.time,real(squeeze(freqold.fourierspctrm(1,1,freq,:))))\nplot(freqnew.time,real(squeeze(freqnew.fourierspctrm(1,1,freq,:))),'r')\nlegend\naxis tight\nxlabel('frequency (Hz)')\nylabel('amplitude')\ntitle('both overlayed, using freq axis of hilbert')\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n%% FOURIER specest_wavelet VS specest_tfr\ncfg = [];\ncfg.trials = 1;\ncfg.keeptrials = 'yes';\ncfg.keeptapers = 'yes';\ncfg.pad = 6;\ncfg.foi = 2:5:20;\ncfg.toi = 0:0.05:4; %data.time{1}(1):(1/data.fsample):data.time{1}(end);\ncfg.output = 'fourier';\ncfg.calcdof = 'yes';\ncfg.correctt_ftimwin = 'no';\n% new style\ncfg.method = 'wavelet';\ntic; freqwav = ft_freqanalysis(cfg,data); toc\n% old style\ncfg.foi = freqwav.freq;\ncfg.method = 'tfr';\ntic; freqtfr = ft_freqanalysis(cfg,data); toc\n\n\n\n% plot first trial first channel, single timepoint\ntimepoint = 50;\nfigure\nsubplot(4,1,1)\nplot(freqtfr.freq,real(squeeze(freqtfr.fourierspctrm(1,1,:,timepoint))))\naxis tight\nxlabel('frequency (Hz)')\nylabel('amplitude')\ntitle('tfr implementation')\nsubplot(4,1,2)\nplot(freqwav.freq,real(squeeze(freqwav.fourierspctrm(1,1,:,timepoint))))\naxis tight\nxlabel('frequency (Hz)')\nylabel('amplitude')\ntitle('wavelet implementation')\nsubplot(4,1,3)\nplot(freqtfr.freq,angle(squeeze(freqtfr.fourierspctrm(1,1,:,timepoint))))\naxis tight\nxlabel('frequency (Hz)')\nylabel('phase')\ntitle('tfr implementation')\nsubplot(4,1,4)\nplot(freqwav.freq,angle(squeeze(freqwav.fourierspctrm(1,1,:,timepoint))))\naxis tight\nxlabel('frequency (Hz)')\nylabel('phase')\ntitle('wavelet implementation')\n\n\n\n\n\n\n\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/failed_old_specest_vs_oldimplementation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.48757918254300536}} {"text": "addpath('/home/liisa/080812/');\naddpath('/home/rheintz/matlab/');\n\nglobal para;\n\ns=19;\n\n% beadsAt=[180 504; 207 489; 253 236; 399 276; 262 54; 364 49; 393 168; 410 156; 300 139; 190 138; 376 282; 182 459; 333 449; 367 467; 415 453; 204 550; 175 579];\n\nmyres=para.res_resIm\nfprintf('Please select bead coordinates by left clicking. Finish with right click\\n');\nbeadsAt=dipgetcoords(100);\nfprintf('%d beads selected\\n',size(beadsAt,1));\nbeadsAt(end,:)=[];\n\n[sumBdsHighRes,mybdsHRes,sumBdsSum,mybdsSum]=MeanFromCoord(myres,beadsAt,s,para.res_sumIm)\n\n%myresSum=para.res_sumIm;\n%[sumBdsSum,mybdsSum]=MeanFromCoord(myresSum,beadsAt,s)\n\n%im = readtimeseries('beads1_000');\n%myres=squeeze(sum(im(:,:,3:5)));\n%[sumBdsRaw,mybdsRaw]=MeanFromCoord(myres,beadsAt,s)\n\n% [params,res,fitted]=FitDataNDFast([10 10 0; 1000 s/2 s/2],sumBdsSum,300,'idiv')\n\n[fittedSum,paramsSum,idiv,myfunct] = FitDataND('c(1)*exp(-((x{1}-c(2)).^2+(x{2}-c(3)).^2)/c(4))+c(5)',[max(sumBdsSum) 0 0 20 min(sumBdsSum)],sumBdsSum,1000);\nsqrt(paramsSum(4))*para.res_resampledPixelsize(1) * 2*sqrt(log(2)) % to get FWHM\nsumBdsSum-fittedSum\n\n[fittedHRes,paramsHRes,idiv,myfunct] = FitDataND('c(1)*exp(-((x{1}-c(2)).^2+(x{2}-c(3)).^2)/c(4))+c(5)',[max(sumBdsHighRes) 0 0 20 min(sumBdsHighRes)],sumBdsHighRes,1000);\nsqrt(paramsHRes(4))*para.res_resampledPixelsize(1)* 2*sqrt(log(2)) % to get FWHM\nsumBdsHighRes-fittedHRes\n\n\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/matlab_tools/ExtractResults.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.48757918254300536}} {"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 ct = matRad_calcHU(ct)\n% matRad function to calculate Hounsfield units from a dicom ct \n% that originally uses intensity values\n%\n% call\n% ct = matRad_calcHU(ct)\n%\n% input\n% ct: unprocessed dicom ct data which are stored as intensity values (IV)\n%\n% HU = IV * slope + intercept\n%\n% output\n% ct: ct struct with cube with HU\n%\n% References\n% -\n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Copyright 2015 the matRad development team. \n% \n% This file is part of the matRad project. It is subject to the license \n% terms in the LICENSE file found in the top-level directory of this \n% distribution and at https://github.com/e0404/matRad/LICENSES.txt. No part \n% of the matRad project, including this file, may be copied, modified, \n% propagated, or distributed except according to the terms contained in the \n% LICENSE file.\n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfor i = 1:ct.numOfCtScen\n ct.cubeHU{i} = double(ct.cubeIV{i}) * double(ct.dicomInfo.RescaleSlope) + double(ct.dicomInfo.RescaleIntercept);\nend\n\nct = rmfield(ct,'cubeIV');\n\nend\n", "meta": {"author": "e0404", "repo": "matRad", "sha": "0a03aee5ef4a100dbc4bef8927db41b59f44946e", "save_path": "github-repos/MATLAB/e0404-matRad", "path": "github-repos/MATLAB/e0404-matRad/matRad-0a03aee5ef4a100dbc4bef8927db41b59f44946e/dicom/matRad_calcHU.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": "% Run experiments for simulated datasets.\n% Usage: Q = metoffice_experiment_pca('hadsst2d1', 1, 40, 4)\n\nfunction [ Q, perfmeas ] = metoffice_experiment_pca(dataset, anomalies, D, remove_val)\n\n%\n% Load data\n%\n\nif nargin < 4 || isempty(remove_val)\n remove_val = 1;\nend\n[data,folder,maskfile] = metoffice_getdata(dataset, anomalies, remove_val);\n\n% Form the data matrix\nY = data.data;\n[M,N] = size(Y);\nObs = ~isnan(Y);\n\n%\n% PCA inference\n%\n\n% Number of components\nif nargin < 3 || isempty(D)\n D = 120;\nend\n\n% Filename for saving the results\n%folder = [folder '/pca'];\nmkdir(folder);\nfilename = sprintf('%s/%s/pca_D=%d_anomalies=%d_remval=%02d_%s', ...\n folder, ...\n dataset, ...\n D, ...\n anomalies, ...\n remove_val, ...\n datestr(now,'yyyymmdd'))\n\n% PCA module for X (one constant component for modeling bias)\nprior.mu = [1; zeros(D-1,1)];\nprior.CovX = diag([1e-6; ones(D-1,1)]);\nX_module = factor_module_iid('prior', prior);\n\n% ARD module for W\nW_module = factor_module_ard();\n\n% Isotropic noise (precisions weighted proportionally to grid size)\n[LON,LAT] = meshgrid(data.lon, data.lat);\nweights = cosd(LAT(:));\nweights = metoffice_remove_bins(weights,maskfile);\nweights = repmat(weights, [1, N]);\nnoise_module = noise_module_isotropic('init', struct('tau', 10), ...\n 'weights', weights);\n\n% Run VB PCA\nQ = vbfa(D, Y, W_module, X_module, noise_module, ...\n 'maxiter', 2, ...\n 'rotate', true, ...\n 'autosavefile', filename, ...\n 'autosave', [1 20:20:2000]);\n\nif nargout == 2\n % Reconstruct\n Yrec = Q.W'*Q.X;\n \n % Remove the autosave file\n delete( [ filename '.mat' ] )\n\n addpath /home/alexilin/matlab/metoffice\n Yrec = add_land( Yrec, dataset );\n Yrec = add_climatology( Yrec, dataset, anomalies );\n perfmeas = compute_rmse( Yrec, dataset, remove_val );\n\nelse\n % Reconstruct\n Yrec = Q.W'*Q.X;\n \n % Some performance measures\n fprintf('Weighted training RMSE of the reconstruction: %f\\n', ...\n rmsew(Y(Obs)-Yrec(Obs),weights(Obs)));\n\nend\n\n% Save the results\n%save(filename, '-struct', 'Q');\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_pca.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": "% This file is part of the project NILM-Eval (https://github.com/beckel/nilm-eval).\n% Licence: GPL 2.0 (http://www.gnu.org/licenses/gpl-2.0.html)\n% Copyright: ETH Zurich, 2014\n% Author: Romano Cicchetti\n\n%params\ndataset = 'thun';\nhouseholds = [1,2,3,4,5,6];\nevalDays_type = 'completeSM-first90';\ngranularity = 1;\n\npower_pct = {};\nexisting = {};\nfor h = 1:length(households)\n house = households(h);\n path_to_evalDays = strcat(pwd, '/input/evaluation_days/', dataset, '/', evalDays_type, '/', num2str(house, '%02d'), '.mat');\n load(path_to_evalDays); % evalDays\n\n % total consumption\n smartmeter_consumption = read_smartmeter_data(dataset, house, evalDays, granularity, 'powerallphases');\n missing_values_idx_sm = smartmeter_consumption == -1; \n total_consumption = sum(smartmeter_consumption(~missing_values_idx_sm));\n\n % consumption of each appliance\n appliances = findAppliances(house, 'eco');\n for appliance = appliances\n plug_consumption = read_plug_data(dataset, house, appliance, evalDays, granularity);\n missing_values_idx_plug = plug_consumption == -1;\n sum_plug_consumption = sum(plug_consumption(~missing_values_idx_plug));\n ratio = nnz(~missing_values_idx_sm) / nnz(~missing_values_idx_plug);\n extrapolated_plug_consumption = ratio*sum_plug_consumption;\n power_pct{appliance, h} = strcat(num2str(100*extrapolated_plug_consumption / total_consumption, '%.0f'), ' \\%');\n existing{appliance, h} = strcat(num2str(100*nnz(~missing_values_idx_plug) / nnz(~missing_values_idx_sm), '%.0f'), ' \\%');\n end\n\n %power_pct{18,h} = sum(power_pct(~isnan(power_pct(:,h)),h));\nend\n\nrowLabels = {'Fridge', 'Freezer', 'Microwave', 'Dishwasher', 'Entertainment',...\n 'Water kettle', 'Stove', 'Coffee machine', 'Washing machine', 'Dryer', 'Lamp', 'PC', 'Laptop', 'TV', 'Stereo', 'Tablet', 'Router'};\ncolumnLabels = {'House 1', 'House 2', 'House 3', 'House 4', 'House 5', 'House 6'};\nmatrix2latex(power_pct, 'dataset.tex', 'rowLabels', rowLabels, 'columnLabels', columnLabels, 'format', '%.0f');\nmatrix2latex(existing, 'dataset2.tex', 'rowLabels', rowLabels, 'columnLabels', columnLabels, 'format', '%0.2f');\n", "meta": {"author": "beckel", "repo": "nilm-eval", "sha": "83a2cd5fb911299cc267bd9998636934af781915", "save_path": "github-repos/MATLAB/beckel-nilm-eval", "path": "github-repos/MATLAB/beckel-nilm-eval/nilm-eval-83a2cd5fb911299cc267bd9998636934af781915/Matlab/projects/general/analysis/pie_chart_table.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": " 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 pred = ml_predictsvmperf(trials, model)\n% Prediction function for the Support Vector Machine (SVMperf).\n% Prediction = ml_predictsvmperf(Trials, Model)\n%\n% In:\n% Trials : the data a matrix, as in ml_predict\n%\n% Model : predictive model as produced by ml_trainsvmlight\n%\n% Out:\n% Prediction : discrete probability distribution, formatted as\n% {'disc' [NxC] [Cx1]}, with element #2 being the per-class probability and \n% element #3 the original target values per class\n% thus, the expected target values are Prediction{2}*Prediction{3}\n%\n% See also:\n% ml_trainsvmperf\n%\n% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD\n% 2010-04-04\n\nif isfield(model,'voted')\n pred = ml_predictvote(trials,model);\nelse\n trials = hlp_applyscaling(trials,model.sc_info);\n raw_pred = min(+1,max(-1,svmperfclassify(trials, ones(size(trials,1),1), model, '-v 0')));\n pred = {'disc', [(1-raw_pred)/2 1-(1-raw_pred)/2], model.classes};\nend", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/code/machine_learning/ml_predictsvmperf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591568, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.48742712186244413}} {"text": "function [F,h,x] = sedumi2yalmip(At,b,c,K)\n\nnvars = length(b);\nx = sdpvar(nvars,1);\n\n% No reason to try to do factor tracking here\nx = flush(x);\n\nif size(At,2)~=length(b)\n At = At';\nend\n\nF = ([]);\ntop = 1;\n\nif isvalidfield(K,'f')\n X = c(top:top+K.f-1)-At(top:top+K.f-1,:)*x;\n F = F + (X(:) == 0);\n top = top + K.f;\nend\n\nif isvalidfield(K,'l')\n X = c(top:top+K.l-1)-At(top:top+K.l-1,:)*x;\n F = F + (X(:)>=0);\n top = top + K.l;\nend\n\nif isvalidfield(K,'q')\n for i = 1:length(K.q)\n X = c(top:top+K.q(i)-1)-At(top:top+K.q(i)-1,:)*x;\n F = F + (cone(X(2:end),X(1)));\n top = top + K.q(i);\n end\nend\n\nif isvalidfield(K,'r')\n for i = 1:length(K.r)\n X = c(top:top+K.r(i)-1)-At(top:top+K.r(i)-1,:)*x;\n F = F + (rcone(X(3:end),X(2),X(1)));\n top = top + K.r(i);\n end\nend\n\nif isvalidfield(K,'s')\n for i = 1:length(K.s)\n [ix,iy,iv] = find([c(top:top+K.s(i)^2-1) At(top:top+K.s(i)^2-1,:)]);\n off = (ix-1)/(K.s(i)+1);\n if all(off == round(off))\n X = c(top:top+K.s(i)^2-1)-At(top:top+K.s(i)^2-1,:)*x;\n if isa(X,'sdpvar')\n F = F + (diag(reshape(X,K.s(i),K.s(i))) >= 0);\n else\n X\n i\n 'silly data!'\n end\n top = top + K.s(i)^2;\n else\n X = c(top:top+K.s(i)^2-1)-At(top:top+K.s(i)^2-1,:)*x;\n X = reshape(X,K.s(i),K.s(i));\n X = (X+X')/2;\n F = F + (X >= 0);\n top = top + K.s(i)^2;\n end\n end\nend\n\nh = -b'*x;\n\nfunction ok = isvalidfield(K,fld)\nok = 0;\nif isfield(K,fld)\n s = getfield(K,fld);\n if prod(size(s))>0\n if s(1)>0\n ok = 1;\n end\n end\nend\n\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/extras/sedumi2yalmip.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.4873532659926905}} {"text": "function hf_out = lhs_operation(hf, samplesf, reg_filter, sample_weights, feature_reg)\n\n% This is the left-hand-side operation in Conjugate Gradient\n\n% size of the padding\nnum_features = length(hf);\noutput_sz = [size(hf{1},1), 2*size(hf{1},2)-1];\npad_sz = cellfun(@(hf) (output_sz - [size(hf,1), 2*size(hf,2)-1]) / 2, hf, 'uniformoutput',false);\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 in each block\nsh_cell = cellfun(@(hf,samplesf) mtimesx(samplesf, permute(hf, [3 4 1 2]), 'speed'), hf, samplesf, 'uniformoutput', false);\n\n% sum over all feature blocks\nsh = sh_cell{1}; % assumes the feature with the highest resolution is first\nfor k = 2:num_features\n sh(:,1,1+pad_sz{k}(1):end-pad_sz{k}(1), 1+pad_sz{k}(2):end) = ...\n sh(:,1,1+pad_sz{k}(1):end-pad_sz{k}(1), 1+pad_sz{k}(2):end) + sh_cell{k};\nend\n\n% weight all the samples\nsh = bsxfun(@times,sample_weights,sh);\n\n% multiply with the transpose\nhf_out = cellfun(@(samplesf,pad_sz) permute(conj(mtimesx(sh(:,1,1+pad_sz(1):end-pad_sz(1), 1+pad_sz(2):end), 'C', samplesf, 'speed')), [3 4 2 1]), ...\n samplesf, pad_sz, 'uniformoutput', false);\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\nreg_pad = cellfun(@(hf, reg_filter) min(size(reg_filter,2)-1, size(hf,2)-1), hf, reg_filter, 'uniformoutput', false);\n\n% add part needed for convolution\nhf_conv = cellfun(@(hf,reg_pad) cat(2, hf, conj(rot90(hf(:, end-reg_pad:end-1, :), 2))), hf, reg_pad, 'uniformoutput', false);\n\n% do first convolution\nhf_conv = cellfun(@(hf_conv, reg_filter) convn(hf_conv, reg_filter), hf_conv, reg_filter, 'uniformoutput', false); \n\n% do final convolution and put toghether result\nhf_out = cellfun(@(hf_conv, hf_data, reg_filter, hf, reg_pad, feature_reg) hf_data + convn(hf_conv(:,1:end-reg_pad,:), reg_filter, 'valid') + feature_reg * hf, ...\n hf_conv, hf_out, reg_filter, hf, reg_pad, feature_reg, 'uniformoutput', false); \n\nend", "meta": {"author": "martin-danelljan", "repo": "Continuous-ConvOp", "sha": "a79708be1f6f8bd8ec5489281cb37b164bebea83", "save_path": "github-repos/MATLAB/martin-danelljan-Continuous-ConvOp", "path": "github-repos/MATLAB/martin-danelljan-Continuous-ConvOp/Continuous-ConvOp-a79708be1f6f8bd8ec5489281cb37b164bebea83/implementation/lhs_operation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4873455149627974}} {"text": "filename='Tests_Triangle_Linear';\nptype = 'MACRO';\nmethod = 'SIMPALL';\nmaterialType = 'ISOTROPIC';\ninitial_case = 'full';\ncost = {'compliance','perimeterInterior'};\nweights = [1 1];\nconstraint = {'volumeConstraint'};\n%optimizer = 'DualNestedInPrimal';\noptimizer = 'AlternatingPrimalDual';\n\noptimizerUnconstrained = 'SLERP'; \nincrementFactor = 1;\ndesignVariable = 'LevelSet';\nfilterType = 'PDE';\n\nnsteps = 1;\nVfrac_final = 0.3;\noptimality_final =1e-3;\nconstr_final =1e-3;\n\nVfrac_initial = 1;\noptimality_initial = 1e-2;\nconstr_initial = 1e-3;\n\nTOL.rho_plus = 1;\nTOL.rho_minus = 0;\nTOL.E_plus = 1;\nTOL.E_minus = 1e-3;\nTOL.nu_plus = 1/3;\nTOL.nu_minus = 1/3;\n\nplotting = false;\nprinting = false;\nmonitoring = false;\n\nmaxiter = 2;\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Input/test_interiorPerimeter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4873455058937098}} {"text": "function f_x = ParFor2(in1)\n%PARFOR2\n% F_X = PARFOR2(IN1)\n\n% This function was generated by the Symbolic Math Toolbox version 8.2.\n% 20-Sep-2019 09:35:34\n\nu = in1(:,1);\nux = in1(:,4);\nuxx = in1(:,5);\nuxxx = in1(:,6);\nf_x = (u.*1.034234549167718e16+ux.*6.60584588804096e15+uxx.*1.215161942676603e17-uxxx.*4.609471812108288e15-u.*ux.*5.122148099342336e15+u.*uxx.*5.033451929390285e16+u.*uxxx.*5.000975400599552e15-2.603066969792512e15)./(u.*3.126164642771763e16+4.756339916996608e16);\n", "meta": {"author": "dynamicslab", "repo": "SINDy-PI", "sha": "42799b8e5a7585e400aa4bc3c83cfd659046cbb4", "save_path": "github-repos/MATLAB/dynamicslab-SINDy-PI", "path": "github-repos/MATLAB/dynamicslab-SINDy-PI/SINDy-PI-42799b8e5a7585e400aa4bc3c83cfd659046cbb4/Comparison/PDE_Comparison/Implicit_SINDy/TempFunctions/ParFor2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950907764118, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4873455036264377}} {"text": "function SV=gmm2sv(mix)\n%--------------------------------------------------------------------------\n%Usage: SuperVECTOR=gmm2sv(mix);\n% input : mix: GMM structure of Netlab\n% output: SuperVECTOR: GMM Supervector\n% \n% This program concatenates means of GMM to form SuperVector.\n% Written by Md. Sahidullah (Graduate Student, IIT Kharagpur)\n% Use this code works with Netlab toolbox\n% http://www1.aston.ac.uk/eas/research/groups/ncrg/resources/netlab/\n% If you have any query or suggestion please mail me sahidullahmd@gmail.com\ntemp=mix.centres';\nSV=temp(:);\n%--------------END OF CODE-------------------------------------------------", "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/31678-useful-matlab-functions-for-speaker-recognition-using-adapted-gaussian-mixture-model/gmm2sv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7401743735019594, "lm_q2_score": 0.6584175139669998, "lm_q1q2_score": 0.4873437709032416}} {"text": "function regresdiagplot3d(sdist,odist,rdist,cutoffsd,cutoffod,cutoffrd,k,class,multi,labsd,labod,labresd,labels)\n\n%REGRESDIAGPLOT3D is a 3D-outlier map which visualizes the orthogonal distance, \n% the score distance and the residual distance calculated in a PCR or PLSR analysis.\n%\n% I/O: regresdiagplot3D(sdist,odist,rdist,cutoffsd,cutoffrd,k,class,labsd,labod,labresd,labels)\n%\n% Example: out=rpcr(X,Y);\n% regresdiagplot3d(out.sd,out.od,out.resd,out.cutoff.sd,cutoff.od,...\n% out.cutoff.resd,out.k,out.class,1,out.labsd,out.labod,out.labresd,0)\n%\n% Uses function: putlabel\n%\n% Created on by S.Verboven\n% Last revision: 09/04/2004\n% \n\n%INITIALIZATION%\nif nargin<13\n labels=0;\nend\nif nargin<10\n labsd=3;\n labod=3;\n labresd=3;\n labels=0;\nend\nif nargin==10 \n labsd=3\n labels=0;\n labresd=3;\n labod=3;\nend\nif nargin==11\n labels=0;\n labresd=3;\n labod=3;\nend\nif nargin==12\n labels=0;\n labresd=3;\nend\nif nargin<9\n error('A required input variable is missing!')\nend\n \n%all LTS-analysis in RPCR are intercept included!!!\n% if ask==2 %multivariate analysis\n% %residual distances\n% \n% else %univariate analysis\n% %standardized residuals\n% cutoffz=2.5; \n% end\ncutoffxx=cutoffsd;\ncutoffxy=cutoffsd; \ncutoffyy=cutoffod;\ncutoffyx=cutoffod;\ncutoffz=cutoffrd;\nx=sdist;\ny=odist;\nz=rdist; \n\n\n%%%%%%%MAIN FUNCTION%%%%%%%\nset(gcf,'Name', '3D-Outlier map (regression)', 'NumberTitle', 'off')%,'Renderer','OpenGL');\n\n%%%%%%%%Odist=0 not yet included in this standalone!!!!!!!!! included in\n%%%%%%%%makeplot function!!!!\nplot3(x,y,z,'ko','markerfacecolor',[0.75 0.75 0.75])\n\nhold on\naxhandle=gca;\nylen=get(axhandle, 'Ylim');\nxlen=get(axhandle,'Xlim');\nzlen=get(axhandle,'Zlim');\nxrange=xlen(2)-xlen(1);\nupLimx=max(cutoffxx,xlen(2))+xrange*0.1;\nlowLimx=xlen(1)-xrange*0.1;\nyrange=ylen(2)-ylen(1);\nupLimy=ylen(2)+yrange*0.1;\nlowLimy=ylen(1)-yrange*0.1;\nzrange=zlen(2)-zlen(1);\nupLimz=max(cutoffz,zlen(2))+zrange*0.1;\nif cutoffz==2.5\n lowLimz=min(-2.5,zlen(1))-zrange*0.1;\nelse\n lowLimz=min(cutoffz,zlen(1))-zrange*0.1;\nend\n \n%axis square;\nset(gca, 'Xlim',[lowLimx upLimx],'Ylim',[lowLimy upLimy],'Zlim',[lowLimz,upLimz])\nhold on\n\nxlabel('Score distance')\nylabel('Orthogonal distance')\nif cutoffz~=2.5\n zlabel('Residual distance')\nelse\n zlabel('Standardized Residual')\nend\ngrid on\n\n\n%in XY-space\n%red plane \"vertical\" on x axis\noppy=[upLimy:-0.01:lowLimy];\nn=length(oppy);\nh=(upLimz-lowLimz)/n;\noppz=[lowLimz:h:upLimz];\n\nX1=cutoffxx*ones(n);\nY1=repmat(oppy,n,1);\nZ1=repmat([oppz(1:n-1)'; upLimz],1,n);\nsurf(X1,Y1,Z1,'edgecolor','none','facecolor','r')\nalpha(.3)\n\n\n%blue \"horizontal\" planes orthogonal on z-axis\n%in ZX and ZY-space\noppx=[lowLimx:0.05:upLimx];\nn=length(oppx);\nX2=repmat(oppx,n,1);\nh=(upLimy-lowLimy)/n;\noppy=[lowLimy:h:upLimy];\nY2=repmat(oppy(1:n)',1,n);\nZ2=cutoffz*ones(n);\nsurf(X2,Y2,Z2,'edgecolor','none','facecolor','b')\nalpha(0.3)\n\n% in XY-space\n%green plane \"vertical\" on y axis\noppx=[upLimx:-0.01:lowLimx];\nn=length(oppx);\nh=(upLimz-lowLimz)/n;\noppz=[lowLimz:h:upLimz];\nX1=repmat(oppx,n,1);\nY1=cutoffyy*ones(n);\nZ1=repmat([oppz(1:n-1)'; upLimz],1,n);\nsurf(X1,Y1,Z1,'edgecolor','none','facecolor','g')\nalpha(0.3)\n\nif multi==0 %univariate case\n surf(X2,Y2,-Z2,'edgecolor','none','facecolor','b')\n alpha(0.3)\nend\n\nif labels~=0\n putlabel(x,y,labels,z,labels)\nelse\n plotnumbers(x,y,labsd,labod,5,z,labresd)\nend\nhold off", "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/LIBRA/regresdiagplot3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.48734376098096976}} {"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 [mri] = align_fsaverage2mni(mri)\n\n% ALIGN_FSAVERAGE2MNI performs an affine alignment of the anatomical volume from\n% FSAVERAGE towards MNI coordinates. Only the homogeneous transformation matrix is\n% modified and the coordsys-field is updated.\n%\n% Use as\n% mri = align_fsaverage2mni(mri)\n% where the first input argument is a FieldTrip MRI-structure.\n%\n% with fsaverage we mean MNI305\n% with mni we mean MNI152, i.e. the template used in SPM\n%\n% See http://freesurfer.net/fswiki/CoordinateSystems\n%\n% See also ALIGN_CTF2ACPC, ALIGN_NEUROMAG2ACPC\n\nfsaverage2mni = [\n 0.9975 -0.0073 0.0176 -0.0429\n 0.0146 1.0009 -0.0024 1.5496\n -0.0130 -0.0093 0.9971 1.1840\n ];\n\nassert(strcmp(mri.coordsys, 'fsaverage'), 'incorrect input coordinate system ''%s''', mri.coordsys);\nmri.transform = fsaverage2mni * mri.transform;\nmri.coordsys = 'mni';\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/external/fieldtrip/utilities/private/align_fsaverage2mni.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.48732581653352813}} {"text": "% sound2gyro.m\n% evaluate effect of sound signal on phone internal gyro\n% publish('sound2gyro.m','doc');\n\nFs = 200; % 200 sps default\n[filenam, pathnam] = uigetfile('*.txt', 'get measurements data file');\nfid = fopen(filenam,'r');\n% 0.0\n% 0.000000 -0.044288\n% 5046272.000000 -0.044288\n% L2:L212 =[txyz] (tinnsec)\n% repeat n times\nn=20;\nf_in = zeros(n,1);\ntxyz = zeros(200,4,n);\nfrewind(fid),\ni=1;\nf_in(i) = str2double(fgetl(fid)); % read a line, 1st is noise freq\nwhile ~isnan(f_in(i))\n linenums = 4;\n cntlines = 1;\n while linenums == 4\n % # of nums per line\n % counting for sampnum\n % loop to read one noise sequence\n tt = fgetl(fid);\n ttnum = str2num(tt);\n linenums = length(ttnum); %\n if linenums ==4,\n txyz(cntlines,:,i) = ttnum;\n cntlines = cntlines+1;\n end;\n end;\n % get next line chars\n % make numbers\n sampnum = cntlines - 1; % last was 1 or nan\n i = i+1;\n if isempty(ttnum), f_in(i)=nan; else f_in(i) = ttnum; end;\nend\n\nf_in(i:end)=[]; % clean the rest\ntxyz(:,:,i:end) = [];\nn = i-1; % last one was NAN\n% set # of columns for plots\nif n>5 \n pcols = 2; \nelse\n pcols = 1;\nend;\nprows = n/pcols;\nfclose(fid);\n\nfilenam = 'RAFDOCS-#7775044Magn.TXT';\n\nif findstr(filenam,'77750') % .. 28 | 44\n savetxyz = txyz;\n resamp; % returns newtxyz, f_in, Fs, nlen\n len = min(nlen);\n txyz = zeros(len,4, length(f_in));\n for kf = 1:n,\n txyz(:,:,kf) = newtxyz{kf}(1:len,:);\n end\n xyz = txyz(:,2:4,:);\n time = squeeze(txyz(:,1,:));\n t = time;\nelse %% verify, update -> len, n\n len = 199;\n % clean\n % orig in nsec, Fs\n % clean\n t = repmat((0:len-1)'/Fs,1,n);\nend;\n\nxyzstr = 'XYZ';\n\nxyz = txyz(1:len,2:4,:); % 199x3xn\n% x10 = squeeze(txyz(1:len,2,:));\n% y10 = squeeze(txyz(1:len,3,:));\n% z10 = squeeze(txyz(1:len,4,:));\n\nfor d = 1:3 % dimensions\n figure\n mn = min(min(squeeze(xyz(:,d,:))));\n mx = max(max(squeeze(xyz(:,d,:))));\n for i=1:n\n subplot(prows, pcols,i)\n curr = xyz(:,d,i);\n plot(t(:,i),curr,'.-')\n axis([0 t(end,i) mn mx]);\n title([ xyzstr(d) '-meas. for freq = ' num2str(f_in(i)) ' Hz'])\n xlabel('time [s]'), grid on\n end;\n if pcols>1,\n set(gcf,'posi',[80 80 750 1000])\n end;\n emarkpl( filenam)\nend;\n\nfigure;\nplot(diff(t(:,:)))\nxlabel ('sample #')\nylabel('diff(time) [sec]')\ntitle('Sample time interval variation')\ndtser = diff(t);\n[Val, Bin]=hist(dtser(:),100); % Val, Bin\nline(Val*len/max(Val),Bin,'linew',3,'colo','k')\naxis tight\ntmu = mean(dtser(:));\ntsi = std (dtser(:));\nlegend(['\\mu= ' num2str(tmu*1e3) ', \\sigma= ' num2str(tsi*1e3) ' [ms]'])\nemarkpl( filenam);\n\nmeans = zeros(3,n);\nsigms = means;\ns1=24; % 1st sample\nif findstr(filenam,'7775028')\n s1 = 10;\nend;\nxyzCln = cell(3,1); % each cell is X, Y or Z, no transient\nlinecol='bgrcmyk'; % colors order\nfor d = 1:3 % dim\n xyzCln{d} = squeeze(xyz(s1:len,d,:)); %176xn samples, dimension d, all n freqs\n mn = min(xyzCln{d}(:)); mx = max(xyzCln{d}(:));\n aa = [0 1 mn mx]; % for all subplot axes\n figure\n for i=1:n\n subplot(prows, pcols,i)\n plot(t(s1:len,i),xyzCln{d}(:,i),'.-')\n axis(aa); grid on\n title([ xyzstr(d) '-meas. for freq = ' num2str(f_in(i)) ' Hz'])\n %sqd = squeeze(txyz(s1:len,d+1,i));\n means(d,i) = mean(xyzCln{d}(:,i));\n sigms(d,i) = std (xyzCln{d}(:,i));\n xlabel(['[\\mu \\sigma]=[' num2str([means(d,i) sigms(d,i)]) ']'])\n end\n if pcols>1\n set(gcf,'posi',[80 80 750 1000])\n end;\n emarkpl( filenam)\nend;\n\nsubplot(211)\n%semilogx(f_in, means','.-')\nplot(f_in, means','.-')\ntitle('mean')\nlegend('X', 'Y', 'Z',0)\naxis tight, grid on\nsubplot(212)\n%semilogx(f_in, sigms','.-')\nplot(f_in, sigms','.-')\ntitle('sigma')\nlegend('X', 'Y', 'Z',0)\nxlabel ('disturb. freq')\naxis tight, grid on\nemarkpl( filenam)\n\nfigure\nfor d=1:3\n subplot(3,1,d)\n stem3(f_in,t(s1:end,1), xyzCln{d},'.')\n view(-26,34)\n mesh(audiof,t(s1:end,1), squeeze(xyz(s1:end,d,:)))\n contour3(audiof,t(s1:end,1), squeeze(xyz(s1:end,d,:)))\n xlabel('freq[Hz]'), ylabel('time[sec]'), title(xyzstr(d))\n axis tight\nend;\n\nif pcols>1,\n set(gcf,'posi',[80 80 750 1000])\nend\nemarkpl( filenam);\n\nHs=spectrum.welch;\n% EstimationMethod: 'Welch'\n% SegmentLength: 64\n% OverlapPercent: 50\n% WindowName: 'Hamming'\n% SamplingFlag: 'symmetric'\n% psd(Hs,,'Fs',Fs)\n\naxnum = zeros(3,1);\nfor ax = 1:3, % dim x, y or z\n axnum(ax) = figure ;\n for i=1:n\n subplot(prows, pcols,i)\n psd(Hs,xyzCln{d}(:,i),'Fs',Fs);\n % set(get(gca,'chi'),'colo','m'),\n axis tight,\n aa=axis;\n ine (rem(f_in(i),Fs/2)*[1;1],aa(3:4),'color', 'r')\n he=legend('PSD',['Noise freq=' num2str(f_in(i)) ' Hz'],0); \n set(he,'fontsi',8, 'box', 'off');\n end;\n xlabel(['Frequency (Hz) Axis: ' xyzstr(ax)]);\nend;\nfor ax = 1:3,\n figure(axnum(ax))\n if pcols>1,\n set(gcf,'posi',[80 80 750 1000])\n end\n emarkpl( filenam)\nend;\n\nHs.SegmentLength = len-s1+1; % 176\n\naxnum = zeros(3,1);\nfor ax = 1:3 % dim x, y or z\n % t_frqin = squeeze(txyz(s1:len,ax+1,:)); dimentions x freq.in\n axnum(ax) = figure ;\n for i=1:n\n subplot(prows, pcols,i)\n psd(Hs,xyzCln{d}(:,i),'Fs',Fs);\n axis tight, aa=axis;\n line (rem(f_in(i),Fs/2)*[1;1],aa(3:4),'color', 'r')\n he=legend('PSD',['Noise freq=' num2str(f_in(i)) ' Hz']); \n set(he,'fontsi',8, 'box', 'off');\n end;\n xlabel(['Frequency (Hz) Axis: ' xyzstr(ax)]);\nend;\nfor ax = 1:3\n figure(axnum(ax))\n if pcols>1,\n set(gcf,'posi',[80 80 750 1000])\n end\n emarkpl( filenam)\nend;", "meta": {"author": "yueyuzhao", "repo": "gyrophone", "sha": "aa816eec3d7a17d9e30ab7afa0d4b79ef0a7a82e", "save_path": "github-repos/MATLAB/yueyuzhao-gyrophone", "path": "github-repos/MATLAB/yueyuzhao-gyrophone/gyrophone-aa816eec3d7a17d9e30ab7afa0d4b79ef0a7a82e/sound2gyro.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.48730008633136934}} {"text": "function kern = rbfperiodic2KernExpandParam(kern, params)\n\n% RBFPERIODIC2KERNEXPANDPARAM Create kernel structure from RBFPERIODIC2 kernel's parameters.\n% FORMAT\n% DESC returns a RBF periodic covariance with variying period kernel structure filled with the\n% parameters in the given vector. This is used as a helper function to\n% enable parameters to be optimised in, for example, the NETLAB\n% optimisation functions.\n% ARG kern : the kernel structure in which the parameters are to be\n% placed.\n% ARG param : vector of parameters which are to be placed in the\n% kernel structure.\n% RETURN kern : kernel structure with the given parameters in the\n% relevant locations.\n%\n% SEEALSO : rbfperiodic2KernParamInit, rbfperiodic2KernExtractParam, kernExpandParam\n%\n% COPYRIGHT : Neil D. Lawrence, 2007, 2009\n%\n% MODIFICATIONS : Andreas C. Damianou, 2011\n%\n% MODIFICATIONS : Michalis K. Titsias, 2011\n\n% KERN\n\nkern.inverseWidth = params(1);\nkern.variance = params(2);\nkern.factor = params(3);\nkern.period = 2*pi/kern.factor;\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/rbfperiodic2KernExpandParam.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.4873000828454976}} {"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 inv1 = de_ftab_inv1(fit, s1, varargin)\n%function inv1 = de_ftab_inv1(fit, s1, [options])\n%|\n%| Build object that does 1D inverse of BH function for 1st material component,\n%| (usually water), for conventional \"water only\" beam-hardening correction.\n%|\n%| in\n%|\tfit\tstrum\tinitialized by de_ftab_fit()\n%|\ts1\t[N]\ts_1 sample values for building table (ftab.sls.sl{1})\n%|\n%| option\n%|\t'll'\t1\twhich component (default: 1)\n%|\t'type'\tchar\t'interp' cubic interpolation (default)\n%|\t\t\t'exp'\tlog(exp()) form - under development\n%|\t'show'\t0|1\tplot it?\n%|\n%| out\n%|\tinv1\tstrum\n%|\tmethods:\n%|\t\tinv1.fun(hf1)\tmap log values into corrected values\n%|\t\t\t(corresponding to line-integral of material density)\n%|\t\tinv1.plot(fit)\tshow fit\n%|\n%| Copyright 2008-09-28, Jeff Fessler, University of Michigan\n\nif nargin < 1, ir_usage, end\nif nargin == 1 && streq(fit, 'test'), de_ftab_inv1_test, return, end\n\narg.show = false;\narg.type = 'interp'; % cubic interpolation\narg.ll = 1; % which material, one of {1, ..., LL}\narg = vararg_pair(arg, varargin);\n\n% although we need only the 1D array of s1 values,\n% fit.fmfun requires a [n1 1 LL] array. here the other components are zero.\nLL = fit.LL; % usually 1 anyway\nsll = s1; sll(1,1,LL) = 0; % [n1 1 L]\n\n% evaluate nonlinear BH function for each of the M spectra\nf1 = fit.fmfun(sll); % [n1 1 M]\n%f1 = squeeze(f1(:,1,:)); % [n1 M] % changed 2008-12-19\nf1 = squeeze(f1); % [n1 M]\n\nst.s1 = s1;\nst.f1 = f1;\n\nswitch arg.type\ncase 'interp'\n\tinv1_fun = @de_ftab_inv1_interp;\ncase 'exp'\n\tst = de_ftab_inv1_exp_init(st, fit, arg);\n\tinv1_fun = @de_ftab_inv1_exp_eval;\notherwise\n\tfail('unknown type %s', arg.type)\nend\n\nmeth = {'fun', inv1_fun, '(fh1 [N M]) -> [N M]';\n\t'plot', @de_ftab_inv1_plot, '(fit)'};\n\ninv1 = strum(st, meth);\n\nif arg.show && im\n\tinv1.plot(fit);\nend\n\n\n% de_ftab_inv1_exp_init()\nfunction st = de_ftab_inv1_exp_init(st, fit, arg);\n\ns1 = st.s1;\nf1 = st.f1;\n\narg.fit0 = true; % todo\narg.fit0 = false;\narg.chat = true;\narg.thresh = 1e-16;\narg.nexp = 91;\n\ny = exp(s1);\nwt = ones(size(y)); % todo\nWh = spdiag(wt, 'nowarn');\n\nMM = size(f1,2);\nfor mm=1:MM\n\tf_coef = fit.coef{mm};\n\tf_exp = fit.mac{mm}(:,1); % for ll=1 only\n\temin = 1 / max(f_exp);\n\temax = 1 / min(f_exp);\n\tinv_exp = linspace(emin, emax, arg.nexp)'; % [Ne 1] candidate exps\n\tAb = exp(f1(:,mm) * inv_exp'); % [*Ns Ne] \"over-complete\" basis\n\n\t% initial coefficients for each candidate exponent\n\tif arg.fit0\n\t\tfder0 = fit.mac_eff(mm,1);\n\t\tinv_der0 = 1 / fder0;\n\t\twarg = {'inprodv', inv_exp' / inv_der0};\n\telse\n\t\twarg = {};\n\tend\n\tx = wls_simplex(Ab, y(:), Wh, [], warg{:}); % [Ne 1]\n\n\tif 1 % reduce to fewer essential terms\n\t\tie = x > arg.thresh; % find key energies\n\t\tif arg.chat\n\t\t\tprintm('%d coefficients of %d for m=%d', ...\n\t\t\t\tsum(ie), length(ie), mm)\n\t\tend\n\t\tinv_exp = inv_exp(ie);\n\n\t\t% final coefficients at key exponents\n\t\tif arg.fit0\n\t\t\tfder0 = fit.mac_eff(mm,1);\n\t\t\tinv_der0 = 1 / fder0;\n\t\t\twarg = {'inprodv', inv_exp' / inv_der0}; % shorter now\n\t\telse\n\t\t\twarg = {};\n\t\tend\n\t\tA = Ab(:,ie); % [*Ns Ne] final basis\n\t\tx = wls_simplex(A, y(:), Wh, [], warg{:}); % [Ne 1]\n\tend\n\n\tst.exp.coef{mm} = x; % [Ne 1]\n\tst.exp.exp{mm} = inv_exp;\nend\n\n\n% de_ftab_inv1_exp_eval()\nfunction s1hat = de_ftab_inv1_exp_eval(st, fh1)\n\nMM = size(st.f1,2);\ndim = size(fh1);\nfh1 = reshapee(fh1, [], MM); % [N M]\ns1hat = zeros(size(fh1), 'single');\nfor mm=1:MM\n\ttmp = exp(fh1(:,mm) * st.exp.exp{mm}'); % [*N Ne]\n\ts1hat(:,mm) = log(tmp * st.exp.coef{mm}); % [*N 1]\nend\ns1hat = reshape(s1hat, dim);\n\nwarn 'untested'\n\n\n% de_ftab_inv1_interp()\n% inverse based on interpolation\nfunction s1hat = de_ftab_inv1_interp(st, fh1)\n\ns1 = st.s1;\nf1 = st.f1;\n\nMM = size(f1,2);\ndim = size(fh1);\nfh1 = reshapee(fh1, [], MM);\ns1hat = zeros(size(fh1), 'single');\nfor mm=1:MM\n\ts1hat(:,mm) = interp1(f1(:,mm), s1, fh1(:,mm), 'pchip', 'extrap');\nend\ns1hat = reshape(s1hat, dim);\n\n\n% de_ftab_inv1_plot()\nfunction out = de_ftab_inv1_plot(st, fit)\n\nif nargin ~= 2, fail 'need \"fit\" argument', end\n\ns1 = st.s1;\n\ns4 = max(s1);\ns4 = linspace(-0.0*s4, 1.0*s4, 4*length(s1)+1)'; % [n4] fine sampling\nLL = fit.LL;\nMM = fit.MM;\nsll = s4; sll(1,1,LL) = 0; % [n4 1 L]\n\nf4 = fit.fmfun(sll); % [n4 1 M]\n%f4 = squeeze(f4(:,1,:)); % [n4 M]\nf4 = squeeze(f4); % [n4 M]\n\ns4i = st.fun(f4); % [n4 M] one correction for each spectrum\nerr = s4i - repmat(s4, [1 MM]); % [n4 M]\n\nclf, pl = @(n,m) subplot(200 + MM*10 + (n-1)*MM + m);\nfor mm=1:MM\n\tpl(1,mm)\n\tplot(s4, f4(:,mm), 'c-', s4i(:,mm), f4(:,mm), 'y:', ...\n\t\ts4, s4 * fit.mac_eff(mm), '--') % monenergetic line\n\tir_legend({'true (fine)', 'fit', 'mono'})\n\tm = num2str(mm);\n\taxis tight, xlabel 's1', ylabel(['f' m]), title(['inv1 fit m=' m])\n\n\tpl(2,mm)\n\tplot(s4, err(:,mm), '.-')\n\taxis tight, xlabel 's1', ylabel(['err' m]), title 'inv1 error'\nend\nprompt\n\nif nargout, out = []; end\n\n\n% de_ftab_inv1_test()\nfunction de_ftab_inv1_test\nstype = 'ps1';\nmtype = {'water', 'bone'};\nxrs = xray_read_spectra(stype);\nmas = xray_read_mac(mtype);\nsls = de_ftab_sls;\nfm = de_ftab_fm(sls.sll, mas.mac(xrs.en), xrs.Ide);\nsl = sls.sl;\nfit = de_ftab_fit(sl, fm, 'type', 'exp', 'mtype', mtype, 'show', 0);\nitypes = {'exp', 'interp'};\nfor ii=1:length(itypes)\n\titype = itypes{ii};\n\tinv1 = de_ftab_inv1(fit, sl{1}, 'type', itype);\n%\tinv1.fun([0 0])\n\tif im, inv1.plot(fit); end\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/ct/de_ftab_inv1.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 [ candidates, scores ] = sample_bing_windows( im, num_samples)\n%SAMPLE_BING_WINDOWS Will generate equaly distributed windows in space,\n%following Bing sizes\n% Bing uses 29 specific sizes, this method spread this sizes homogenously\n% inside the image\nscores = [];\nim_wh = [size(im, 2), size(im, 1)];\n\noriginal_bing_window_sizes = [[512 512 ]; [256, 512 ]; [128, 512 ]; [64, 512 ]; ...\n [512, 256 ]; [256, 256 ]; [128, 256 ]; [64, 256 ]; [32, 256 ]; ...\n [512, 128 ]; [256, 128 ]; [128, 128 ]; [64, 128 ]; [32, 128 ]; [16, 128 ]; ...\n [512, 64 ]; [256, 64 ]; [128, 64 ]; [64, 64 ]; [32, 64 ]; [16, 64 ]; ...\n [128, 32 ]; [64, 32 ]; [32, 32 ]; [16, 32 ]; ...\n [64, 16 ]; [32, 16 ]; [16, 16 ]];\n\n%original_bing_window_sizes = [[64, 128]; [32, 128 ]];\n\noriginal_num_window_sizes = size(original_bing_window_sizes, 1);\n\nbing_window_sizes = [];\n\n% we filter window sizes to fit inside the image\nfor i=1:size(original_bing_window_sizes, 1),\n window_wh = original_bing_window_sizes(i, :);\n \n if(sum(window_wh < im_wh) == 2),\n bing_window_sizes = [bing_window_sizes; window_wh];\n else\n % the window is disregarded\n end\n \n \nend\n\nnum_window_sizes = size(bing_window_sizes, 1);\n\nassert(num_samples > num_window_sizes);\n\n\ncandidates = [];\nif num_window_sizes ~= original_num_window_sizes, \n % we add one candidate that covers the whole image size\n candidates = [0, 0, im_wh];\nend\n \n\nuse_v0 = false;\n\nif use_v0,\n % will have as many splits in x and y axis (non-square strides)\n \n sqrt_num_samples_size = floor(sqrt(num_samples / num_window_sizes));\n samples_per_size = sqrt_num_samples_size * sqrt_num_samples_size;\n assert(samples_per_size > 3);\n extra_samples = num_samples - (samples_per_size * num_window_sizes) - size(candidates, 1);\n delta_samples = ((sqrt_num_samples_size + 1) * (sqrt_num_samples_size + 1)) - samples_per_size;\n \n divisions_per_size = repmat(sqrt_num_samples_size, 1, num_window_sizes);\n \n start_extra_size_index = 6; % because we like 256x256 (and smaller)\n for i = start_extra_size_index:num_window_sizes,\n if extra_samples > delta_samples,\n divisions_per_size(i) = divisions_per_size(i) + 1;\n extra_samples = extra_samples - delta_samples;\n else\n fprintf('Added %i extra sizes\\n', i - 1);\n break;\n end\n end\n \n \n for i = 1:num_window_sizes,\n \n num_divisions = divisions_per_size(i);\n window_wh = bing_window_sizes(i, :);\n x1 = 1;\n y1 = 1;\n x2 = im_wh(1) - window_wh(1);\n y2 = im_wh(2) - window_wh(2);\n \n assert(x2 > 1);\n assert(y2 > 1);\n \n [xx, yy] = meshgrid(linspace(x1, x2, num_divisions), ...\n linspace(y1, y2, num_divisions));\n top_left_xy = [xx(:) yy(:)];\n for j = 1:size(top_left_xy, 1),\n xy = top_left_xy(j, :);\n window = [xy, xy + window_wh];\n candidates = [candidates; window];\n end\n \n end\n \nelse\n % v1\n % will use square strides\n \n \n num_samples_per_size = floor(num_samples / num_window_sizes);\n \n stride_per_size = zeros(1, num_window_sizes);\n total_placed_samples = size(candidates, 1);\n for i = 1:num_window_sizes,\n \n window_wh = bing_window_sizes(i, :);\n x2 = im_wh(1) - window_wh(1);\n y2 = im_wh(2) - window_wh(2);\n \n assert(x2 > 0);\n assert(y2 > 0);\n \n block_area = (x2 * y2) / num_samples_per_size;\n stride = sqrt(block_area);\n assert(stride > 0);\n \n num_samples_placed = compute_num_samples_placed(im_wh, window_wh, stride);\n \n while(num_samples_placed > num_samples_per_size)\n stride = stride + 1; % larger stride, less placements\n num_samples_placed = compute_num_samples_placed(im_wh, window_wh, stride);\n end\n \n assert(num_samples_placed <= num_samples_per_size);\n \n total_placed_samples = total_placed_samples + num_samples_placed;\n assert(total_placed_samples <= num_samples);\n \n stride_per_size(i) = stride;\n end\n \n assert(total_placed_samples <= num_samples);\n \n sqrt_num_samples_size = floor(sqrt(num_samples / num_window_sizes));\n samples_per_size = sqrt_num_samples_size * sqrt_num_samples_size;\n% assert(samples_per_size > 3);\n assert(samples_per_size > 0);\n extra_samples = num_samples - total_placed_samples;\n assert(extra_samples >= 0);\n \n start_extra_size_index = 6; % because we like 256x256 (and smaller)\n for i = start_extra_size_index:num_window_sizes,\n \n window_wh = bing_window_sizes(i, :);\n stride = stride_per_size(i);\n \n num_samples_placed = compute_num_samples_placed(im_wh, window_wh, stride);\n \n new_stride = stride * 0.75;\n %new_stride = stride - 1;\n new_num_samples_placed = compute_num_samples_placed(im_wh, window_wh, new_stride);\n \n delta_samples = new_num_samples_placed - num_samples_placed;\n \n if extra_samples > delta_samples,\n stride_per_size(i) = new_stride;\n total_placed_samples = total_placed_samples + delta_samples;\n extra_samples = extra_samples - delta_samples;\n else\n fprintf('Added %i extra sizes\\n', i - start_extra_size_index);\n break;\n end\n end\n \n if extra_samples > 0,\n fprintf('%i extra_samples remaining\\n', extra_samples);\n end\n \n for i = 1:num_window_sizes,\n \n window_wh = bing_window_sizes(i, :);\n stride = stride_per_size(i);\n x1 = 1;\n y1 = 1;\n x2 = im_wh(1) - window_wh(1);\n y2 = im_wh(2) - window_wh(2);\n \n x_dots = x1 + (mod(x2 - x1, stride) / 2): stride : x2;\n y_dots = y1 + (mod(y2 - y1, stride) / 2): stride : y2;\n \n assert(x2 > 0);\n assert(y2 > 0);\n \n [xx, yy] = meshgrid(x_dots, y_dots);\n top_left_xy = [xx(:) yy(:)];\n for j = 1:size(top_left_xy, 1),\n xy = top_left_xy(j, :);\n window = [xy, xy + window_wh];\n candidates = [candidates; window];\n end\n \n end\n \n assert(size(candidates, 1) == total_placed_samples);\nend\n\nassert(size(candidates, 1) <= num_samples);\nend\n\n\nfunction [ret] = compute_num_samples_placed(im_wh, window_wh, stride)\nx1 = 1;\ny1 = 1;\nx2 = im_wh(1) - window_wh(1);\ny2 = im_wh(2) - window_wh(2);\n\nx_dots = x1 + (mod(x2 - x1, stride) / 2): stride : x2;\ny_dots = y1 + (mod(y2 - y1, stride) / 2): stride : y2;\nnum_samples_placed = size(x_dots, 2) * size(y_dots, 2);\nret = num_samples_placed;\nend\n\n\n", "meta": {"author": "hosang", "repo": "detection-proposals", "sha": "858368afffde5ff4028020fcb1dd4381705ccbfb", "save_path": "github-repos/MATLAB/hosang-detection-proposals", "path": "github-repos/MATLAB/hosang-detection-proposals/detection-proposals-858368afffde5ff4028020fcb1dd4381705ccbfb/baselines/sample_bing_windows.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.4872840365056372}} {"text": "function opts = getdata(dataformat)\n\nfor i = 1:200\n imshow(reshape(images(:,i),144,176),[]); \n pause(0.1);\nend\n\nif strcmp(dataformat,'surveillance-video-Hall')\n load Hall_airport_1000_1496_497_144_176_gray.mat;\n D = images(:,1:200); [n1,n2] = size(images); % imn1 = 144; imn2 = 176;\n opts.D = D; opts.mu = norm(D)/1.25;\n Xs = D; Ys = D;\n \nelseif strcmp(dataformat,'surveillance-video-Campus-color')\n% load Campus_trees_1000_1993_994_128_160_gray.mat;\n load Campus_trees_1000_1996_997_128_160_R.mat; DR = images(:,181:500); \n load Campus_trees_1000_1995_996_128_160_G.mat; DG = images(:,181:500);\n load Campus_trees_1000_1994_995_128_160_B.mat; DB = images(:,181:500);\n D = [DR, DG, DB];\n [n1,n2] = size(D); % imn1 = 128; imn2 = 160;\n opts.D = D; opts.mu = norm(D)/1.25;\n Xs = D; Ys = D;\nend\n\nopts.Xs = Xs; opts.Ys = Ys;\nopts.n1 = n1; opts.n2 = n2;\nopts.sigma = 1e-6; opts.maxitr = 500; opts.rho = 1/sqrt(n1); \nopts.eta_mu = 2/3; opts.eta_sigma = 2/3;\nopts.muf = 1e-6;\nopts.sigmaf = 1e-6;\nopts.epsilon = 1e-7;\nopts.sv = 100;\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/LSADM/getdata.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 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": "% Estimate spatial covariance matrix for sentences using a mask. The mask\n% specifies speech presense probability at all time frequency locations,\n% with a 1 means speech present and 0 means speech absent. \n%\nfunction curr_layer = F_MVDR_spatialCov(input_layer, curr_layer)\ninput = input_layer.a;\nfs = curr_layer.fs;\nfreqBin = curr_layer.freqBin;\nnFreqBin = length(freqBin);\n\n[D,T,N] = size(input);\nif isfield(curr_layer, 'noiseCovL2')\n noiseCovL2 = curr_layer.noiseCovL2;\nelse\n noiseCovL2 = 0; % add noiseCovRegularization*\\lambda*I to noise covariance, where \\lambda is the maximum eigenvalue\nend\n\nD = D/2;\nspeechCov = input(1:D,:,:,:);\nnoiseCov = input(D+1:end,:,:,:);\n\ndimTmp = size(speechCov,1) / nFreqBin;\nnCh = sqrt(dimTmp);\n\nspeechCov = reshape(speechCov, nCh, nCh, nFreqBin, T, N);\nnoiseCov = reshape(noiseCov, nCh, nCh, nFreqBin, T, N);\n\nspeechCov_cell = num2cell(speechCov, [1 2]); % convert to cell array and call cellfun for speed\nnoiseCov_cell = num2cell(noiseCov, [1 2]); \n\n% add regularization\nif noiseCovL2 > 0\n eig_val = cellfun(@GetEigVal, noiseCov_cell, 'UniformOutput', 0);\n eig_val = cell2mat(eig_val);\n noise_floor = eig_val(end,:,:,:,:) * noiseCovL2;\n noise_floor(:) = 100;\n % because our noise floor depends on noise covariance and network\n % parameters, it will not be able to pass through gradient check. This\n % is because we didn't consider this dependancy in the backpropagation.\n % But this should not have much effect on the training.\n noise_floor_cell = num2cell(noise_floor, 1);\n noiseCov_cell = cellfun(@DiagLoading, noiseCov_cell, noise_floor_cell, 'UniformOutput', 0);\nend\n\nninv_x = cellfun(@(x,n) (inv( n )*x), speechCov_cell, noiseCov_cell, 'UniformOutput', 0);\nlambda = cellfun(@(x) abs(trace(x)), ninv_x, 'UniformOutput', 0);\nif 0 % only lambda\n weight = cellfun(@(x,y) ones(size(x,1),1)/y, ninv_x, lambda, 'UniformOutput', 0);\nelseif 0 % no lambda\n weight = cellfun(@(x) x(:,1), ninv_x, 'UniformOutput', 0);\nelse\n weight = cellfun(@(x,y) x(:,1)/y, ninv_x, lambda, 'UniformOutput', 0);\nend\noutput = cell2mat(weight);\noutput = permute(output, [3 1 2 4 5]);\noutput = reshape(output, nFreqBin*nCh, T, N);\n\ncurr_layer.a = output;\ncurr_layer.lambda = lambda;\ncurr_layer.phi_s = speechCov_cell;\ncurr_layer.phi_n = noiseCov_cell;\nif noiseCovL2>0\n curr_layer.noise_floor = noise_floor_cell;\nend\nend\n\n%% \nfunction ev = GetEigVal(A)\n[~,V] = eig(A);\nev = diag(V);\nend\n\nfunction B = DiagLoading(A, alpha)\nD = size(A,1);\nB = A + alpha * eye(D);\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/F_MVDR_spatialCov.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.48717556320583105}} {"text": "function [irf_record_allt,favar]=tvbvarirf2(beta_gibbs,D_record,It,Bu,IRFperiods,n,m,p,k,T,favar)\n\n\n\n% Favar preliminaries\nif favar.FAVAR==1\n signresX_index=[];\n npltX=favar.npltX;\n if npltX>0\n favar_FAVAR=1;\n plotX_index=favar.plotX_index;\n else\n favar_FAVAR=0;\n plotX_index=[];\n end\n %relevant loadings\n relLindex=[signresX_index;plotX_index];\n % reshape the L gibbs draws\n Lgibbs=reshape(favar.L_gibbs,size(favar.L,1),size(favar.L,2),It-Bu);\n Lgibbs=Lgibbs(relLindex,:,:);\nelse\n npltX=0;\n favar_FAVAR=0;\n Lgibbs=NaN;\nend\n\n% create the cell aray that will store the values from the simulations\nirf_record_allt=cell(n,n);\nfavar.IRF.favar_irf_record_allt=cell(npltX,n);\n\n% loop over sample periods\nfor tt=1:T\n % loop over iterations\n for jj=1:It-Bu\n % draw beta\n beta=beta_gibbs{tt}(:,jj);\n D=reshape(D_record(:,It-Bu),n,n);\n if favar_FAVAR==1\n Lg=squeeze(Lgibbs(:,:,It-Bu)); % this is different for IRFt4, we need to record the index there and adjust the case\n end\n [~,ortirfmatrix]=bear.irfsim(beta,D,n,m,p,k,IRFperiods);\n \n % if we have FAVAR restrictions we scale the ortirfmatrix from the previous step\n if favar_FAVAR==1\n favar_ortirfmatrix=[];\n % scale with loading\n for uu=1:npltX %over variables in X that we choose to plot\n for mm=1:IRFperiods\n for ll=1:n % over shocks\n favar_ortirfmatrix(uu,ll,mm)=Lg(uu,:)*ortirfmatrix(:,ll,mm);\n end\n end\n end\n end\n \n % save\n for kk=1:n\n for ll=1:n\n for mm=1:IRFperiods\n irf_record_allt{kk,ll}(jj,mm,tt)=ortirfmatrix(kk,ll,mm);\n end\n end\n end\n \n if favar_FAVAR==1\n for uu=1:npltX % loop over variables\n for ll=1:n % loop over shocks\n for mm=1:IRFperiods\n favar.IRF.favar_irf_record_allt{uu,ll}(jj,mm,tt)=favar_ortirfmatrix(uu,ll,mm);\n end\n end\n end\n end\n end\nend\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/tvbvarirf2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.48717556320583105}} {"text": "close all;\nclear all;\nclc;\n\ndata_file_path = 'bin/mmv_phase_transition_snr_30db_s_16.mat';\noptions.export = true;\noptions.export_dir = 'bin';\noptions.export_name = 'mmv_snr_30_db_s_16';\noptions.chosen_ks = [2, 4, 8, 16, 32, 64];\noptions.subtitle = 'MMV, SNR=30dB s=16';\nspx.pursuit.PhaseTransitionAnalysis.print_results(data_file_path, ...\n 'CoSaMP', options);\n\n", "meta": {"author": "indigits", "repo": "sparse-plex", "sha": "43cae2978f62938d001baaa03308a2a717ee6c9b", "save_path": "github-repos/MATLAB/indigits-sparse-plex", "path": "github-repos/MATLAB/indigits-sparse-plex/sparse-plex-43cae2978f62938d001baaa03308a2a717ee6c9b/experiments/cosamp_mmv/print_mmv_phase_transition_snr_30db_s_16.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.487175563205831}} {"text": "% testing on new December 2016 price data\n\ndataArray = csvread('results.csv');\nprices = transpose(dataArray(:,2));\naskVolume = dataArray(:,3);\nbidVolume = dataArray(:,4);\n\nprices = prices(1:2:end);\naskVolume = askVolume(1:2:end);\nbidVolume = bidVolume(1:2:end);\n\n% estimate transaction fee at %1\n[error,jinzhi,bank,buy,sell,proba] = brtrade(prices,bidVolume,askVolume, 1);\n\n% set up plots\nmake_plots(prices, buy, sell, proba, bank, error);\n", "meta": {"author": "panditanvita", "repo": "BTCpredictor", "sha": "76fc3744563aa160c0fca76b9a7d7974bf1c1a20", "save_path": "github-repos/MATLAB/panditanvita-BTCpredictor", "path": "github-repos/MATLAB/panditanvita-BTCpredictor/BTCpredictor-76fc3744563aa160c0fca76b9a7d7974bf1c1a20/test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4871755568948}} {"text": "function [tt]=tt_qreshape(tt,s,sz)\n\n% Reshapes the cores of the input (Q)TT representation.\n% s (scalar) is the number of mode indices in each core of the input representation;\n% sz is a matrix of size d x s1, where d is the number of cores and s1 is the number of mode indices in each core of the output representation;\n% sz(k,alpha) is the mode size of the alpha-th index in the k-th core of the output representation.\n% k-th component of prod(sz,2) is the overall numbers of mode degrees of freedom of the k-th core of the output representation \n%\n% April 26, 2011\n% Vladimir Kazeev\n% vladimir.kazeev@gmail.com\n% INM RAS\n% Moscow, Russia\n%\n\nd=size(tt,1);\nfor k=1:d\n\tszk=size(tt{k});\n\tszk=[szk,ones(1,s)];\n\tszkr=szk(s+1:numel(szk));\n\ttt{k}=reshape(tt{k},[sz(k,:),szkr]);\nend\n\nreturn\nend", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/core/tt_qreshape.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.48715241235987483}} {"text": "function intlablogo(angle,screensaver)\n%INTLABLOGO Show INTLAB logo\n%\n% intlablogo\n%\n%put cursor into figure and press\n%\n% o open\n% c close\n% q quit\n%\n%The call\n%\n% intlablogo(angles)\n%\n%shows the dodecahedron in opening angles.\n%\n\n%The call\n% intlablogo([],1)\n%generates a screensaver picture using\n% generate file: print -djpeg100 -zbuffer picturefile\n%\n\n% written 10/16/98 S.M. Rump\n% modified 04/04/04 S.M. Rump revision\n% modified 10/13/05 S.M. Rump name and fonts adapted\n% modified 09/06/07 S.M. Rump version number\n% modified 06/24/08 S.M. Rump screensaver\n%\n\n if nargin<=1\n screensaver = 0;\n end\n\n psi1 = 10.8123169636;\n psi2 = 52.6226318594;\n \n for i=1:5\n P{i} = polar2rect(1,72*i,psi2);\n P{5+i} = polar2rect(1,72*i,psi1);\n P{10+i} = polar2rect(1,72*i-36,-psi1);\n P{15+i} = polar2rect(1,72*i-36,-psi2);\n end\n \n M = zeros(18,5,3);\n \n M(1,:,:) = [ P{ 1} P{ 5} P{10} .5*(P{10}+P{11}) .5*(P{1}+P{6}) ]';\n M(2,:,:) = [ P{ 1} P{ 2} P{ 3} P{ 4} P{ 5} ]';\n M(3,:,:) = [ P{ 5} P{ 4} P{ 9} P{15} P{10} ]';\n M(4,:,:) = [ P{ 3} P{ 8} P{14} P{ 9} P{ 4} ]';\n M(5,:,:) = [ P{10} P{15} .5*(P{15}+P{20}) .5*(P{10}+P{11}) P{10}]';\n M(6,:,:) = [ P{ 1} P{ 2} .5*(P{2}+P{7}) .5*(P{6}+P{1}) P{1}]';\n M(7,:,:) = [ P{15} P{ 9} P{14} .5*(P{14}+P{19}) .5*(P{20}+P{15}) ]';\n M(8,:,:) = [ P{2} P{3} P{8} .5*(P{8}+P{13}) .5*(P{2}+P{7}) ]';\n M(9,:,:) = [ P{8} P{14} .5*(P{14}+P{19}) .5*(P{8}+P{13}) P{8} ]';\n M(10:18,:,:) = -M(1:9,:,:);\n \n dil = .25*( P{14}+P{19} + P{20}+P{15} );\n for i=1:3\n M(:,:,i) = M(:,:,i) - dil(i);\n end\n phi = atan2(dil(2),dil(1));\n T = [ cos(phi) -sin(phi) 0 ; ...\n sin(phi) cos(phi) 0 ; ...\n 0 0 1 ];\n M = reshape( reshape(M,90,3)*T , 18,5,3 );\n Az = 23.75; El = 12.5;\n close\n \n % show a couple of angles\n if nargin~=0\n if ~isempty(angle)\n psi = angle(1);\n omegaold = 0;\n for omega=angle\n psi = omega-omegaold;\n M = showlogo(psi,M,screensaver);\n omegaold = omega;\n pause(0.05)\n end\n return\n end\n end\n \n % open/close by hand\n psi = 30;\n delta = 5;\n omega = psi;\n change = 1;\n \n while change\n clf\n M = showlogo(psi,M,screensaver);\n if screensaver\n print -djpeg100 -zbuffer picturefile\n close\n return\n end\n change = 0;\n \n if ~screensaver\n title( [ 'move cursor into window and press \"o\" or \"c\" or, \"q\" for quit' ], ...\n 'FontName','Sans Serif','Fontsize',10 );\n end\n shg\n waitforbuttonpress\n switch get(gcf,'CurrentCharacter')\n case 'o', \n if omega <= 180,\n psi = delta; omega = omega + delta;\n else\n psi = 0;\n end\n change = 1;\n case 'c', \n if omega >= delta\n psi = -delta; omega = omega - delta;\n else\n psi = 0;\n end\n change = 1;\n end\n end\n close\n \n\nfunction M = showlogo(psi,M,screensaver)\n% opens logo by angle psi from current setting\n clf\n axis off\n axis equal\n if screensaver\n M = 1.25*M;\n axis([-2.4 1.2 -1.5 2.1 -1 1.8])\n else\n axis([-1.5 1.5 -1.7 1.7 -.8 1.5])\n end\n axis manual\n hold on\n Az = 23.75; El = 12.5;\n view(Az,El)\n \n for i=10:18\n rand('state',0);\n fill3(M(i,:,1),M(i,:,2),M(i,:,3),rand(1,5,3));\n end\n \n psi_ = psi/180*pi;\n T = [ cos(psi_) 0 -sin(psi_) ; ...\n 0 1 0 ; ...\n sin(psi_) 0 cos(psi_) ];\n M(1:9,:,:) = reshape( reshape(M(1:9,:,:),45,3)*T , 9,5,3 );\n \n for i=1:9\n rand('state',0);\n fill3(M(i,:,1),M(i,:,2),M(i,:,3),rand(1,5,3));\n end\n addtext(screensaver)\n hold off\n \n\nfunction x = polar2rect(r,phi,psi) % in degrees\n x = zeros(3,1);\n sigma = pi/180;\n phi = sigma*phi;\n psi = sigma*psi;\n x(1) = cos(phi).*cos(psi);\n x(2) = sin(phi).*cos(psi);\n x(3) = sin(psi);\n x = r*x;\n\n\nfunction addtext(screensaver)\n if screensaver\n text(-1,-4 ,['INTLAB - INTerval LABoratory (Version ' intvalinit('version',0) ')'], ...\n 'Fontsize',12, ...\n 'FontName','MS Reference Sans Serif', ...\n 'HorizontalAlignment','left');\n text(-.42,-5.2,'The Matlab toolbox for Reliable Computing - www.ti3.tuhh.de/rump', ...\n 'Fontsize',10, ...\n 'FontName','Arial', ...\n 'HorizontalAlignment','left');\n text(-.36,-6.2,'Siegfried M. Rump, Institute for Reliable Computing, Hamburg University of Technology ', ...\n 'Fontsize',10, ...\n 'FontName','Arial', ...\n 'HorizontalAlignment','left');\n else\n text(-1,-4 ,['INTLAB - INTerval LABoratory (Version ' intvalinit('version',0) ')'], ...\n 'Fontsize',17, ...\n 'FontName','MS Reference Sans Serif', ...\n 'HorizontalAlignment','left');\n text(-.1,-5.2,'The Matlab toolbox for Reliable Computing - www.ti3.tuhh.de/rump', ...\n 'Fontsize',10, ...\n 'FontName','Arial', ...\n 'HorizontalAlignment','left');\n text(-.02,-6.2,'Siegfried M. Rump, Institute for Reliable Computing, Hamburg University of Technology ', ...\n 'Fontsize',10, ...\n 'FontName','Arial', ...\n 'HorizontalAlignment','left');\n end\n if ~screensaver\n str(1) = {' x = hessianinit(xs);'};\n str(2) = {' y = f(x);'};\n str(3) = {' xs = xs - y.hx\\\\y.dx'';'};\n text(-.5, 7.2,str, ...\n 'HorizontalAlignment','right', ...\n 'Fontsize',13, ...\n 'FontName','Courier');\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/intlablogo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.4871523949324532}} {"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": "%==============================================================================\n% This code is part of the Matlab-based toolbox\n% FAIR - Flexible Algorithms for Image Registration. \n% For details see \n% - https://github.com/C4IR and\n% - http://www.siam.org/books/fa06/\n%==============================================================================\n% This is a testing environment for the files in the folder kernel/data\n% 1. Based on data/contents, a list of required files is generated and it \n% is verified, that all files are present; additional files are listed.\n% 2. All c-files are compiled.\n% 3. All files are executed.\n% 4. Check administrative modul Trafo.m\n% 5. Transform certain 2D and 3D grids \n%==============================================================================\n\nFAIRcheckFiles(mfilename);\n\n%% Test module trafo, start with syntax\ntrafo('reset','trafo','splineTransformation2D',...\n 'p',[4,5],'omega',[1,1],'m',[6,40]);\ntrafo('disp');\n[scheme,parameter] = trafo;\ntrafo('clear');\n%% test 2D cases\n\nomega = [0,1,0,2]; \nm = [6,7]; \nxc = getCellCenteredGrid(omega,m);\ncenter = (omega(2:2:end)+omega(1:2:end))'/2;\n\n% initialize various transformations\ntrafos = {\n 'affine2D',{},...\n 'affine2Dsparse',{},...\n 'rigid2D',{},...\n 'rotation2D',{'c',center},...\n 'translation2D',{},...\n 'splineTransformation2D',{'p',[4,5],'omega',omega,'m',m},...\n 'splineTransformation2Dsparse',{'p',[4,5],'omega',omega,'m',m}\n };\n\nfor k=2:length(trafos)/2,\n fprintf(2,'\\n\\n\\ntest [ %s ] --- %d of %d\\n',...\n trafos{2*k-1},k,length(trafos)/2)\n optn = trafos{2*k};\n trafo('reset','trafo',trafos{2*k-1},'debug','on',optn{:});\n trafo('disp');\n wc = trafo('w0');\n fctn = @(wc) trafo(wc,xc);\n checkDerivative(fctn,wc+randn(size(wc)),'fig',1+mod(k,2));\n title(trafo)\n builtin('pause',2);\nend;\n\n%% test 3D cases\nomega = [0,1,0,2,0,3]; m = [6,7,8]; xc = getCellCenteredGrid(omega,m);\ntrafos = {\n 'affine3D',{},...\n 'affine3Dsparse',{},...\n 'rigid3D',{},...\n 'splineTransformation3Dsparse',{'p',[4,5,6],'omega',omega,'m',m},...\n 'translation3D',{}\n };\n\nfor k=1:length(trafos)/2,\n fprintf('\\n\\n\\ntest [ %s ] --- %d of %d\\n',...\n trafos{2*k-1},k,length(trafos)/2)\n optn = trafos{2*k};\n trafo('reset','trafo',trafos{2*k-1},'debug','on',optn{:});\n trafo('disp');\n wc = trafo('w0');\n fctn = @(wc) trafo(wc,xc);\n checkDerivative(fctn,wc+randn(size(wc)),'fig',1+mod(k,2));\n title(trafo)\n builtin('pause',2);\nend;\n\ntestEnd;\n%==============================================================================\n", "meta": {"author": "C4IR", "repo": "FAIR.m", "sha": "975edebd37b833ae76696792870de5c05efcb9cb", "save_path": "github-repos/MATLAB/C4IR-FAIR.m", "path": "github-repos/MATLAB/C4IR-FAIR.m/FAIR.m-975edebd37b833ae76696792870de5c05efcb9cb/kernel/transformations/testTransformations.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.48714332245737285}} {"text": "function img = imresizeAspect(img, maxSize)\n% function img = imresizeAspect(img, maxSize)\n% If image is larger than max size, reduce size, preserving aspect ratio of input.\n%\n% If size(input) = [y x] and maxSize = [yy xx],\n% then size(output) is given by the following (where a=y/x)\n% if ymin_level,1,'first');\n stop = find(abs(in)>min_level,1,'last');\n if isempty(start)\n start = maxidx;\n end\n if isempty(stop)\n stop = maxidx;\n end\n range = [start stop];\nend\n", "meta": {"author": "m-r-s", "repo": "hearingaid-prototype", "sha": "973b4c8e793a0ac78e8d1e7bd40e518876fc3c83", "save_path": "github-repos/MATLAB/m-r-s-hearingaid-prototype", "path": "github-repos/MATLAB/m-r-s-hearingaid-prototype/hearingaid-prototype-973b4c8e793a0ac78e8d1e7bd40e518876fc3c83/tools/estimate_feedback.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.48705509142629017}} {"text": "function dataout=modeBSS(nummics, numrefs, datain)\n%\n% Use Aux-IVA to solve dr, aec and separation.\n% nummics: no. of mic channels\n% numrefs: no. of reference channels\n% datain: input data\n% dataout: output data\n%\n\n%% perform stft\naddpath('stft2');\n% fft size\nfftsize=512;\nstftshift=fftsize/2;\n\nM=nummics;\nR=numrefs;\nN=M;\n\nXtf=cell(M+R, 1);\nfor m=1:M+R\n Xtf{m}=stft(datain(:, m), stftshift, fftsize, false);\nend\n[K, T]=size(Xtf{1});\n\nYtf=cell(M, 1);\nfor m=1:M\n Ytf{m}=zeros(K, T);\nend\n\n%% params\n% dr filter length\nDR_FLEN=5;\n% forgetting factor for bss\nBF_FORGET=0.999;\n% the shape parameter of the source prior\nGAMMA=0.2;\n%\n% used to keep stable\n%\nVAR_BIAS=0.01;\nSTABLE_EPS=1e-3;\nBF_DIAGLOAD=1e-6;\n\n%% space for bss\n% data buffer\nfsize=M+R+M*DR_FLEN;\nBufdata=zeros(K, fsize);\n% current mic backup\nMiccurrent=zeros(K, M);\n\n% the weighted correlation matrices\nC1=cell(K, 1);\nC2=cell(K, 1);\nfor k=1:K\n C1{k}=STABLE_EPS*eye(fsize, fsize);\n C2{k}=STABLE_EPS*eye(fsize, fsize);\nend\n\n% demixing matrices\nDemix=cell(K, 1);\nfor k=1:K\n Demix{k}=eye(fsize, fsize);\nend\n\n%% perform iteration\nfor tau=1:T\n Bssout=zeros(K, M);\n \n %\n % shift in new data\n %\n % shift old mic data back\n Bufdata=circshift(Bufdata, M, 2);\n % shift in delayed mic data\n Bufdata(:, M+R+1:M+R+M)=Miccurrent;\n \n % mic data backup\n for m=1:M\n Miccurrent(:, m)=Xtf{m}(:, tau);\n end\n % current mic data\n Bufdata(:, 1:M)=Miccurrent;\n \n % shift in reference data\n for r=1:R\n Bufdata(:, M+r)=Xtf{M+r}(:, tau);\n end\n \n %\n % calculate nonlinearity\n %\n phi1=0;\n phi2=0;\n \n for k=1:K\n x=Bufdata(k, :).';\n y=Demix{k}*x;\n % output data\n Bssout(k, :)=y(1:M).';\n \n phi1=phi1+abs(y(1))^2;\n phi2=phi2+abs(y(2))^2;\n end\n \n phi1=(1-BF_FORGET)*(phi1+VAR_BIAS)^((GAMMA-2)/2);\n phi2=(1-BF_FORGET)*(phi2+VAR_BIAS)^((GAMMA-2)/2);\n\n % update the demixing matrices\n for k=1:K\n %\n % accumulate the weighted correlation\n %\n x=Bufdata(k, :).';\n C1{k}=BF_FORGET*C1{k}+phi1*(x*x');\n C2{k}=BF_FORGET*C2{k}+phi2*(x*x');\n \n %\n % update demixing matrix\n %\n H1=inv(Demix{k}*C1{k}+BF_DIAGLOAD*eye(fsize, fsize));\n w1=H1(:, 1);\n \n H2=inv(Demix{k}*C2{k}+BF_DIAGLOAD*eye(fsize, fsize));\n w2=H2(:, 2);\n \n D=eye(fsize, fsize);\n D(1, :)=w1';\n D(2, :)=w2';\n \n %\n % solve the scaling ambiguity\n %\n A=inv(D);\n \n if abs(A(1, 1))>=abs(A(2, 1))\n a1=A(1, 1);\n else\n a1=A(2, 1);\n end\n \n if abs(A(2, 2))>=abs(A(1, 2))\n a2=A(2, 2);\n else\n a2=A(1, 2);\n end\n \n D=eye(fsize, fsize);\n D(1, :)=a1*w1';\n D(2, :)=a2*w2';\n \n Demix{k}=D;\n end\n \n for m=1:M\n Ytf{m}(:, tau)=Bssout(:, m);\n end\nend\n\n%% perform istft and output signal\ndataout=zeros(dataLength(T, stftshift, fftsize ), N);\nfor n=1:N\n dataout(:, n)=istft(Ytf{n}, stftshift, false);\nend\n\nend\n", "meta": {"author": "nay0648", "repo": "unified2021", "sha": "006d3d99da7c0f9c535994ef58355ef36a83d510", "save_path": "github-repos/MATLAB/nay0648-unified2021", "path": "github-repos/MATLAB/nay0648-unified2021/unified2021-006d3d99da7c0f9c535994ef58355ef36a83d510/Experiment/modeBSS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.48705509142629017}} {"text": "function [mh,mS] = pred_coxphhs(gp, x, y, xt, varargin)\n%PRED_COXPHHS Return hazard and survival functions\n%\n% Description\n% [H,S] = PRED_COXPHHS(GP,X,Y,XT) \n% Returns hazard and survival functions for the inputs XT. GP is the\n% Gaussian process structure, X and Y are the training inputs and\n% outputs.\n%\n% Copyright (c) 2012-2013 Ville Tolvanen, 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\nntime=size(gp.lik.xtime,1);\nif iscell(gp)\n % prediction for GP_IA cell array\n nGP = numel(gp);\n mh=zeros(size(xt,1),ntime,nGP);\n mS=zeros(size(xt,1),ntime,nGP);\n P_TH=zeros(1,nGP);\n for i1=1:nGP\n % make prediction for each gp in cell array\n Gp=gp{i1};\n P_TH(:,i1) = Gp.ia_weight;\n [mh(:,:,i1), mS(:,:,i1)]=pred_coxphhs(Gp, x, y, xt, varargin{:});\n mh(:,:,i1)=P_TH(:,i1)*mh(:,:,i1);\n mS(:,:,i1)=P_TH(:,i1)*mS(:,:,i1);\n end\n % combine predictions\n mh=sum(mh,3);\n mS=sum(mS,3);\n return\nelseif numel(gp.jitterSigma2)>1\n nmc=size(gp.jitterSigma2,1);\n mh=zeros(size(xt,1),ntime,nmc);\n mS=zeros(size(xt,1),ntime,nmc);\n for i1=1:nmc\n Gp = take_nth(gp,i1);\n [mh(:,:,i1), mS(:,:,i1)]=pred_coxphhs(Gp, x, y, xt, varargin{:});\n end\n % combine predictions\n mh=mean(mh,3);\n mS=mean(mS,3);\n return\nend\n\n[Ef1, Ef2, Covf] = pred_coxph(gp,x,y,xt, varargin{:});\nnsamps = 10000; \nif isfield(gp.lik, 'stratificationVariables')\n ind_str=gp.lik.stratificationVariables;\n ux=unique([x(:,ind_str); xt(:,ind_str)],'rows');\n nu=size(ux,1);\n for i1=1:size(ux,1)\n uind{i1}=find(xt(:,ind_str)==ux(i1,:));\n end\n nf1=ntime*nu;\nelse\n nf1=ntime;\nend\nsd=gp.lik.stime(2)-gp.lik.stime(1);\n\nSigm_tmp=Covf;\nSigm_tmp=(Sigm_tmp+Sigm_tmp')./2;\n% f_star=mvnrnd(Ef1, Sigm_tmp(1:ntime,1:ntime), nsamps);\nf_star=mvnrnd([Ef1;Ef2], Sigm_tmp, nsamps);\n\nf1=f_star(:,1:nf1);\nf2=f_star(:,(nf1+1):end);\n\nla1=exp(f1);\neta2=exp(f2);\n\nif ~isfield(gp.lik, 'stratificationVariables')\n hb=(la1'*sd);\n cumsumtmp=cumsum(hb)';\n for i1=1:size(eta2,2)\n mh(i1,:)=mean(bsxfun(@times,hb',eta2(:,i1)));\n Stime=exp(-bsxfun(@times,cumsumtmp,eta2(:,i1)));\n mS(i1,:)=mean(Stime);\n end\nelse\n for i2=1:length(uind)\n hb=(la1(:,(i2-1)*ntime+1:i2*ntime)'*sd);\n cumsumtmp=cumsum(hb)';\n for i1=1:size(uind{i2},1)\n ind=uind{i2}(i1);\n mh(ind,:)=mean(bsxfun(@times,hb',eta2(:,ind)));\n Stime=exp(-bsxfun(@times,cumsumtmp,eta2(:,ind)));\n mS(ind,:)=mean(Stime);\n end\n end\nend\n\n\n\nend\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/gp/pred_coxphhs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4870550803087373}} {"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": "\nfunction [GAmp,GTime]=GxRadial(p)\n\nglobal VCtl;\nglobal VObj;\nglobal VVar;\n\nt1Start=p.t1Start;\nt2Middle=p.t2Middle;\nt3Start=p.t3Start;\ntRamp=p.tRamp;\nGx1Sign=p.Gx1Sign;\nGx2Sign=p.Gx2Sign;\nGx3Sign=p.Gx3Sign;\n\n% 2D radial encoding\nFOV = VCtl.FOVFreq; % choose FOVFreq as real FOV\nRes = VCtl.ResFreq; % choose ResFreq as real resolution\n\nswitch VCtl.R_AngPattern\n case 'Linear'\n eval(['R_AngRange=' VCtl.R_AngRange ';']);\n AngInc = R_AngRange / VCtl.R_SpokeNum;\n case 'Golden'\n AngInc = 111.246 * (pi/180); % Golden-angle sample\nend\n\nGxAmp=(1/FOV)/((VObj.Gyro/(2*pi))*(1/VCtl.BandWidth));\ntHalf=1/(2*(VObj.Gyro/(2*pi))*GxAmp*(FOV/Res));\n[GAmp1,GTime1]=StdTrap(t1Start-tRamp, ...\n t1Start+tHalf+tRamp, ...\n t1Start, ...\n t1Start+tHalf, ...\n GxAmp*cos(AngInc * (VVar.PhaseCount - 1))*Gx1Sign,2,2,2);\n[GAmp2,GTime2]=StdTrap(t2Middle+VCtl.TEAnchorTime-tHalf-tRamp, ...\n t2Middle+VCtl.TEAnchorTime+tHalf+tRamp, ...\n t2Middle+VCtl.TEAnchorTime-tHalf, ...\n t2Middle+VCtl.TEAnchorTime+tHalf, ...\n GxAmp*cos(AngInc * (VVar.PhaseCount - 1))*Gx2Sign,2,2,2);\n[GAmp3,GTime3]=StdTrap(t3Start-tRamp, ...\n t3Start+tHalf+tRamp, ...\n t3Start, ...\n t3Start+tHalf, ...\n GxAmp*cos(AngInc * (VVar.PhaseCount - 1))*Gx3Sign,2,2,2);\n \nGAmp=GAmp2;\nGTime=GTime2;\n\nif Gx1Sign~=0\n GAmp=[GAmp1, GAmp];\n GTime=[GTime1, GTime];\nend\n\nif Gx3Sign~=0\n GAmp=[GAmp, GAmp3];\n GTime=[GTime, GTime3];\nend\n\n[GTime,m,n]=unique(GTime);\nGAmp=GAmp(m);\n\n\nend\n", "meta": {"author": "leoliuf", "repo": "MRiLab", "sha": "5cdcf1f7b67759700685d3a26ffeb70e55325567", "save_path": "github-repos/MATLAB/leoliuf-MRiLab", "path": "github-repos/MATLAB/leoliuf-MRiLab/MRiLab-5cdcf1f7b67759700685d3a26ffeb70e55325567/Macro/SeqElem/GxR/GxRadial.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.4869110640457778}} {"text": "% Script to scale a phase map so that max = pi and min =-pi radians.\n% Writes out scaled image prepended with 'sc'.\n% Chloe Hutton 25/02/04\n% SPM Update - 13/11/06\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Chloe Hutton\n% $Id: pm_scale_phase.m 4446 2011-08-30 10:50:29Z guillaume $\n\n\nV = spm_vol(spm_select(1,'image','Select phase image to scale'));\nvol = spm_read_vols(V);\n\nmn = min(vol(:));\nmx = max(vol(:));\nsvol = -pi+(vol-mn)*2*pi/(mx-mn);\n\n% Output image struct\noV = struct(...\n 'fname', spm_file(V.fname,'prefix','sc'),...\n 'dim', V.dim(1:3),...\n 'dt', [4 spm_platform('bigend')],...\n 'mat', V.mat,...\n 'descrip', 'Scaled phase');\n\nspm_write_vol(oV,svol);\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/FieldMap/pm_scale_phase.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4868415847773131}} {"text": "\nmaxiter = 20;\nrestartProb = 0.50;\ndim_drug = 100;\ndim_prot = 400;\n\ndrugNets = {'Sim_mat_drug_drug', 'Sim_mat_drug_disease', 'Sim_mat_drug_se', 'Sim_mat_Drugs'};\nproteinNets = {'Sim_mat_protein_protein', 'Sim_mat_protein_disease', 'Sim_mat_Proteins'};\n\ntic\nX = DCA(drugNets, dim_drug, restartProb, maxiter);\ntoc\ntic\nY = DCA(proteinNets, dim_prot, restartProb, maxiter);\ntoc\n\ndlmwrite(['../feature/drug_vector_d', num2str(dim_drug), '.txt'], X, '\\t');\ndlmwrite(['../feature/protein_vector_d', num2str(dim_prot), '.txt'], Y, '\\t');\n", "meta": {"author": "luoyunan", "repo": "DTINet", "sha": "725c5d04db5cc342eb4d84bce2872db0cfd6da8c", "save_path": "github-repos/MATLAB/luoyunan-DTINet", "path": "github-repos/MATLAB/luoyunan-DTINet/DTINet-725c5d04db5cc342eb4d84bce2872db0cfd6da8c/src/run_DCA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4868415797488322}} {"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": "% lssep; \t\t\n% separate close local minimizers\n% and maybe add a few global points\n%\n\n\nnsep=0;\n\nwhile nsepnloc,\n % select nloc best interval midpoints\n ff=min(flist(ind),flist(ind-1));\n [ff,ind]=sort(ff);\n aa=aa(ind(1:nloc));\n end;\n for alp=aa,\n if prt>2, disp(['separate minimizer at ',num2str(alp)]); end;\n % new function value\n falp=feval(func,data,x+alp*p);\n alist=[alist,alp];flist=[flist,falp];\n nsep=nsep+1;\n if nsep>=nmin, break; end; \n end;\n lssort;\nend;\n\n% instead of unnecessary separation, add some global points\nfor times=1:nmin-nsep, \n lsnew;\t\t\t% extrapolation or split\nend;\n", "meta": {"author": "lacerbi", "repo": "optimviz", "sha": "2cc41c19ffeaaa9a23239f53d80691cf3599357d", "save_path": "github-repos/MATLAB/lacerbi-optimviz", "path": "github-repos/MATLAB/lacerbi-optimviz/optimviz-2cc41c19ffeaaa9a23239f53d80691cf3599357d/utils/mcs/gls/lssep.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.4866968190835878}} {"text": "function [result_features]=back_find_low_node_para(result_dir,nSubj,k_times,nROI,w,cross_val,ttest_p,midw_lasso)\n\n% This function aims to find features used in the classification, suitable\n% for the SR,SLR,SGR,GSR,WSR,WSGR,SSGSR network construction method. And it is also\n% suitable for the LOOCV or the 10-fold cross validation. The found\n% features can be applied on the visualization software to present the\n% important brain regions or links.\n% Input:\n% result_dir: the directory you want to store all the result files;\n% nSubj: number of subjects;\n% k_times: times of 10-fold cross validation;\n% nROI: number of ROIs \n% w: weight of each selected features;\n% cross_val: loocv or 10-fold;\n% ttest_pm,midw_lasso: the feature selection indexes of ttest or\n% lasso;\n% \n% Output:\n% result_features: cell array, consisting of the averaged weight and occurrence of the features;\n\n% Written by Zhen Zhou, zzstefan@email.unc.edu\n% IDEA lab, https://www.med.unc.edu/bric/ideagroup\n% Department of Radiology and BRIC, University of North Carolina at Chapel Hill\n\n\n\n\n% clear all\n% load SR_10_fold_middle.mat;\n% load SR_loocv_middle.mat;\n% cross_val='loocv';\n% ttest_p=feature_index_ttest;\n% midw_lasso=feature_index_lasso;\nfprintf('Begin contributing feature identification\\n');\nif strcmpi(cross_val,'10-fold')\n for i=1:size(ttest_p,1)\n for j=1:size(ttest_p,2)\n tmp=find(ttest_p{i,j}<0.05);\n tmp_b{i,j}=find(midw_lasso{i,j});\n index=tmp(tmp_b{i,j});\n for k=1:length(index)\n [first{i,j,k}(1),first{i,j,k}(2)]=find_elements(nROI,index(k));\n end\n end\n end\nelseif strcmpi(cross_val,'loocv')\n for i=1:length(ttest_p)\n tmp=find(ttest_p{i}<0.05);\n tmp_b{i}=find(midw_lasso{i});\n index=tmp(tmp_b{i});\n for k=1:length(index)\n [first{i,k}(1),first{i,k}(2)]=find_elements(nROI,index(k));\n end\n end\nend\n\n%first=cellfun(@(x) x',first,'UniformOutput',false);\ntemp=first(:);\n\n[a1,b,c]=unique(cellfun(@char,temp,'un',0));\nlo=histc(c,1:max(c));\nloo=lo(:)>1;\nout=[temp(b(loo)),num2cell(lo(loo))];\nout(1,:)=[];\n\n\nAll_link=out(find(cell2mat(out(:,2))>0),1);%find all links which exists in any one LOOCV fold\nif strcmpi(cross_val,'10-fold')\n for j=1:length(All_link)\n weight=[];\n temp_index=cell2mat(cellfun(@(x)isequal(x,All_link{j}),first,'un',0));\n ind=find(temp_index);\n [A,B,C]=ind2sub(size(temp_index),ind);\n for k=1:length(A)\n weight=[weight,w{A(k),B(k)}(C(k))];\n end\n all_weight(j)=mean(weight);\n end\nelseif strcmpi(cross_val,'loocv')\n for j=1:length(All_link)\n weight=[];\n temp_index=cell2mat(cellfun(@(x)isequal(x,All_link{j}),first,'un',0));\n [A,B]=find(temp_index);\n for k=1:length(A)\n weight=[weight,w{A(k)}(B(k))];\n end\n all_weight(j)=mean(weight);\n end\nend\n\nmatrix_1=zeros(nROI,nROI);\nmatrix_2=zeros(nROI,nROI);\nfor m=1:size(out,1)\n matrix_1(out{m,1}(1),out{m,1}(2))=all_weight(m);\n matrix_1(out{m,1}(2),out{m,1}(1))=all_weight(m);\n matrix_2(out{m,1}(1),out{m,1}(2))=out{m,2};\n matrix_2(out{m,1}(2),out{m,1}(1))=out{m,2};\nend\nresult_features{1}=matrix_1;\n\nif strcmpi(cross_val,'loocv')\n matrix_2=matrix_2/nSubj;\nelseif strcmpi(cross_val,'10-fold')\n matrix_2=matrix_2/(10*k_times);\nend\nresult_features{2}=matrix_2;\n\n\nfigure('visible','off');\nsubplot(1,2,1);\nimagesc(matrix_1);\ncolormap jet\ncolorbar\naxis square\nxlabel('ROI');\nylabel('ROI');\ntitle('Averaged weight');\n\nsubplot(1,2,2);\nimagesc(matrix_2);\ncolormap jet\ncolorbar\naxis square\nxlabel('ROI');\nylabel('ROI');\ntitle('Normalized occurence');\nprint(gcf,'-r1000','-dtiff',char(strcat(result_dir,'/result_features_weigthAndOccurence.tiff')));\n\n\nfprintf('End contributing feature identification\\n');\n", "meta": {"author": "zzstefan", "repo": "BrainNetClass", "sha": "556cda9516429a964100e1ac0bace4258194b4a1", "save_path": "github-repos/MATLAB/zzstefan-BrainNetClass", "path": "github-repos/MATLAB/zzstefan-BrainNetClass/BrainNetClass-556cda9516429a964100e1ac0bace4258194b4a1/Function/AddedFuntions/back_find_low_node_para.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.48668623603767797}} {"text": "function obj = createRaster(obj, varargin)\n% CREATERASTER Create raster from point cloud.\n\n% Input parsing ----------------------------------------------------------------\n\nvalidRasterValue = {'average' 'linear' 'mask' 'plane'};\n\np = inputParser;\np.addParameter('CellSize' , 1 , @(x) isnumeric(x) && x>0);\np.addParameter('RasterValue' , 'average', @(x) any(strcmpi(x, validRasterValue)));\np.addParameter('SearchRadius' , 3 , @(x) isnumeric(x) && x>0); % for 'RasterValue' 'average' and 'plane'\np.parse(varargin{:});\np = p.Results;\n\n% Start ------------------------------------------------------------------------\n\nprocHierarchy = {'POINTCLOUD' 'RASTER'};\nmsg('S', procHierarchy);\nmsg('I', procHierarchy, sprintf('Point cloud label = ''%s''', obj.label));\nmsg('I', procHierarchy, sprintf('IN: RasterValue = ''%s''', p.RasterValue));\nmsg('V', p.CellSize, 'IN: CellSize', 'Prec', 2);\nif any(strcmpi(p.RasterValue, {'average' 'plane'}))\n msg('V', p.SearchRadius, 'IN: SearchRadius', 'Prec', 2);\nend\n\n% Create query points ----------------------------------------------------------\n\n% Origin (lower left point) of points\nlim.min = min(obj.X(obj.act,[1 2]));\n% Round origin (raster maps have coincident cell centers if mod(100, p.CellSize) == 0)\nlim.min = (floor(lim.min/100))*100;\n\n% Find raster cells in which points lie (starts with 0/0 at lower left corner (o))\n% +-----+-----+-----+\n% + 1/0 | 1/1 | 1/2 |\n% +-----+-----+-----+\n% + 0/0 | 0/1 | 0/2 |\n% o-----+-----+-----+\nrowCol = [floor((obj.X(obj.act,1)-lim.min(1))/p.CellSize) ...\n floor((obj.X(obj.act,2)-lim.min(2))/p.CellSize)];\n\n% Remove multiple points\nrowCol = unique(rowCol, 'rows');\n\n% Transformation of indices to coordinate system ('query points')\nxq = lim.min(1)+p.CellSize/2+rowCol(:,1)*p.CellSize;\nyq = lim.min(2)+p.CellSize/2+rowCol(:,2)*p.CellSize;\n\n% Assign RasterValue -----------------------------------------------------------\n\n% Moving average\nif strcmpi(p.RasterValue, 'average')\n idxAct = find(obj.act);\n ns = createns(obj.X(idxAct,[1 2]));\n idxSearchRadius = ns.rangesearch([xq yq], p.SearchRadius);\n zq = cellfun(@(x) mean(obj.X(idxAct(x),3)), idxSearchRadius);\nend\n\n% Linear interpolation\nif strcmpi(p.RasterValue, 'linear')\n F = scatteredInterpolant(obj.X(obj.act,1), obj.X(obj.act,2), obj.X(obj.act,3), 'linear', 'none');\n zq = F(xq, yq);\nend\n\n% Mask\nif strcmpi(p.RasterValue, 'Mask')\n zq = 1;\nend\n\n% Moving planes\nif strcmpi(p.RasterValue, 'plane')\n idxAct = find(obj.act);\n msg('S', {procHierarchy{:} 'BUILD 2D KD-TREE'});\n ns = createns(obj.X(idxAct,[1 2]));\n msg('E', {procHierarchy{:} 'BUILD 2D KD-TREE'});\n msg('S', {procHierarchy{:} 'NNSEARCH'});\n idxSearchRadius = ns.rangesearch([xq yq], p.SearchRadius);\n msg('E', {procHierarchy{:} 'NNSEARCH'});\n\n msg('S', {procHierarchy{:} 'PLANE INTERPOLATION'});\n for c = 1:numel(xq)\n\n x = obj.X(idxAct(idxSearchRadius{c}),1);\n y = obj.X(idxAct(idxSearchRadius{c}),2);\n z = obj.X(idxAct(idxSearchRadius{c}),3);\n\n xm = mean(x);\n ym = mean(y);\n zm = mean(z);\n\n C = cov([x-xm, y-ym, z-zm]);\n [V, ~] = eig(C);\n n = V(:,1);\n\n if numel(n) ~= 3\n zq(c) = NaN;\n else\n zq(c) = zm - (n(1)*(xq(c)-xm) + n(2)*(yq(c)-ym)) / n(3);\n end\n\n end\n msg('E', {procHierarchy{:} 'PLANE INTERPOLATION'});\n\nend\n\n% Create GeoTiff ---------------------------------------------------------------\n\n% Size of data array\nsizeA = max(rowCol)-min(rowCol)+1;\n\n% World matrix\nW = [p.CellSize 0 min(xq)\n 0 -p.CellSize max(yq)];\n\n% Create spatialref.MapRasterReference object for GeoTiff\nR = maprasterref(W, [sizeA(2) sizeA(1)]); % cols -> x, rows -> y\n\n% Initialize data array with noData values\nA = NaN(sizeA);\n\n% Linear indices\nidxLin = sub2ind(size(A), rowCol(:,1)-min(rowCol(:,1))+1, ...\n rowCol(:,2)-min(rowCol(:,2))+1);\n\n% Set data values\nA(idxLin) = zq;\n\n% Transform A, so that element 1,1 is upper, left corner (min(xq), max(yq))\nA = flipud(A');\n\n% Raster reduction point\nif strcmpi(p.RasterValue, 'mask')\n RedPoi = [obj.redPoi(1) obj.redPoi(2) 0]; % no height reduction\nelse\n RedPoi = obj.redPoi;\nend\n\n% Add grid object to pointCloud object\nobj.raster = raster({A R}, ...\n obj.label, ...\n 'RedPoi', RedPoi);\n\n% End --------------------------------------------------------------------------\n\nmsg('E', procHierarchy);\n\n% 4Debug -----------------------------------------------------------------------\n\n% save2('n:\\Dropbox\\Matlab\\Scripts\\2013_05\\testgrid.xyz', [xq yq zeros(numel(xq),1)], '%.3f %.3f %.3f\\n');\n\nend", "meta": {"author": "pglira", "repo": "Point_cloud_tools_for_Matlab", "sha": "4768f45e7d3527c52e911eb0450c31ca19b58f72", "save_path": "github-repos/MATLAB/pglira-Point_cloud_tools_for_Matlab", "path": "github-repos/MATLAB/pglira-Point_cloud_tools_for_Matlab/Point_cloud_tools_for_Matlab-4768f45e7d3527c52e911eb0450c31ca19b58f72/classes/@pointCloud/createRaster.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.48668623165225844}} {"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 [Hkt, cx, cy, Wxk] = loglikGaPreadparamWfix(x,qqq)\n% [Hkt, cx, cy, Wxk] = loglikGaPreadparam(varargin);\n\nsigpsf = qqq{2}; %std deviation of the PSF gaussian approx\npeval = qqq{5}; %parameters\n% Hkt_linear=x(1:end-peval.ncomp*2); % intensities\n% cx=x(end-peval.ncomp*2+1:end-peval.ncomp); %x-coordinates of the centers\n% cy=x(end-peval.ncomp+1:end); % y-coordinates of the centers\n% Hkt_linear=qqq{6}; % intensities\nHkt_linear=x; % intensities\ncx= qqq{6};\ncy= qqq{7};\n\nsigpsf_vec=repmat(sigpsf,peval.ncomp,1); %all psfs same sigma\n\n% this is anoying as it depends when the simulation was performed/... grr\ncxy_vec=[cx'+1, cy'+1]; %different notation of the dip_image/new version\n% cxy_vec=[cx'+0.5, cy'+0.5]; %different notation of the dip_image/old version\na_vec=1./(sigpsf_vec.^2*2*pi); % all normalised to 1\n\nHkt=reshape(Hkt_linear, peval.ncomp, peval.nt);\n% generate PSFs from given parameters:\nWxkpix=gauss2dmultislice([peval.nx, peval.ny, peval.ncomp], cxy_vec, sigpsf_vec, a_vec);\nWxkpix=normalizePSF(Wxkpix); %normalize PSFs to 1\nWxk=reshape(Wxkpix,peval.nx*peval.ny, peval.ncomp);\nend\n\nfunction Wnorm=normalizePSF(W)\nsw=size(W);\nif numel(sw)<3 %if ncomp=1... \n sw(3) = 1;\nend\nWr=reshape(W, sw(1)*sw(2),sw(3));\nq=squeeze(sum(Wr,1));\nWrnorm=Wr./repmat(q,sw(1)*sw(2),1);\nWnorm=reshape(Wrnorm,sw(1), sw(2), sw(3));\nend\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/conjgradfunctions/loglikGaPreadparamWfix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4866044463458908}} {"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 [ node_coord, node_att, node_marker ] = triangle_node_data_example ( ...\n node_num, node_dim, node_att_num, node_marker_num )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_NODE_DATA_EXAMPLE returns the node information for the example.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 October 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NODE_NUM, the number of nodes.\n%\n% Input, integer NODE_DIM, the spatial dimension.\n%\n% Input, integer NODE_ATT_NUM, number of node attributes \n% listed on each node record.\n%\n% Input, integer NODE_MARKER_NUM, 1 if every node record \n% includes a final boundary marker value.\n%\n% Output, real NODE_COORD(NODE_DIM,NODE_NUM), the nodal \n% coordinates.\n%\n% Output, real NODE_ATT(NODE_ATT_NUM,NODE_NUM), the nodal \n% attributes.\n%\n% Output, integer NODE_MARKER(NODE_MARKER_NUM,NODE_NUM), \n% the node markers.\n%\n node_coord = [ ...\n 0.0, 0.0; ...\n 1.0, 0.0; ...\n 2.0, 0.0; ...\n 3.0, 0.0; ...\n 4.0, 0.0; ...\n 0.0, 1.0; ...\n 1.0, 1.0; ...\n 2.0, 1.0; ...\n 3.0, 1.0; ...\n 4.0, 1.0; ...\n 0.0, 2.0; ...\n 1.0, 2.0; ...\n 2.0, 2.0; ...\n 3.0, 2.0; ...\n 4.0, 2.0; ...\n 0.0, 3.0; ...\n 1.0, 3.0; ...\n 2.0, 3.0; ...\n 0.0, 4.0; ...\n 1.0, 4.0; ...\n 2.0, 4.0 ]';\n\n node_att = [];\n\n node_marker = [ ...\n 1; 1; 1; 1; 1; 1; 0; 0; 0; 1; ...\n 1; 0; 0; 1; 1; 1; 0; 1; 1; 1; ...\n 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/triangle_io/triangle_node_data_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.7025300636233415, "lm_q1q2_score": 0.4866018164798436}} {"text": "%ADDCIRCLE Add a circle to the current plot\n%\n% addcircle(center, radius)\n% addcircle(center, radius, linestyle)\n%\n% Returns the graphics handle for the circle.\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 h = addcircle(center, radius, varargin)\n\n\tn = 100;\n\n\tth = [0:n]'/n*2*pi;\n\tcth = cos(th);\n\tsth = sin(th);\n\n ih = ishold;\n hold on\n handles = []; % list of handles for circles\n\n for i=1:numrows(center)\n handles = [handles; patch(radius(i)*cos(th)+center(i,1), radius(i)*sin(th)+center(i,2), varargin{:})];\n end\n if ih == 0,\n hold off\n end\n\n if nargout > 0,\n h = handles;\n end\n\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/addcircle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.48660180325144653}} {"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": "% takes NimgFirstRegistration mean image and aligns it to itself\n% does nonrigid registration across specified blocks\n% returns mean image for registration\n\nfunction ops = nonrigidAlignIterative(data, ops)\n\n% uu = squeeze(sum(sum(data(:,:,:).^2,1),2));\n% [~, isort] = sort(uu, 'descend');\n% ops.mimg = data(:,:,isort(50));\n\n\n% take most correlated frames to compute initial mean image\nmimg = pick_reg_init(data);\n\nnumBlocks = numel(ops.yBL);\ndsold = zeros(size(data,3), 2, numBlocks);\nerr = zeros(ops.NiterPrealign, 1);\n%%\nfor i = 1:ops.NiterPrealign \n dsnew = zeros(size(data,3), 2, numBlocks,'double');\n Corr = zeros(size(data,3), numBlocks,'double');\n for ib = 1:numBlocks\n % collect ds\n ops.mimg = mimg(ops.yBL{ib},ops.xBL{ib});\n % compute offsets from each frame to mean image and subtract mean\n % offset (centered at offset = 0)\n\tif ops.kriging\n\t [dsnew(:,:,ib), Corr(:,ib)] = ...\n\t regoffKriging(data(ops.yBL{ib},ops.xBL{ib},:), ops, 1);\n\telse\n\t [dsnew(:,:,ib), Corr(:,ib)] = ...\n\t regoffLinear(data(ops.yBL{ib},ops.xBL{ib},:), ops, 1);\n\tend\n end\n \n % register frames\n dreg = nonrigidRegFrames(data, ops.xyMask, dsnew);\n \n % sort by correlation and take mean of most correlated frames\n [~, igood] = sort(mean(Corr,2), 'descend');\n if i 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 M = median_filter(im)\n % MEDIAN_FILTER simpler wrapper for calling medfilt2 on each channel\n %\n % M = median_filter(im)\n %\n % Input:\n % im w by h by c image\n % Output:\n % M median filtered image in each channel\n %\n\n % This could probably be a one-liner using num2cell and cellfun\n M = zeros(size(im));\n for c = 1 : size(im,3)\n M(:,:,c) = medfilt2(im(:,:,c));\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/imageprocessing/median_filter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.48650158843584385}} {"text": "\n% 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 qu = unit(q)\n%Quaternion.unit Unitize a quaternion\n%\n% QU = Q.unit() is a quaternion which is a unitized version of Q\n\n qu = q / norm(q);\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/unit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.4864541069842384}} {"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 calpak_test012 ( )\n\n%*****************************************************************************80\n%\n%% CALPAK_TEST012 tests JED_TO_YJF_ROMAN and YJF_TO_JED_ROMAN.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 08 March 2013\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CALPAK_TEST012\\n' );\n fprintf ( 1, ' For the Roman calendar:\\n' );\n fprintf ( 1, ' JED_TO_YJF_ROMAN: JED -> YJF.\\n' );\n fprintf ( 1, ' YJF_TO_JED_ROMAN: YJF -> JED.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' JED (in) YJF JED (out)\\n' );\n fprintf ( 1, '\\n' );\n\n jed_epoch = epoch_to_jed_roman ( );\n\n i = 0;\n\n while ( 1 )\n\n i = i + 1;\n jed1 = jed_test ( i );\n \n if ( jed1 < 0.0 )\n break\n end\n\n if ( jed_epoch <= jed1 )\n\n [ y2, j2, f2 ] = jed_to_yjf_roman ( jed1 );\n\n s2 = yjf_to_s_roman ( y2, j2, f2 );\n\n jed3 = yjf_to_jed_roman ( y2, j2, f2 );\n\n fprintf ( 1, ' %11.2f %20s %11.2f\\n', jed1, s2, jed3 );\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/calpak/calpak_test012.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.4864541011818112}} {"text": "function p = PlotHVLines(positions,direction,varargin)\n\n%PlotHVLines - Plot vertical (resp. horizontal) lines at listed x (resp. y).\n%\n% USAGE\n%\n% p = PlotHVLines(positions,direction,options)\n%\n% positions list of abscissae/ordinates\n% direction optional direction: 'h' or 'v' (default = 'v')\n% options for function plot\n%\n\n% Copyright (C) 2008-2012 by Micha\u00ebl Zugaro\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 3 of the License, or\n% (at your option) any later version.\n\nif nargin < 1,\n \terror('Incorrect number of parameters (type ''help PlotHVLines'' for details).');\nend\nif nargin < 2,\n\tdirection = 'v';\nelse\n\tdirection = lower(direction);\nend\nif min(size(positions)) > 2,\n \terror('List of abscissae/ordinates is not a vector (type ''help PlotHVLines'' for details).');\nelse\n\tpositions = positions(:);\nend\n\nif ~isstring_FMAT(direction,'h','v'),\n\tvarargin = {direction,varargin{:}};\n\tdirection = 'v';\nend\n\nhold on;\nif strcmp(direction,'v'),\n\tyLim = ylim;\n\tfor i = 1:size(positions,1),\n\t\tplot([positions(i,1) positions(i,1)],yLim,varargin{:});\n\tend\nelse\n\txLim = xlim;\n\tfor i = 1:size(positions,1),\n\t\tplot(xLim,[positions(i,1) positions(i,1)],varargin{:});\n\tend\nend", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/FMAToolbox/Plot/PlotHVLines.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.48645410118181115}} {"text": "function layer2colors=riverplot_recolor_layer2(sim_matrix,layer1colors)\n\n\n% ..\n% Programmers' notes:\n% List dates and changes here, and author of changes\n% Created July 2016 by Tor Wager\n% \n% 8/21/2017 Stephan Geuter\n% changed normalization to used absolute similarity values (l21). Before, negative\n% values could distort the normalization factor resulting RGB values\n% outside the [0-1] interval. \n% ..\n\n\n\n[n2, n1]=size(sim_matrix);\nfor i=1:n2\n temp_color=[0 0 0];\n for j=1:n1\n temp_color= temp_color + layer1colors{j}*abs(sim_matrix(i,j))/sum(abs(sim_matrix(i,:)));\n end\n \n if any(isnan(temp_color));\n temp_color=[.5 .5 .5]; \n end\n layer2colors{i}=temp_color;\nend", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Visualization_functions/riverplot/riverplot_recolor_layer2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.4864540972828432}} {"text": "function Pset=str2poly(strcell,varnames)\n% POLY2STR - convert multivariate polynomials from strings to arrays\n% usage: Pset=poly2str(strcell,varnames)\n%\n% INPUTS: strcell, varnames\n% strcell is a cell array of strings, one per polynomial\n% all numbers must be whole or decimal form (no scientific notation)\n% brackets and double negatives are not allowed.\n% All spaces in the strings are ignored.\n% varnames (optional) is a cell array of strings which must include all\n% variable names that occur in strcell [default: {'x1','x2',...}]\n%\n% OUTPUTS: Pset\n% Pset is a cell array of polynomial coefficients where row j of Pset{i}\n% is [c,k1,k2,...] representing the monomial c*x1^k1*x2^k2*...\n%\n% EXAMPLE:\n% str2poly({'x1*x2^2'}) % returns {[1,1,2]}\n% str2poly({'-x1*x2^2'}) % returns {[-1,1,2]}\n% str2poly({'-1*x1*x2^2'}) % returns {[-1,1,2]}\n% str2poly({'- 1 * x 1 * x 2 ^ 2'}) % returns {[-1,1,2]}\n%\n% SEE ALSO:\n% groebner, poly2str\n\n% Author: Ben Petschel 19/6/2009\n%\n% Change history:\n% 19/6/2009 - first release\n% 22/6/2009 - fixed bug in handling \"-x1\" etc.\n% 17/7/2009 - allow whitespace in strings\n% 20/3/2010 - changed array representation to rectangular instead of n-d\n\nif nargin<2,\n varnames = {}; % will fill in varnames later, as needed\nend;\nPset = cell(size(strcell));\n\nfor i=1:numel(strcell),\n str = strcell{i};\n \n % ignore all spaces\n remain = str;\n remain = strrep(remain,' ','');\n \n % first insert \"+\" before every \"-\", for easier term separation later\n str = '';\n while ~isempty(remain),\n if remain(1)=='-',\n if isempty(str),\n str = '-';\n else\n str = [str,'+-'];\n end;\n end;\n [tok,remain]=strtok(remain,'-');\n str = [str,tok];\n end;\n \n % now separate into terms\n remain = str;\n terms = [];\n while ~isempty(remain),\n coeff = 1;\n exps = [];\n [term,remain]=strtok(remain,'+');\n % process term, separating into products\n rem2 = term;\n while ~isempty(rem2),\n [part,rem2]=strtok(rem2,'*');\n if ~isnan(str2double(part)),\n % part is a number, multiply it by the coefficient\n coeff = coeff * str2double(part);\n else\n % part is var^n or var or -var^n or -var\n if part(1)=='-',\n coeff = -coeff;\n part=part(2:end);\n if isempty(part),\n error('isolated minus sign');\n end;\n end;\n ind = find(part=='^');\n if isempty(ind),\n var = part;\n expo = 1;\n else\n ind = ind(1);\n var = part(1:ind-1);\n expo = str2double(part(ind+1:end));\n if isnan(expo),\n % exponent is not valid\n error('invalid exponent in part %s',part);\n end;\n end;\n if isempty(varnames),\n % see if var is of form 'x1' etc\n if (length(var)>1) && (var(1)=='x') && ~isnan(str2double(var(2:end))),\n % variable name is ok\n k = str2double(var(2:end));\n else\n error('variable name not of form \"x1\",\"x2\",...');\n end;\n else\n ind = strmatch(var,varnames);\n if isempty(ind),\n error('variable name not in list');\n end;\n k = ind(1);\n end;\n if length(exps) 0) \n AC{block,1} = 'LP';\n AC{block,2} = K.l;\n A = At(top:top+n-1,:);\n CC = c(top:top+n-1,:);\n AC{block,3} = [-A(:,1:m) CC(:,1)];\n block = block+1;\n top = top+K.l;\n end\n if (K.q > 0) \n error(' Cannot accept SOCP cones\\n');\n end\n\n if (K.s > 0) \n for i = 1:length(K.s)\n n = K.s(i);\n AC{block,1} = 'SDP';\n AC{block,2} = n;\n A = At(top:top+n^2-1,:);\n CC = c(top:top+n^2-1,:);\n indicies = triu(reshape(1:n^2,n,n));\n indicies = indicies(find(indicies));\n AC{block,3} = [-A(indicies,1:m) CC(indicies,1)];\n block = block+1;\n top = top+n*n;\n end\n end \n \n%%\n\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/OptiToolbox/Solvers/dsdp/distribution/matlab/readsedumi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658109754052, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4864510252089266}} {"text": "function [LOSS, CSP, LDA] = MI_calibration_2(file,band,fs,interval,varargin)\n\nopt=opt_cellToStruct(varargin{:});\ncls=opt.nClass;\nswitch cls\n case 2\n marker={'1','right';'2','left'};\n case 3\n marker={'1','right';'2','left';'3','foot'};\n case 4\n marker={'1','right';'2','left';'3','foot';'4','rest'};\nend\nfield={'x','t','fs','y_dec','y_logic','y_class','class', 'chan'};\n[EEG.data, EEG.marker, EEG.info]=Load_EEG(file,{'device','brainVision';'marker',marker;'fs',fs});\nCNT_=opt_eegStruct({EEG.data, EEG.marker, EEG.info}, field);\n\nif ~isfield(opt,'channel'),opt.channel=1:EEG.data.nCh;end\nif ~isfield(opt,'erd'),opt.erd=0;end\n\n% cross validation parameters\nCV.var.band=band;\nCV.var.interval=interval;\nCV.var.fv='logvar'; % temp\nCV.var.classfier='LDA'; % temp\nCV.var.evaluation='KFold'; % temp\nCV.var.k=5; % temp\nCV.prep={\n 'CNT=prep_filter(CNT, {\"frequency\", band})'\n 'SMT=prep_segmentation(CNT, {\"interval\", interval})'\n };\nCV.train={\n '[SMT, CSP_W, CSP_D]=func_csp(SMT,{\"nPatterns\", [3]})'\n 'FT=func_featureExtraction(SMT, {\"feature\",fv})'\n '[CF_PARAM]=func_train(FT,{\"classifier\",classfier})'\n };\nCV.test={\n 'SMT=func_projection(SMT, CSP_W)'\n 'FT=func_featureExtraction(SMT, {\"feature\",fv})'\n '[cf_out]=func_predict(FT, CF_PARAM)'\n };\nCV.option={\n 'evaluation' , 'k'\n };\n\nn=size(CNT_.class,1);\npairIndex=[];\nfor i=1:(n-1)\n pairIndex=[pairIndex,[1:i;(1:i)+(n-i)]];\nend\n[~,I]=sort(sum(pairIndex));\npairIndex=pairIndex(:,I);\npairClass=cell(size(pairIndex));\nfor i=1:length(pairClass(:))\n pairClass{i}=CNT_.class(pairIndex(i),2);\nend\npairNum=size(pairIndex,2);\nLOSS=cell(pairNum,2);\nCSP=cell(pairNum,2);\nLDA=cell(pairNum,2);\n\nfor pair=1:pairNum\n\n pairstr=sprintf('%s vs %s',char(pairClass{1,pair}),char(pairClass{2,pair}));\n disp(pairstr);\n \n CNT=prep_selectClass(CNT_,{'class',{pairClass{1,pair}, pairClass{2,pair}}});\n CNT=prep_selectChannels(CNT,{'Index',opt.channel});\n \n %% Pre-processing module\n CNT=prep_filter(CNT, {'frequency', band});\n SMT=prep_segmentation(CNT, {'interval', interval});\n \n %% Spatial-frequency optimization module\n [SMT, CSP_W, CSP_D]=func_csp(SMT,{'nPatterns', [3]});\n FT=func_featureExtraction(SMT, {'feature',CV.var.fv});\n \n %% Classifier module\n [CF_PARAM]=func_train(FT,{'classifier',CV.var.classfier});\n \n %% Evaluation\n [loss]=eval_crossValidation_(CNT, CV);\n \n CSP{pair,1}=CSP_W; CSP{pair,2}=pairstr;\n LDA{pair,1}=CF_PARAM; LDA{pair,2}=pairstr;\n LOSS{pair,1}=loss;LOSS{pair,2}=pairstr;\n \n \nend\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/Paradigm/MI/MI_calibration_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4864510192840863}} {"text": "function y = h2y(h)\n\n% Y = h2y(H)\n%\n% Hybrid-H to Admittance transformation\n%\n% H and Y are matrices of size [2,2,F]\n% where F is the number of frequencies\n\n% 30.09.2011 - better 0-protection, faster division\n% add multiple frequencies (old: martie 27)\n\nif any(h(1,1,:) == 0)\n disp('h2y > correspondent admittance matrix non-existent');\nelse\n y = zeros(size(h));\n den = 1./h(1,1,:);\n y(1,1,:) = den;\n y(1,2,:) = -h(1,2,:).*den;\n y(2,1,:) = h(2,1,:).*den;\n y(2,2,:) = h(2,2,:) - h(1,2,:).*h(2,1,:).*den;\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/h2y.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.48645101335924595}} {"text": "function [x,pnum,pgauss] = spm_mci_postslices (post,M,U,Y,Nbins)\n% Univariate slices through posterior density\n% FORMAT [x,pnum,pgauss] = spm_mci_postslices (post,M,U,Y,Nbins)\n%\n% post posterior data structure\n% M,U,Y as usual\n% Nbins Number of bins per dimension\n%\n% x [Np x Nbins] matrix where x(p,:) is domain for pth variable\n% pnum [Np x Nbins] where pnum(p,j) = p(x(p)=xj|x(\\p),Y) ie. the posterior\n% density of variable p conditioned on the posterior mean of the other\n% variables. This is estimated numerically from evaluation of log joint\n% pgauss As pnum but under assumption that posterior is multivariate Gaussian\n%__________________________________________________________________________\n% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny\n% $Id: spm_mci_postslices.m 6697 2016-01-27 14:57:28Z spm $\n\ntry, Nbins=Nbins; catch, Nbins=50; end\n\nk=5; % Defines width of domain in number of SDs\n\n% For computing log prior term\nM = spm_mci_priors (M);\nM = spm_mci_minit (M);\n\n% Need high tolerances to avoid drop-outs in log-joint plots\nM.reltol=1e-6;\nM.abstol=1e-6;\n\nNp=length(post.Ep);\nEp=post.Ep;\ns=sqrt(diag(post.Cp));\npE=spm_vec(M.pE);\nfor p=1:Np,\n xmin=Ep(p)-k*s(p);\n xmax=Ep(p)+k*s(p);\n x(p,:)=linspace(xmin,xmax,Nbins);\n P = Ep;\n for j=1:Nbins,\n % Get parameters in eigenspace of prior\n P(p) = x(p,j);\n par = M.V'*(P-pE);\n eq(j) = spm_mci_joint (par,M,U,Y);\n pg(j) = spm_mvNpdf(P,Ep,post.Cp);\n end\n eq=exp(eq);\n pnum(p,:)=eq/sum(eq);\n pgauss(p,:)=pg/sum(pg);\nend\n\nfigure\nfor i=1:Np,\n subplot(Np,1,i);\n plot(x(i,:),pgauss(i,:),'r');\n hold on\n plot(x(i,:),pnum(i,:),'k');\n legend('Gaussian','Numeric');\n xlabel(sprintf('P(%d)',i));\nend", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/mci/inference/spm_mci_postslices.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.48644001190483266}} {"text": "function view = computeSpatialGradient(view)\n%\n% view = computeSpatialGradient(view)\n%\n% Loads the meanMap, then uses estFilIntGrad to compute the spatial gradient.\n%\n% To use this spatial gradient for inhomogeneity correction,\n% - set dataTYPES(*).blockedAnalysis(*).inhomoCorrect = 2\n% - load spatial gradient (from the File menu)\n% - compute corAnal (from the Analysis menu)\n%\n% djh, 7/11/01\n% Ress, 04/05 Modified to allow NaNs in meanMap.\n\n% Tried various alternatives for computing spatial gradient:\n% - more blurring in estFilIntGrad\n% [not much difference]\n% - aniso3\n% [looks essentially like no blurring]\n% - do nothing\n% [looks a lot like estFilIntGrad, except for a scale factor]\n\n% Load meanMap from spatialGradMap.mat, if it exists\nview = loadMeanMap(view);\n\n% Initialize to empty cell array\nnScans = numScans(view);\nmap = cell(1,nScans);\n\n%% Compute the robust estimate of spatial gradient from meanMap\n% put up a mrvWaitbar if needed\nverbose = prefsVerboseCheck;\nif verbose\n waitHandle = mrvWaitbar(0,'Computing spatial gradient from mean images. Please wait...');\nend\n\n% main loop: across scans\nfor iScan = 1:nScans\n map1 = view.map{iScan};\n map1(~isfinite(map1)) = min(map1(:));\n map{iScan} = estFilIntGrad(map1);\n %map{iScan} = estPolIntGrad(view.map{iScan},[3,3,3],1);\n %map{iScan} = aniso3(view.map{iScan},'tukeyPsi',100,100);\n\n % a 2nd check for non-finite values is necessary (e.g., for motioncomp\n % data)\n map{iScan}( isnan(map{iScan}) | isinf(map{iScan}) ) = min(map1(:));\n\n if verbose, mrvWaitbar(iScan/nScans); end\nend\n\nif verbose\n close(waitHandle);\nend\n\n% Initial save; so if setParameterMap fails we're not screwed\nmapName = 'spatialGrad';\nsave( fullfile(dataDir(view), 'spatialGrad.mat'), 'map', 'mapName' );\n\n% Set parameter map\nview = setParameterMap(view,map,'spatialGrad');\n\n% Save file (again)\nsaveParameterMap(view);\n\nreturn\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/SignalProc/computeSpatialGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.48644001190483266}} {"text": "function ll = fgplvmLogLikelihood(model)\n\n% FGPLVMLOGLIKELIHOOD Log-likelihood for a GP-LVM.\n% FORMAT\n% DESC returns the log likelihood for a given GP-LVM model.\n% ARG model : the model for which the log likelihood is to be\n% computed. The model contains the data for which the likelihood is\n% being computed in the 'y' component of the structure.\n% RETURN ll : the log likelihood of the data given the model.\n%\n% COPYRIGHT : Neil D. Lawrence, 2005, 2006, 2009\n%\n% SEEALSO : gpLogLikelihood, fgplvmCreate\n%\n% MODIFICATIONS : Carl Henrik Ek, 2008, 2009\n%\n% FGPLVM\n\n \nll = gpLogLikelihood(model);\n\nif isfield(model, 'dynamics') && ~isempty(model.dynamics)\n % A dynamics model is being used.\n ll = ll + modelLogLikelihood(model.dynamics);\nelseif isfield(model, 'prior') && ~isempty(model.prior)\n for i = 1:model.N\n ll = ll + priorLogProb(model.prior, model.X(i, :));\n end\nend\n\nswitch model.approx\n case {'dtc', 'dtcvar', 'fitc', 'pitc'}\n if isfield(model, 'inducingPrior') && ~isempty(model.inducingPrior)\n for i = 1:model.k\n ll = ll + priorLogProb(model.inducingPrior, model.X_u(i, :)); \n end\n end\n otherwise\n % do nothing\nend\n\nif(isfield(model,'constraints')&&~isempty(model.constraints))\n for(i = 1:1:model.constraints.numConstraints)\n ll = ll + constraintLogLikelihood(model.constraints.comp{i},model.X);\n end\nend\n\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/fgplvm/fgplvmLogLikelihood.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4864400064098423}} {"text": "display('Testing data')\ntotal_test = cell(5+1,1);\ntest_folder = 'C:\\Users\\brend_000\\Documents\\MATLAB\\Machine Learning\\Ghost Target\\Images\\cambridge';\nfor x = 1:5\n display(['Reading img', num2str(x)])\n img = imread([test_folder,'\\img', num2str(x),'.jpg']);\n data = cell(8,8);\n mynxel = nxel(8,img);\n [a,b] = size(mynxel);\n for i = 1:a\n for j = 1:b\n data{i,j} = readImage(mynxel{i,j});\n end\n end\n total_test{1,1} = 'Image';\n total_test{x+1,1} = ['img',num2str(x)];\n total_test{1,2} = 'Feature';\n total_test{x+1,2} = data;\n \n load([test_folder,'_labels\\img',num2str(x),'.mat']);\n total_test{1,3} = 'Label Set';\n total_test{x+1,3} = imgLabel;\nend\nload('model.mat')\nload('pca_model')\n\n\n[x_test, y_test, accuracy, test_labels, confusion_matrix] = validate(total_test,model,'naive');\nsave('Results\\confusion_matrix_naive.mat','confusion_matrix');\n\n[x_test, y_test, accuracy, test_labels, pca_confusion_matrix] = validate(total_test,pca_model,'pca');\nsave('Results\\confusion_matrix_pca.mat','pca_confusion_matrix');\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u8bc6\u522b\u7b97\u6cd5/Ghost-Target-master/main_with_model.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4864400009148518}} {"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": "% Copyright 2017 Google Inc.\n%\n% Licensed under the Apache License, Version 2.0 (the \"License\");\n% you may not use this file except in compliance with the License.\n% You may obtain a copy of the License at\n%\n% https://www.apache.org/licenses/LICENSE-2.0\n%\n% Unless required by applicable law or agreed to in writing, software\n% distributed under the License is distributed on an \"AS IS\" BASIS,\n% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n% See the License for the specific language governing permissions and\n% limitations under the License.\n\n% Returns set of parameters\n% set light_mode = true to run the code in a sub optimal but faster mode\n% set light_mode = false to obtain the results reported in the RED paper\n\nfunction params = GetUniformDeblurSDParams(light_mode)\n\n% regularization factor\nparams.lambda = 0.02;\n\n% number of outer iterations\nif light_mode\n params.outer_iters = 500;\nelse\n params.outer_iters = 1500;\nend\n\n% level of noise assumed in the regularization-denoiser\nparams.effective_sigma = 3.25;\n\n", "meta": {"author": "google", "repo": "RED", "sha": "31142ab55ad37c25f6704f5bfe81e7fec39360f0", "save_path": "github-repos/MATLAB/google-RED", "path": "github-repos/MATLAB/google-RED/RED-31142ab55ad37c25f6704f5bfe81e7fec39360f0/parameters/GetUniformDeblurSDParams.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.4863626684698639}} {"text": "function test_ft_spike_jpsth()\n\n% MEM 2gb\n% WALLTIME 00:10:00\n% DEPENDENCY ft_spike_jpsth\n\n%%\n% 1 channelcmb with same latency, gamma\n% 1 channelcmb with fixed spike times\n% 1 channelcmb with shifted latency to see effect\n% 1 lfp channel\n% latencies equal\n\nspikesPerTrial = 10;\nnTrials = 10;\nshapePar = 2;\nscalePar = 3;\ntime = linspace(0, 1, 1000);\n\ndata.trial(1:nTrials) = {zeros(1, length(time))};\ndata.time(1:nTrials) = {time};\ndata.fsample = 1000;\n\nfor iTrial = 1:nTrials\n iUnit = 1; % lfp channel\n data.trial{iTrial}(iUnit, :) = rand(1, 1000);\n \n iUnit = 2;\n spikeTimes = [];\n while length(spikeTimes)1) = [];\n end\n spikeTimes = spikeTimes(1:spikesPerTrial);\n for iSpike = 1:length(spikeTimes)\n smp(iSpike) = nearest(time, spikeTimes(iSpike));\n end\n data.trial{iTrial}(iUnit, smp) = 1;\n data.trial{iTrial}(3, smp) = 1;\n \n iUnit = 4; % unit with fixed positions\n spikeTimes = spikeTimes + 0.01;\n smp = [];\n for iSpike = 1:length(spikeTimes)\n smp(iSpike) = nearest(time, spikeTimes(iSpike));\n end\n data.trial{iTrial}(iUnit, smp) = 1;\n \n iUnit = 5;\n spikeTimes = [];\n while length(spikeTimes)1) = [];\n end\n spikeTimes = spikeTimes(1:spikesPerTrial);\n for iSpike = 1:length(spikeTimes)\n smp(iSpike) = nearest(time, spikeTimes(iSpike));\n end\n data.trial{iTrial}(iUnit, smp) = 1;\n \n iUnit = 6;\n smp = [];\n spikeTimes = linspace(0.1, 0.9, 9);\n for iSpike = 1:length(spikeTimes)\n smp(iSpike) = nearest(time, spikeTimes(iSpike));\n end\n data.trial{iTrial}(iUnit:iUnit+1, smp) = 1;\n \n iUnit = 8;\n smp = [];\n spikeTimes = linspace(0.1, 0.9, 9)+0.01;\n for iSpike = 1:length(spikeTimes)\n smp(iSpike) = nearest(time, spikeTimes(iSpike));\n end\n data.trial{iTrial}(iUnit:iUnit+1, smp) = 1;\n \nend % for each trial\n\n\nfor iChan = 1:9\n data.label{iChan} = strcat('chan', num2str(iChan));\nend\n\n%%\n% show that the psth works also with the poisson format\n\ncfgDE.spikechannel = 2:9;\nspike = ft_checkdata(data, 'datatype', 'spike', 'feedback', 'yes');\n\n\n%%\n% we compute the psth by calling the psth function\ncfg = [];\ncfg.binsize = 0.003;\ncfg.outputunit = 'rate';\ncfg.keeptrials ='yes'; \npsth = ft_spike_psth(cfg, spike);\n\n%%\ncfg = [];\ncfg.method = 'jpsth';\ntic, jpsth = ft_spike_jpsth(cfg, psth);toc\n\n%%\nfigure\ncfg = [];\ncfg.interpolate = 4;\ncfg.window = 'gausswin';\ncfg.winlen = 0.02\ncfg.channelcmb = {jpsth.label{1}, jpsth.label{2}};\nft_spike_plot_jpsth(cfg, jpsth)\npause(1)\nclose all\n%%\nfigure\ncfg.channelcmb = {jpsth.label{1}, jpsth.label{3}};\nft_spike_plot_jpsth(cfg, jpsth)\n% note the shift along the diagonal\nfigure\ncfg = [];\ncfg.channelcmb = {'chan7' 'chan6'};\nft_spike_plot_jpsth(cfg, jpsth)\n\nfigure\ncfg = [];\ncfg.channelcmb = {'chan8' 'chan6'};\nft_spike_plot_jpsth(cfg, jpsth)\npause(1)\nclose all\n\n%% test with the sdf\ncfg = [];\ncfg.keeptrials = 'yes';\ncfg.timwin = [-0.01 0.01];\n[sdf] = ft_spikedensity(cfg, data);\ncfg = [];\ncfg.channelcmb = {'chan2' 'chan3'};\ntic, jpsth = ft_spike_jpsth(cfg, sdf);toc\n% note that it works on SDF as well!\nfigure\ncfg = [];\ncfg.channelcmb = {'chan3' 'chan2'};\nft_spike_plot_jpsth(cfg, jpsth)\npause(1)\nclose all\n\n\n%%\ncfg = [];\ncfg.method = 'shiftpredictor';\ntic, jpsth = ft_spike_jpsth(cfg, psth);toc\ncfg = [];\nfigure\ncfg.channelcmb = {'chan5' 'chan2'};\nft_spike_plot_jpsth(cfg, jpsth)\npause(1)\nclose all\n\n% note the randomness around 0, shiftpredictor gives same result\n%%\nfigure\ncfg.channelcmb = {'chan3' 'chan2'};\nft_spike_plot_jpsth(cfg, jpsth)\n\npause(1)\nclose all\n\n%% test the normalization option\ncfg = [];\ncfg.normalization = 'yes';\ntic, jpsth = ft_spike_jpsth(cfg, psth);toc\ncfg = [];\nfor iCmb1 = 1:7\n for iCmb2 = iCmb1:8\n figure\n cfg.channelcmb = {jpsth.label{iCmb1}, jpsth.label{iCmb2}};\n ft_spike_plot_jpsth(cfg, jpsth)\n end\nend\nfigure\ncfg.channelcmb = {'chan8', 'chan9'};\nft_spike_plot_jpsth(cfg, jpsth)\n\nnanmax(jpsth.jpsth(:))\nnanmin(jpsth.jpsth(:))\npause(1)\nclose all\n\n% note how the normalized lies between -1 and 1\n%%\ncfg = [];\ncfg.normalization = 'yes';\ncfg.method = 'shiftpredictor';\ntic, jpsth = ft_spike_jpsth(cfg, psth);toc\ncfg = [];\n%%\nfor iCmb1 = 1:7\n for iCmb2 = iCmb1:8\n figure\n cfg.channelcmb = {jpsth.label{iCmb1}, jpsth.label{iCmb2}};\n ft_spike_plot_jpsth(cfg, jpsth)\n end\nend\npause(1)\nclose all\n\n%%\nfigure\ncfg.channelcmb = {'chan8' , 'chan9'};\nft_spike_plot_jpsth(cfg, jpsth)\n\nfigure\ncfg.channelcmb = {'chan3' , 'chan2'};\nft_spike_plot_jpsth(cfg, jpsth)\npause(1)\nclose all\n\n% note how the normalized lies between -1 and 1\n\n%% check how the jpsth behaves if psth was based on variable trial length\n% create data with variable length at the start\n\nclear\nspikesPerTrial = 10;\nnTrials = 100;\nshapePar = 2;\nscalePar = 3;\n\ndata = [];\ndata.time = cell(1, nTrials);\ndata.trial = cell(1, nTrials);\n\nfor iTrial = 1:nTrials\n \n % create the latency, start and end have a jitter of 100 ms\n latencyBeg = 0 + (100*(rand-0.5))/1000; % is going to include some trials, and exlude some\n latencyEnd = 1 + (100*(rand-0.5))/1000;\n timeAxis = latencyBeg:0.001:latencyEnd;\n n = length(timeAxis);\n \n data.trial{iTrial} = zeros(3, n);\n \n iUnit = 1;\n spikeTimes = [];\n smp = [];\n while length(spikeTimes)1) = [];\n for iSpike = 1:length(spikeTimes)\n smp(iSpike) = nearest(timeAxis, spikeTimes(iSpike));\n end\n smp(smp>n) = [];\n data.trial{iTrial}(iUnit, smp) = 1;\n \n iUnit = 2;\n spikeTimes = spikeTimes + 0.02;\n smp = [];\n spikeTimes(spikeTimes>1) = [];\n for iSpike = 1:length(spikeTimes)\n smp(iSpike) = nearest(timeAxis, spikeTimes(iSpike));\n end\n smp(smp>n) = [];\n data.trial{iTrial}(iUnit, smp) = 1;\n \n iUnit = 3;\n spikeTimes = linspace(0, 1, 10);\n spikeTimes(spikeTimes>timeAxis(end) | spikeTimes>\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_gedge.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879991, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.4863512845270539}} {"text": "function [ V ] = GetValues( Q , knn , p )\n%GETVALUE Summary of this function goes here\n% Detailed explanation goes here\n\nV = Q(knn,:)' * p ;\n\nend\n\n\n", "meta": {"author": "epfl-lasa", "repo": "ML_toolbox", "sha": "61cc1245a2abe0c86a737d7b48bd645b28ffebee", "save_path": "github-repos/MATLAB/epfl-lasa-ML_toolbox", "path": "github-repos/MATLAB/epfl-lasa-ML_toolbox/ML_toolbox-61cc1245a2abe0c86a737d7b48bd645b28ffebee/methods/reinforcement_learning/mountain_car_functions/GetValues.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149978955813, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4863351949074384}} {"text": "function [ know, x ] = p42_sol ( n )\n\n%*****************************************************************************80\n%\n%% P42_SOL returns the solution for problem 42.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 March 2002\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the problem. This value\n% is only needed for those problems with variable N.\n%\n% Output, integer KNOW.\n% If KNOW is 0, then the solution is not known.\n% If KNOW is positive, then the solution is known, and is returned in X.\n%\n% Output, real X(N), the solution, if known.\n%\n know = 1;\n\n x = ones ( n, 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/test_opt/p42_sol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.48633519135519626}} {"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 S = cgf_fitS_sc2(A,X, sparsity, noise_var, beta, epsilon, sigma, tol, disp_ocbsol, disp_patnum, disp_stats, Sinit)\n% cgf_fitS -- fit internal vars S to the data X using fast congugate gradient\n% Usage\n% S = cgf_fitS(A,X,noise_var,beta,sigma,\n% [tol, disp_ocbsol, disp_patnum, disp_stats])\n% Inputs\n% A basis functions\n% X data vectors\n% noise_var variance of the noise (|x-As|^2)\n% beta steepness term for prior\n% sigma scaling term for prior\n% tol solution tolerance (default 0.001)\n% disp_ocbsol display info from the fitting process\n% disp_patnum display the pattern number\n% disp_stats display summary statistics for the fit\n% Outputs\n% S the estimated coefficients\n\nmaxiter=100;\n\n[L,M] = size(A);\nN = size(X,2);\n\nif ~exist('tol','var');\t\ttol = 0.001;\t\t\tend\nif ~exist('disp_ocbsol','var');\tdisp_ocbsol = 0;\t\tend\nif ~exist('disp_patnum','var');\tdisp_patnum = 1;\t\tend\nif ~exist('disp_stats','var');\tdisp_stats = 1;\t\t\tend\nif ~exist('maxiter','var');\t\tmaxiter = 8;\t\t\tend\nif ~exist('reduction','var');\treduction = 8;\t\t\tend\n\n% XXX: we don't use initialization for \"log\" sparsity function because of local optima\nif ~exist('Sinit','var') %|| strcmp(sparsity, 'log') || strcmp(sparsity, 'huberL1') || strcmp(sparsity, 'epsL1')\n\tSinit=A'*X;\n\tnormA2=sum(A.*A)';\n\tfor i=1:N\n Sinit(:,i)=Sinit(:,i)./normA2;\n\tend\n initiated = 0;\nelse\n initiated = 1;\nend\n\nif ~strcmp(sparsity, 'log') && ~strcmp(sparsity, 'huberL1') && ~strcmp(sparsity, ...\n 'epsL1')\n\terror('sparsity function is not properly specified!\\n');\nend\n\nlambda=1/noise_var;\n\nif strcmp(sparsity, 'huberL1') || strcmp(sparsity, 'epsL1')\n\tif ~exist('epsilon','var') || isempty(epsilon) || epsilon==0\n\t\terror('epsilon was not set properly!\\n')\n\tend\nend\n\nS = zeros(M,N);\ntic\nif ~initiated\n if strcmp(sparsity, 'log')\n [S niters nf ng] = cgf_sc2(A,X,Sinit,0,lambda,beta,sigma,tol,maxiter, disp_ocbsol,disp_patnum);\n elseif strcmp(sparsity, 'huberL1') \n [S niters nf ng] = cgf_sc2(A,X,Sinit,1,lambda,beta,sigma,tol,maxiter, disp_ocbsol,disp_patnum, epsilon);\n elseif strcmp(sparsity, 'epsL1')\n [S niters nf ng] = cgf_sc2(A,X,Sinit,2,lambda,beta,sigma,tol,maxiter, disp_ocbsol,disp_patnum, epsilon);\n end\nelse\n if strcmp(sparsity, 'log')\n [S niters nf ng] = cgf_sc2(A,X,Sinit,0,lambda,beta,sigma,tol,maxiter, disp_ocbsol,disp_patnum);\n elseif strcmp(sparsity, 'huberL1') \n [S niters nf ng] = cgf_sc2(A,X,Sinit,1,lambda,beta,sigma,tol,maxiter, disp_ocbsol,disp_patnum, epsilon);\n elseif strcmp(sparsity, 'epsL1')\n [S niters nf ng] = cgf_sc2(A,X,Sinit,2,lambda,beta,sigma,tol,maxiter, disp_ocbsol,disp_patnum, epsilon);\n end\n% for i=1:size(X,2)\n% [aa,bb] = sort(abs(Sinit(:,i)));\n% bb = flipud(bb);\n% active = bb(1:M/reduction);\n% if strcmp(sparsity, 'log')\n% [S2 niters nf ng] = cgf_sc2(A(:,active),X(:,i),Sinit(:,i),0,lambda,beta,sigma,tol,maxiter, disp_ocbsol,disp_patnum);\n% elseif strcmp(sparsity, 'huberL1') \n% [S2 niters nf ng] = cgf_sc2(A(:,active),X(:,i),Sinit(:,i),1,lambda,beta,sigma,tol,maxiter, disp_ocbsol,disp_patnum, epsilon);\n% elseif strcmp(sparsity, 'epsL1')\n% [S2 niters nf ng] = cgf_sc2(A(:,active),X(:,i),Sinit(:,i),2,lambda,beta,sigma,tol,maxiter, disp_ocbsol,disp_patnum, epsilon);\n% end\n% S(active,i) = S2;\n% end\n% fprintf('%d',reduction);\nend\nt = toc;\n\nif (disp_stats)\n fprintf(' aits=%6.2f af=%6.2f ag=%6.2f at=%7.4f\\n', ...\n niters/N, nf/N, ng/N, t/N);\nend\n", "meta": {"author": "thomas-koehler", "repo": "SupER", "sha": "d8c6f2e4b26db002ff55bc2beba18639f1d0bb49", "save_path": "github-repos/MATLAB/thomas-koehler-SupER", "path": "github-repos/MATLAB/thomas-koehler-SupER/SupER-d8c6f2e4b26db002ff55bc2beba18639f1d0bb49/matlab/algorithms/SRAlgorithms/Aplus/CVPR08-SR/Sparse_coding/sc2/cgf_fitS_sc2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.48633517748980976}} {"text": " function inv2 = de_ftab_inv2(fit, sl, varargin)\n%function inv2 = de_ftab_inv2(fit, sl, [options])\n%|\n%| Build object that does polynomial inverse of BH function.\n%| (To map log data into corresponding to line-integrals of material density.)\n%|\n%| in\n%|\tfit\tstrum\tinitialized by de_ftab_fit()\n%|\tsl\tcell\t{s1, ..., sL} see sls.sl from de_ftab_sls.m\n%|\n%| option\n%|\t'itype'\tchar\t'T' or 'fixlinear' or 'fit' todo\n%|\t\t\t\t'fixlinear' is default which means\n%|\t\t\t\tuse ftab.T for linear terms and then\n%|\t\t\t\tfit higher-order polynomial for rest\n%|\t'T'\t[L M]\tftab.T - linearization at 0, if desired\n%|\t'show'\t0|1\tplot it?\n%|\n%| out\n%|\tinv2\tstrum\n%|\tmethods:\n%|\t\tinv2.fun(hf)\t\tmap log values into corrected values\n%|\t\tinv2.plot(fit, sl)\tshow fits\n%|\n%| Copyright 2008-09-28, Jeff Fessler, University of Michigan\n\nif nargin < 1, ir_usage, end\nif nargin == 1 && streq(fit, 'test'), fail('run de_ftab test'), return, end\n\n% option defaults\narg.emax = 4;\narg.T = [];\narg.esum = 6;\n%arg.itype = 'T';\n%arg.itype = 'fit'; % general fit\narg.itype = 'fixlinear'; % fix linear coefficients based on T, fit rest\n%arg.wt = sll{2}.^3;\t% weighting\n%arg.wt = 1 ./ (0*sll{2} + 1);\t% weighting\narg.show = false;\n\narg = vararg_pair(arg, varargin);\n\ninv2 = de_ftab_inv2_setup(fit, sl, arg);\n\n\n%\n% de_ftab_inv2_setup()\n% add methods to ftab related to polynomial approximation to its inverse\n%\nfunction inv2 = de_ftab_inv2_setup(fit, sl, arg)\n\nLL = fit.LL;\nMM = fit.MM;\n\nif fit.MM < fit.LL\n\twarn('not making inv2() for MM=%d < LL=%d', fit.MM, fit.LL)\n\tinv2 = [];\nreturn\nend\n\nswitch arg.itype\ncase 'T' % 1st-order poly based on T\n\tif isempty(arg.T), fail 'need T', end\n\tcoef = arg.T'; % [K L], K=M\n\texpo = eye(MM); % [K M], K=M\n\ncase {'fit', 'fixlinear'}\n\tsll = ndgrid_jf('mat', sl{:}); % [(Ns) L]\n\tsll = reshapee(sll, [], LL); % [*Ns L]\n\tftmp = fit.fmfun(sll); % [*Ns M]\n\n\texpo = de_poly_expo(MM, 'emax', arg.emax, 'esum', arg.esum);\n\texpo(1,:) = []; % remove DC term\n\tbasis = de_poly_eval(ftmp, [], expo, 'basis', 1); % [*Ns K]\n\n% todo: consider weighting?\n\tif streq(arg.itype, 'fixlinear')\n\t\tif isempty(arg.T), fail 'need T', end\n\t\tjf_equal(expo(1:MM,1:MM), eye(MM)) % linear terms\n\t\tKK = size(expo,1); % # of coefficients\n\t\tcoef = zeros(KK, LL);\n\t\tcoef(1:MM,:) = arg.T'; % [M L]\n\t\tlin = de_poly_eval(ftmp, coef(1:MM,:), expo(1:MM,:)); % [*Ns L]\n\t\tbasis = basis(:,(MM+1):end); % [*Ns K-M]\n\t\tcoef((MM+1):end,:) = basis \\ (sll - lin); % [K-M L]\n\telse\n\t\tcoef = basis \\ sll; % [K L]\n\tend\n\notherwise\n\tfail('bad itype %s', arg.itype)\nend\n\narg.coef = coef;\narg.expo = expo;\n\nif 1 % display polynomial fit errors\n\ttmp = de_poly_eval(ftmp, coef, expo);\n\tfor ll=1:LL\n\t\tprintm('worst inverse poly error l=%d: %g of %g', ll, ...\n\t\t\tmax(abs(tmp(:,ll) - sll(:,ll))), max(sll(:,ll)))\n\tend\nend\n\n%\n% old way: (todo: remove?)\n% Build polynomial approximation to shat = (T F)^{-1}(z).\n% Use weighted fitting so that soft tissue is fit well!\n%\n\nif 0\t% this polynomial way seems insufficiently accurate!?\n\tftab.inv.basis_func = ir_poly2_fun(3);\n\ttmp = ftab.inv.basis_func(z1(:), z2(:));\n\tftab.inv.nbasis = length(ftab.inv.basis_func(0,0));\n\tftab.inv.coef = zeros(ftab.inv.nbasis,2);\n\tfor ll=1:ftab.LL\n\t\tftab.inv.coef(:,ll) = (diag_sp(wt(:)) * tmp) \\ ...\n\t\t\t(wt(:) .* sll{ll}(:));\n\tend\nend\n\n%ftab.inv.eval = @(ftab,fha) de_ftab_invert(ftab,fhat);\n\nfun = @(inv2, fhat) de_ftab_inv2_eval(inv2, fhat);\nmeth = {'fun', fun, '(fhat [() M]) -> [() L]';\n\t'plot', @de_ftab_inv2_plot, '(fit, sl)'};\ninv2 = strum(arg, meth);\n\n\n\n%\n% de_ftab_inv2_eval()\n% todo\n%\nfunction shat = de_ftab_inv2_eval(inv2, fhat)\nshat = de_poly_eval(fhat, inv2.coef, inv2.expo);\n\n\n%\n% de_ftab_inv2_plot()\n% see how well a grid of s values is recovered\n%\nfunction out = de_ftab_inv2_plot(inv2, fit, sl)\nLL = fit.LL;\nif LL == 2\n\tsll = ndgrid_jf('mat', sl{:});\n\tftmp = fit.fmfun(sll);\n\tshat = inv2.fun(ftmp);\n\tif im\n\t\tclf\n\t%\tplot(sl{1}, sl{2}, shat, '.')\n\t\tplot(shat(:,:,1), shat(:,:,2), '.')\n\t\taxis tight\n\t\txlabel 's1', ylabel 's2'\n\t\ttitle 's -> (fit) -> f -> (inv2) -> s'\n\tprompt\n\tend\nelse\n\twarn 'inv2_plot only for L=2'\nend\n\nif nargout, out = []; end\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/ct/de_ftab_inv2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234878, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4863027615043638}} {"text": "function reg = modifiedconv(tr,condf,varargin)\n% :Usage:\n% ::\n%\n% model = modifiedconv(tr,condf,heighteq [all opt],delayeq,ttopeakeq,uonseteq)\n%\n% :Inputs:\n%\n% **tr:**\n% repetition time (sampling rate) of scanning, in seconds\n%\n% **condf:**\n% condition function\n% an indicator vector of zeros and ones, where ones indicate event\n% onsets\n%\n% This is a simplified modified convolution that uses nonlinear saturation in height only\n% with a guess as to what the decrease in saturation is as a function of\n% the time since previous stimulation (exponential model, alpha version)\n%\n% For the full set of equations modifying height, time-to-peak, and\n% dispersion as a function of stumulus history, see\n% modifiedconv_wager2005.m\n%\n% \n% :Examples:\n% ::\n%\n% condf = [1 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0]';\n% X = modifiedconv(2,condf);\n% % X is convolved predictor\n% plot(X)\n% X2 = conv(condf,spm_hrf(2)./max(spm_hrf(2)));\n% hold on;\n% plot(X2,'r');\n% legend({'Modified' 'Linear'})\n%\n% :Please see:\n% Wager, T. D., Hernandez, L., Vasquez, A., Nichols, T., and Noll, D.\n% C. (2005). Accounting for nonlinear BOLD effects in fMRI: Parameter \n% estimates and model for accurate prediction in variable-duration blocked \n% and rapid event-related studies. Neuroimage.\n%\n% ..\n% 06/20/01 Tor Wager\n% ..\n\n%heighteq = []; delayeq = []; peakeq = []; uonseteq = [];\n\n% ---------------------------------------------------------------------\n% * defaults\n% ---------------------------------------------------------------------\nheight = 1; delay = 0; peak = 6; uonset = 16;\ndispers = 1; udisp = 1; rtou = 6; klength = 32;\nrtou = Inf; % get rid of undershoot\n\np = [peak uonset dispers udisp rtou delay klength];\n\nhrf = spm_hrf(tr,p)./ max(spm_hrf(tr,p));\n\n%heighteq = inline('1.7141.*(exp(-2.1038.*x)) + 0.4932.*(exp(-0.0770.*x))');\n%delayeq = inline('-13.4097.*(exp(-1.0746.*x)) + 4.8733.*(exp(-0.1979.*x))');\n%peakeq = inline('37.5445.*(exp(-2.6760.*x)) + -3.2046.*(exp(-0.2120.*x)) + 5.6344');%\n\n% new idea: model nonlinear saturation response as a function of \n% a fixed saturation response (that we know is e.g., 1-(.6658 x original) with a\n% stimulus 1 s before) x an exponential discount factor for how LONG AGO the\n% previous stimulus occurred\n% SO THAT: Rnow = Ro - sum(s(t-to)gamm(t-to)\n% gam(1) should be 1-.6658, and area under gam should be no more than 1,\n% because you can never lose more than 100% of the signal\n% BUT we may end up having to take interactions betwn stim into account,\n% which is harder: e.g., a stim occurs .5 s before and another occurs .3\n% sec before. The .3 one is going to produce a smaller response and thus\n% less saturation, and you can never saturate more than 1 (100%) even w/\n% many stimuli occurring in a short time frame (w/i 1 s)\n% SO this model, now, can predict negative response values with more than\n% 100% sat. \n\ngam = inline('(1-.6658) * (1./exp(-a))*exp(-a*t)','t','a');\na = .7; % let's assume this is the exp for now. gives 70% sat w/hist 1:5, 74% w/hist 1:10 \n\n\nmyzeros = zeros(length(condf),1);\nmylen = length(myzeros);\nnumels = 12 ./ tr; % number of elements to count\n\nreg = myzeros;\n\nwhstim = find(condf); % which elements contain indicators of stimulation\n\nif any(condf(whstim)>1) \n disp('warning: modifiedconv not valid for onset mag > 1, which you appear to have entered.'), \nend\n \nfor i = 1:length(whstim)\n \n j = whstim(i); % index of which element\n \n % for each element, get predicted height\n\n\t\t\ttrialdelta = myzeros;\n\t\t\ttrialdelta(j) = 1;\n\t\t\ttrialp = p;\n\t\t\t\n\t\t\t% figure out how many of same type came before\n % 1 is \"first stim in sequence\"\n \n %myc = condf(j-min(29,j)+1:j)\n %myw = timeweights(end-length(myc)+1:end)\n \n myc = condf(j-min(numels,j)+1:j); % recent events, including current stim\n \n wh = find(myc(1:end-1)); % which elements\n \n times = length(myc) - wh; % times at which these occurred in elements\n times = times * tr; % convert to seconds\n \n s = myc(wh); % stimulus intensity at each time, probably 1 for typical indicator vector\n \n sat = sum(s .* gam(times,a)); % total saturation\n \n height = max(0,1 - sat); % magnitude of this event\n \n trialdelta = myzeros;\n trialdelta(j) = condf(j);\n \n\t\t\tmytrialpred = conv(height.*hrf,trialdelta);\n\t\t\tmytrialpred = mytrialpred(1:mylen);\n\n\t\t\treg = reg + mytrialpred;\n \n\t\t\nend\n\n\nreturn\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Model_building_tools/modifiedconv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430436757312, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4863027541626569}} {"text": "function [vec,rotMat]=ITRS2TEME(x,Jul1,Jul2,deltaTTUT1,xpyp,LOD)\n%%ITRS2TEME Convert from the International Terrestrial Reference\n% System (ITRS) into the True Equator Mean Equinox (TEME) of date \n% coordinate system. The TEME system is non-standard and is\n% generally only used in the Specialized General Perturbations 4\n% (SGP4) orbital propagation algorithm. Note that the velocity\n% conversion does not include the (small) centrifugal effect of\n% polar motion.\n%\n%INPUTS: x The NXnumVec collection of vectors to convert. N can be 3, or\n% 6. If the vectors are 3D, then they are position. 6D vectors\n% are assumed to be position and velocity, whereby the angular\n% velocity of the Earth's rotation is taken into account using a\n% non-relativistic formula.\n% Jul1, Jul2 Two parts of a Julian date given in terrestrial time (TT).\n% The units of the date are days. The full date is the sum of\n% both terms. The date is broken into two parts to provide more\n% bits of precision. It does not matter how the date is split.\n% deltaTTUT1 An optional parameter specifying the difference between TT\n% and UT1 in seconds. This information can be obtained from\n% http://www.iers.org/nn_11474/IERS/EN/DataProducts/EarthOrientationData/eop.html?__nnn=true\n% or \n% http://www.usno.navy.mil/USNO/earth-orientation/eo-products\n% If this parameter is omitted or if an empty matrix is passed,\n% then the value provided by the function getEOP will be used\n% instead.\n% xpyp xpyp=[xp;yp] are the polar motion coordinates in radians\n% including the effects of tides and librations. If this\n% parameter is omitted or an empty matrix is passed the value\n% from the function getEOP will be used.\n% LOD The difference between the length of the day using terrestrial\n% time, international atomic time, or UTC without leap seconds\n% and the length of the day in UT1. This is an instantaneous\n% parameter (in seconds) proportional to the rotation rate of the\n% Earth. This is only needed if more than just position\n% components are being converted.\n%\n%The conversion from the TEME to the pseudo-Earth-Fixed (PEF) coordinate\n%system is described in [1] and the relationship between the ITRS and the\n%PEF is described in [2].\n%\n%The velocity transformation deals with the instantaneous rotational\n%velocity of the Earth using a simple Newtonian velocity addition.\n%Basically, the axis of rotation in the Pseudo-Ears-Fixed (PEF) frame is\n%the z-axis (The PEF is akin to a less-accurate version of the TIRS).\n%The rotation rate in that system is Constants.IERSMeanEarthRotationRate\n%adjusted using the Length-of-Day (LOD) Earth Orientation Parameter (EOP).\n%Thus, in the PEF, the angular velocity vector is [0;0;omega], where omega\n%is the angular velocity accounting for the LOD EOP. Consequently, one\n%account for rotation by transforming from the ITRS to the PEF,\n%adding the cross product of Omega with the position in the PEF, and\n%then converting to the TEME. This is a simple Newtonian conversion.\n%\n%The algorithm can be compiled for use in Matlab using the \n%CompileCLibraries function.\n%\n%The algorithm is run in Matlab using the command format\n%[vec,rotMat]=ITRS2TEME(x,Jul1,Jul2);\n%or if more parameters are known,\n%[vec,rotMat]=ITRS2TEME(x,Jul1,Jul2,deltaTTUT1,xpyp,LOD);\n%\n%REFERENCES:\n%[1] D. A. Vallado, P. Crawford, R. Hujsak, and T. Kelso, \"Implementing\n% the revised SGP4 in STK,\" in Proceedings of the AGI User Exchange,\n% Washington, DC, 17?18 Oct. 2006, slides. [Online].\n% Available: http://www.agi.com/downloads/events/2006-agi-user-exchange/8_revised_sgp4_vallado2.pdf\n%[2] D. A. Vallado, J. H. Seago, and P. K. Seidelmann, \"Implementation\n% issues surrounding the new IAU reference systems for astrodynamics,\"\n% in Proceedings of the 16th AAS/AIAA Space Flight Mechanics\n% Conference, Tampa, FL, 22?26 Jan. 2006. [Online].\n% Available: http://www.centerforspace.com/downloads/files/pubs/AAS-06-134.pdf\n%\n%December 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nerror('This function is only implemented as a mexed C or C++ function. Please run CompileCLibraries.m to compile the function for use.')\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Coordinate_Systems/Celestial_and_Terrestrial_Systems/ITRS2TEME.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303236047049, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.48624560146643997}} {"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": "classdef CLIA < ALGORITHM\n% \n% Evolutionary algorithm with cascade clustering and reference point incremental learning\n\n%------------------------------- Reference --------------------------------\n% H. Ge, M. Zhao, L. Sun, Z. Wang, G. Tan, Q. Zhang, and C. L. P. Chen, A\n% many-objective evolutionary algorithm with two interacting processes:\n% Cascade clustering and reference point incremental learning, IEEE\n% Transactions on Evolutionary Computation, 2019, 23(4): 572-586.\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 global stable_threshold delta crowding_pick_flag;\n [stable_threshold, delta] = Algorithm.ParameterSet([0, 0, 0], 2 * Problem.N);\n [Z, P, A, S, SVM] = initialize(Problem);\n while Algorithm.NotTerminated(S)\n MatingPool = TournamentSelection(2, Problem.N, sum(max(0, P.cons), 2)); \n Offspring = OperatorGA(Problem,P(MatingPool));\n A = update_archive(A, [P, Offspring], Z, ceil(0.33 * Problem.M * Problem.N), Problem);\n % SELECTION OF INDIVIDUALS\n [P, ICA, ICN] = cascade_cluster([P, Offspring], Z, 'PDM', Problem.N, Problem.FE < Problem.maxFE);\n % ADAPTATION OF REFERENCE VECTORS \n [Z, SVM] = incremental_learn(Z, ICA, ICN, A, SVM, Problem);\n if Problem.FE >= Problem.maxFE && crowding_pick_flag\n S = crowding_pick(update_archive(A, P, Z, [], Problem), Problem.N, 'precise');\n else\n S = P;\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/CLIA/CLIA.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 FN = flipped_normals(V,F)\n%FLIPPED_NORMALS Compute the flipped normals of a triangle mesh\n%\n% FN = flipped_normals(V,F);\n%\n% Inputs:\n% V,F triangle mesh\n% Outputs:\n% FN flipped normals of the mesh V,N\n\n%Compute per-face normals.\nN = normals(V,F);\nN = N ./ normrow(V,F);\n\n%Flip the per-face normals.\nFN = -N;\n\nend\n\n", "meta": {"author": "odedstein", "repo": "sgi-introduction-course", "sha": "52278fc3b3dab52febb110a1a09d770f46b5e417", "save_path": "github-repos/MATLAB/odedstein-sgi-introduction-course", "path": "github-repos/MATLAB/odedstein-sgi-introduction-course/sgi-introduction-course-52278fc3b3dab52febb110a1a09d770f46b5e417/008_normals/solution/flipped_normals.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.6825737473266736, "lm_q1q2_score": 0.4861509993012466}} {"text": "function poolBconv()\n global config mem;\n curr_layer_idx = config.misc.current_layer;\n mem.grads{curr_layer_idx+1} = mem.deltas{curr_layer_idx+1} * mem.activations{curr_layer_idx}';\n mem.grads{curr_layer_idx+1+config.layer_num} = sum(mem.deltas{curr_layer_idx+1}, 2);\n\tmem.delta_act = config.weights{curr_layer_idx+1}' * mem.deltas{curr_layer_idx+1};\nend\n\n", "meta": {"author": "jimmy-ren", "repo": "vcnn_double-bladed", "sha": "a4de90e845875f6e30632f2e879d3afb81c0ebc1", "save_path": "github-repos/MATLAB/jimmy-ren-vcnn_double-bladed", "path": "github-repos/MATLAB/jimmy-ren-vcnn_double-bladed/vcnn_double-bladed-a4de90e845875f6e30632f2e879d3afb81c0ebc1/layers_adapters/poolBconv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718435083355188, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.4860874531662123}} {"text": "function reduction_example ( n )\n\n%*****************************************************************************80\n%\n%% REDUCTION_EXAMPLE shows an example of a parallel reduction operation.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 August 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the size of the array.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'REDUCTION_EXAMPLE:\\n' );\n fprintf ( 1, ' The MATLAB PARFOR command can carry out certain\\n' );\n fprintf ( 1, ' \"reduction\" operations in parallel.\\n' );\n\n if ( nargin < 1 )\n fprintf ( 1, '\\n' );\n n = input ( ' Enter N, the size of the vector.\\n' );\n end\n%\n% Set up a random data vector.\n%\n x = rand ( n );\n%\n% Sum its entries.\n%\n\n total1 = 0.0;\n for i = 1 : n\n total1 = total1 + x(i);\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Sum all entries of X, in sequential mode:\\n' );\n fprintf ( 1, ' TOTAL1 = %f\\n', total1 );\n%\n% Sum its entries in parallel.\n%\n total2 = 0.0;\n parfor i = 1 : n\n total2 = total2 + x(i);\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Sum all entries of X, in parallel mode:\\n' );\n fprintf ( 1, ' TOTAL2 = %f\\n', total2 );\n%\n% Sum some of its entries.\n%\n total3 = 0.0;\n for i = 1 : n\n if ( 0.5 < x(i) )\n total3 = total3 + x(i);\n end\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Sum entries of X greater than 1/2, in sequential mode:\\n' );\n fprintf ( 1, ' TOTAL3 = %f\\n', total3 );\n%\n% Sum some of its entries in parallel.\n%\n total4 = 0.0;\n parfor i = 1 : n\n if ( 0.5 < x(i) )\n total4 = total4 + x(i);\n end\n end\n\n fprintf ( 1, ' Sum entries of X greater than 1/2, in parallel mode:\\n' );\n fprintf ( 1, ' TOTAL4 = %f\\n', total4 );\n\n return\nend\n\n \n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/matlab_parallel/reduction_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.629774621301746, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.4860874498610153}} {"text": "function cluster_center = cluster_initialize_1 ( dim_num, point_num, ...\n cluster_num, point )\n\n%*****************************************************************************80\n%\n%% CLUSTER_INITIALIZE_1 initializes the clusters to data points.\n%\n% Discussion:\n%\n% The cluster centers are simply chosen to be the first data points.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 04 October 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the number of spatial dimensions.\n%\n% Input, integer POINT_NUM, the number of points.\n%\n% Input, integer CLUSTER_NUM, the number of clusters.\n%\n% Input, real POINT(DIM_NUM,POINT_NUM), the coordinates \n% of the points.\n%\n% Output, real CLUSTER_CENTER(DIM_NUM,CLUSTER_NUM),\n% the coordinates of the cluster centers.\n%\n cluster_center(1:dim_num,1:cluster_num) = point(1:dim_num,1:cluster_num)\n\n return\nend", "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/kmeans/cluster_initialize_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6297746074044135, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.48608744243964647}} {"text": "function net = LLRAddMasking(net, upsample_fac, bilinear_up, upsample_2x_per_layer)\n\nif upsample_2x_per_layer\n post_name = '_bil_x2';\nelse\n post_name = '';\nend\nup_name = [num2str(upsample_fac) 'x'];\npre_up_name = [num2str(2 * upsample_fac) 'x'];\n\n\npool_size = (upsample_fac * 2) / bilinear_up + 1;\nassert(pool_size == 9);\npad_size = floor(pool_size)/2;\n% Dilation of class probabilities\nnet.addLayer(['prob_' pre_up_name], dagnn.SoftMax(), ['prediction_' pre_up_name post_name], ['prob_' pre_up_name], {});\nnet.addLayer(['prob_dilate_' pre_up_name], dagnn.Pooling('stride', [1 1], 'poolSize', [pool_size pool_size], ...\n 'pad', [pad_size, pad_size, pad_size, pad_size]), ['prob_' pre_up_name], ['prob_' pre_up_name '_dilate'], {});\n\n% Dilation of negative of class probabilities\nnet.addLayer(['neg_prob_' pre_up_name], Neg(), ['prob_' pre_up_name], ['neg_prob_' pre_up_name], {});\n['neg_prob_' pre_up_name]\nnet.addLayer(['neg_prob_dilate_' pre_up_name], dagnn.Pooling('stride', [1 1], 'poolSize', [pool_size pool_size], ...\n 'pad', [pad_size, pad_size, pad_size, pad_size]), ['neg_prob_' pre_up_name], ['neg_prob_' pre_up_name '_dilate'], {});\n\n% Sum of two dilation\nnet.addLayer(['bound_mask' pre_up_name], dagnn.Sum(), {['prob_' pre_up_name '_dilate'], ['neg_prob_' pre_up_name '_dilate']}, ['bound_mask' pre_up_name]) ;\nnet.addLayer(['dot_prod_' up_name], DotProduct(), {['bound_mask' pre_up_name], ['prediction_' up_name '_add']}, ['pred_' up_name '_aft_DP']) ;\nnet.setLayerInputs(['sum' up_name], {['prediction_' pre_up_name post_name], ['pred_' up_name '_aft_DP']});\n\n\n", "meta": {"author": "aimerykong", "repo": "Recurrent-Pixel-Embedding-for-Instance-Grouping", "sha": "748ade6b969c7861c2a9009cd0f0ffb27004677c", "save_path": "github-repos/MATLAB/aimerykong-Recurrent-Pixel-Embedding-for-Instance-Grouping", "path": "github-repos/MATLAB/aimerykong-Recurrent-Pixel-Embedding-for-Instance-Grouping/Recurrent-Pixel-Embedding-for-Instance-Grouping-748ade6b969c7861c2a9009cd0f0ffb27004677c/libs/layerExt/LRRAddMasking.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.48608743582925246}} {"text": "function test_failed = test_libltfat_dgt_fb(varargin)\ntest_failed = 0;\n\nfprintf(' =============== %s ================ \\n',upper(mfilename));\n\ndefinput.flags.complexity={'double','single'};\n[flags]=ltfatarghelper({},definput,varargin);\ndataPtr = [flags.complexity, 'Ptr'];\n\n[~,~,enuminfo]=libltfatprotofile;\nphaseconv = enuminfo.ltfat_phaseconvention;\n\nfftwflags = struct('FFTW_MEASURE',0,'FFTW_ESTIMATE',64,'FFTW_PATIENT',32,'FFTW_DESTROY_INPUT',1,...\n 'FFTW_UNALIGNED',2,'FFTW_EXHAUSTIVE',8,'FFTW_PRESERVE_INPUT',16);\n\nLarr = [350 350 9 1];\nglarr = [ 20 10 9 1];\naarr = [ 10 10 9 1];\nMarr = [ 35 35 3 1];\nWarr = [ 1 3 3 1];\n\nfor do_complex = 0:1\n complexstring = '';\n if do_complex, complexstring = 'complex'; end\n\n for idx = 1:numel(Larr)\n L = Larr(idx);\n W = Warr(idx);\n a = aarr(idx);\n M = Marr(idx);\n gl = glarr(idx);\n\n N = L/a;\n\n if do_complex\n g = randn(gl,1,flags.complexity) + 1i*randn(gl,1,flags.complexity);\n f = randn(L,W,flags.complexity) + 1i*randn(L,W,flags.complexity); \n gin = complex2interleaved(g);\n fin = complex2interleaved(f);\n else\n g = randn(gl,1,flags.complexity);\n f = randn(L,W,flags.complexity);\n gin = g; fin = f;\n end\n \n fPtr = libpointer(dataPtr,fin);\n gPtr = libpointer(dataPtr,gin);\n c = cast(randn(M,N,W)+1i*randn(M,N,W),flags.complexity);\n cout = complex2interleaved(c);\n coutPtr = libpointer(dataPtr,cout);\n\n truec = dgt(f,g,a,M);\n\n funname = makelibraryname('dgt_fb',flags.complexity,do_complex);\n status = calllib('libltfat',funname,fPtr,gPtr,L,gl,W,a,M,phaseconv.LTFAT_FREQINV,coutPtr);\n\n res = norm(reshape(truec,M,N*W) - interleaved2complex(coutPtr.Value),'fro');\n [test_failed,fail]=ltfatdiditfail(res+status,test_failed);\n fprintf(['DGT FREQINV L:%3i, gl:%3i, W:%3i, a:%3i, M:%3i %s %s %s %s\\n'],L,gl,W,a,M,complexstring,flags.complexity,ltfatstatusstring(status),fail);\n\n truec = dgt(f,g,a,M,'timeinv');\n status = calllib('libltfat',funname,fPtr,gPtr,L,gl,W,a,M,phaseconv.LTFAT_TIMEINV,coutPtr);\n\n res = norm(reshape(truec,M,N*W) - interleaved2complex(coutPtr.Value),'fro');\n [test_failed,fail]=ltfatdiditfail(res+status,test_failed);\n fprintf(['DGT TIMEINV L:%3i, gl:%3i, W:%3i, a:%3i, M:%3i %s %s %s %s\\n'],L,gl,W,a,M,complexstring,flags.complexity,ltfatstatusstring(status),fail);\n\n % With plan\n c = cast(randn(M,N,W)+1i*randn(M,N,W),flags.complexity);\n cout = complex2interleaved(c);\n coutPtr = libpointer(dataPtr,cout);\n\n plan = libpointer();\n funname = makelibraryname('dgt_fb_init',flags.complexity,do_complex);\n statusInit = calllib('libltfat',funname,gPtr,gl,a,M,phaseconv.LTFAT_FREQINV,fftwflags.FFTW_MEASURE,plan);\n\n funname = makelibraryname('dgt_fb_execute',flags.complexity,do_complex);\n statusExecute = calllib('libltfat',funname,plan, fPtr,L,W,coutPtr);\n\n funname = makelibraryname('dgt_fb_done',flags.complexity,do_complex);\n statusDone = calllib('libltfat',funname,plan);\n\n truec = dgt(f,g,a,M);\n res = norm(reshape(truec,M,N*W) - interleaved2complex(coutPtr.Value),'fro');\n [test_failed,fail]=ltfatdiditfail(res+statusInit,test_failed);\n fprintf(['DGT FREQINV WP L:%3i, gl:%3i, W:%3i, a:%3i, M:%3i %s %s %s %s\\n'],L,gl,W,a,M,complexstring,flags.complexity,ltfatstatusstring(status),fail);\n\n %%%%%%\n c = cast(randn(M,N,W)+1i*randn(M,N,W),flags.complexity);\n cout = complex2interleaved(c);\n coutPtr = libpointer(dataPtr,cout);\n\n plan = libpointer();\n funname = makelibraryname('dgt_fb_init',flags.complexity,do_complex);\n statusInit = calllib('libltfat',funname,gPtr,gl,a,M,phaseconv.LTFAT_TIMEINV,fftwflags.FFTW_MEASURE,plan);\n\n funname = makelibraryname('dgt_fb_execute',flags.complexity,do_complex);\n statusExecute = calllib('libltfat',funname,plan, fPtr,L,W,coutPtr);\n\n funname = makelibraryname('dgt_fb_done',flags.complexity,do_complex);\n statusDone = calllib('libltfat',funname,plan);\n\n truec = dgt(f,g,a,M,'timeinv');\n res = norm(reshape(truec,M,N*W) - interleaved2complex(coutPtr.Value),'fro');\n [test_failed,fail]=ltfatdiditfail(res+statusInit,test_failed);\n fprintf(['DGT TIMEINV WP L:%3i, gl:%3i, W:%3i, a:%3i, M:%3i %s %s %s %s\\n'],L,gl,W,a,M,complexstring,flags.complexity,ltfatstatusstring(status),fail);\n end\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/libltfat/modules/libltfat/testing/mUnit/test_libltfat_dgt_fb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4860874292188582}} {"text": "function stat=valsol(time,v,P,vsat,azel,opt)\n\nglobal glc\n%chi-sqr(n) (alpha=0.001)\nchisqr=[ \n 10.8,13.8,16.3,18.5,18.5,22.5,24.3,26.1,27.9,29.6,...\n 31.3,32.9,34.5,36.1,37.7,39.3,40.8,42.3,43.8,45.3,...\n 46.8,48.3,49.7,51.2,52.6,54.1,55.5,56.9,58.3,59.7,...\n 61.1,62.5,63.9,65.2,66.6,68.0,69.3,70.7,72.1,73.4,...\n 74.7,76.0,77.3,78.6,80.0,81.3,82.6,84.0,85.4,86.7,...\n 88.0,89.3,90.6,91.9,93.3,94.7,96.0,97.4,98.7,100 ,...\n 101 ,102 ,103 ,104 ,105 ,107 ,108 ,109 ,110 ,112 ,...\n 113 ,114 ,115 ,116 ,118 ,119 ,120 ,122 ,123 ,125 ,...\n 126 ,127 ,128 ,129 ,131 ,132 ,133 ,134 ,135 ,137 ,...\n 138 ,139 ,140 ,142 ,143 ,144 ,145 ,147 ,148 ,149 ];\nstat=1; nx=3+glc.NSYS;\n\n%chi-square test for residuals\nnv=size(v,1); var=P^-1;\nfor i=1:nv\n v(i)=v(i)/sqrt(var(i,i));\nend\nif nv>nx && dot(v,v)>chisqr(nv-nx)\n [wn,sow]=time2gpst(time);\n fprintf('Warning:GPS week = %d sow = %.3f,chi-square test error! v=%.3f \\n',wn,sow,dot(v,v));\n stat=0;\n return;\nend\n\n%validate GDOP\nns=0; n=size(vsat,1); azels=zeros(n,2);\nfor i=1:n\n if vsat(i)==0,continue;end\n azels(ns+1,:)=azel(i,:);\n ns=ns+1;\nend\nif nsopt.maxgdop\n [wn,sow]=time2gpst(time);\n fprintf('Warning:GPS week = %d sow = %.3f,GDOP test error! GDOP=%.3f \\n',wn,sow,dop(1));\n stat=0;\n return;\nend\n\nreturn\n\n", "meta": {"author": "kaichen686", "repo": "GINav", "sha": "bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666", "save_path": "github-repos/MATLAB/kaichen686-GINav", "path": "github-repos/MATLAB/kaichen686-GINav/GINav-bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666/src/gnss/spp/valsol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.48607795239790613}} {"text": "%% Zero Padding Function\n% Input data is the sequence s, Target length N\n% output:\n% zs :zero padded signal\n% nozs = number of zeros\n% [nozs zs] = zpp(s, N)\n% 22/04/2011\nfunction [nozs zs]=zpp(s, N)\nL=length(s);\nsz=zeros(N,1);\nnozs=N-L;\nsz(1:L/2)=s(1:L/2);\n\nsz(end-L/2+1:end)=s(end-L/2+1:end);\nzs=sz;\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/36309-simulation-of-an-ofdm-system-with-the-psd/OFDM only/zpp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.48600125547378215}} {"text": "path('toolbox',path);\n%% read pcd and show it\nclear;clc;close all; \nfilename = '../data/2D/n.mat';\nload(filename);\nP.pts = M.verts;\nclear('M');\nnpts = size(P.pts, 1);\n[P.bbox, P.diameter] = GS.compute_bbox(P.pts);\n\n%% call farthest_sampling_by_sphere\nP.sample_radius = P.diameter*0.02;\n[P.spls,P.corresp] = farthest_sampling_by_sphere(P.pts, P.sample_radius);\n\n%% call connect_by_inherit_neigh\nk=5;\nkdtree = kdtree_build(P.pts);\nP.neigh = zeros(npts, k);\nfor i = 1:npts\n% P.neigh(i,:) = flipud( kdtree_k_nearest_neighbors(kdtree, P.pts(i,:), k))';\n P.neigh(i,:) = kdtree_k_nearest_neighbors( kdtree, P.pts(i,:), k)';\nend\n \nP.spls_adj = connect_by_inherit_neigh(P.pts, P.spls, P.corresp, P.neigh);\n\nfigure; movegui('northeast');set(gcf,'color','white');hold on;\nplot3( P.spls(:,1), P.spls(:,2), P.spls(:,3), '.r', 'markersize', 1);\naxis off; axis equal;set(gcf,'Renderer','OpenGL');\nGS.plot_connectivity(P.spls, P.spls_adj, 1)\nview3d zoom;\n\nkdtree_delete( kdtree );", "meta": {"author": "taiya", "repo": "cloudcontr", "sha": "9c27e747136c5286c9a6e9f9c6b278f63cd5312f", "save_path": "github-repos/MATLAB/taiya-cloudcontr", "path": "github-repos/MATLAB/taiya-cloudcontr/cloudcontr-9c27e747136c5286c9a6e9f9c6b278f63cd5312f/matlab/test_connect_by_inherit_neigh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48593359052279467}} {"text": "function [C_df,Df] = extract_DF_F_new(A,C,b,f,P,options)\n\n% extract DF/F signals after performing NMF\n% inputs: Y raw data (d X T matrix, d # number of pixels, T # of timesteps)\n% A matrix of spatial components (d x K matrix, K # of components)\n% C matrix of temporal components (K x T matrix)\n% P neuron structure, used to read the baseline activity for each\n% component of C\n% options structure used for specifying method for determining DF\n% default method is the median of the trace. By changing\n% options.df_prctile an arbitray percentile can be used (between 0 and 100).\n% a moving window can also be established by specifying options.df_window\n\n% outputs: C_df temporal components in the DF/F domain\n% Df background for each component to normalize the filtered raw data \n\n% Written by: \n% Eftychios A. Pnevmatikakis, Simons Foundation, 2016\n\n%memmaped = isobject(Y);\ndefoptions = CNMFSetParms;\nif nargin < 6 || isempty(options)\n options = defoptions;\nend\nif ~isfield(options,'df_prctile') || isempty(options.df_prctile)\n options.df_prctile = defoptions.df_prctile;\nend\nif ~isfield(options,'df_window') || isempty(options.df_window)\n options.df_window = defoptions.df_window;\nend\nif ~isfield(options,'full_A') || isempty(options.full_A); full_A = defoptions.full_A; else full_A = options.full_A; end\n\n[K,T] = size(C);\n\nBas = zeros(K,T);\n\nif ~(nargin < 5 || isempty(P))\n bas_val = cell2mat(P.b);\n Ntr = size(bas_val,2);\n if Ntr > 1\n ln = diff(P.cs_frtrs);\n for i = 1:Ntr\n Bas(:,:,P.cs_frtrs(i)+1:P.cs_frtrs(i+1)) = repmat(bas_val(:,i),1,ln(i));\n end\n else\n Bas = repmat(bas_val,1,T);\n end\nend\n\nnA = sqrt(sum(A.^2));\n\nAA = A'*A;\nAA(1:K+1:end) = 0;\n\nCf = bsxfun(@times,C - Bas,nA(:).^2);\nC2 = repmat(AA*bas_val,1,T) + (A'*b)*f;\n\nif isempty(options.df_window) || (options.df_window > size(C,2))\n if options.df_prctile == 50\n Df = median(C2,2);\n else\n Df = prctile(C2,options.df_prctile,2);\n end\n C_df = bsxfun(@times,Cf,1./Df(:));\nelse\n if options.df_prctile == 50\n if verLessThan('matlab','2015b')\n warning('Median filtering at the boundaries might be inaccurate due to zero padding.')\n Df = medfilt1(C2,options.df_window,[],2);\n else\n Df = medfilt1(C2,options.df_window,[],2,'truncate');\n end\n else\n Df = zeros(size(C2));\n for i = 1:size(Df,1);\n df_temp = running_percentile(C2(i,:), options.df_window, options.df_prctile);\n Df(i,:) = df_temp(:)';\n end\n end\n C_df = Cf./Df;\nend ", "meta": {"author": "flatironinstitute", "repo": "CaImAn-MATLAB", "sha": "49b7884e93348d50df7173e1619d7499468bb1f6", "save_path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB", "path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB/CaImAn-MATLAB-49b7884e93348d50df7173e1619d7499468bb1f6/utilities/extract_DF_F_new.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48593359052279467}} {"text": "function results = classify(data, net, labels, debug);\n% CLASSIFY Classifies the given data using the given trained SFAM.\n% RESULTS = CLASSIFY(DATA, NET, LABELS, DEBUG) \n%\tDATA is an M-by-D matrix where M is the number of samples and D is the size of the feature\n%\tspace. NET is a previously trained SFAM network. LABELS is a M-vector containing the correct\n%\tlabels for the data. If you don't have them, give it as an empty-vector []. \n%\tDEBUG is a scalar to control the verbosity of the program during training. If 0, nothing will\n%\tbe printed, otherwise every DEBUG iterations an informatory line will be printed. \n%\n% Emre Akbas, May 2006\n%\n\nresults = [];\nhits=0;\n\ntic;\nfor s=1:size(data,1)\n input = data(s,:);\n\n % Complement code input\n input = [input 1-input];\n\n % Compute the activation values for each prototype.\n activation = ones(1,length(net.weights));\n for i=1:length(net.weights)\n\tactivation(i) = sum(min(input,net.weights{i}))/...\n\t\t (net.alpha + sum(net.weights{i}));\n end\n\n % Sort activation values \n [sortedActivations, sortedIndices] = sort(activation,'descend');\n\n % Iterate over the prototypes with decreasing activation-value\n results(s)=-1;\n for p=sortedIndices\n\t% Compute match of the current candidate prototype \n\tmatch = sum(min(input,net.weights{p}))/net.D;\n\n\t% Check resonance\n\tif match>=net.vigilance\n\t results(s) = net.labels(p);\n\n\t if ~isempty(labels)\n\t\tif labels(s)==results(s), hits = hits + 1; end;\n\t end\n\n\t break;\n\tend\n end\n\n if mod(s,debug)==0\n\telapsed = toc;\n\tfprintf(1,'Tested %4dth sample. Hits so far: %3d which is %.3f%%.\\tElapsed %.2f seconds.\\n',s,hits,100*hits/s,elapsed);\n\ttic;\n end\nend % samples loop\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/11721-simplified-fuzzy-artmap-neural-network/classify.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48593359052279467}} {"text": "function i4vec_aminz_test ( )\n\n%*****************************************************************************80\n%\n%% I4VEC_AMINZ_TEST tests I4VEC_AMINZ;\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n n = 10;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4VEC_AMINZ_TEST\\n' );\n fprintf ( 1, ' For an integer vector:\\n' );\n fprintf ( 1, ' I4VEC_AMINZ: minimum nonzero absolute entry;\\n' );\n \n seed = 123456789;\n\n b = -n;\n c = n;\n\n [ a, seed ] = i4vec_uniform_ab ( n, b, c, seed );\n \n i4vec_print ( n, a, ' Input vector:' );\n\n fprintf ( 1, '\\n' );\n\n aval = i4vec_aminz ( n, a );\n\n fprintf ( 1, ' Minimum abs nonzero: %f\\n', aval );\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_aminz_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.4859335874136445}} {"text": "function grad = f_grad(XX,XY,w)\n%f_grad\n% \ngrad = XX*w-XY;\nend\n\n", "meta": {"author": "xiubooth", "repo": "ML_Codes", "sha": "927c93ca7e4e452525a989f5a8cc22b73bb1b3d4", "save_path": "github-repos/MATLAB/xiubooth-ML_Codes", "path": "github-repos/MATLAB/xiubooth-ML_Codes/ML_Codes-927c93ca7e4e452525a989f5a8cc22b73bb1b3d4/Simu_Matlab/f_grad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48593358430449435}} {"text": "% a very basic UTE-like sequence, without ramp-sampling, ramp-RF and other\n% tricks yet. Achieves TE in the range of 300-400 us\n\n% set system limits\nsys = mr.opts('MaxGrad', 28, 'GradUnit', 'mT/m', ...\n 'MaxSlew', 100, 'SlewUnit', 'T/m/s', 'rfRingdownTime', 20e-6, ...\n 'rfDeadTime', 100e-6, 'adcDeadTime', 10e-6);\n\nseq=mr.Sequence(sys); % Create a new sequence object\nfov=250e-3; Nx=256; % Define FOV and resolution\nalpha=10; % flip angle\nsliceThickness=3e-3; % slice\nTR=10e-3; % TR\nNr=128; % number of radial spokes\ndelta= 2* pi / Nr; % angular increment; try golden angle pi*(3-5^0.5) or 0.5 of it\nro_duration=2.56e-3; % read-out time: controls RO bandwidth and T2-blurring\nro_os=2; % oversampling\nro_asymmetry=1; % 0: fully symmetric 1: half-echo\nminRF_to_ADC_time=50e-6; % the parameter wich defines TE (together with the RO asymmetyry)\n\n% more in-depth parameters\nrfSpoilingInc=117; % RF spoiling increment\n\n% Create alpha-degree slice selection pulse and gradient\n[rf, gz, gzReph] = mr.makeSincPulse(alpha*pi/180,'Duration',1e-3,...\n 'SliceThickness',sliceThickness,'apodization',0.5,'timeBwProduct',2,...\n 'centerpos',1,'system',sys);\n\n% Align RO assymmetry to ADC samples\nNxo=round(ro_os*Nx);\nro_asymmetry = round(ro_asymmetry*Nxo/2)/Nxo*2; % check whether we need to use 2Nx or so...\n% Define other gradients and ADC events\ndeltak=1/fov/(1+ro_asymmetry);\nro_area=Nx*deltak;\ngx = mr.makeTrapezoid('x','FlatArea',ro_area,'FlatTime',ro_duration,'system',sys);\nadc = mr.makeAdc(Nxo,'Duration',gx.flatTime,'Delay',gx.riseTime,'system',sys);\ngxPre = mr.makeTrapezoid('x','Area',-(gx.area-ro_area)/2 -gx.amplitude*adc.dwell/2 - ro_area/2*(1-ro_asymmetry),'system',sys);\n\n% gradient spoiling\ngxSpoil=mr.makeTrapezoid('x','Area',0.2*Nx*deltak,'system',sys);\n\n% Calculate timing\n%ceil((TE - mr.calcDuration(gxPre) - gz.fallTime - gz.flatTime/2 ...\n% - mr.calcDuration(gx)/2)/seq.gradRasterTime)*seq.gradRasterTime;\n% calculate actual achieved TE\nTE = gz.fallTime + mr.calcDuration(gxPre,gzReph)+gx.riseTime + adc.dwell*Nxo/2*(1-ro_asymmetry);\ndelayTR=ceil((TR - mr.calcDuration(gxPre,gzReph) - mr.calcDuration(gz) ...\n - mr.calcDuration(gx))/seq.gradRasterTime)*seq.gradRasterTime;\nassert(all(delayTR>=mr.calcDuration(gxSpoil)));\n\nfprintf('TE= %d us\\n', round(TE*1e6));\n\nif mr.calcDuration(gzReph) > mr.calcDuration(gxPre) \n gxPre.delay=mr.calcDuration(gzReph) - mr.calcDuration(gxPre);\nend\n\nrf_phase=0;\nrf_inc=0;\n\nfor i=1:Nr\n for c=1:2\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 % UTE: alternate GZ\n gz.amplitude=-gz.amplitude;\n gzReph.amplitude=-gzReph.amplitude;\n %\n seq.addBlock(rf,gz);\n phi=delta*(i-1);\n gpc=gxPre; gps=gxPre; gpc.amplitude=gxPre.amplitude*cos(phi); gps.amplitude=gxPre.amplitude*sin(phi); gps.channel='y';\n grc=gx; grs=gx; grc.amplitude=gx.amplitude*cos(phi); grs.amplitude=gx.amplitude*sin(phi); grs.channel='y';\n gsc=gxSpoil; gss=gxSpoil; gsc.amplitude=gxSpoil.amplitude*cos(phi); gss.amplitude=gxSpoil.amplitude*sin(phi); gss.channel='y';\n seq.addBlock(gpc,gps,gzReph);\n seq.addBlock(grc,grs,adc);\n seq.addBlock(gsc,gss,mr.makeDelay(delayTR));\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%%\nseq.plot();\n\n%% plot gradients to check for gaps and optimality of the timing\ngw=seq.waveforms_and_times();\nfigure; plot(gw{1}(1,:),gw{1}(2,:),gw{2}(1,:),gw{2}(2,:),gw{3}(1,:),gw{3}(2,:)); % plot the entire gradient shape\n\n%% k-space trajectory calculation\n[ktraj_adc, t_adc, ktraj, t_ktraj, t_excitation, t_refocusing] = seq.calculateKspacePP();\n\n% plot k-spaces\nfigure; plot(t_ktraj, 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%\nseq.setDefinition('FOV', [fov fov sliceThickness]);\nseq.setDefinition('Name', 'ute');\n\nseq.write('ute.seq'); % Write to pulseq file\n\n%seq.install('siemens');\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/writeUTE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48593358430449424}} {"text": "function [dim] = pos2dim3d(pos,dimold)\n\n% POS2DIM3D reconstructs the volumetric dimensions from an ordered list of \n% positions. optionally, the original dim can be provided, and the (2:end)\n% elements are appended to the output.\n%\n% Use as\n% [dim] = pos2dim3d(pos, dimold)\n% where pos is an ordered list of positions and where the (optional)\n% dimold is a vector with the original dimensionality of the anatomical\n% or functional data.\n%\n% The output dim is a 1x3 or 1xN vector of which the first three elements\n% correspond to the 3D volumetric dimensions.\n%\n% See also POS2DIM, POS2TRANSFORM\n\n% Copyright (C) 2009, Jan-Mathijs Schoffelen\n\nif nargin==1 && ~isstruct(pos),\n dimold = zeros(0,2);\nelseif isstruct(pos),\n % the input is a FieldTrip data structure\n dimord = pos.dimord;\n dimtok = tokenize(dimord, '_');\n for i = 1:length(dimtok)\n if strcmp(dimtok{i},'pos'),\n dimold(i,1) = size(pos.pos,1);\n else\n dimold(i,1) = numel(getfield(pos, dimtok{i}));\n end\n end\n pos = pos.pos;\nelse\n if size(pos,1)~=dimold(1),\n ft_error('the first element in the second input should be equal to the number of positions');\n end\nend\n\n% extract the dim now that the bookkeeping is done\ndim = pos2dim(pos);\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/pos2dim3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.4859305133593912}} {"text": "classdef PrintMicroStructuresForGaussianMean < handle\n \n properties (Access = private)\n rho\n xi\n phi\n stressProblem\n end\n \n properties (Access = private)\n rhoV\n xiV\n phiV\n hMesh\n pNorm\n fileName\n outPutPath \n end\n \n methods (Access = public)\n \n function obj = PrintMicroStructuresForGaussianMean()\n obj.init();\n for iTest = 3:3%length(obj.rhoV)\n obj.rho = obj.rhoV(iTest);\n obj.xi = obj.xiV(iTest);\n obj.computePhiV(); \n for iphi = 1:length(obj.phiV)\n obj.phi = obj.phiV(iphi);\n obj.printOptimalMicroStructure(iTest,iphi); \n end\n end\n end\n \n end\n \n methods (Access = private)\n \n function init(obj)\n obj.rhoV = [0.9 0.9 0.5 0.5];\n obj.xiV = [83.7951 58.0865 39.0219 27.0665]*pi/180;\n obj.pNorm = 16;\n obj.fileName = 'OptimalMicroForStress';\n obj.outPutPath = '/home/alex/git-repos/MicroStructurePaper/'; \n end\n \n function computePhiV(obj)\n obj.phiV = [0,pi/4,pi/2,3*pi/4,pi,obj.xi,pi - obj.xi];\n end\n \n function printOptimalMicroStructure(obj,iTest,iPhi)\n obj.createStressProblem(iTest,iPhi);\n obj.stressProblem.computeOptimalExponent();\n obj.stressProblem.printOptimalMicroStructure();\n end\n \n function createStressProblem(obj,iTest,iPhi)\n s.rho = obj.rho;\n s.txi = obj.xi;\n s.fileName = [obj.fileName,'Case',num2str(iTest),'Phi',num2str(iPhi)];\n s.phi = obj.phi;\n s.hMesh = [];\n s.pNorm = obj.pNorm;\n sProblem = OneOptimalExponentComputerAndFunctionVariation(s);\n obj.stressProblem = sProblem;\n end \n \n end\n \nend", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/Homogenization/Sources/VadamecumCalculator/PrintMicroStructuresForGaussianMean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660688, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.4859305105544893}} {"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 sgmga_vcn_tests ( )\n\n%*****************************************************************************80\n%\n%% SGMGA_VCN_TESTS tests SGMGA_VCN.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 21 May 2010\n%\n% Author:\n%\n% John Burkardt\n%\n addpath ( '../sandia_rules' );\n\n timestamp ( );\n\n test_num = 12;\n\n dim_num_array(1:test_num,1) = [ 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4 ]';\n level_max_array(1:test_num,1) = [ 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 2, 3 ]';\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SGMGA_VCN_TESTS\\n' );\n fprintf ( 1, ' calls SGMGA_VCN_TEST.\\n' );\n%\n% Isotropic examples.\n%\n for test = 1 : test_num\n\n dim_num = dim_num_array(test);\n importance(1:dim_num,1) = 1.0;\n level_weight = sgmga_importance_to_aniso ( dim_num, importance );\n level_max = level_max_array(test);\n q_min = level_max - sum ( level_weight(1:dim_num) );\n q_max = level_max;\n\n sgmga_vcn_test ( dim_num, importance, level_weight, q_min, q_max );\n\n end\n%\n% Zero weight example.\n%\n dim_num = 3;\n importance = [ 1.0, 0.0, 1.0]';\n level_weight = sgmga_importance_to_aniso ( dim_num, importance );\n level_max = 2\n q_min = level_max - sum ( level_weight(1:dim_num) );\n q_max = level_max;\n\n sgmga_vcn_test ( dim_num, importance, level_weight, q_min, q_max );\n%\n% Anisotropic examples.\n%\n for test = 1 : test_num\n\n dim_num = dim_num_array(test);\n importance(1:dim_num,1) = ( 1 : dim_num );\n level_weight = sgmga_importance_to_aniso ( dim_num, importance );\n level_max = level_max_array(test);\n q_min = level_max - sum ( level_weight(1:dim_num) );\n q_max = level_max;\n\n sgmga_vcn_test ( dim_num, importance, level_weight, q_min, q_max );\n\n end\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SGMGA_VCN_TESTS:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n rmpath ( '../sandia_rules' );\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_vcn_tests.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.4859304948209936}} {"text": "%compute dcentralheadang\nfunction [data,units]=compute_dcentralheadang(trx,n)\n\nlarvae=trx.exp2flies{n};\nnumlarvae=numel(larvae);\n%absdtailheadang=cell(1,numlarvae);\ndcentralheadang=cell(1,numlarvae);\nfor i=1:numlarvae\n larva=larvae(i);\n% absdtailheadang{1,i}=real(acos(cos(tailheadang{1,i}(1:end-1)).*cos(tailheadang{1,i}(2:end))+sin(tailheadang{1,i}(1:end-1)).*sin(tailheadang{1,i}(2:end))))./trx(i).dt;\n% temp=tailheadang{1,i}-pi/2;\n% cosperp=sign(cos(temp(1:end-1)).*cos(tailheadang{1,i}(2:end))+sin(temp(1:end-1)).*sin(tailheadang{1,i}(2:end)));\n% temp2=bsxfun(@times,absdtailheadang{1,i},cosperp);\n dcentralheadang{1,i}=modrange(diff(trx(larva).centralheadang),-pi,pi)./trx(larva).dt;\n % KB: this angle distance didn't make sense to me, changed to one that\n % made sense to me\n %dcentralheadang{1,i}=(mod1(trx(larva).centralheadang(2:end)-trx(larva).centralheadang(1:end-1),pi)-pi)./trx(larva).dt;\nend\n\nunits=parseunits('rad/s');\ndata=dcentralheadang;\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/larva_compute_perframe_features/compute_dcentralheadang.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4859234061538386}} {"text": "function [G,E,R,data] = arap_gradient(V,F,U,varargin)\n % ARAP_GRADIENT Compute the Gradient of an as-rigid-as-possible for a mesh in\n % rest configuration (V,F) with vertices now at U, according to \"A Simple\n % Geometric Model for Elastic Deformations\" [Chao et al. 2010]\n %\n % G = arap_gradient(V,F,U)\n % [G,E,R] = arap_gradient(V,F,U,'ParameterName',ParameterValue, ...)\n %\n % Inputs:\n % V #V by dim rest vertex positions\n % F #F by simplex-size simplex indices into V\n % U #V by dim deformed vertex positions\n % Optional:\n % 'Rotations' followed by R dim by dim by #R list of best fit\n % rotations\n % 'Energy' followed by either 'spokes','spokes-and-rims','elements'\n % Outputs:\n % G #V by dim list of gradient vectors per vertex\n % E arap energy\n % R dim by dim by #R list of best fit rotations\n % data \n %\n % See also: arap, arap_hessian\n %\n % Example:\n % % Given a mesh (V,F) and deformed positions U0, flow to energy minimum\n % % using Newton's method.\n % clf;\n % hold on;\n % tsurf(F,V,fphong,'FaceColor','r','SpecularStrength',0,'AmbientStrength',0.5);\n % t = tsurf(F,U0,fphong,'FaceColor','b','SpecularStrength',0,'AmbientStrength',0.5);\n % hold off;\n % axis equal;\n % view(2);\n % camlight;\n % U = U0;\n % delta_t = 1e-1;\n % while true\n % [G,E] = arap_gradient(V,F,U);\n % U = U - delta_t * G;\n % U = bsxfun(@plus,U,mean(V)-mean(U)+[max(V(:,1))-min(V(:,1)) 0 0]);\n % t.Vertices = U;\n % title(sprintf('E = %g\\n',E),'FontSize',20);\n % drawnow;\n % end\n %\n\n % default values\n switch size(F,2)\n case 4\n energy = 'elements';\n case 3\n energy = 'spokes-and-rims';\n end\n single_precision = true;\n R = [];\n data = [];\n % Map of parameter names to variable names\n params_to_variables = containers.Map( ...\n {'Energy','Rotations','Data','SinglePrecision'}, ...\n {'energy','R','data','single_precision'});\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 % TODO: implement \"flat\" arap like `arap.m`, for now use placeholders with\n % non-flat defaults.\n ref_V = V;\n ref_F = F;\n dim = size(ref_V,2);\n flat = false;\n\n if isempty(data)\n ss = size(F,2);\n data.L = cotmatrix(V,F);\n if isempty(R)\n data.CSM = covariance_scatter_matrix(ref_V,ref_F,'Energy',energy);\n end\n [~,data.K] = arap_rhs(ref_V,ref_F,[],'Energy',energy);\n end\n\n % compute covariance matrix elements\n S = zeros(size(data.CSM,1),dim);\n S(:,1:dim) = data.CSM*repmat(U,dim,1);\n % dim by dim by n list of covariance matrices\n SS = permute(reshape(S,[size(data.CSM,1)/dim dim dim]),[2 3 1]);\n % fit rotations to each deformed vertex\n R = fit_rotations(SS,'SinglePrecision',single_precision);\n\n nr = size(R,3);\n Rcol = reshape(permute(R,[3 1 2]),nr*dim*dim,1);\n dV = data.K * Rcol;\n dV = reshape(dV,[size(V,1) dim]);\n\n G = -(data.L*U + dV);\n if nargout > 1\n E = trace(-U'*0.5*data.L*U - U'*dV - V'*0.5*data.L*V);\n end\n\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/arap_gradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.48592339572087545}} {"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 estimatedLabels = GMLVQ_classify(Data, model)\n\n%GMLVQ_classify.m - classifies the given data with the given model\n%\n% estimatedLabels = GMLVQ_classify(Data, model)\n%\n% Input and output arguments: \n% trainSet (struct)\n% (matrix) matrix with training samples in its rows\n% model : GMLVQ model with prototypes w their labels c_w and the matrix omega\n% \n% estimatedLabels : the estimated labels\n%\n% example for usage:\n% trainSet = [1,2,3;4,5,6;7,8,9];\n% trainLab = [1;1;2];\n% GMLVQ_model=gmlvq_core(trainSet,trainLab); % minimal parameters required\n% estimatedTrainLabels = GMLVQ_classify(trainSet, GMLVQ_model);\n% trainError = mean( trainLab ~= estimatedTrainLabels );\n% \n% Kerstin Bunte\n% kerstin.bunte@googlemail.com\n% Mon Nov 05 09:05:52 CEST 2012\n%\n% Conditions of GNU General Public License, version 2 and BSD License apply.\n% See file 'license-gpl2.txt' and 'BSD_license.txt' enclosed in this package.\n% Programs are not for use in critical applications!\n%\n\n% Contributed to SOM Toolbox vs2, December 3rd, 2012 by Alexander Schulz\n% Copyright (c) Kerstin Bunte\n% http://www.cis.hut.fi/projects/somtoolbox/\n\nif isstruct(Data)\n Data = Data.data;\nend\n\nif ~isfield(model, 'w')\n model.c_w = som_label2num(model.labels);\n dist = computeDistance(Data, model.codebook, model);\nelse\n dist = computeDistance(Data, model.w, model);\nend\n\n[~, index] = min(dist,[],2);\n\nestimatedLabels = model.c_w(index);\n\n\n\nfunction distance = computeDistance(X, W, model)\nnb_samples = size(X,1);\ndistance = zeros(nb_samples,length(model.c_w));\n\n\n% tic;\n% for i = 1:size(W,1)\n% delta = X - ones(P,1) * W(i,:);\n% delta = bsxfun(@minus, X, W(i,:));\n% delta(isnan(delta)) = 0;\n % Hadamard product: to skip unnecessary calculation between two different examples\n% distance(1:nb_samples,i) = sum( ((delta*model.omega'*model.omega).*delta) ,2 ); \n% wi = W(i,:);\n% distance(1:nb_samples,i) = sum( (( (X-wi(ones(nb_samples,1),:)) *model.omega'*model.omega).*(X-wi(ones(nb_samples,1),:))) ,2 );\n% end\n% disp(toc);\nif isfield(model,'psis')\n if length(model.psis)~=size(W,1)\n classes = unique(model.c_w);\n for i = 1:size(W,1)\n matrixIdx = classes==model.c_w(i);\n% delta = X-ones(nb_samples,1)*W(i,:); \n% distance(1:nb_samples,i) = sum( ((delta* model.psis{matrixIdx}'*model.psis{matrixIdx}).*delta) ,2 );\n distance(1:nb_samples,i) = sum((bsxfun(@minus, X, W(i,:))*model.psis{matrixIdx}').^2, 2);\n end\n else\n for i = 1:size(W,1)\n% delta = X-ones(nb_samples,1)*W(i,:);\n% distance(1:nb_samples,i) = sum( ((delta* model.psis{i}'*model.psis{i}).*delta) ,2 );\n distance(1:nb_samples,i) = sum((bsxfun(@minus, X, W(i,:))*model.psis{i}').^2, 2);\n end\n end\nelse\n if isfield(model,'lambda')\n for i = 1:size(W,1)\n% delta = X-ones(nb_samples,1)*W(i,:);\n% distance(1:nb_samples,i) = sum( (( delta *model.lambda).*delta) ,2 );\n delta = bsxfun(@minus, X, W(i,:));\n distance(1:nb_samples,i) = sum(bsxfun(@times,delta.^2,model.lambda), 2);\n% distance(1:nb_samples,i) = sum( (( delta *model.lambda).*delta) ,2 );\n end\n end\n if isfield(model,'omega')\n % tic;\n for i = 1:size(W,1)\n% delta = X-ones(nb_samples,1)*W(i,:);\n% distance(1:nb_samples,i) = sum( (( delta *model.omega'*model.omega).*delta) ,2 );\n distance(1:nb_samples,i) = sum((bsxfun(@minus, X, W(i,:))*model.omega').^2, 2);\n end\n % disp(toc);\n end\nend\n", "meta": {"author": "ilarinieminen", "repo": "SOM-Toolbox", "sha": "f2597abc1ae33c2060e0443d49e854011ff21831", "save_path": "github-repos/MATLAB/ilarinieminen-SOM-Toolbox", "path": "github-repos/MATLAB/ilarinieminen-SOM-Toolbox/SOM-Toolbox-f2597abc1ae33c2060e0443d49e854011ff21831/contrib/gmlvq/GMLVQ_classify.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4859233957208754}} {"text": "function ins=ins_time_updata(ins)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% INS time update\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Copyright (C) 2020-2025, by Kai Chen, All rights reserved.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nins.Phi=update_trans_mat(ins);\n\nG=zeros(15,15);\nG(1:3,1:3)=-ins.Cnb;\nG(4:6,4:6)=ins.Cnb;\nG(10:12,10:12)=eye(3);\nG(13:15,13:15)=eye(3);\n\nQ0=G*ins.Q*G';\nP0=ins.P+0.5*Q0;\nins.P=ins.Phi*P0*ins.Phi'+0.5*Q0;\n\n% ins.P=ins.Phi*ins.P*ins.Phi'+ins.Q;\n\nreturn", "meta": {"author": "kaichen686", "repo": "GINav", "sha": "bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666", "save_path": "github-repos/MATLAB/kaichen686-GINav", "path": "github-repos/MATLAB/kaichen686-GINav/GINav-bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666/src/ins/ins_time_updata.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.48592339050439354}} {"text": "function check = triangle_check ( a, b, c )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_CHECK checks the parameters of the Triangle CDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 October 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, B, C, the parameters of the PDF.\n% A <= B <= C and A < C.\n%\n% Output, logical TRIANGLE_CHECK, is true if the parameters are legal.\n%\n if ( b < a )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRIANGLE_CHECK - Fatal error!\\n' );\n fprintf ( 1, ' B < A.\\n' );\n check = 0;\n return\n end\n\n if ( c < b )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRIANGLE_CHECK - Fatal error!\\n' );\n fprintf ( 1, ' C < B.\\n' );\n check = 0;\n return\n end\n\n if ( a == c )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRIANGLE_CHECK - Fatal error!\\n' );\n fprintf ( 1, ' A == C.\\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/triangle_check.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.4859007429360179}} {"text": "% This is something I always wondered...\n% Manuel Diaz, NTU, 2014.01.21\n\n%\nA = magic(6);\n\n% \nidx = 1:6; \nidx_new = repmat(idx,[6,1]);\n\n% \nx = linspace(0,1,6);\nv = sin(2*pi*x);\n\n% operation\nb = A.*v(idx_new); \ndisp(b);\n\n% conclusion:\n% matlab indexes = c++ pointers ;)\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/CFD/index_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.4859007346941444}} {"text": "filename='Cantileverbeam_Hexahedra_Linear_Structured';\nptype = 'MACRO';\nmethod = 'SIMPALL';\nmaterialType = 'ISOTROPIC';\ninitial_case = 'holes';\ncost = {'compliance', 'perimeter'};\nweights = [1 0.001];\nconstraint = {'volumeConstraint'};\noptimizer = 'HAMILTON-JACOBI'; \nincrementFactor = 1;\ndesignVariable = 'LevelSet';\nfilterType = 'P1';\nconstraint_case = 'INEQUALITY';\n\nnsteps = 10;\nVfrac_final = 0.1;\nPerimeter_target=3.5;\noptimality_final =1e-4;\nconstr_final =1e-4;\n\nBCscale_factor = 0.3;\nHJiter0 = 1;\ne2 = 100;\nN_holes = [12 5 5];\nR_holes = 0.4;\nphase_holes = [0 0 0];\n\nVfrac_initial = 0.6;\noptimality_initial = 5e-2;\nconstr_initial = 5e-2;\n\nTOL.rho_plus = 1;\nTOL.rho_minus = 0;\nTOL.E_plus = 1;\nTOL.E_minus = 1e-3;\n\n% maxiter = 1;\nTOL.nu_plus = 0.3;\nTOL.nu_minus = 0.3;\n\nplotting = 1;\nprinting = 0;\nmonitoring = 1;\nmonitoring_interval = 1;", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/Benchmarks/Cantilever/CantileverHexahedra_Case_5_2_3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.48566917182556074}} {"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 varargout = meshVertexClustering(vertices, faces, spacing, varargin)\n%MESHVERTEXCLUSTERING Simplifies a mesh using vertex clustering.\n%\n% [V2, F2] = meshVertexClustering(V, F, SPACING)\n% [V2, F2] = meshVertexClustering(MESH, SPACING)\n% MESH2 = meshVertexClustering(...)\n%\n% Simplifies a mesh using vertex clustering. Input mesh is specified\n% either by a pair V, F containing the vertex coordinates and the faces\n% informations, or by a structure with fields 'vertices' and 'faces'.\n%\n% The SPACING input defines the size of the grid. It can be either a\n% scalar (uniform grid) or a 1-by-3 row vector. \n%\n% The output is specified either in two outputs, or in a structure with\n% fields 'vertices' and 'faces'.\n%\n% Example\n% [x, y, z] = meshgrid(1:100, 1:100, 1:100);\n% img = hypot3(x-51.12, y-52.23, z-53.34);\n% [faces, vertices] = isosurface(img, 45);\n% [v2, f2] = meshVertexClustering(vertices, faces, 10);\n% figure; axis equal; axis([0 100 0 100 0 100]);\n% drawMesh(v2, f2);\n%\n% See also \n% reducepatch, smoothMesh\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@inra.fr\n% Created: 2019-01-28, using Matlab 9.5.0.944444 (R2018b)\n% Copyright 2019-2022 INRA - Cepia Software Platform\n\n%% Initialisation\n\nif isstruct(vertices)\n if nargin > 2\n varargin = [{spacing} varargin(:)];\n end\n spacing = faces;\n\n mesh = vertices;\n vertices = mesh.vertices;\n faces = mesh.faces;\nend\n\n% ensure input mesh is a triangulation\nfaces = triangulateFaces(faces);\n\n% ensure spacing is a 1-by-3 array\nif isscalar(spacing)\n spacing = [spacing spacing spacing];\nend\n\n% extract grid origin\norigin = [0 0 0];\nif ~isempty(varargin)\n origin = varargin{1};\nend\n\n\n%% Apply grid simplification\n\n% identify the vertices belonging to the same grid\n[v2, I, J] = unique(round(bsxfun(@rdivide, bsxfun(@minus, vertices, origin), spacing)), 'rows');\n\n\n%% compute reduced vertex coordinates\n\n% compute coordinates of new vertices\nfor iVertex = 1:length(I)\n gridVertices = vertices(J == iVertex, :);\n v2(iVertex, :) = mean(gridVertices, 1);\nend\n\n\n%% Compute new faces\n\n% create empty array\nfaces2 = zeros(0, 3);\n\n% iterate over old faces, and keep only faces whose vertices belong to\n% different cell grids\nnFaces = size(faces, 1);\nfor iFace = 1:nFaces\n % current face\n face = faces(iFace, :);\n \n % equivalent face with new vertices\n face2 = J(face)';\n \n % some vertices may belong to same cell, so we need to adjust\n % processing\n nInds = length(unique(face2));\n if nInds == 3\n % vertices belong to three different cells -> create a new face\n \n % keep smaller vertex at first position\n [tmp, indMin] = min(face2); %#ok\n face2 = circshift(face2, [1-indMin 0]);\n \n % append the new face to the array\n faces2 = [faces2 ; face2]; %#ok\n end\nend\n\n% remove duplicate faces\nfaces2 = unique(faces2, 'rows');\n\nif nargout == 1\n varargout{1} = struct('vertices', v2, 'faces', faces2);\nelse\n varargout = {v2, faces2};\nend\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/meshes3d/meshVertexClustering.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.48560064953749354}} {"text": "% LOOK FOR SINGULAR POINTS IN JOINT SPACE\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 singular_points = find_singular_points(param)\n\nsingular_points=[];\n\nq=[0 0 0 0];\n\nteta = eval(param.DH.theta);\nd = eval(param.DH.d);\na = eval(param.DH.a);\nalfa = eval(param.DH.alpha);\n\n%J = eval(param.J)\n\n\nq1=-pi:0.05:pi;\nq2=-pi:0.05:pi;\n\nfor i=1:length(q1),\n fprintf('\\nIteration %d of %d', i, length(q1))\n for j=1:length(q2),\n q=[q1(i) q2(j) 0];\n J = eval(param.J);\n \n val = det(J);\n if abs(val) < 0.0001\n singular_points = [singular_points q'];\n end\n end\nend", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/demos/more_demos/find_singular_points.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290698, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4855166773348802}} {"text": "function [C,phi,S12,S1,S2,t,f,zerosp,confC,phistd,Cerr]=cohgrampt(data1,data2,movingwin,params,fscorr)\n% Multi-taper time-frequency coherence - two point processes given as times\n%\n% Usage:\n%\n% [C,phi,S12,S1,S2,t,f,zerosp,confC,phistd,Cerr]=cohgrampt(data1,data2,movingwin,params,fscorr)\n% Input: \n% Note units have to be consistent. Thus, if movingwin is in seconds, Fs\n% has to be in Hz. see chronux.m for more information.\n%\n% data1 (structure array of spike times with dimension trials; also accepts 1d array of spike times) -- required\n% data2 (structure array of spike times with dimension trials; also accepts 1d array of spike times) -- required\n% movingwin (in the form [window winstep] -- required\n% params: structure with fields tapers, pad, Fs, fpass, err, trialave\n% - optional\n% tapers : precalculated tapers from dpss or in the one of the following\n% forms: \n% (1) A numeric vector [TW K] where TW is the\n% time-bandwidth product and K is the number of\n% tapers to be used (less than or equal to\n% 2TW-1). \n% (2) A numeric vector [W T p] where W is the\n% bandwidth, T is the duration of the data and p \n% is an integer such that 2TW-p tapers are used. In\n% this form there is no default i.e. to specify\n% the bandwidth, you have to specify T and p as\n% well. Note that the units of W and T have to be\n% consistent: if W is in Hz, T must be in seconds\n% and vice versa. Note that these units must also\n% be consistent with the units of params.Fs: W can\n% be in Hz if and only if params.Fs is in Hz.\n% The default is to use form 1 with TW=3 and K=5\n% Note that T has to be equal to movingwin(1).\n%\n%\t pad\t\t (padding factor for the FFT) - optional (can take values -1,0,1,2...). \n% -1 corresponds to no padding, 0 corresponds to padding\n% to the next highest power of 2 etc.\n%\t\t\t \t e.g. For N = 500, if PAD = -1, we do not pad; if PAD = 0, we pad the FFT\n%\t\t\t \t to 512 points, if pad=1, we pad to 1024 points etc.\n%\t\t\t \t Defaults to 0.\n% Fs (sampling frequency) - optional. Default 1.\n% fpass (frequency band to be used in the calculation in the form\n% [fmin fmax])- optional. \n% Default all frequencies between 0 and Fs/2\n% err (error calculation [1 p] - Theoretical error bars; [2 p] - Jackknife error bars\n% [0 p] or 0 - no error bars) - optional. Default 0.\n% trialave (average over trials when 1, don't average when 0) - optional. Default 0\n% fscorr (finite size corrections, 0 (don't use finite size corrections) or \n% 1 (use finite size corrections) - optional\n% (available only for spikes). Defaults 0.\n% Output:\n% C (magnitude of coherency time x frequencies x trials for trialave=0; \n% time x frequency for trialave=1)\n% phi (phase of coherency time x frequencies x trials for no trial averaging; \n% time x frequency for trialave=1)\n% S12 (cross spectrum - time x frequencies x trials for no trial averaging; \n% time x frequency for trialave=1)\n% S1 (spectrum 1 - time x frequencies x trials for no trial averaging; \n% time x frequency for trialave=1)\n% S2 (spectrum 2 - time x frequencies x trials for no trial averaging; \n% time x frequency for trialave=1)\n% t (time)\n% f (frequencies)\n% zerosp (1 for windows and trials where spikes were absent (in either channel),zero otherwise)\n% confC (confidence level for C at 1-p %) - only for err(1)>=1\n% phistd - theoretical/jackknife (depending on err(1)=1/err(1)=2) standard deviation for phi \n% Note that phi + 2 phistd and phi - 2 phistd will give 95% confidence\n% bands for phi - only for err(1)>=1 \n% Cerr (Jackknife error bars for C - use only for Jackknife - err(1)=2)\n\nif nargin < 3; error('Need data1 and data2 and window parameters'); end;\nif nargin < 4; params=[]; end;\n\nif length(params.tapers)==3 & movingwin(1)~=params.tapers(2);\n error('Duration of data in params.tapers is inconsistent with movingwin(1), modify params.tapers(2) to proceed')\nend\n\n[tapers,pad,Fs,fpass,err,trialave,params]=getparams(params);\nif nargin < 5 || isempty(fscorr); fscorr=0; end;\n\nif nargout > 10 && err(1)~=2; \n error('Cerr computed only for Jackknife. Correct inputs and run again');\nend;\nif nargout > 8 && err(1)==0;\n error('Errors computed only if err(1) is not equal to zero');\nend;\n\n[N,Ch]=check_consistency(data1,data2);\n[mintime1,maxtime1]=minmaxsptimes(data1);\n[mintime2,maxtime2]=minmaxsptimes(data2);\nmintime=min(mintime1,mintime2);\nmaxtime=max(maxtime1,maxtime2);\n\ntn=mintime+movingwin(1)/2:movingwin(2):maxtime-movingwin(1)/2;\nNwin=round(Fs*movingwin(1)); % number of samples in window\n% Nstep=round(movingwin(2)*Fs); % number of samples to step through\nnfft=max(2^(nextpow2(Nwin)+pad),Nwin);\nf=getfgrid(Fs,nfft,fpass); Nf=length(f);\nparams.tapers=dpsschk(tapers,Nwin,Fs); % check tapers\nnw=length(tn);\nif trialave;\n C=zeros(nw,Nf);\n S12=zeros(nw,Nf);\n S1=zeros(nw,Nf);\n S2=zeros(nw,Nf);\n phi=zeros(nw,Nf);\n Cerr=zeros(2,nw,Nf);\n% phierr=zeros(2,nw,Nf);\n phistd=zeros(nw,Nf);\nelse\n C=zeros(nw,Nf,Ch);\n S12=zeros(nw,Nf,Ch);\n S1=zeros(nw,Nf,Ch);\n S2=zeros(nw,Nf,Ch);\n phi=zeros(nw,Nf,Ch);\n Cerr=zeros(2,nw,Nf,Ch);\n% phierr=zeros(2,nw,Nf,Ch);\n phistd=zeros(nw,Nf,Ch);\nend;\nzerosp=zeros(nw,Ch);\n\nfor n=1:nw;\n t=linspace(tn(n)-movingwin(1)/2,tn(n)+movingwin(1)/2,Nwin);\n datawin1=extractdatapt(data1,[t(1) t(end)]);datawin2=extractdatapt(data2,[t(1) t(end)]);\n if nargout==11;\n [c,ph,s12,s1,s2,f,zsp,confc,phie,cerr]=coherencypt(datawin1,datawin2,params,fscorr,t);\n% phierr(1,n,:,:)=squeeze(phie(1,:,:));\n% phierr(2,n,:,:)=squeeze(phie(2,:,:));\n phistd(n,:,:)=phie;\n Cerr(1,n,:,:)=squeeze(cerr(1,:,:));\n Cerr(2,n,:,:)=squeeze(cerr(2,:,:));\n elseif nargout==10;\n [c,ph,s12,s1,s2,f,zsp,confc,phie]=coherencypt(datawin1,datawin2,params,fscorr,t);\n% phierr(1,n,:,:)=squeeze(phie(1,:,:));\n% phierr(2,n,:,:)=squeeze(phie(2,:,:));\n phistd(n,:,:)=phie;\n else\n [c,ph,s12,s1,s2,f,zsp]=coherencypt(datawin1,datawin2,params,fscorr,t);\n end;\n C(n,:,:)=c;\n phi(n,:,:)=ph;\n S12(n,:,:)=s12;\n S1(n,:,:)=s1;\n S2(n,:,:)=s2;\n zerosp(n,:)=zsp;\nend;\nt=tn;\nC=squeeze(C); phi=squeeze(phi);S12=squeeze(S12); S1=squeeze(S1); S2=squeeze(S2);zerosp=squeeze(zerosp);\nif nargout > 9; confC=confc; end;\nif nargout==11;Cerr=squeeze(Cerr);end;\n% if nargout==10; phierr=squeeze(phierr);end\nif nargout==10; phistd=squeeze(phistd);end\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/chronux_2_12/spectral_analysis/pointtimes/cohgrampt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.5888891307678321, "lm_q1q2_score": 0.4855166722549758}} {"text": "function y = log_sum_exp( x, dim )\n\n%LOG_SUM_EXP log(sum(exp(x))).\n% LOG_SUM_EXP(X) = LOG(SUM(EXP(X)).\n%\n% When used in a CVX model, LOG_SUM_EXP(X) causes CVX's successive\n% approximation method to be invoked, producing results exact to within\n% the tolerance of the solver. This is in contrast to LOGSUMEXP_SDP,\n% which uses a single SDP-representable global approximation.\n%\n% If X is a matrix, LOGSUMEXP_SDP(X) will perform its computations\n% along each column of X. If X is an N-D array, LOGSUMEXP_SDP(X)\n% will perform its computations along the first dimension of size\n% other than 1. LOGSUMEXP_SDP(X,DIM) will perform its computations\n% along dimension DIM.\n%\n% Disciplined convex programming information:\n% LOG_SUM_EXP(X) is convex and nondecreasing in X; therefore, X\n% must be convex (or affine).\n\nerror( nargchk( 1, 2, nargin ) );\nif ~isreal( x ),\n error( 'Argument must be real.' );\nend\ny = exp( x );\nif nargin == 1,\n y = sum( y );\nelse\n y = sum( y, dim );\nend\ny = log( y );\n\n% Copyright 2010 Michael C. Grant and Stephen P. Boyd. \n% See the file COPYING.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/cvx-1.21.b795/functions/log_sum_exp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.4855138535715639}} {"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": "%filename='test2d_micro';\nfilename = 'MicroQuad';\nptype = 'MICRO';\nmethod = 'SIMPALL';\nmaterialType = 'ISOTROPIC';\ninitial_case = 'circleInclusion';\ncost={'chomog_alphabeta'};\nweights=[1];\nconstraint = {'volumeConstraint'};\nconstraint_case = 'EQUALITY';\n%incrementFactor = 1;\n%designVariable = 'Density';\ndesignVariable = 'LevelSet';\nfilterType = 'P1';\nfracRadius = 0.51;\n%optimizer = 'IPOPT';\noptimizer = 'DualNestedInPrimal';\n%optimizer = 'AlternatingPrimalDual';\n\n%optimizerUnconstrained = 'PROJECTED GRADIENT';\n%line_search_initiator = 'INCREASING LAST STEP';\n%incrementFactor = 1.95;\n\noptimizerUnconstrained = 'SLERP';\n\n\nnsteps = 1;\nVfrac_final = 0.4;\nPerimeter_target=1;\noptimality_final = 1*1e-3;\nconstr_final =1e-12;\n\nVfrac_initial = 0.8;\noptimality_initial = 1*1e-3;\nconstr_initial = 1e-12;\n\nTOL.rho_plus = 1;\nTOL.rho_minus = 0;\nTOL.E_plus = 1;\nTOL.E_minus = 1e-3;\nTOL.nu_plus = 1/3;\nTOL.nu_minus = 1/3;\n\n%Micro\nepsilon_isotropy_initial=1e-1;\nepsilon_isotropy_final = 1e-3;\nmicro.alpha =[1 1 0]';\nmicro.beta =[1 1 0]';\n\n\n\n% For all tests\nplotting = true;\nprinting = true;\nmonitoring = true;\nmonitoring_interval = 1;\nmaxiter = 100;", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/Applications/MaterialDesign/CompositeMaterialDesignQuadLevelSetP1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.5660185351961016, "lm_q1q2_score": 0.48551265044045594}} {"text": "function train_CNN_model(varargin)\n\nsetup('useGPU', true);\n\ntic\n\n% Load the data\nroot_loc = 'D:\\Datasets\\detection_validation';\nlocation = [root_loc, '/prep_data/'];\n\nfaceCheckersLoc_train = dir([location 'face_validator_train_*']); \nfaceCheckersLoc_test = dir([location 'face_validator_test_*']);\n\ncorrs_all = [];\nrmses_all = [];\n\nfaceCheckers = struct;\n\n% As we will be training a classifier that will act as a regressor,\n% binarize it\nnum_bins = 30;\n\nfor i=1:numel(faceCheckersLoc_train)\n \n load([location faceCheckersLoc_train(i).name]);\n \n % set a max value to the error\n errors(errors > 3) = 3;\n errors_train = quantizeContinuous(errors, 0, 3, num_bins);\n examples_train = single(examples);\n clear examples\n \n mean_ex = mean(examples_train);\n std_ex = std(examples_train); \n std_ex = std_ex / 256;\n examples_train = bsxfun(@times, bsxfun(@minus, examples_train, mean_ex), 1./std_ex);\n num_examples_train = size(examples_train,1);\n \n % Add rows and columns untill we have 60 x 60 image\n \n % keep adding rows\n while(size(mask,1) < 60) \n mask = cat(1, mask, false(1, size(mask,2)));\n triX = cat(1, triX, -ones(1, size(mask,2)));\n end\n \n % keep adding cols\n while(size(mask,2) < 60) \n mask = cat(2, mask, false(size(mask,1),1));\n triX = cat(2, triX, -ones(size(triX,1),1));\n end\n\n examples_r = single(zeros(size(mask, 1), size(mask, 2), num_examples_train));\n \n img_curr = zeros(size(mask));\n for e=1:num_examples_train\n \n img_curr(mask) = examples_train(e,:);\n examples_r(:, :, e) = img_curr;\n \n end \n \n imdb.images.data = examples_r;\n clear examples_r\n imdb.images.label = errors_train';\n imdb.images.id = 1:numel(errors_train);\n \n % Split data for training and validation (20%)\n imdb.images.set = ones(1, numel(errors_train));\n imdb.images.set(round(4*end/5):end) = 2;\n \n % Visualize some of the data\n figure(10) ; clf ; colormap gray ;\n subplot(1,2,1) ;\n pos_samples = squeeze(imdb.images.data(:,:,imdb.images.label==1)); \n vl_imarraysc(pos_samples(:,:,1:20)) ;\n axis image off ;\n title('Positive training data') ;\n\n subplot(1,2,2) ;\n neg_samples = squeeze(imdb.images.data(:,:,imdb.images.label>5)); \n vl_imarraysc(neg_samples(:,:,1:20)) ;\n axis image off ;\n title('Negative training data') ;\n \n net = initializeFaceCNN(num_bins) ;\n \n trainOpts.batchSize = 100 ;\n trainOpts.numEpochs = 20;\n trainOpts.continue = true ;\n trainOpts.gpus = [1] ;\n trainOpts.learningRate = 0.001 ;\n trainOpts.expDir = ['trained/intermediate/face_validator_' num2str(i)];\n trainOpts.errorFunction = 'regression';\n trainOpts = vl_argparse(trainOpts, varargin);\n\n % Call training function in MatConvNet\n [net,info] = cnn_train_reg(net, imdb, @getBatch, trainOpts) ;\n\n % Move the CNN back to the CPU if it was trained on the GPU\n if numel(trainOpts.gpus) > 0\n net = vl_simplenn_move(net, 'cpu') ;\n end\n\n % Save the result for later use\n net.layers(end) = [] ;\n net.imageMean = mean_ex ;\n net.imageStd = std_ex;\n \n% save('data/face-experiment/facecnn.mat', '-struct', 'net') ;\n\n \n % Evaluate on the test data, also evaluate using correlation and RMSE \n load([location faceCheckersLoc_test(i).name]);\n \n % set a max value to the error\n errors(errors > 3) = 3;\n errors_test = errors;\n errors_q = quantizeContinuous(errors, 0, 3, num_bins);\n errors_test_q = errors_q;\n examples_test = single(examples);\n examples_test = bsxfun(@times, bsxfun(@minus, examples_test, net.imageMean), 1./net.imageStd);\n num_examples_test = size(examples_test,1);\n \n % keep adding rows\n while(size(mask,1) < 60) \n mask = cat(1, mask, false(1, size(mask,2)));\n triX = cat(1, triX, -ones(1, size(mask,2)));\n end\n \n % keep adding cols\n while(size(mask,2) < 60) \n mask = cat(2, mask, false(size(mask,1),1));\n triX = cat(2, triX, -ones(size(triX,1),1));\n end \n \n examples_r = single(zeros(size(mask, 1), size(mask, 2), num_examples_test));\n \n img_curr = zeros(size(mask));\n for e=1:num_examples_test\n \n img_curr(mask) = examples_test(e,:);\n examples_r(:, :, e) = img_curr;\n \n end \n examples_test = zeros(size(examples_r,1), size(examples_r,2), 1, size(examples_r,3));\n examples_test(:) = single(examples_r(:)); \n \n ids = 1:99:num_examples_test;\n \n errors_all_test = zeros(num_examples_test,1);\n for k=1:numel(ids)-1\n examples_test_sm = single(examples_test(:,:,:,ids(k):ids(k+1)-1));\n res = vl_simplenn(net, examples_test_sm, [], []);\n res = gather(res(end).x);\n [~,res] = sort(res, 3, 'descend') ;\n res = squeeze(res);\n res = res(1,:);\n\n errors_test_rec = unQuantizeContinuous(res, 0, 3, num_bins)';\n errors_all_test(ids(k):ids(k+1)-1) = errors_test_rec;\n end\n errors_all_test = errors_all_test(1:ids(end));\n corrs_test = corr(errors_all_test, errors_test(1:numel(errors_all_test)));\n rmse_test = sqrt(mean((errors_all_test-errors_test(1:numel(errors_all_test))).^2));\n\n corrs_all = cat(1, corrs_all, corrs_test);\n rmses_all = cat(1, rmses_all, rmse_test);\n\n net.corrs = corrs_test;\n net.rmse = rmse_test;\n save([trainOpts.expDir, '/facecnn.mat'], '-struct', 'net');\n \n % The CNN\n faceCheckers(i).cnn = net;\n \n % The orientation\n faceCheckers(i).centres = centres;\n \n % The info for preprocessing \n faceCheckers(i).mask = mask;\n faceCheckers(i).nPix = nPix;\n faceCheckers(i).minX = minX;\n faceCheckers(i).minY = minY;\n \n faceCheckers(i).destination = shape(:,1:2); \n tri = load([location faceCheckersLoc_train(i).name], 'triangulation');\n faceCheckers(i).triangulation = tri.triangulation;\n faceCheckers(i).triX = triX;\n faceCheckers(i).mask = mask;\n faceCheckers(i).alphas = alphas;\n faceCheckers(i).betas = betas;\n \n faceCheckers(i).mean_ex = mean_ex;\n faceCheckers(i).std_ex = std_ex;\n \n WriteOutFaceCheckersCNNbinary(\"trained/validator_cnn.txt\", faceCheckers); \nend\n\nsave('trained/faceCheckers.mat', 'faceCheckers', 'corrs_all', 'rmses_all');\n\nend\n% --------------------------------------------------------------------\nfunction [im, labels] = getBatch(imdb, batch)\n% --------------------------------------------------------------------\n im = imdb.images.data(:,:,batch) ;\n im = reshape(im, 60, 60, 1, []) ;\n labels = imdb.images.label(1,batch) ;\nend\n\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/face_validation/train_CNN_model.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.48551264632443425}} {"text": "function bvalues=scd_scheme_bvalue(scheme)\ngyro = 42.57; % kHz/mT\nscheme(:,8) = gyro*scheme(:,4).*scheme(:,6); % um-1\nbvalues=(2*pi*scheme(:,8)).^2.*(scheme(:,5)-scheme(:,6)/3);\nend", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/src/Models_Functions/Diffusion/scd_scheme_bvalue.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4855126422084125}} {"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": "% computes cell and neuropil fluorescence for surround model of neuropil\nfunction [ops, stat, Fcell, FcellNeu] = extractSignalsSurroundNeuropil2(ops, stat)\n\nNk = numel(stat); % all ROIs\n\nNy = numel(ops.yrange);\nNx = numel(ops.xrange);\n\nstat = getNonOverlapROIs(stat, Ny, Nx);\n\n[Ly, Lx] = size(ops.mimg);\n\n% create cell masks and cell exclusion areas\n[stat, cellPix, cellMasks] = createCellMasks(stat, Ny, Nx);\n\n% create surround neuropil masks\n[ops, neuropMasks] = createNeuropilMasks(ops, stat, cellPix);\n\n% add surround neuropil masks to stat\nfor k = 1:Nk\n stat(k).ipix_neuropil = find(squeeze(neuropMasks(k,:,:))>0);\nend\n\n%%\nradius0 = 2; % cells you choose\n[stat, centerMasks, surroundMasks] = ...\n createCenterSurroundMasks2(ops, stat, Ny, Nx, 1, radius0);\n\nivcell = [stat.radius]>=radius0;\nNkv = sum(ivcell);\ncenterMasks = centerMasks(ivcell, :);\nsurroundMasks = surroundMasks(ivcell, :);\n%%\n% convert masks to sparse matrices for fast multiplication\nneuropMasks = sparse(double(neuropMasks(:,:)));\ncellMasks = sparse(double(cellMasks(:,:)));\ncenterMasks = sparse(double(centerMasks(:,:)));\nsurroundMasks = sparse(double(surroundMasks(:,:)));\n\n%% get fluorescence and surround neuropil\nnimgbatch = 2000;\nix = 0;\nfclose all;\nfid = fopen(ops.RegFile, 'r');\n\ntic\nF = NaN(Nk, sum(ops.Nframes), 'single');\nFneu = NaN(Nk, sum(ops.Nframes), 'single');\ncF = NaN(Nkv, sum(ops.Nframes), 'single');\nsF = NaN(Nkv, sum(ops.Nframes), 'single');\n\nwhile 1\n data = fread(fid, Ly*Lx*nimgbatch, '*int16');\n if isempty(data)\n break;\n end\n \n data = reshape(data, Ly, Lx, []);\n data = data(ops.yrange, ops.xrange, :);\n NT = size(data,3);\n data = reshape(data, [], NT);\n data = double(data);\n \n % process the data\n %data = my_conv2(data, ops.sig, [1 2]);\n \n % compute cell fluorescence\n % each mask is weighted by lam (SUM TO 1)\n F(:,ix + (1:NT)) = cellMasks * data;\n \n % compute neuropil fluorescence\n Fneu(:,ix + (1:NT)) = neuropMasks * data;\n \n % compute neuropil fluorescence\n cF(:,ix + (1:NT)) = centerMasks * data;\n sF(:,ix + (1:NT)) = surroundMasks * data;\n \n ix = ix + NT;\n if rem(ix, 3*NT)==0\n fprintf('Frame %d done in time %2.2f \\n', ix, toc)\n end\nend\nfclose(fid);\n\n%% get z drift\nif getOr(ops, 'getZdrift', 0)\n cFt = my_conv2(cF,.5, 2);\n sFt = my_conv2(sF,.5, 2);\n \n cFt = ordfilt2(cFt,1, true(1,100),[], 'symmetric');\n sFt = ordfilt2(sFt,1, true(1,100),[], 'symmetric');\n \n ratCS = log(max(1e-4,cFt )) - log(max(1e-4,sFt));\n ratCS = zscore(ratCS, 1, 2);\n \n [u, s, v] = svdecon(ratCS);\n \n ops.zdrift = v(:,1);\n \n figure(10)\n plot(v(:,1))\n hold all\nend\n%%\n% keyboard;\n\n% get activity stats\n[stat, F, Fneu] = getActivityStats(ops, stat, F, Fneu);\n\n%\ncsumNframes = [0 cumsum(ops.Nframes)];\nFcell = cell(1, length(ops.Nframes));\nFcellNeu = cell(1, length(ops.Nframes));\nfor i = 1:length(ops.Nframes)\n Fcell{i} = F(:, csumNframes(i) + (1:ops.Nframes(i)));\n FcellNeu{i} = Fneu(:, csumNframes(i) + (1:ops.Nframes(i)));\nend\n", "meta": {"author": "cortex-lab", "repo": "Suite2P", "sha": "c6a8ea9f01ffc8555429978e7fe97f843ad5b6d5", "save_path": "github-repos/MATLAB/cortex-lab-Suite2P", "path": "github-repos/MATLAB/cortex-lab-Suite2P/Suite2P-c6a8ea9f01ffc8555429978e7fe97f843ad5b6d5/signalExtraction/extractSignalsSurroundNeuropil2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463334, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4855126380923907}} {"text": "% This file performs the dual channel speech enhancement based on GSC beamformer and postfilter.\n% Refer to \"Analysis of Two-Channel Generalized Sidelobe Canceller (GSC) With Post-Filtering\".\n\nclear\nclc\n\n%% Load audio file\n\naudioname = 'carmix';\n[x, fs0 ] = audioread([audioname,'.wav']);\nfs = 16e3;\nx = resample(x,fs,fs0);\nNtime = size(x,1);\nNmic = size(x,2);\nif Nmic ~= 2\n error('The number of channels does not equal 2!')\nend\n\n%% Set parameters\n\nNFFT = 256;\nf = 0:fs/NFFT:fs/2;\nfull = 0:fs/NFFT:fs-fs/NFFT;\nlen = 17e-2;\nfragsize = 256;\noverlap = 0.5;\nc = 340;\nlamdaB0 = 1.54;\nomegalow = 1;\nomegahigh = 3;\ngamma0 = 4.6;\nalpha = 0.92;\nalphas = 0.80;\nalphadconst = 0.85;\nKL = 9; \nKR = 50; \nphi0 = 0.25;\n% b = [1 3 4 3 1] / 12;\nb = hanning(5).';\nb = b/sum(b);\nGmin = 10^(-20/20); % -20dB\nvmax = 5;\nEPIS = 1E-10;\nangle1 = 0;\nangle2 = 0.1;\nxia = 0.98;\nximin = 10^(-15/10);\n\n%% set window\n\nwin_1 = hanning(fragsize).';\nwin_2 = hanning(NFFT).';\nwin_pre = sqrt(win_1);\nwin_post = sqrt(win_2);\nwin_pre = sqrt(win_pre);\nwin_post = sqrt(win_post);\nscale_fac = sqrt(NFFT/sum(win_1));\nscale_postfac = 1.0 / sqrt(NFFT/sum(win_2));\nwin_pre = win_pre * scale_fac;\nwin_post = win_post * scale_postfac;\n\n%% Cutframes\n\n% ptout = zeros(Nmic, Nframe, fragsize);\nfor m = 1:Nmic\n [ptout(m,:,:), Nframe] = cutframe(x(:,m), fragsize, overlap);\nend\n\n%% Process\n\nZ = zeros(Nmic,NFFT/2+1);\npt = zeros(Nmic,fragsize);\npxx = zeros(NFFT,Nmic);\nq = ones(Nframe,NFFT/2+1);\np = zeros(Nframe,NFFT/2+1);\nyxx = zeros(Nframe,NFFT/2+1);\nyt = zeros(Nframe,NFFT);\nalphad = zeros(Nframe,NFFT/2+1);\nv = zeros(Nframe,NFFT/2+1);\ngamma = ones(Nframe,NFFT/2+1);\ngammas = ones(Nframe,NFFT/2+1);\nxi = zeros(Nframe,NFFT/2+1);\nphi = zeros(Nframe,NFFT/2+1);\nSY = zeros(Nframe,NFFT);\nMY = zeros(Nframe,NFFT);\nSU = zeros(Nframe,NFFT);\nMU = zeros(Nframe,NFFT);\nlamdad = zeros(Nframe,NFFT/2+1);\nGH1 = zeros(Nframe,NFFT/2+1);\nG = ones(Nframe,NFFT/2+1);\nlamdaBY = zeros(Nframe,NFFT/2+1);\nlamdaBU = zeros(Nframe,NFFT/2+1);\nomega = zeros(Nframe,NFFT/2+1);\nphi_tilt = zeros(1,Nframe);\nYMAT = zeros(Nframe,NFFT);\nUMAT = zeros(Nframe,NFFT);\n\ndeltak = 2*pi*full * len * sin(angle1*pi/180) / c + angle2*pi/180;\nW = 0.5 * conj([exp(1i*deltak/2); exp(-1i*deltak/2)]);\nB = 0.5 * conj([exp(1i*deltak/2); -exp(-1i*deltak/2)]);\ncoh = sinc(2*pi*full*len/c); % diffused noise field\nH = 1i*imag(exp(1i*deltak).*coh) ./ (1-real(exp(1i*deltak).*coh));\n\n% compute OMEGA_HIGH\n% sincwl = min(sinc(2*pi*f*len/c), 0.998);\n% OMEGA_HIGH = 0.57 * cot(deltak(1:NFFT/2+1)/2).^2 .* (1-sincwl).^2 ./ max((1-sincwl.*cos(deltak(1:NFFT/2+1))).^2, EPIS);\n% OMEGA_HIGH = 0.57 * cot(deltak(1:NFFT/2+1)/2).^2;\n% OMEGA_HIGH = 0.57 * sin(2*pi*f*len*sin(0)/c).^2 ./ (sin(deltak(1:NFFT/2+1)/2).^2 .* sin(2*pi*f*len*sin(0)/c-deltak(1:NFFT/2+1)/2).^2);\n\nhbar = waitbar(0,'Please wait...');\nfor n = 1:Nframe\n waitbar(n/Nframe,hbar);\n \n% % *************** GSC part **************************************\n% pt1 = [zeros(1,(NFFT-fragsize)/2), reshape(ptout(1,n,:),1,fragsize), zeros(1,(NFFT-fragsize)/2)];\n% pt2 = [zeros(1,(NFFT-fragsize)/2), reshape(ptout(2,n,:),1,fragsize), zeros(1,(NFFT-fragsize)/2)];\n% pt = [ pt1 .* win_pre.' ; pt2 .* win_pre.'];\n pt1 = [reshape(ptout(1,n,:),1,fragsize) .* win_pre, zeros(1,NFFT-fragsize)];\n pt2 = [reshape(ptout(2,n,:),1,fragsize) .* win_pre, zeros(1,NFFT-fragsize)];\n pt = [ pt1 .' pt2.' ];\n pxx = fft(pt,NFFT);\n Z = pxx.';\n Y = sum(conj(W) .* Z) - conj(H) .* sum(conj(B) .* Z);\n U = sum(conj(B) .* Z);\n\n % ********** Postfilter part *************************************\n if n == 1 \n SY(n,:) = abs(Y).^2;\n MY(n,:) = abs(Y).^2;\n lamdad(n,:) = abs(Y(1:NFFT/2+1)).^2;\n SU(n,:) = abs(U).^2;\n MU(n,:) = abs(U).^2;\n GH1(n,:) = ones(1,NFFT/2+1);\n gamma(n,:) = ones(1,NFFT/2+1);\n \n param_Y = initialise_parameters(MY(n,:).',fs,'imcra');\n param_U = initialise_parameters(MU(n,:).',fs,'imcra');\n \n alphad(n,:) = alphadconst + (1-alphadconst) * p(n,:);\n lamdad(n+1,:) = alphad(n,:) .* lamdad(n,:) + (1-alphad(n,:)) .* abs(Y(1:NFFT/2+1)).^2;\n \n xi(n,:) = xia + (1-xia) * max(gamma(n,:)-1,0); % initialization of a priori SNR \n else\n Ymat = buildmat(Y,length(b));\n Umat = buildmat(U,length(b));\n SY(n,:) = alphas * SY(n-1,:) + (1-alphas) * b * abs(Ymat).^2;\n SU(n,:) = alphas * SU(n-1,:) + (1-alphas) * b * abs(Umat).^2;\n param_Y = noise_estimation((abs(Y).^2).','imcra',param_Y);\n param_U = noise_estimation((abs(U).^2).','imcra',param_U);\n MY(n,:) = param_Y.noise_ps.';\n MU(n,:) = param_U.noise_ps.';\n \n \n lamdaBY(n,:) = SY(n,1:NFFT/2+1) ./ max(MY(n,1:NFFT/2+1), EPIS);\n lamdaBU(n,:) = SU(n,1:NFFT/2+1) ./ max(MU(n,1:NFFT/2+1), EPIS);\n \n% omega(n,:) = max(SY(n,1:NFFT/2+1) - MY(n,1:NFFT/2+1), 0) ./ max(SU(n,1:NFFT/2+1) - MU(n,1:NFFT/2+1), 0.001*MY(n,1:NFFT/2+1));\n omega(n,:) = max(SY(n,1:NFFT/2+1) - MY(n,1:NFFT/2+1), 0) ./ max(SU(n,1:NFFT/2+1) - MU(n,1:NFFT/2+1), EPIS);\n \n % decide q according to fig.4\n for k = 1:NFFT/2+1\n if lamdaBY(n,k) > lamdaB0\n if lamdaBU(n,k) > lamdaB0\n % ***** compute phi, using eq.33 ***********\n if omega(n,k) <= omegalow\n phi(n,k) = 0;\n else\n if omegalow < omega(n,k) && omega(n,k) <= omegahigh % OMEGA_HIGH(k) % replace omegahigh with OMEGA_HIGH(k)\n phi(n,k) = (omega(n,k) - omegalow) / (omegahigh - omegalow);\n% if omegalow < omega(n,k) <= OMEGA_HIGH(k) % OMEGA_HIGH(k) % replace omegahigh with OMEGA_HIGH(k)\n% phi(n,k) = (omega(n,k) - omegalow) / (OMEGA_HIGH(k) - omegalow);\n else\n phi(n,k) = 1;\n end\n end\n % ******************************************\n else\n phi(n,k) = 1;\n end\n else\n phi(n,k) = 0;\n end\n end\n \n % compute eq.34\n phi_tilt(n) = sum(phi(n,KL:KR)) / (KR-KL+1);\n \n gammas(n,:) = abs(Y(1:NFFT/2+1)).^2 ./ MY(n,1:NFFT/2+1);\n \n % compute q, using eq.35\n if phi_tilt(n) > phi0\n for k = 1:NFFT/2+1\n if (gammas(n,k) <= 1) || (phi_tilt(n) <= phi0)\n q(n,k) = 1;\n else \n q(n,k) = max( (gamma0-gammas(n,k))/(gamma0-1) , 1-phi(n,k) );\n end\n end\n else\n q(n,:) = ones(1,NFFT/2+1);\n end\n \n q(n,:) = min(q(n,:),1);\n q(n,:) = max(q(n,:),0);\n\n % compute xi, using eq.37\n gamma(n,:) = abs(Y(1:NFFT/2+1)).^2 ./ max(lamdad(n,1:NFFT/2+1), EPIS);\n \n xi(n,:) = alpha * GH1(n-1,:).^2 .* gamma(n-1,:) + (1-alpha) * max(gamma(n,:)-1,0);\n xi(n,:) = max(xi(n,:), ximin);\n v(n,:) = gamma(n,:) .* xi(n,:) ./ (1+xi(n,:));\n \n % compute GH1, using eq.38\n GH1(n,:) = ones(1,NFFT/2+1);\n index = find(v(n,:) > vmax);\n GH1(n,index) = xi(n,index) ./ (1+xi(n,index));\n index = find(0