{"text": "function demoImOrientedBox(varargin)\n%DEMOIMORIENTEDBOX Demo file for using function imOrientedBox\n%\n% Syntax\n% demoImOrientedBox\n% The demo runs automatically. A basic segmentation is performed on a\n% demo image, then oriented boxes are computed for each particle and\n% displayed on the original image. \n%\n% Example\n% demoImOrientedBox\n%\n% See also\n% demoImMaxFeretDiameter, imOrientedBox\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2011-05-09, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011 INRA - Cepia Software Platform.\n\n\n%% Image segmentation\n\n% read image\nimg = imread('rice.png');\nfigure(1); clf;\nimshow(img);\n\n% compute background\nbg = imopen(img, ones(30, 30));\nimg2 = img - bg;\nfigure(2); clf;\nimshow(img2);\n\n% display histogram, to identify the threshold value\nfigure(3); clf;\nimHistogram(img2);\n\n% image binarisation, and remove particles touching border\nbin = img2 > 50;\nbin = imclearborder(bin, 4);\nimshow(bin);\n\n% compute image labels, using minimal connectivity\nlbl = bwlabel(bin, 4);\nnLabels = max(lbl(:));\n\n% display label image\nrgb = label2rgb(lbl, jet(nLabels), 'w', 'shuffle');\nfigure(4); clf;\nimshow(rgb);\n\n\n%% Compute enclosing oriented boxes\n\n% call the function\nboxes = imOrientedBox(lbl);\n\n% display result\nhold on;\ndrawOrientedBox(boxes, 'linewidth', 2);\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/imMeasures/demoImOrientedBox.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.3499320087587727}}
{"text": "function splabels = msLabelMap2Sp(lmap, smap)\n\nnocell = false;\nif ~iscell(lmap)\n nocell = true;\n lmap = {lmap};\n smap = {smap};\nend\n\n% if ~exist('maxlab', 'var') || isempty(maxlab)\n% maxlab = 0;\n% for f = 1:numel(lmap)\n% maxlab = max(maxlab, max(lmap{f}(:)));\n% end\n% end\n\nfor f = 1:numel(lmap)\n\n nseg = max(smap{f}(:));\n stats = regionprops(smap{f}, 'PixelIdxList');\n idx = {stats.PixelIdxList};\n \n splabels{f} = zeros(nseg, 1);\n for s = 1:nseg\n splabels{f}(s) = mode(double(lmap{f}(idx{s})));\n end\nend\n \nif nocell\n splabels = splabels{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/panoContext_code/Toolbox/SpatialLayout_shrink/spatiallayoutcode/GeometricContext/ms/multipleSegmentations/msLabelMap2Sp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6224593171945416, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.34993200088419046}}
{"text": "function field=meg_forward(dip_par,forwpar)\n% calculates the magnetic field of n dipoles\n% in a realistic volume conductor\n% usage: field=meg_forward(dip_par,forwpar)\n%\n% input:\n% dip_par nx6 matrix where each row contains location (first 3 numbers)\n% and moment (second 3 numbers) of a dipole\n% forwpar structure containing all information relevant for this\n% calculation; forwpar is calculated with meg_ini\n% You have here an option to include linear transformations in\n% the forward model by specifying forpwar.lintrafo=A\n% where A is an NxM matrix. Then field -> A field\n% You can use that, e.g., if you can write the forward model\n% with M magnetometer-channels plus a matrix multiplication\n% transforming this to a (eventually higher order) gradiometer.\n%\n% output:\n% field mxn matrix where the i.th column is the field in m channels\n% of the i.th dipole\n%\n% note: No assumptions about units are made (i.e. no scaling factors)\n%\n% Copyright (C) 2003, Guido Nolte\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\ndevice_sens=forwpar.device_sens;\n\nfield_sens_sphere=getfield_sphere(dip_par,forwpar.device_sens,forwpar.center);\nfield=field_sens_sphere;clear field_sens_sphere;\nif isfield(forwpar,'device_ref')\n field=field-getfield_sphere(dip_par,forwpar.device_ref,forwpar.center);\nend\nif isfield(forwpar,'device_weights')\n field=field+forwpar.weights*getfield_sphere(dip_par,forwpar.device_weights,forwpar.center);\nend\n\nif forwpar.order>0\n coeff=forwpar.coeff_sens;\n if isfield(forwpar,'device_ref')\n coeff=coeff-forwpar.coeff_ref;\n end\n if isfield(forwpar,'device_weights')\n coeff=coeff+forwpar.coeff_weights*forwpar.weights';\n end\n field=field+getfield_corr(dip_par,coeff,forwpar.center,forwpar.order);\nend\n\nif isfield(forwpar,'lintrafo');\n field=forwpar.lintrafo*field;\nend\n\nreturn % main function\n\n\nfunction field=getfield_sphere(source,device,center)\n[ndip,ndum]=size(source);\n[nchan,ndum]=size(device);\nx1=source(:,1:3)-repmat(center',ndip,1);\nn1=source(:,4:6);\nx2=device(:,1:3)-repmat(center',nchan,1);\nn2=device(:,4:6);\n%spherical\nbt=leadsphere_all(x1',x2',n2');\nn1rep=reshape(repmat(n1',1,nchan),3,ndip,nchan);\nb=dotproduct(n1rep,bt);\nfield=b';\nreturn\n\nfunction field=getfield_corr(source,coeffs,center,order)\n[ndip,ndum]=size(source);\nx1=source(:,1:3)-repmat(center',ndip,1);\nn1=source(:,4:6);\n%correction\nif order>0\n scale=10;\n [bas,gradbas]=legs(x1,n1,order,scale);\n nbasis=(order+1)^2-1;\n coeffs=coeffs(1:nbasis,:);\n field=-(gradbas*coeffs)';\nend\nreturn\n\nfunction out=crossproduct(x,y)\n% usage: out=testprog(x,y)\n% testprog calculates the cross-product of vector x and y\n[n,m,k]=size(x);\nout=zeros(3,m,k);\nout(1,:,:)=x(2,:,:).*y(3,:,:)-x(3,:,:).*y(2,:,:);\nout(2,:,:)=x(3,:,:).*y(1,:,:)-x(1,:,:).*y(3,:,:);\nout(3,:,:)=x(1,:,:).*y(2,:,:)-x(2,:,:).*y(1,:,:);\nreturn\n\nfunction out=dotproduct(x,y)\n% usage: out=dotproduct(x,y)\n% testprog calculates the dotproduct of vector x and y\n[n,m,k]=size(x);\noutb=x(1,:,:).*y(1,:,:)+x(2,:,:).*y(2,:,:)+x(3,:,:).*y(3,:,:);\nout=reshape(outb,m,k);\nreturn\n\nfunction result=norms(x)\n[n,m,k]=size(x);\nresultb=sqrt(x(1,:,:).^2+x(2,:,:).^2+x(3,:,:).^2);\nresult=reshape(resultb,m,k);\nreturn\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/forward/private/meg_forward.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.34986642796912015}}
{"text": "% averef() - convert common-reference EEG data to average reference\n% Note that this old function is not being used in EEGLAB. The\n% function used by EEGLAB is reref().\n%\n% Usage:\n% >> data = averef(data);\n% >> [data_out W_out S_out meandata] = averef(data,W);\n%\n% Inputs:\n% data - 2D data matrix (chans,frames*epochs) \n% W - ICA weight matrix\n%\n% Outputs:\n% data_out - Input data converted to average reference.\n% W_out - ICA weight matrix converted to average reference\n% S_out - ICA sphere matrix converted to eye()\n% meandata - (1,dataframes) mean removed from each data frame (point)\n%\n% Note: If 2 args, also converts the weight matrix W to average reference:\n% If ica_act = W*data, then data = inv(W)*ica_act; \n% If R*data is the average-referenced data, \n% R*data=(R*inv(W))*ica_act and W_out = inv(R*inv(W));\n% The average-reference ICA maps are the columns of inv(W_out).\n%\n% Authors: Scott Makeig and Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 1999 \n%\n% See also: reref()\n\n% Copyright (C) 1999 Scott Makeig, SCCN/INC/UCSD, scott@sccn.ucsd.edu\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% 12/16/99 Corrected denomiator on the suggestion of Ian Nimmo-Smith, Cambridge UK\n% 01-25-02 reformated help & license -ad \n\nfunction [data, W, S, meandata] = averef(data, W, S)\n\nif nargin<1\n help averef\n return\nend\nchans = size(data,1);\nif chans < 2 \n help averef\n return\nend\n\n% avematrix = eye(chans)-ones(chans)*1/chans;\n% data = avematrix*data; % implement as a matrix multiply\n% else (faster?)\n\nmeandata = sum(data)/chans;\ndata = data - ones(chans,1)*meandata;\n\n% treat optional ica parameters\nif nargin == 2\n\twinv = pinv(W);\n size1 = size(winv,1);\n\tavematrix = eye(size1)-ones(size1)*1/size1;\n\tW = pinv(avematrix*winv);\nend;\nif nargin >= 3\n\twinv = pinv(W*S);\n size1 = size(winv,1);\n\tavematrix = eye(size1)-ones(size1)*1/size1;\n\tW = pinv(avematrix*winv);\n\tS = eye(chans);\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/functions/miscfunc/averef.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.3498664224245379}}
{"text": "function T45=T45(h)\nT45=2.78e-3*h+139.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/19470-isa-chart/T45.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.3497829660931603}}
{"text": "function [dat] = read_nexstim_nxe(filename, begsample, endsample, chanindx)\n\n% READ_NEXSTIM_NXE reads specified samples from a NXE continuous datafile\n%\n% Use as\n% [hdr] = read_nexstim_nxe(filename)\n% where\n% filename name of the datafile, including the .bdf extension\n% This returns a header structure with the following elements\n% hdr.Fs sampling frequency\n% hdr.nChans number of channels\n% hdr.nSamples number of samples per trial\n% hdr.nSamplesPre number of pre-trigger samples in each trial\n% hdr.nTrials number of trials\n% hdr.label cell-array with labels of each channel\n%\n% Or use as\n% [dat] = read_nexstim_nxe(filename, begsample, endsample, chanindx)\n% where\n% filename name of the datafile, including the .nxe extension\n% begsample index of the first sample to read\n% endsample index of the last sample to read\n% chanindx index of channels to read (optional, default is all)\n% This returns a Nchans X Nsamples data matrix\n\n% Written by Vladimir Litvak based on functions provided by Nexstim\n%\n% Copyright (C) 2007, Vladimir Litvak\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\nif nargin==1\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % read the header\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n hdr.Fs = 1450;\n hdr.nChans = 64;\n hdr.label = cell(64,1);\n hdr.label(1:4)= {'GATE', 'TRIG1', 'TRIG2','EOG'};\n hdr.label(5:64) = {\n 'Fp1'\n 'Fpz'\n 'Fp2'\n 'AF1'\n 'AFz'\n 'AF2'\n 'F7'\n 'F3'\n 'F1'\n 'Fz'\n 'F2'\n 'F4'\n 'F8'\n 'FT9'\n 'FT7'\n 'FC5'\n 'FC3'\n 'FC1'\n 'FCz'\n 'FC2'\n 'FC4'\n 'FC6'\n 'FT8'\n 'FT10'\n 'T7'\n 'C5'\n 'C3'\n 'C1'\n 'Cz'\n 'C2'\n 'C4'\n 'C6'\n 'T8'\n 'TP9'\n 'TP7'\n 'CP5'\n 'CP3'\n 'CP1'\n 'CPz'\n 'CP2'\n 'CP4'\n 'CP6'\n 'TP8'\n 'TP10'\n 'P9'\n 'P7'\n 'P3'\n 'P1'\n 'Pz'\n 'P2'\n 'P4'\n 'P8'\n 'P10'\n 'PO3'\n 'POz'\n 'PO4'\n 'O1'\n 'Oz'\n 'O2'\n 'Iz'};\n\n % it is continuous data, therefore append all records in one trial\n hdr.nTrials = 1;\n\n fid=fopen_or_error(filename,'r','l');\n fseek(fid,0,'eof');\n numBytes = ftell(fid);\n hdr.nSamples = (numBytes/2)/hdr.nChans;\n\n hdr.nSamplesPre = 0;\n\n fclose(fid);\n\n % return the header\n dat = hdr;\n\nelse\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % read the data\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n sfEEG = (1/2000) * (10/65535) * 1000000;\n sfEOG = (1/400) * (10/65535) * 1000000;\n sfTRIG = 10 * (10/65535);\n\n numChannels = 64;\n\n fid = fopen_or_error(filename,'r','l');\n fseek(fid, 2*numChannels*(begsample-1),'bof');\n data = fread(fid,[numChannels endsample-begsample+1],'short');\n fclose(fid);\n\n data(1:3,:) = sfTRIG.*data(1:3,:);\n data(4,:) = sfEOG.*data(4,:);\n data(5:64,:) = sfEEG.*data(5:64,:);\n\n if nargin<4\n chanindx = 1:numChannels;\n end\n\n dat = data(chanindx,:);\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/fileio/private/read_nexstim_nxe.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.3497766813416758}}
{"text": "function [ind,value] = cnn_classifier(A,dims,classifier,thr)\n\n%cnn_classifer classify spatial components using a pretrained CNN\n%classifier using the keras importer add on.\n% IND = cnn_classifier(A,dims,classifier,thr) returns a binary vector indicating\n% whether the set of spatial components A, with dimensions of the field\n% of view DIMS, pass the threshold THR for the given CLASSIFIER\n%\n% [IND,VALUE] = cnn_classifier(A,dims,classifier,thr) also returns the\n% output value of the classifier \n%\n% INPUTS:\n% A: 2d matrix\n% dims: vector with dimensions of the FOV\n% classifier: path to pretrained classifier model (downloaded if it\n% doesn't exist)\n% thr: threshold for accepting component (default: 0.2)\n%\n% note: The function requires Matlab version 2017b (9.3) or later, Neural\n% Networks toolbox version 2017b (11.0) or later, the Neural Network \n% Toolbox(TM) Importer for TensorFlow-Keras Models.\n\n% Written by Eftychios A. Pnevmatikakis. Classifier trained by Andrea\n% Giovannucci, Flatiron Institute, 2017\n\nK = size(A,2); % number of components\n\nif verLessThan('matlab','9.3') || verLessThan('nnet','11.0') || isempty(which('importKerasNetwork'))\n warning(strcat('The function cnn_classifier requires Matlab version 2017b (9.3) or later, Neural\\n', ...\n 'Networks toolbox version 2017b (11.0) or later, the Neural Networks ', ...\n 'Toolbox(TM) Importer for TensorFlow-Keras Models.'))\n ind = true(K,1);\n value = ones(K,1);\nelse\n if ~exist('thr','var'); thr = 0.2; end\n\n A = A/spdiags(sqrt(sum(A.^2,1))'+eps,0,K,K); % normalize to sum 1 for each compoennt\n A_com = extract_patch(A,dims,[50,50]); % extract 50 x 50 patches\n\n if ~exist(classifier,'file')\n url = 'https://www.dropbox.com/s/1csymylbne7yyt0/cnn_model.h5?dl=1';\n classifier = 'cnn_model.h5';\n outfilename = websave(classifier,url);\n end\n\n net_classifier = importKerasNetwork(classifier,'ClassNames',[\"rejected\",\"accepted\"]);\n out = predict(net_classifier,double(A_com));\n value = out(:,2);\n ind = (value >= thr);\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/cnn_classifier.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3497766813416757}}
{"text": "% Demo for Structured Edge Detector (please see readme.txt first).\naddpath(genpath('../piotr_toolbox'));\n\n%% set opts for training (see edgesTrain.m)\nopts=edgesTrain(); % default options (good settings)\nopts.modelDir='models/'; % model will be in models/forest\nopts.modelFnm='modelBsds'; % model name\nopts.nPos=5e5; opts.nNeg=5e5; % decrease to speedup training\nopts.useParfor=0; % parallelize if sufficient memory\n\n%% train edge detector (~20m/8Gb per tree, proportional to nPos/nNeg)\ntic, model=edgesTrain(opts); toc; % will load model if already trained\n\n%% set detection parameters (can set after training)\nmodel.opts.multiscale=0; % for top accuracy set multiscale=1\nmodel.opts.sharpen=2; % for top speed set sharpen=0\nmodel.opts.nTreesEval=4; % for top speed set nTreesEval=1\nmodel.opts.nThreads=4; % max number threads for evaluation\nmodel.opts.nms=0; % set to true to enable nms\n\n%% evaluate edge detector on BSDS500 (see edgesEval.m)\nif(0), edgesEval( model, 'show',1, 'name','' ); end\n\n%% detect edge and visualize results\nI = imread('peppers.png');\ntic, E=edgesDetect(I,model); toc\nfigure(1); im(I); figure(2); im(1-E);\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/edges-master/edges-master/edgesDemo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3497766813416757}}
{"text": "function printv(v)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Copyright (C) 2020-2025, by Kai Chen, All rights reserved.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nn=size(v,1);\nfprintf('v =\\n');\nfor i=1:n\n fprintf('%11.6f',v(i));\n fprintf('\\n');\nend\nfprintf('nv=%d\\n',n);\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/debug/printv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.34975756122516144}}
{"text": "function bicycle_lock ( )\n\n%*****************************************************************************80\n%\n%% BICYCLE_LOCK finds the combination on a typical bicycle lock.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 11 May 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n timestamp ( )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BICYCLE_LOCK\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' A bicycle combination lock consists of 3 dials,\\n' );\n fprintf ( 1, ' each having 10 symbols, 0 through 9.\\n' );\n fprintf ( 1, ' We seek to determine the combination C.\\n' );\n%\n% Set the combination randomly.\n% We can think of the combination as a number between 0 and 999.\n%\n rng ( 'shuffle' );\n c = randi ( [ 0, 999 ], 1, 1 );\n%\n% To find the combination, simply generate every number between 0 and 999,\n% and then try it.\n%\n for a = 0 : 999\n\n if ( a == c )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The combination is %d!\\n', c );\n break\n end\n \n end\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BICYCLE_LOCK\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\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/combination_lock/bicycle_lock.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.3497575514522014}}
{"text": "function Cw = getCameraCenter(camRtC2W)\n\nCw = camRtC2W(1:3,4);\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/getCameraCenter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.34975754789168645}}
{"text": "function [P,Uinit] = parafac_als(X,R,opts)\n%PARAFAC_ALS Deprecated. Use CP_ALS instead.\n% \n% See also CP_ALS.\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\nif (nargout == 2) & (nargin == 3)\n [P,Uinit] = cp_als(X,R,opts); \nelseif (nargout == 2) & (nargin == 2)\n [P,Uinit] = cp_als(X,R); \nelseif (nargout == 2) & (nargin == 1)\n [P,Uinit] = cp_als(X); \nelseif (nargout == 1) & (nargin == 3)\n P = cp_als(X,R,opts); \nelseif (nargout == 1) & (nargin == 2)\n P = cp_als(X,R); \nelseif (nargout == 1) & (nargin == 1)\n P = cp_als(X); \nend\n \n\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/parafac_als.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.34975754077065646}}
{"text": "function varargout = squeeze(varargin)\n%SQUEEZE Squeeze a CHEBFUN2 to one variable, if possible.\n% G = squeeze(F) returns a CHEBFUN2 if F depends on x and y. If F depends only\n% on the x-variable a row CHEBFUN is returned and if it depends on just the\n% y-variable a column CHEBFUN is returned.\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}] = squeeze@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/squeeze.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.34975754077065646}}
{"text": "function vout = Ptransp_solve(L, vin)\n%Ptransp_solve Auxi,ilary function for IR Tools\n%\n% vout = Ptransp_solve\n%\n% This computes vout = L'\\vin. If L is a function handle, then we use the\n% user-supplied function, which is passed via options as 'RegMatrix'.\n% Otherwise, we use the backslash operator.\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 Licence. A separate license file should be provided as part \n% of the package.\n\nif isa(L, 'function_handle')\n transp_flag = 'transp';\n vout = L(vin, transp_flag);\nelse\n vout = (L')\\vin;\nend", "meta": {"author": "jnagy1", "repo": "IRtools", "sha": "040ef13d27873b6391aedd4ec06c453e1add9066", "save_path": "github-repos/MATLAB/jnagy1-IRtools", "path": "github-repos/MATLAB/jnagy1-IRtools/IRtools-040ef13d27873b6391aedd4ec06c453e1add9066/Extra/Ptransp_solve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6442251201477015, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.34972616382558286}}
{"text": "function out = rdivide(T,S)\n\nif isa(S,'double') \n \n if numel(S)>1\n S = repmat(reshape(S,[ones(1,T.rank) size(T)]), [3*ones(1,T.rank),1,1]); \n end\n \n T.M = T.M ./ S;\n out = T;\n \nelseif isa(S,'tensor')\n \n T.M = T.M ./ S.M;\n out = T;\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/TensorAnalysis/@tensor/rdivide.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3497261564093474}}
{"text": "classdef AltitudeTermCondition < AbstractEventTerminationCondition\n %AltitudeTermCondition Summary of this class goes here\n % Detailed explanation goes here\n \n properties\n altitude(1,1) double = 0; %km\n bodyInfo KSPTOT_BodyInfo\n end\n \n methods\n function obj = AltitudeTermCondition(altitude)\n obj.altitude = altitude;\n end\n \n function evtTermCondFcnHndl = getEventTermCondFuncHandle(obj) \n evtTermCondFcnHndl = @(t,y) obj.eventTermCond(t,y);\n end\n \n function initTermCondition(obj, initialStateLogEntry)\n obj.bodyInfo = initialStateLogEntry.centralBody;\n end\n \n function name = getName(obj)\n name = sprintf('Altitude (%.3f km)', obj.altitude);\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 = 'Altitude';\n params.paramUnit = 'km';\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.altitude;\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 = AltitudeOptimizationVariable(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 = AltitudeTermCondition(paramValue);\n end\n end\n \n methods(Access=private)\n function [value,isterminal,direction] = eventTermCond(obj, t,y) \n rVect = y(1:3);\n vVect = y(4:6);\n cartElem = CartesianElementSet(t, rVect(:), vVect(:), obj.bodyInfo.getBodyCenteredInertialFrame());\n geoElem = cartElem.convertToFrame(obj.frame).convertToGeographicElementSet();\n \n actualAltitude = geoElem.alt;\n \n value = actualAltitude - obj.altitude;\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/@AltitudeTermCondition/AltitudeTermCondition.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3497261564093474}}
{"text": "function boundaryBenchGraphs(pbDir)\n% function boundaryBenchGraphs(pbDir)\n%\n% Create graphs, after boundaryBench(pbDir) has been run.\n%\n% See also boundaryBench.\n%\n% David Martin \n% May 2003\n\nfname = fullfile(pbDir,'scores.txt');\nscores = dlmread(fname); % iid,thresh,r,p,f\nfname = fullfile(pbDir,'score.txt');\nscore = dlmread(fname); % thresh,r,p,f\n\n% create the overall PR graph\nfname = fullfile(pbDir,'pr.txt');\npr = dlmread(fname); % thresh,r,p,f\nh = figure(1); clf; hold on;\nprplot(h,pr(:,2),pr(:,3),sprintf('F=%4.2f',score(4)));\nph=plot(score(2),score(3),'ko','MarkerFaceColor','k','MarkerSize',10);\nlh=legend(ph,sprintf('F=%4.2f @(%4.2f,%4.2f) t=%4.2f',...\n score(4),score(2),score(3),score(1)));\np=get(lh,'Position');\np(1)=0.25;\np(2)=0.15;\nset(lh,'Position',p);\nprint(h,'-depsc2',fullfile(pbDir,'pr.eps'));\nprint(h,'-djpeg95','-r36',fullfile(pbDir,'pr_half.jpg'));\nprint(h,'-djpeg95','-r0',fullfile(pbDir,'pr_full.jpg'));\n%close(h);\n\niids = imgList('test');\nfor i = 1:numel(iids),\n iid = iids(i);\n fprintf(2,'Processing image %d/%d (iid=%d)...\\n',i,numel(iids),iid);\n\n % create PR graphs for this image\n fname = fullfile(pbDir,sprintf('%d_pr.txt',iid));\n pri = dlmread(fname);\n h = figure(1); clf; hold on;\n prplot(h,pri(:,2),pri(:,3),sprintf('%d F=%4.2f',iid,scores(i,5)));\n ph=plot(scores(i,3),scores(i,4),'ko','MarkerFaceColor','k','MarkerSize',10);\n lh=legend(ph,sprintf('F=%4.2f @(%4.2f,%4.2f) t=%4.2f',...\n scores(i,5),scores(i,3),scores(i,4),scores(i,2)));\n p=get(lh,'Position');\n p(1)=0.25;\n p(2)=0.15;\n set(lh,'Position',p);\n print(h,'-depsc2',fullfile(pbDir,sprintf('%d_pr.eps',iid)));\n print(h,'-djpeg95','-r36',fullfile(pbDir,sprintf('%d_pr_half.jpg',iid)));\n print(h,'-djpeg95','-r0',fullfile(pbDir,sprintf('%d_pr_full.jpg',iid)));\n %close(h);\nend\n\nfunction prplot(h,r,p,ti)\nfigure(h); \nplot(r,p,'ko-');\nbox on;\ngrid on;\nset(gca,'Fontsize',12);\nset(gca,'XTick',[0 .25 .5 .75 1]);\nset(gca,'YTick',[0 .25 .5 .75 1]);\nset(gca,'XGrid','on');\nset(gca,'YGrid','on');\nxlabel('Recall');\nylabel('Precision');\ntitle(ti);\naxis square;\naxis([0 1 0 1]);\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/external/segbench/lib/matlab/boundaryBenchGraphs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3497261564093474}}
{"text": "function inls = countCorrespondences(M, Btree, epsilon)\n\n [idx, dist] = knnsearch(Btree, M');\n in_idx = find(dist<=epsilon);\n \n inls = length(idx(in_idx));\n\nend", "meta": {"author": "intellhave", "repo": "SDRSAC", "sha": "b081721e9dfd7843d75aa12f30025b2bd7c8f024", "save_path": "github-repos/MATLAB/intellhave-SDRSAC", "path": "github-repos/MATLAB/intellhave-SDRSAC/SDRSAC-b081721e9dfd7843d75aa12f30025b2bd7c8f024/countCorrespondences.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6442251064863695, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.34972615640934734}}
{"text": "clear;close all;\nim1=imread('page.png');\nim2=imread('tshape.png');\nbwim1=adaptivethreshold(im1,11,0.03,0);\nbwim2=adaptivethreshold(im2,15,0.02,0);\nsubplot(2,2,1);\nimshow(im1);\nsubplot(2,2,2);\nimshow(bwim1);\nsubplot(2,2,3);\nimshow(im2);\nsubplot(2,2,4);\nimshow(bwim2);", "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/8647-local-adaptive-thresholding/adaptivethreshold/testadaptivethreshold.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3497261489931118}}
{"text": "function [M] = ROIcmap(nc,opt)\n% [M] = ROIcmap([nc],[opt]);\n% creates a colormap with\n% no color too close to grayscale,\n% no two consecutive colors too close\n% no colors exeedingly close to another in the map\n% no colors too close to a background color (optional)\n% nc: number of colors in map. Default is 64\n% opt: optional options structure\n% .show: Figure handle in which to show the map\n% Default is 1. Set to 0 for no show.\n% In show mode, you get to pick colors with mouse\n% and read in their values. Hit enter to exit from\n% this mode.\n% .state: State of the random number generator.\n% Default is 0.\n% .write: Name of file to write colormap into\n% Default is '', no writing. Use something like\n% ROI64s0.1D.cmap, for a 64 cols, seed 0 colormap.\n% .avoid: Color to avoid getting close to.\n% .verb: verbosioty. 1 is default. 0 is for quiet\n% returns\n% M: The colormap.\n%\n%see also readXcol, rgbdectohex, and ScaleToMap\n% Ziad S. Saad SSCC/NIMH/NIH, saadz@mail.nih.gov\n\nif (nargin == 0),\n nc = 64;\n opt.show = 1;\nelseif (nargin == 1),\n opt.show = 1;\nend\n\nif (isempty(nc)), nc = 64; end\n\nif (~isfield(opt,'show') | isempty(opt.show)), opt.show = 1; end\nif (~isfield(opt,'state') | isempty(opt.state)), opt.state = 0; end\nif (~isfield(opt,'write') | isempty(opt.write)), opt.write = ''; end\nif (~isfield(opt,'verb') | isempty(opt.verb)), opt.verb = 1; end\nif (~isfield(opt,'avoid') | isempty(opt.avoid)), opt.avoid = []; end\n\n%initialize rng\nrand('state',opt.state);\n\nM = zeros(nc,3);\nalldiff_lim = 0.5; %between 0 and 1, controls how different all colors in map are.\n %The first few colors can be quite different, high alldiff_lim\n %The difference is adjusted as more colors are demanded.\ng_lim = 0.2; %limit for too gray (0-1)\nd_lim = 0.40; %limit for too dim (0-3)\nb_lim = 2.2; %limit for too bright (0-3)\nfor (i=1:1:nc),\n M(i,:) = rand(1,3);\n cnt = 0;\n %reject if too gray or too close to previous color\n while ( toogray(M(i,:), g_lim, d_lim, b_lim) | tooclose(M,i, 0.6, alldiff_lim) | (~isempty(opt.avoid) & (sum(abs(M(i,:)-opt.avoid)) < 0.6))),\n M(i,:) = rand(1,3);\n cnt = cnt + 1;\n if (cnt > 2000), % too tight, relax\n alldiff_lim = max([0.95.*alldiff_lim 0.02]) ;\n d_lim = max([0.95.*d_lim 0.01]);\n b_lim = min([b_lim*1.05, 8.0]);\n if (opt.verb) fprintf(1,'Reduced alldiff_lim to %g, d_lim to %g, b_lim to %g\\n', alldiff_lim, d_lim, b_lim); end\n cnt = 0;\n end\n end\n if (opt.verb) fprintf(1,'Color %d OK\\n', i); end\nend\nif (opt.verb) fprintf(1,'alldiff_lim final was %g, d_lim final was %g, b_lim final was %g\\n', alldiff_lim, d_lim, b_lim); end\n\nif (~isempty(opt.write)),\n optw.OverWrite = 'p';\n wryte3(M, opt.write, optw);\nend\n\nif (opt.show),\n ShowCmap(M, opt.show);\nend\n\nreturn;\n\n\nfunction [a] = toogray(c, g_lim, d_lim, b_lim)\n\n a = 0;\n dc = abs(c - mean(c));\n cs = sum(c);\n if (dc(1) < g_lim & dc(2) < g_lim & dc(3) < g_lim), a = 1; return; end\n if (cs < d_lim | cs > b_lim), a = 1; return; end\n return;\n\nfunction [a] = tooclose(M,i,prev_lim, alldiff_lim)\n\n if (i==1), a = 0; return; end\n\n a = 1;\n\n %too close to previous ?\n dc = abs(M(i,:)-M(i-1,:));\n if (sum(dc) < prev_lim), return; end\n\n %too close to one before?\n if (i > 2),\n for (j=1:1:i-2),\n dc = abs(M(i,:)-M(j,:));\n if (dc(1) < alldiff_lim & dc(2) < alldiff_lim & dc(3) < alldiff_lim), return; end\n end\n end\n %OK if you get here\n a = 0;\n return;\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/ROIcmap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3497261489931118}}
{"text": "% mycorr2 modified version of the 2D correlation\n% for the use with im2col and col2im\n% see GETPOINT\n%\n%\n% $Id: mycorr2.m,v 2.0 2003/06/19 12:06:52 svoboda Exp $\n\n% Note: It written in order to gain speed. The clarity of the code suffers accordingly\n\nfunction R = mycorr2(X,G,Gn,Gn2)\n\n% Gn = G-mean(G);\n% Gn2 = sqrt(sum(Gn.^2));\n\nmX\t= repmat(mean(X),size(X,1),1);\nmXn = X - mX;\nsmX\t= sum(mXn.^2);\n\nnumerator = (mXn'*Gn)';\ndenominator = smX*Gn2;\n\nR = numerator./denominator;\n\nreturn", "meta": {"author": "strawlab", "repo": "MultiCamSelfCal", "sha": "0a26c88c63d8513eab76553033a9a6fb15ba6575", "save_path": "github-repos/MATLAB/strawlab-MultiCamSelfCal", "path": "github-repos/MATLAB/strawlab-MultiCamSelfCal/MultiCamSelfCal-0a26c88c63d8513eab76553033a9a6fb15ba6575/MultiCamSelfCal/FindingPoints/mycorr2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.5, "lm_q1q2_score": 0.34962721052937923}}
{"text": "function mtrFigureGASMatchedPathDist(machineDir, imageDir)\n\nsubjVec = {'tony_nov05','thor_nov05','sil_nov05'};\n%subjVec = {'thor_nov05'};\nthreshVec = [1000];\nctFile = 'paths500k_5k.dat';\nsttFile = 'stt_clip.dat';\ndistMatricesFile = 'distMatricesGAS.mat';\nbSavePlot = 0;\n\nfor ss = 1:length(subjVec)\n subjDir = fullfile(machineDir,subjVec{ss}); \n figure;\n \n fgDir = fullfile(subjDir, 'conTrack');\n disp(['cd ' fgDir]);\n cd(fgDir); \n [meanD, maxD] = mtrMatchPathways(fullfile(subjDir,'dt6.mat'), fullfile(subjDir,'fibers',sttFile), ctFile);\n\n % Save out the figures to the image dir\n subplot(2,1,1); hist((min(meanD,[],2)));\n xlabel('Mean distance to closest conTrack path (mm)');\n subplot(2,1,2); hist((min(maxD,[],2)));\n xlabel('Max distance to closest conTrack path (mm)');\n save(distMatricesFile,'meanD','maxD');\n \n if(bSavePlot)\n set(gcf,'Position',[504 687 436 259]);\n figFilename = fullfile(subjDir,imageDir,['distHist.png'])\n set(gcf,'PaperPositionMode','auto');\n print('-dpng', figFilename);\n end\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/mtrFigureGASMatchedPathDist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.5, "lm_q1q2_score": 0.34962721052937923}}
{"text": "%TRPRINT Compact display of homogeneous transformation\n%\n% TRPRINT(T, OPTIONS) displays the homogoneous transform in a compact \n% single-line format. If T is a homogeneous transform sequence then each \n% element is printed on a separate line.\n%\n% S = TRPRINT(T, OPTIONS) as above but returns the string.\n%\n% TRPRINT T is the command line form of above, and displays in RPY format.\n%\n% Options::\n% 'rpy' display with rotation in roll/pitch/yaw angles (default)\n% 'euler' display with rotation in ZYX Euler angles\n% 'angvec' display with rotation in angle/vector format\n% 'radian' display angle in radians (default is degrees)\n% 'fmt', f use format string f for all numbers, (default %g)\n% 'label',l display the text before the transform\n%\n% Examples::\n% >> trprint(T2)\n% t = (0,0,0), RPY = (-122.704,65.4084,-8.11266) deg\n%\n% >> trprint(T1, 'label', 'A')\n% A:t = (0,0,0), RPY = (-0,0,-0) deg\n%\n% See also TR2EUL, TR2RPY, TR2ANGVEC.\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 out = trprint(T, varargin)\n \n if ischar(T)\n % command form: trprint T\n trprint( evalin('base', T) );\n return;\n end\n\n opt.fmt = [];\n opt.mode = {'rpy', 'euler', 'angvec'};\n opt.radian = false;\n opt.label = '';\n\n opt = tb_optparse(opt, varargin);\n\n s = '';\n\n if size(T,3) == 1\n if isempty(opt.fmt)\n opt.fmt = '%g';\n end\n s = tr2s(T, opt);\n else\n if isempty(opt.fmt)\n opt.fmt = '%8.2g';\n end \n \n for i=1:size(T,3)\n % for each 4x4 transform in a possible 3D matrix\n s = char(s, tr2s(T(:,:,i), opt) );\n end\n end\n\n % if no output provided then display it\n if nargout == 0\n disp(s);\n else\n out = s;\n end\nend\n\nfunction s = tr2s(T, opt)\n % print the translational part if it exists\n if ~isempty(opt.label)\n s = sprintf('%8s: ', opt.label);\n else\n s = '';\n end\n if ~isrot(T)\n s = strcat(s, sprintf('t = (%s),', vec2s(opt.fmt, transl(T)')));\n end\n\n % print the angular part in various representations\n switch (opt.mode)\n case {'rpy', 'euler'}\n % angle as a 3-vector\n if strcmp(opt.mode, 'rpy')\n ang = tr2rpy(T);\n label = 'RPY';\n else\n ang = tr2eul(T);\n label = 'EUL';\n end\n if opt.radian\n s = strcat(s, ...\n sprintf(' %s = (%s) rad', label, vec2s(opt.fmt, ang)) );\n else\n s = strcat(s, ...\n sprintf(' %s = (%s) deg', label, vec2s(opt.fmt, ang*180.0/pi)) );\n end\n case 'angvec'\n % as a vector and angle\n [th,v] = tr2angvec(T);\n if isnan(v(1))\n s = strcat(s, sprintf(' R = nil') );\n elseif opt.radian\n s = strcat(s, sprintf(' R = (%sdeg | %s)', ...\n sprintf(opt.fmt, th), vec2s(opt.fmt, v)) );\n else\n s = strcat(s, sprintf(' R = (%sdeg | %s)', ...\n sprintf(opt.fmt, th*180.0/pi), vec2s(opt.fmt,v)) );\n end\n end\nend\n\nfunction s = vec2s(fmt, v)\n s = '';\n for i=1:length(v)\n s = strcat(s, sprintf(fmt, v(i)));\n if i ~= length(v)\n s = strcat(s, ', ');\n end\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/trprint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.34958202995258797}}
{"text": "function engine = belprop_mrf2_inf_engine(mrf2, varargin) \n% BELPROP_MRF2_INF_ENGINE Belief propagation for MRFs with discrete pairwise potentials\n% engine = belprop_mrf2_inf_engine(mrf2, ...)\n%\n% This is like belprop_inf_engine, except it is designed for mrf2, so is much faster.\n%\n% [ ... ] = belprop_mrf2_inf_engine(..., 'param1',val1, 'param2',val2, ...)\n% allows you to specify optional parameters as name/value pairs.\n% Parameters modifying behavior of enter_evidence are below [default value in brackets]\n%\n% max_iter - max. num. iterations [ 5*nnodes]\n% momentum - weight assigned to old message in convex combination\n% (useful for damping oscillations) [0]\n% tol - tolerance used to assess convergence [1e-3]\n% verbose - 1 means print error at every iteration [0]\n%\n% Parameters can be changed later using set_params \n\n\n% The advantages of pairwise potentials are\n% (1) we can compute messages using vector-matrix multiplication\n% (2) we can easily specify the parameters: one potential per edge\n% In contrast, potentials on larger cliques are more complicated to deal with.\n\n\nnnodes = length(mrf2.adj_mat);\n\n[engine.max_iter, engine.momentum, engine.tol, engine.verbose] = ...\n process_options(varargin, 'max_iter', [], 'momentum', 0, 'tol', 1e-3, ...\n\t\t 'verbose', 0);\n\nif isempty(engine.max_iter) % no user supplied value, so compute default\n engine.max_iter = 5*nnodes;\n %if acyclic(mrf2.adj_mat, 0) --- can be very slow!\n % engine.max_iter = nnodes;\n %else\n % engine.max_iter = 5*nnodes;\n %end\nend\n\nengine.bel = cell(1, nnodes); % store results of enter_evidence here\nengine.mrf2 = mrf2;\n\nengine = class(engine, 'belprop_mrf2_inf_engine');\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/inference/static/@belprop_mrf2_inf_engine/belprop_mrf2_inf_engine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241632752916, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.34958202216224477}}
{"text": "function [nconds cforecast_record cforecast_estimates]=panel3cf(N,n,m,p,k,q,cfconds,cfshocks,cfblocks,data_endo_a,data_exo_a,data_exo_p,It,Bu,Fperiods,const,beta_gibbs,D_record,gamma_record,CFt,Fband)\n\n\n\n% initiate the cell recording the Gibbs sampler draws\ncforecast_record={};\ncforecast_estimates={};\n\n% because conditional forecasts can be computed for many (potentially all) units, loop over units\nfor ii=1:N\n% check wether there are any conditions on unit ii\ntemp=cfconds(:,:,ii);\nnconds(ii,1)=numel(temp(cellfun(@(x) any(~isempty(x)),temp)));\n\n % if there are conditions\n if nconds(ii,1)~=0\n % prepare the elements for conditional forecast estimation, depending on the type of conditional forecasts\n temp1=cfconds(:,:,ii);\n if CFt==1\n temp2={};\n temp3=[];\n elseif CFt==2\n temp2=cfshocks(:,:,ii);\n temp3=cfblocks(:,:,ii);\n end\n % run the Gibbs sampler for unit ii\n cforecast_record(:,:,ii)=bear.cforecast(data_endo_a(:,:,ii),data_exo_a,data_exo_p,It,Bu,Fperiods,temp1,temp2,temp3,CFt,const,beta_gibbs(:,:,ii),D_record(:,:,ii),gamma_record(:,:,ii),n,m,p,k,q);\n % then obtain point estimates and credibility intervals\n cforecast_estimates(:,:,ii)=bear.festimates(cforecast_record(:,:,ii),n,Fperiods,Fband);\n\n % if there are no conditions, return empty elements\n elseif nconds(ii,1)==0\n cforecast_record(:,:,ii)=cell(n,1);\n cforecast_estimates(:,:,ii)=cell(n,1);\n end\nend\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "european-central-bank", "repo": "BEAR-toolbox", "sha": "f33aae80c40f7a2e78a54de99b2ce3663f59aa75", "save_path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox", "path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox/BEAR-toolbox-f33aae80c40f7a2e78a54de99b2ce3663f59aa75/tbx/bear/+bear/panel3cf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.3493296577372672}}
{"text": "function model = mpt_enumeration_mpmilp(Matrices,options)\n% Variable bounds when all binary variables are relaxed\n[global_lower,global_upper] = mpt_detect_and_improve_bounds(Matrices,Matrices.lb,Matrices.ub,Matrices.binary_var_index,options);\n\nMatrices.lb = global_lower;\nMatrices.ub = global_upper;\nif any(Matrices.lb(end-Matrices.nx+1:end) == Matrices.ub(end-Matrices.nx+1:end))\n model = [];\n return\nend\n\n% Enumerate a sufficent set of binary cases\n% (exploit SOS and pure binary constraints)\n[enums,Matrices] = mpt_enumerate_binary(Matrices);\n\nmodel = [];\nfor i = 1:size(enums,2);\n if options.verbose & rem(i,20)==0\n disp(['Binary node ' num2str(i) '/' num2str(size(enums,2))]);\n end\n % Create node problem\n lower = global_lower;\n upper = global_upper;\n lower(Matrices.binary_var_index) = enums(:,i);\n upper(Matrices.binary_var_index) = enums(:,i);\n % Pre-solve, solve and merge\n model = mpt_solvenode(Matrices,lower,upper,Matrices,model,options);\nend\n", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/modules/parametric/mpt_enumeration_mpmilp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7772998508568417, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.34931282774562084}}
{"text": "function [cl,clpos,clneg,clrpos,clrneg] = cluster_sigregions(cl,pthr,varargin)\n% [cl,clpos,clneg,clrpos,clrneg] = cluster_ttest(clusters,pthr,[behavioral regressor])\n% tor wager Oct 9, 2003\n%\n% does t-tests on cluster timeseries and all voxels\n% which should contain group data (e.g., con* data)\n% \n% if optional behavioral regressor is entered,\n% computes cluster extent nonparametric p-values, and reports\n% extent npm p-values for intercept and behavioral reg.\n% \n% writes output to cluster_ttest_output.txt\n\nfid = fopen('cluster_ttest_output.txt','a');\n\nif length(varargin) > 0, beh = varargin{1};,end\n\nfor i = 1:length(cl)\n \n% df = n - k primary threshold\ntthr1 = abs(tinv(pthr,size(cl(i).all_data,1) - size(cl(i).ttest.t,1)));\n\n% ----------------------------------------\n% * do nonparametric permutation \n% ----------------------------------------\n\nif ~isfield(cl(i),'npm_ttest'),cl(i).npm_ttest = [];,end\nif isfield(cl(i).npm_ttest,'tmax') & isfield(cl(i).npm_ttest,'textmax')\n tthr = cl(i).npm_ttest.tthr ;\n rthr = cl(i).npm_ttest.rthr ;\n tnegthr = cl(i).npm_ttest.tnegthr ;\n rnegthr = cl(i).npm_ttest.rnegthr ;\n tmax = cl(i).npm_ttest.tmax ;\n tmin = cl(i).npm_ttest.tmin ;\n rmax = cl(i).npm_ttest.rmax ;\n rmin = cl(i).npm_ttest.rmin ;\n textmax = cl(i).npm_ttest.textmax ;\n rextmax = cl(i).npm_ttest.rextmax ;\nelse\n \n[tthr,rthr,tnegthr,rnegthr,tmax,rmax,tmin,rmin,textmax,rextmax] = ...\n npm_ttest(cl(i).all_data,1000,beh,pthr,cl(i).XYZ);\nclose\n\ncl(i).npm_ttest.tthr = tthr;\ncl(i).npm_ttest.rthr = rthr;\ncl(i).npm_ttest.tnegthr = tnegthr;\ncl(i).npm_ttest.rnegthr = rnegthr;\ncl(i).npm_ttest.tmax = tmax;\ncl(i).npm_ttest.rmax = rmax;\ncl(i).npm_ttest.textmax = textmax;\ncl(i).npm_ttest.rextmax = rextmax;\ncl(i).npm_ttest.tmin = tmin;\ncl(i).npm_ttest.rmin = rmin;\n\nend\n\nfprintf(fid,'\\nCl.\\tVoxels\\tThreshold\\tMask\\tData\\t\\n');\nfprintf(fid,'\\tx\\ty\\tz\\tVoxels\\tCluster corr. p.\\tMax. t\\tCorrected p\\tDirection of effect\\tr\\n');\nfprintf(fid,'%3.0f\\t%3.0f\\t%3.4f\\t%s\\t%s\\t\\n',i,cl(i).numVox,pthr,cl(i).P,cl(i).imP(1,:));\n\n% ----------------------------------------\n% * get sig clusters\n% ----------------------------------------\n\nclpos(i).from_cluster = i;\nclpos(i).M = cl(i).M;\nclpos(i).voxSize = cl(i).voxSize;\nclpos(i).threshold = tthr1;\nclpos(i).title = 'Positive effects';\n\nclrpos(i).from_cluster = i;\nclrpos(i).M = cl(i).M;\nclrpos(i).voxSize = cl(i).voxSize;\nclrpos(i).threshold = tthr1;\nclrpos(i).title = 'Positive correlations';\n\nsig = cl(i).ttest.t > tthr1;\n\nif any(sig(1,:))\n clpos(i).XYZ = cl(i).XYZ(:,find(sig(1,:))); \n clpos(i).XYZmm = cl(i).XYZmm(:,find(sig(1,:)));\n clpos(i).Z = cl(i).Z(:,find(sig(1,:))); \n clpos(i).t = cl(i).ttest.t(:,find(sig(1,:))); \n gopos(i) = 1;\n \n % print table entry\n wcl = spm_clusters(clpos(i).XYZ);\n clpos(i).clusters = wcl;\n for j = 1:max(wcl)\n \n wh = find(wcl==j);\n \n % corrected p\n \n xyz = mean(clpos(i).XYZmm(:,wh),2)';\n if length(xyz) == 1, xyz = clpos(i).XYZmm(:,wh)';,end\n nv = length(wh);\n \n if length(wh)>1,max_t = max(clpos(i).t(:,wh)'); max_t = max_t(1);,\n else, max_t = clpos(i).t(1,wh);\n end\n \n clpos(i).center = xyz;\n \n extcor_p = 1 - (sum(textmax <= nv) ./ length(textmax));\n max_p = 1 - (sum(tmax <= max_t) ./ length(tmax));\n\n fprintf(fid,'\\t%3.0f\\t%3.0f\\t%3.0f\\t%3.0f\\t%3.4f\\t%3.2f\\t%3.4f\\t+\\n', ...\n xyz(1),xyz(2),xyz(3),nv,extcor_p,max_t,max_p)\n end\n \nelse\n gopos(i) = 0;\nend\n\nif any(sig(2,:))\n clrpos(i).XYZ = cl(i).XYZ(:,find(sig(2,:))); \n clrpos(i).XYZmm = cl(i).XYZmm(:,find(sig(2,:)));\n clrpos(i).Z = cl(i).Z(:,find(sig(2,:))); \n clrpos(i).t = cl(i).ttest.t(:,find(sig(2,:))); \n gorpos(i) = 1;\n \n % print table entry\n wcl = spm_clusters(clrpos(i).XYZ);\n clrpos(i).clusters = wcl;\n for j = 1:max(wcl)\n \n wh = find(wcl==j);\n \n % corrected p\n \n xyz = mean(clrpos(i).XYZmm(:,wh),2)';\n if length(xyz) == 1, xyz = clrpos(i).XYZmm(:,wh)';,end\n nv = length(wh);\n \n tmp = cl(i).all_data(:,find(sig(2,:)));\n tmp = tmp(:,wh);\n tmp = corrcoef([tmp beh]);\n tmp = tmp(end,1:end-1);\n max_r = max(tmp);\n if max_r > .99, warning('problem?'),keyboard,end\n \n if length(wh)>1,max_t = max(clrpos(i).t(:,wh)'); max_t = max_t(2);,\n else, max_t = clrpos(i).t(2,wh);\n end\n clrpos(i).center = xyz;\n \n extcor_p = 1 - sum(rextmax <= nv) ./ length(rextmax);\n max_p = 1 - sum(rmax <= max_t) ./ length(rmax);\n\n fprintf(fid,'\\t%3.0f\\t%3.0f\\t%3.0f\\t%3.0f\\t%3.4f\\t%3.2f\\t%3.4f\\t+\\t%3.2f\\n', ...\n xyz(1),xyz(2),xyz(3),nv,extcor_p,max_t,max_p,max_r);\n end\n \nelse\n gorpos(i) = 0;\nend\n\n% negative\n\nclneg(i).from_cluster = i;\nclneg(i).M = cl(i).M;\nclneg(i).voxSize = cl(i).voxSize;\nclneg(i).threshold = tthr1;\nclneg(i).title = 'Negative effects';\n\nclrneg(i).from_cluster = i;\nclrneg(i).M = cl(i).M;\nclrneg(i).voxSize = cl(i).voxSize;\nclrneg(i).threshold = tthr1;\nclrneg(i).title = 'Negative correlations';\n\nsig = cl(i).ttest.t < -tthr1;\n\nif any(sig(1,:))\n clneg(i).XYZ = cl(i).XYZ(:,find(sig(1,:))); \n clneg(i).XYZmm = cl(i).XYZmm(:,find(sig(1,:)));\n clneg(i).Z = cl(i).Z(:,find(sig(1,:))); \n clneg(i).t = cl(i).ttest.t(:,find(sig(1,:))); \n goneg(i) = 1;\n \n % print table entry\n wcl = spm_clusters(clneg(i).XYZ);\n clneg(i).clusters = wcl;\n for j = 1:max(wcl)\n \n wh = find(wcl==j);\n \n % corrected p\n \n xyz = mean(clneg(i).XYZmm(:,wh),2)';\n if length(xyz) == 1, xyz = clpos(i).XYZmm(:,wh)';,end\n nv = length(wh);\n \n if length(wh)>1,max_t = min(clneg(i).t(:,wh)'); max_t = max_t(1);,\n else, max_t = clneg(i).t(1,wh);\n end\n \n clneg(i).center = xyz;\n \n extcor_p = 1 - sum(textmax <= nv) ./ length(textmax);\n max_p = 1 - sum(tmin >= max_t) ./ length(tmin);\n\n fprintf(fid,'\\t%3.0f\\t%3.0f\\t%3.0f\\t%3.0f\\t%3.4f\\t%3.2f\\t%3.4f\\t-\\n', ...\n xyz(1),xyz(2),xyz(3),nv,extcor_p,max_t,max_p);\n end\n \nelse\n goneg(i) = 0;\nend\n\nif any(sig(2,:))\n clrneg(i).XYZ = cl(i).XYZ(:,find(sig(2,:))); \n clrneg(i).XYZmm = cl(i).XYZmm(:,find(sig(2,:)));\n clrneg(i).Z = cl(i).Z(:,find(sig(2,:))); \n clrneg(i).t = cl(i).ttest.t(:,find(sig(2,:))); \n gorneg(i) = 1;\n \n % print table entry\n wcl = spm_clusters(clrneg(i).XYZ);\n clrneg(i).clusters = wcl;\n for j = 1:max(wcl)\n \n wh = find(wcl==j);\n \n % corrected p\n \n xyz = mean(clrneg(i).XYZmm(:,wh),2)';\n if length(xyz) == 1, xyz = clrneg(i).XYZmm(:,wh)';,end\n nv = length(wh);\n \n if length(wh)>1,max_t = min(clrneg(i).t(:,wh)'); max_t = max_t(2);,\n else, max_t = clrneg(i).t(2,wh);\n end\n \n tmp = cl(i).all_data(:,find(sig(2,:)));\n tmp = tmp(:,wh);\n tmp = corrcoef([tmp beh]);\n tmp = tmp(end,1:end-1);\n max_r = min(tmp);\n if max_r > .99, warning('problem?'),keyboard,end\n \n clrneg(i).center = xyz;\n \n extcor_p = 1 - sum(rextmax <= nv) ./ length(rextmax);\n max_p = 1 - sum(rmin >= max_t) ./ length(rmin);\n\n fprintf(fid,'\\t%3.0f\\t%3.0f\\t%3.0f\\t%3.0f\\t%3.4f\\t%3.2f\\t%3.4f\\t-\\t%3.2f\\t\\n', ...\n xyz(1),xyz(2),xyz(3),nv,extcor_p,max_t,max_p,max_r);\n end\n \nelse\n gorneg(i) = 0;\nend\n\nend % loop through clusters\n\nfprintf(fid,'\\n')\n\n\n% Make montage\ntry\n \nif ~isempty(clpos) & ~isempty(clneg)\n montage_clusters([],cl(unique(cat(2,[clpos.from_cluster clneg.from_cluster]))),clpos,clneg,{'k' 'r' 'b'},'nooverlap')\n %hh=get(gcf,'Children');\n %for i = 1:length(hh),axes(hh(i));, h = findobj(gca,'FaceColor',[0 0 0]);, set(h,'FaceAlpha',.5) ,end\nelseif ~isempty(clpos)\n montage_clusters([],cl(cat(2,clpos.from_cluster)),clpos,{'k' 'r'},'nooverlap')\nelseif ~isempty(clneg)\n montage_clusters([],cl,clneg,{'k' 'b'},'nooverlap')\nelse\n disp('No main contrast effects')\nend\n\nif ~isempty(clrpos) & ~isempty(clrneg)\n montage_clusters([],cl(unique(cat(2,[clrpos.from_cluster clrneg.from_cluster]))),clrpos,clrneg,{'k' 'r' 'b'},'nooverlap')\nelseif ~isempty(clrpos)\n montage_clusters([],cl(cat(2,clrpos.from_cluster)),clrpos,{'k' 'r'},'nooverlap')\nelseif ~isempty(clrneg)\n montage_clusters([],cl(cat(2,clrneg.from_cluster)),clrneg,{'k' 'b'},'nooverlap')\nelse\n disp('No correlation effects')\nend\n\ncatch\n disp('error with montage')\nend\n\nfclose(fid);\n\nreturn\n\n\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Cluster_contig_region_tools/Cluster_based_statistics/cluster_sigregions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.34929065314791957}}
{"text": "function scrollsubplot(dx,x,varargin);\n\n% Cette fonction permet l'ajout d'un curseur dynamique sur les figures\n% graphique tout en permettant l'utilisation de sous-graphiques subplot.\n% Cette fonction est une variation de la fonction scrollplot de Wolfgang\n% Stiegmaier et de scrollplotdemo de Steven Lord, slord@mathworks.com.\n%\n% Syntaxe\n% scrollsubplot(dx,x,h1,h2,...hn);\n%\n% Description\n% dx: d\u00e9termine la largeur de la fenetre\n% x: vecteur temps\n% h1...hn: les r\u00e9f\u00e9rences aux sous-graphiques\n%\n% exemple\n% \n% temps = linspace(0,10*pi,100001);\n% Y1 = sin(temps);\n% Y2 = cos(temps);\n% Y3 = sin(temps).^2;\n%\n% h1=subplot(3,1,1);\n% plot(temps,Y1),grid;\n% h2=subplot(3,1,2);\n% plot(temps,Y2),grid;\n% h3=subplot(3,1,3);\n% plot(temps,Y3),grid;\n% scrollsubplot(pi,temps,h1,h2,h3);\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%% Benoit Cantin, 7 mars 2005. %%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Original message\n% :Created by Steven Lord, slord@mathworks.com\n% :Uploaded to MATLAB Central\n% :http://www.mathworks.com/matlabcentral\n% :7 May 2002\n% :Permission is granted to adapt this code for your own use.\n% :However, if it is reposted this message must be intact.\n\n% get current axes\na=gca;\n% This avoids flickering when updating the axis\nset(gcf,'doublebuffer','on');\n% Set appropriate axis limits and settings\nset(a,'xlim',[0 dx]);\n%set(a,'ylim',[min(y) max(y)]);\n\n% Generate constants for use in uicontrol initialization\npos=get(a,'position');\nxmax=max(x);\nxmin=min(x);\n\n% This will create a slider which is just underneath the axis\n% but still leaves room for the axis labels above the slider\nNewpos=[pos(1) pos(2)-0.1 pos(3) 0.05];\n\nfor i = 1:length(varargin);\n %initialize postion of plot\n set(varargin{i},'xlim',[xmin xmin+dx]);\n \n % Cr\u00e9ation des variables h1...hn\n eval(['h',num2str(i), ' = varargin{i};']);\n \n % Setting up callback string to modify XLim of axis (gca)\n % based on the position of the slider (gcbo)\n if i == 1;\n S=['set(h', num2str(i), ' ,''xlim'',get(gcbo,''value'')+[0 ' num2str(dx) '])'];\n else\n S=[S ', set(h', num2str(i), ' ,''xlim'',get(gcbo,''value'')+[0 ' num2str(dx) '])'];\n end\nend\n\n% Creating Uicontrol with initial value of the minimum of x\nh=uicontrol('style','slider',...\n 'units','normalized','position',Newpos,...\n 'callback',S,'min',xmin,'max',xmax-dx,'value',xmin);\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/7073-advanced-scroll-plot-with-subplot-handling/scrollsubplot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.3492906497369998}}
{"text": "function [W,dist_H_V] = shepard(V,C,P,E,CE,p)\n % SHEPARD Compute shepard weights for a list of vertices, given a list of\n % samples and optionally a denominator power value.\n %\n % W = shepard(V,C)\n %\n % Inputs:\n % V list of vertex positions\n % C list of control vertices\n % P list of indices into C for point controls, { 1:size(C,1) }\n % E list of bones, pairs of indices into C, connecting control vertices, \n % { [] }\n % CE list of \"cage edges\", pairs of indices into ***P***, connecting\n % control ***points***. A \"cage edge\" just tells point boundary conditions \n % to vary linearly along straight lines between the end points, and to be\n % zero for all other handles. { [] }\n % p (optional) power for denominator, scalar or list same size as C {2}\n %\n % Outputs:\n % W weights, # vertices by # handles matrix of weights\n %\n % Example:\n % % \"Shape-aware\" shepard weights\n % D = permute(sum((repmat(V,[1,1,size(C,1)]) - ...\n % permute(repmat(C,[1,1,n]),[3,2,1])).^2,2),[1,3,2]);\n % [minD,b] = min(D);\n % snap_C = V(b,:);\n % [BV,ev,ed] = biharmonic_embedding(V,F,6);\n % [W] = shepard(BV,BV(b,:));\n %\n %\n\n % check if either are 3D but really all z's are 0\n V_flat = size(V,2) == 3 && (sqrt(sum(V(:,3).^2)) < 1e-10);\n C_flat = size(C,2) == 3 && (sqrt(sum(C(:,3).^2)) < 1e-10);\n % is both are essentially 2D then ignore z-coords\n if((size(C,2) == 2 || C_flat) && (size(V,2) == 2 || V_flat))\n % ignore z coordinate\n V = V(:,1:2);\n C = C(:,1:2);\n end\n\n assert(size(C,2) == size(V,2));\n dim = size(C,2);\n\n % default p value\n if(~exist('p','var'))\n p = 2;\n end\n\n if(~exist('P','var'))\n P = 1:size(C,1);\n end\n\n if(~exist('E','var'))\n E = [];\n end\n\n if(~exist('CE','var'))\n CE = [];\n end\n\n assert(prod(size(P)) == max(size(P)));\n assert(isempty(E) || size(E,2) == 2);\n assert(isempty(CE) || size(CE,2) == 2);\n assert(isempty(E) || max(E(:))<=size(C,1));\n assert(isempty(CE) || max(CE(:))<=numel(P));\n assert(isempty(P) || max(P(:))<=size(C,1));\n assert(isempty(E) || min(E(:)) >= 1);\n assert(isempty(CE) || min(CE(:)) >= 1);\n assert(isempty(P) || min(P(:)) >= 1);\n\n\n % number of point controls \n np = numel(P);\n nb = size(E,1);\n % number of domain vertices\n n = size(V,1);\n\n % if p is a scalar convert it now to a list the same size as C\n if(prod(size(p)) == 1)\n p = repmat(p,np+nb,1);\n elseif ~isempty(CE)\n if 0 ~= std(p(CE(:)))\n error('Variable powers not supported with cage edges');\n end\n end\n\n dist_P_V = zeros(np,n);\n if(np > 0)\n % vectors from V to every P, where PmV(i,j,:) is the vector from domain\n % vertex j to handle i\n PmV = ...\n permute( ...\n permute(repmat(C(P,:),[1,1,n]),[3,2,1]) - ...\n repmat(V,[1,1,np]),[3,1,2]);\n % distance from V to every P, where dist_P_V(i,j) is the distance from domain\n % vertex j to point handle i\n dist_P_V = sqrt(sum(PmV.^2,3));\n % distance from each corner in P to the next corner so that edge_length(i) \n end\n\n dist_B_V = zeros(nb,n);\n if(nb > 0)\n % loop over bones\n for( ii = 1:nb )\n % project to line\n [t,sqr_d] = project_to_lines(V,C(E(ii,1),:),C(E(ii,2),:));\n d = sqrt(sqr_d);\n % if projected point falls outside of line segment take distance to\n % closest end point\n d(t<0) = sqrt(sum((V(t<0,:)-repmat(C(E(ii,1),:),size(V(t<0,:),1),1)).^2,2));\n d(t>1) = sqrt(sum((V(t>1,:)-repmat(C(E(ii,2),:),size(V(t>1,:),1),1)).^2,2));\n dist_B_V(ii,:) = d';\n end\n end\n\n dist_H_V = [dist_P_V ; dist_B_V];\n % power of each control point seen by each vertex in domain\n pp = repmat(p,1,n);\n W = 1.0./((dist_H_V).^pp);\n\n if(size(CE,1) > 0)\n % zero out previous entries in points with incident cage edges\n W(CE(:),:) = 0;\n % compute projection of each point to each line segment\n [T,sqrD] = project_to_lines(V,C(P(CE(:,1)),:),C(P(CE(:,2)),:));\n % compute weights for each cage edge as if it were a bone\n pce = (p(CE(:,1))+p(CE(:,2)))/2;\n [~,dist_CE_V] = shepard(V,C,[],P(CE),[],pce);\n % compute \"bone weights\" for each cage edge as they were before\n % normalization\n ppce = repmat(pce,1,n);\n WCE = 1.0./((dist_CE_V).^ppce)';\n % clamp distances\n T(T<0) = 0;\n T(T>1) = 1;\n % multiply \"bone weight\" by projection parameter and sum up\n II = repmat(1:n,1,2*size(CE,1))';\n JJ = reshape(repmat(CE(:)',n,1),[],1);\n VV = [WCE(:).*(1-T(:)); WCE(:).*T(:)];\n W = W+sparse(II,JJ,VV,n,np+nb)';\n % cage edges on-samples\n on_sample = dist_CE_V < eps;\n [I,J] = find(on_sample);\n W(:,any(on_sample)) = 0;\n % grab T transpose\n TT = T';\n W(sub2ind(size(W),CE(I,1),J)) = 1-TT(on_sample);\n W(sub2ind(size(W),CE(I,2),J)) = TT(on_sample);\n end\n\n % Handle degenrate case that a control point is on a mesh vertex\n % snap vertices close to corners\n on_sample = dist_H_V < eps;\n W(:,any(on_sample,1)) = 0;\n W(on_sample) = 1;\n\n % normalize W\n W = W./repmat(sum(W,1),np+nb,1);\n\n % we've made W transpose\n W = W';\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/shepard.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3492906463260801}}
{"text": "function M = setdiag(M, v)\n% SETDIAG Set the diagonal of a matrix to a specified scalar/vector.\n% M = set_diag(M, v)\n\n\nn = length(M);\nif length(v)==1\n v = repmat(v, 1, n);\nend\nJ = 1:n+1:n^2;\nM(J) = v;\n\n%M = triu(M,1) + tril(M,-1) + diag(v);\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/murphy/KPMtools/setdiag.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.3492906463260801}}
{"text": "function outstring = demorse(wavfile);\n\n%demorse a morsed input wav file\n\nvis_on = 0;\n\nthreshold = 0.05;\n\nx = wavread(wavfile);\n\n% half-wave rectify x\nx2 = abs(x);\n\n% slow-wave filter \ny = filter(ones(1,20)/20,1, x2);\n\n% threshold (digitize) y\nz = y > threshold;\n% z is now effectively our morse signal\n\nif vis_on\n figure(1);\n subplot(3,1,1);\n plot(x, 'r');\n title('original signal');\n \n subplot(3,1,2);\n plot(y);\n title('HWR + Slow-wave filter -> envelope');\n subplot(3,1,3);\n plot(z, 'o', 'MarkerSize', 2);\n title('Digitized Morse signal')\n \nend\n\n%zero pad z so we always start with an onset\nz = [zeros(10,1); z];\n\n% id tones/spaces -----------------------\n% --> find changes between 0/1 and 1/0\n\nb = diff(z);\n% figure(3); plot(b, '.');\n% 1: change from 1 to 0\n% 0: no change\n% -1: change from 0 to 1\n\nc = b(b~=0);\nc2 = find(b~=0);\n\ntokens = -c .* diff([0; c2]);\n% value == length of token\n% sign == tone/space\n\n% id shorts/longs -----------------------\n\n% since short/long should be bi-modal dist, a regular average should give\n% us a good cutoff point to distinguish between the two? (assuming equal\n% counts of short and long...)\n% use mean as simple cutoff point; smarter algorithms can get smarter about\n% this classification if they want to.\n\n% 1: short, 2: long, +: tone, -: space\ntokens2 = tokens;\n\n% cutoff tones, cutoff spaces;\ncut_t = mean(tokens2(tokens2>0));\ncut_s = mean(tokens2(tokens2<0));\n\ntokens2(tokens > 0 & tokens < cut_t) = 1;\ntokens2(tokens > 0 & tokens > cut_t) = 2;\ntokens2(tokens < 0 & tokens > cut_s) = -1;\ntokens2(tokens < 0 & tokens < cut_s) = -2;\n\n% now tokens 2 is a string of -1s, -2s, 1s, 2s, can trim first known space;\n% put final endstop at end\ntokens2 = [tokens2(2:end); -2];\n\n% can drop little spaces, b/c they don't matter when parsing;\ntokens2(tokens2 == -1) = [];\ntokens3 = tokens2;\ntokens4 = {};\nctr = 1;\nstart_idx = 1;\n\n%parse\ntoparse = find(tokens3(start_idx:end) == -2);\n\nfor j=1:length(toparse)\n a = toparse(j);\n temp = tokens3(start_idx:a-1);\n tokens4{j} = temp;\n % zeropad for easy comparison\n %tokens4{j} = [tokens4{j}; zeros(length(tokens4{j}), 1)];\n start_idx = a+1;\n\nend\n \n% now tokens4 is de-codeable tokens... proceed to setup lookups\n% letters\ncode{1} = [1 2 ];\ncode{2} = [2 1 1 1];\ncode{3} = [2 1 2 1];\ncode{4} = [2 1 1];\ncode{5} = [1];\ncode{6} = [1 1 2 1];\ncode{7} = [2 2 1];\ncode{8} = [1 1 1 1];\ncode{9} = [1 1];\ncode{10} = [1 2 2 2];\ncode{11} = [2 1 2];\ncode{12} = [1 2 1 1];\ncode{13} = [2 2];\ncode{14} = [2 1];\ncode{15} = [2 2 2];\ncode{16} = [1 2 2 1];\ncode{17} = [1 2 1 2];\ncode{18} = [1 2 1];\ncode{19} = [1 1 1];\ncode{20} = [2];\ncode{21} = [1 1 2]; \ncode{22} = [1 1 1 2];\ncode{23} = [1 2 2];\ncode{24} = [2 1 1 2];\ncode{25} = [2 1 2 2];\ncode{26} = [2 2 1 1];\n\n% punct\ncode{27} = [1 2 1 2 1 2];\ncode{28} = [2 2 1 1 2 2];\ncode{29} = [1 1 2 2 1 1]; \ncode{30} = [2 1 1 2 1];\n\n% numbers\n\ncode{31} = [1 2 2 2 2];\ncode{32} = [1 1 2 2 2];\ncode{33} = [1 1 1 2 2];\ncode{34} = [1 1 1 1 2];\ncode{35} = [1 1 1 1 1];\ncode{36} = [2 1 1 1 1];\ncode{37} = [2 2 1 1 1];\ncode{38} = [2 2 2 1 1];\ncode{39} = [2 2 2 2 1];\ncode{40} = [2 2 2 2 2];\n\n\ndecode{1} = 'A';\ndecode{2} = 'B';\ndecode{3} = 'C';\ndecode{4} = 'D';\ndecode{5} = 'E';\ndecode{6} = 'F';\ndecode{7} = 'G';\ndecode{8} = 'H';\ndecode{9} = 'I';\ndecode{10} = 'J';\ndecode{11} = 'K';\ndecode{12} = 'L';\ndecode{13} = 'M';\ndecode{14} = 'N';\ndecode{15} = 'O';\ndecode{16} = 'P';\ndecode{17} = 'Q';\ndecode{18} = 'R';\ndecode{19} = 'S';\ndecode{20} = 'T';\ndecode{21} = 'U';\ndecode{22} = 'V';\ndecode{23} = 'W';\ndecode{24} = 'X';\ndecode{25} = 'Y';\ndecode{26} = 'Z';\ndecode{27} = '.';\ndecode{28} = ',';\ndecode{29} = '?';\ndecode{30} = '/';\ndecode{31} = '1';\ndecode{32} = '2';\ndecode{33} = '3';\ndecode{34} = '4';\ndecode{35} = '5';\ndecode{36} = '6';\ndecode{37} = '7';\ndecode{38} = '8';\ndecode{39} = '9';\ndecode{40} = '0';\n\n\n\n% compare tokens to tables\n\nout1 = [];\n\nfor j = 1:length(tokens4)\n %zero pad temp_tok\n temp_tok = [tokens4{j}; zeros(6 - length(tokens4{j}), 1)];\n for k = 1:length(code)\n if (temp_tok == [code{k}'; zeros(6 - length(code{k}), 1)]);\n out1(j) = char(decode{k});\n %display(decode{k})\n end\n\n end\n\n % if didn't find a match\n if isempty(out1(j))\n out1(j) = '_';\n end\n \nend\n\n% semi-prettify\noutstring = 32*ones(2*length(out1),1);\noutstring(2:2:end) = out1;\noutstring = char(outstring');\n\n%display('demorsed message:')\n%display(outstring);\n\n\n\n\n\n\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/21491-demorse/demorse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.34929064632608}}
{"text": "%% Example\n% real time control of the KUKA iiwa 7 R 800\n% Moving first joint of the robot, using a sinisoidal function\n\n% An example script, it is used to show how to use the different\n% functions of the KUKA Sunrise matlab toolbox\n\n% First start the server on the KUKA iiwa controller\n% Then run this script using Matlab\n\n% Copyright: Mohammad SAFEEA, 15th of June 2017\n\n% Important: Be careful when runnning the script, be sure that no human, nor obstacles\n% are around the robot\n\nclose all,clear all;clc;\n\nwarning('off')\n\nip='172.31.1.147'; % The IP of the controller\n% start a connection with the server\nglobal t_Kuka;\nt_Kuka=net_establishConnection( ip );\n\nif ~exist('t_Kuka','var') || isempty(t_Kuka) || strcmp(t_Kuka.Status,'closed')\n disp('Connection could not be establised, script aborted');\n return;\nend\n \n%% Go to initial position\n\njPos={0,0,0,0,0,0,0};\n\nsetBlueOn(t_Kuka); % turn on blue light\n\nrelVel=0.5;\nmovePTPJointSpace( t_Kuka , jPos, relVel); % move to initial configuration\n\n%% Start direct servo in joint space \nrealTime_startDirectServoJoints(t_Kuka);\n%% Some variables\nw=2.0; % motion constants, frequency rad/sec\nA=pi/6; % motion constants, amplitude of motion\ndt=0;\ncounter=0;\n%% Initiate timing\ntic;\n%% Control loop\ntry \n daCount=0;\n while(dt<(80*pi/w))\n if daCount==0\n t0=toc; % calculate initial time\n t_0=toc;\n daCount=1;\n end\n %% perform trajectory calculation here\n time=toc;\n dt=time-t0;\n jPos{1}=A*(1-cos(w*dt));\n %% Send joint positions to robot\n if(toc-t_0>0.003)\n counter=counter+1;\n sendJointsPositionsf( t_Kuka ,jPos);\n t_0=toc;\n end\n end\n tstart=t0;\n tend=time;\n rate=counter/(tend-tstart);\n %% Stop the direct servo motion\n realTime_stopDirectServoJoints( t_Kuka );\n fprintf('\\nTotal execution time is %f: \\n',tend-t0 );\n fprintf('\\nThe rate of joint nagles update per second is: \\n');\n disp(rate);\n fprintf('\\n')\n pause(2);\n %% turn off light\n setBlueOff(t_Kuka);\n net_turnOffServer( t_Kuka )\n disp('Direct servo motion completed successfully')\n warning('on')\n return;\ncatch\n % in case of error turn off the server\n net_turnOffServer( t_Kuka );\n disp('Error during execution the direct servo motion')\n fclose(t_Kuka); \n warning('on')\nend\n\n", "meta": {"author": "Modi1987", "repo": "KST-Kuka-Sunrise-Toolbox", "sha": "9299bed2b46058aeb4105d7fbff6d2290ce68bba", "save_path": "github-repos/MATLAB/Modi1987-KST-Kuka-Sunrise-Toolbox", "path": "github-repos/MATLAB/Modi1987-KST-Kuka-Sunrise-Toolbox/KST-Kuka-Sunrise-Toolbox-9299bed2b46058aeb4105d7fbff6d2290ce68bba/Matlab_client/kuka0_directServoFast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3492843138337172}}
{"text": "classdef prtClassMilVbDpGmm < prtClass\n % prtClassMilVbDpGmm VBDPGMM MIL Classifier\n %\n % A variational bayes classifier for multiple instance data. There\n % are a number of parameters available for pruning/training.\n % Performnace should (in theory) be somewhat invariant to these. See\n % the text of Manandhar et al., for descriptions.\n %\n % You may need to reduce the dimensionality of the data being used via\n % PCA, PLS, or some other pre-processing prior to using\n % prtClassMilVbDpGmm. We also recommend making sure the data is\n % approximately zero-mean, unit-variance in each of the columns.\n %\n % dsTrain = prtDataGenMultipleInstance;\n % dsTest = prtDataGenMultipleInstance;\n % class = prtClassMilVbDpGmm;\n % class = class.train(dsTrain);\n % yOutTrain = class.run(dsTrain);\n % yOutTest = class.run(dsTest);\n %\n % [pfTrain,pdTrain] = prtScoreRoc(yOutTrain);\n % [pfTest,pdTest] = prtScoreRoc(yOutTest);\n % subplot(1,1,1);\n % plot(pfTrain,pdTrain,pfTest,pdTest);\n %\n\n\n\n\n\n\n\n properties (SetAccess=private)\n name = 'MilVbDpGmm' \n nameAbbreviation = 'MilVbDpGmm' \n isNativeMary = false; % False\n end\n \n \n properties\n maxVbIter = 300;\n \n K0 = 5;\n K1 = 5; \n gamma_0_1_m0 = 1;\n gamma_0_2_m0 = .001;\n gamma_0_1_m1 = 1;\n gamma_0_2_m1 = .001;\n alpha = [10 10];\n \n rvH1\n rvH0\n end\n \n properties (Hidden)\n \n initialFit = [];\n %Dependent on \"d\"\n v_0_m\n v_1_m\n beta_1_m\n beta_0_m\n \n rho_0_1\n rho_0_0\n Phi_0_1\n Phi_0_0\n end\n \n\tmethods\n\t\tfunction self = prtClassMilVbDpGmm(varargin)\n\n\t\t\tself = prtUtilAssignStringValuePairs(self,varargin{:});\n \n self.classTrain = 'prtDataSetClassMultipleInstance';\n self.classRun = 'prtDataSetClassMultipleInstance';\n self.classRunRetained = false;\n end\n\t\t\n end\n \n methods (Access=protected, Hidden = true)\n\t\tfunction self = trainAction(self,dsMil)\n \n milStruct = dsMil.data;\n x = cat(1,milStruct.data);\n \n bagLabels = dsMil.targets;\n expandedBagLabels = dsMil.expandedTargets;\n \n bagIndices = dsMil.getBagInds;\n uniqueBagIndices = unique(bagIndices);\n \n d = size(x,2);\n \n self.v_0_m = d+2;\n self.v_1_m = d+2;\n self.beta_1_m = d;\n self.beta_0_m = d;\n self.rho_0_0 = zeros(1,d);\n self.rho_0_1 = zeros(1,d);\n \n self.Phi_0_0 = eye(d)*d;\n self.Phi_0_1 = eye(d)*d;\n \n% params = struct('K0',5,'K1',5,'gamma_0_1_m0',1,'gamma_0_2_m0',.001,'gamma_0_1_m1',1,'gamma_0_2_m1',.001,...\n% 'v_0_m',d+2,'v_1_m',d+2,'beta_1_m',d,'beta_0_m',d, ...\n% 'rho_0_1',zeros(1,d),'rho_0_0',zeros(1,d),'Phi_0_1',eye(d)*d,'Phi_0_0',eye(d)*d,'alpha',[4 1]*10000);\n \n \n [rvH0,rvH1,xH0,xH1] = initialize(self,{milStruct.data},bagLabels);\n %self.initialFit = self.calculateDataLogLikelihood(self,xH0,xH1);\n ll0 = sum(rvH0.logPdf(xH0));\n ll1 = rvH0.pdf(xH1).*self.alpha(1)/sum(self.alpha) + rvH1.pdf(xH1).*self.alpha(2)/sum(self.alpha);\n self.initialFit = ll0 + sum(log(ll1));\n \n \n [p0,pp] = rvH0.pdf(x);\n phi_0_i = bsxfun(@rdivide,pp,sum(pp,2));\n \n [p1,pp] = rvH1.pdf(x);\n phi_1_i = bsxfun(@rdivide,pp,sum(pp,2));\n phi_1_i(expandedBagLabels == 0,:) = 0;\n p1(expandedBagLabels ==0) = 0;\n \n phi_1_M = p1./(p0 + p1);\n phi_0_M = 1-phi_1_M;\n \n \n locEps = 1e-6;\n \n for vbIter = 1:self.maxVbIter\n %Equations 67 and 68; note, these are different from 20-21 (!)\n % gamma_i_1_m0 = sum(bsxfun(@times,phi_0_M,phi_0_i)) + self.gamma_0_1_m0;\n % gamma_i_2_m0 = cat(2,0,cumsum(gamma_i_1_m0(1:end-1),2)) + self.gamma_0_2_m0;\n %\n % gamma_i_1_m1 = sum(bsxfun(@times,phi_1_M,phi_1_i)) + self.gamma_0_1_m1;\n % gamma_i_2_m1 = cat(2,0,cumsum(gamma_i_1_m1(1:end-1),2)) + self.gamma_0_2_m1;\n \n %Equations 20-21\n gamma_i_1_m0 = sum(bsxfun(@times,phi_0_M,phi_0_i)) + self.gamma_0_1_m0;\n gamma_i_2_m0 = fliplr(cumsum(fliplr(gamma_i_1_m0))) - gamma_i_1_m0 + self.gamma_0_2_m0;\n \n gamma_i_1_m1 = sum(bsxfun(@times,phi_1_M,phi_1_i)) + self.gamma_0_1_m1;\n gamma_i_2_m1 = fliplr(cumsum(fliplr(gamma_i_1_m1))) - gamma_i_1_m1 + self.gamma_0_2_m1;\n \n %Update priors... H0 Gaussian; Equations 77-79 (H0)\n respMat = bsxfun(@times,phi_0_M,phi_0_i);\n nBar0 = sum(respMat)+locEps; %avoid 1./0 problems\n for cluster = 1:self.K0\n mu_i_0(cluster,:) = 1/nBar0(cluster)*sum(bsxfun(@times,respMat(:,cluster),x));\n \n xx = bsxfun(@times,sqrt(respMat(:,cluster)),bsxfun(@minus,x,mu_i_0(cluster,:)));\n c = 1/nBar0(cluster)*xx'*xx;\n cov_i_0(cluster,:) = c(:);\n end\n \n %Update priors... H1 Gaussian; Equations 77-79\n respMat = bsxfun(@times,phi_1_M,phi_1_i);\n nBar1 = sum(respMat)+locEps;\n for cluster = 1:self.K1\n mu_i_1(cluster,:) = 1/nBar1(cluster)*sum(bsxfun(@times,respMat(:,cluster),x));\n \n xx = bsxfun(@times,sqrt(respMat(:,cluster)),bsxfun(@minus,x,mu_i_1(cluster,:)));\n c = 1/nBar1(cluster)*xx'*xx;\n cov_i_1(cluster,:) = c(:);\n end\n \n %Updating hyper-parameters; eqns 81-84\n nu_0 = self.v_0_m + nBar0;\n nu_1 = self.v_1_m + nBar1;\n \n beta_0 = self.beta_0_m + nBar0;\n beta_1 = self.beta_1_m + nBar1;\n \n \n for cluster = 1:self.K0\n rho_0(cluster,:) = self.beta_0_m*self.rho_0_0 + nBar0(cluster)*mu_i_0(cluster,:);\n rho_0(cluster,:) = rho_0(cluster,:)./beta_0(cluster);\n \n %See equation 84; Note: this is different from Equation 84 - 84 is\n %wrong\n %covPart = nBar0(cluster) * reshape(cov_i_0(cluster,:),d,d) * ((mu_i_0(cluster,:) - rho_0(cluster,:))'*(mu_i_0(cluster,:) - rho_0(cluster,:)));\n covPart = nBar0(cluster) * self.beta_0_m * ((mu_i_0(cluster,:) - self.rho_0_0)'*(mu_i_0(cluster,:) - self.rho_0_0));\n covPart = covPart ./ beta_0(cluster);\n \n phiCov = self.Phi_0_0 + nBar0(cluster)*reshape(cov_i_0(cluster,:),d,d) + covPart;\n Phi_0(cluster,:) = phiCov(:)';\n end\n \n for cluster = 1:self.K1\n rho_1(cluster,:) = self.beta_1_m*self.rho_0_1 + nBar1(cluster)*mu_i_1(cluster,:);\n rho_1(cluster,:) = rho_1(cluster,:)./beta_1(cluster);\n \n %See equation 84; Note: this is different from Equation 84 - 84 is\n %wrong\n %covPart = nBar1(cluster) * reshape(cov_i_1(cluster,:),d,d) * ((mu_i_1(cluster,:) - rho_1(cluster,:))'*(mu_i_1(cluster,:) - rho_1(cluster,:)));\n % covPart = nBar1(cluster) * reshape(cov_i_1(cluster,:),d,d) * ((mu_i_1(cluster,:) - self.rho_0_0)'*(mu_i_1(cluster,:) - self.rho_0_0));\n covPart = nBar1(cluster) * self.beta_1_m * ((mu_i_1(cluster,:) - self.rho_0_1)'*(mu_i_1(cluster,:) - self.rho_0_1));\n covPart = covPart ./ beta_1(cluster);\n \n phiCov = self.Phi_0_1 + nBar1(cluster)*reshape(cov_i_1(cluster,:),d,d) + covPart;\n Phi_1(cluster,:) = phiCov(:)';\n end\n \n % Equation 102\n matGamma = psi(gamma_i_1_m0) - psi(gamma_i_1_m0 + gamma_i_2_m0);\n matGamma2 = psi(gamma_i_2_m0) - psi(gamma_i_1_m0 + gamma_i_2_m0);\n log_pi_0 = matGamma + cat(2,0,cumsum(matGamma2(1:end-1)));\n \n matGamma = psi(gamma_i_1_m1) - psi(gamma_i_1_m1 + gamma_i_2_m1);\n matGamma2 = psi(gamma_i_2_m1) - psi(gamma_i_1_m1 + gamma_i_2_m1);\n log_pi_1 = matGamma + cat(2,0,cumsum(matGamma2(1:end-1)));\n \n \n % Equation 105\n nBarM0 = self.alpha(1) + sum(phi_0_M(expandedBagLabels == 1,:));\n nBarM1 = self.alpha(2) + sum(phi_1_M(expandedBagLabels == 1,:));\n log_eta = psi([nBarM0,nBarM1]) - psi(nBarM1+nBarM0);\n \n % \n for cluster = 1:self.K0\n temp_det0 = sum(psi((nu_0(cluster) + 1 - (1:d))/2));\n temp_det0 = temp_det0 + d*log(2);\n log_det_0(cluster) = temp_det0 + log(det(reshape(Phi_0(cluster,:),d,d)^-1));\n end\n for cluster = 1:self.K1\n temp_det1 = sum(psi((nu_1(cluster) + 1 - (1:d))/2));\n temp_det1 = temp_det1 + d*log(2);\n log_det_1(cluster) = temp_det1 + log(det(reshape(Phi_1(cluster,:),d,d)^-1));\n end\n \n \n %Equatioin 113\n for cluster = 1:self.K0\n c = reshape(Phi_0(cluster,:),d,d);\n % v = prtUtilCalcDiagXcInvXT(bsxfun(@minus,x,mu_i_0(cluster,:)),c);\n v = prtUtilCalcDiagXcInvXT(bsxfun(@minus,x,rho_0(cluster,:)),c);\n inner_0_n(:,cluster) = d/beta_0(cluster) + nu_0(cluster).*v;\n end\n \n for cluster = 1:self.K1\n c = reshape(Phi_1(cluster,:),d,d);\n % v = prtUtilCalcDiagXcInvXT(bsxfun(@minus,x,mu_i_1(cluster,:)),c);\n v = prtUtilCalcDiagXcInvXT(bsxfun(@minus,x,rho_1(cluster,:)),c);\n inner_1_n(:,cluster) = d/beta_1(cluster) + nu_1(cluster).*v;\n end\n \n for cluster = 1:self.K0\n eLogPdf0(:,cluster) = -d*log(2*pi) + log_det_0(cluster) - inner_0_n(:,cluster);\n end\n eLogPdf0 = eLogPdf0*1/2;\n \n for cluster = 1:self.K1\n eLogPdf1(:,cluster) = -d*log(2*pi) + log_det_1(cluster) - inner_1_n(:,cluster);\n end\n eLogPdf1 = eLogPdf1*1/2;\n \n phiHat0 = bsxfun(@plus,eLogPdf0,log_pi_0);\n phiHat1 = bsxfun(@plus,eLogPdf1,log_pi_1);\n phiHat1(expandedBagLabels == 0,:) = -inf;\n \n phi_1_i = bsxfun(@rdivide,exp(phiHat1),sum(exp(phiHat1),2));\n phi_0_i = bsxfun(@rdivide,exp(phiHat0),sum(exp(phiHat0),2));\n \n phi_1_i(exp(phiHat1) == 0) = 0;\n phi_0_i(exp(phiHat0) == 0) = 0;\n \n %\n n1 = (log(sum(exp(phiHat1),2))+log_eta(2));\n n0 = (log(sum(exp(phiHat0),2))+log_eta(1));\n phi_1_M = exp(n1)./(exp(n1)+exp(n0));\n phi_1_M(expandedBagLabels == 0) = 0;\n \n phi_0_M = 1-phi_1_M;\n \n for i = 1:size(rho_0,1)\n c = Phi_0(i,:)./nu_0(i);\n c = reshape(c,d,d);\n if vbIter == 1\n mm0(i) = prtRvMvn('mu',rho_0(i,:),'sigma',c);\n else\n mm0(i).mu = rho_0(i,:);\n mm0(i).sigma = c;\n end\n end\n for i = 1:size(rho_1,1)\n c = Phi_1(i,:)./nu_1(i);\n c = reshape(c,d,d);\n if vbIter == 1\n mm1(i) = prtRvMvn('mu',rho_1(i,:),'sigma',c);\n else\n mm1(i).mu = rho_1(i,:);\n mm1(i).sigma = c;\n end\n end\n \n pi0 = exp(log_pi_0); pi0 = pi0./sum(pi0);\n rv0 = prtRvGmm('nComponents',size(mu_i_0,1),'mixingProportions',pi0,'components',mm0);\n \n pi1 = exp(log_pi_1); pi1 = pi1./sum(pi1);\n rv1 = prtRvGmm('nComponents',size(mu_i_1,1),'mixingProportions',pi1,'components',mm1);\n \n \n self.rvH1 = rv1;\n self.rvH0 = rv0;\n \n drawnow;\n if ~mod(vbIter,100);\n disp(vbIter)\n subplot(2,4,1);\n stem(exp(log_pi_0));\n subplot(2,4,2);\n stem(exp(log_eta))\n subplot(2,4,3);\n stem(exp(log_pi_1));\n fprintf('exp(log_pi_0): %.2f\\n',exp(log_pi_0))\n fprintf('exp(log_pi_1): %.2f\\n',exp(log_pi_1))\n \n \n subplot(2,4,4);\n self.isTrained = true;\n yOut = self.run(dsMil);\n prtScoreRoc(yOut);\n \n subplot(2,4,5:8);\n if d > 1\n plot(x(expandedBagLabels == 0,1),x(expandedBagLabels == 0,2),'b.');\n hold on;\n plot(x(expandedBagLabels == 1,1),x(expandedBagLabels == 1,2),'r.');\n \n for i = 1:size(rho_0,1)\n c = Phi_0(i,:)./nu_0(i);\n c = reshape(c,d,d);\n if d > 1\n % plotMvnEllipse(rho_0(i,1:2),c(1:2,1:2),1);\n end\n mm0(i) = prtRvMvn('mu',rho_0(i,:),'sigma',c);\n end\n for i = 1:size(rho_1,1)\n c = Phi_1(i,:)./nu_1(i);\n c = reshape(c,d,d);\n if d > 1\n % plotMvnEllipse(rho_1(i,1:2),c(1:2,1:2),1);\n end\n mm1(i) = prtRvMvn('mu',rho_1(i,:),'sigma',c);\n end\n hold on; h = plot(rho_0(:,1),rho_0(:,2),'ko'); set(h,'MarkerFaceColor','k');\n hold on; h = plot(rho_1(:,1),rho_1(:,2),'go'); set(h,'MarkerFaceColor','g');\n \n hold off;\n end\n drawnow;\n end\n \n end\n end\n \n function yOut = runAction(self,dsMil)\n \n for n = 1:dsMil.nObservations\n milStruct = dsMil.data(n);\n data = milStruct.data; \n \n h1 = self.rvH1.logPdf(data);\n h0 = self.rvH0.logPdf(data);\n l0 = h0'-prtUtilSumExp([h0';h1']);\n \n h0LogProbabilityBag = sum(l0);\n %exp(h0LogProbabilityBag)\n \n y(n,1) = 1-exp(h0LogProbabilityBag);\n end\n \n yOut = prtDataSetClass(y,dsMil.targets);\n end\n \n function [h0Mix,h1Mix,xH0,xH1] = initialize(self,xBag,bagLabels)\n \n %H0 Kmeans\n xH0 = cat(1,xBag{bagLabels == 0});\n idx0 = kmeans(xH0,self.K0,'Replicates',1,'EmptyAction','singleton','MaxIter',100);\n uIds = unique(idx0);\n \n for idx = 1:length(uIds)\n rvH0struct(idx).mean = mean(xH0(idx0 == idx,:),1);\n \n try\n rvH0struct(idx).cov = cov(xH0(idx0 == idx,:));\n chol(rvH0struct(idx).cov);\n assert(size(xH0,2) == size(rvH0struct(idx).cov,2)); \n catch ME\n rvH0struct(idx).cov = diag(var(xH0(idx0 == idx,:))) + eye(size(xH0,2));\n end\n \n rvH0(idx) = prtRvMvn('mu',rvH0struct(idx).mean,'sigma',rvH0struct(idx).cov);\n pi(idx) = sum(idx0 == idx)./length(idx0);\n \n end\n pi = pi./sum(pi);\n h0Mix = prtRvGmm('nComponents',length(rvH0),'mixingProportions',pi,'components',rvH0);\n \n %Least likely H1\n h1Bags = xBag(bagLabels == 1);\n for h1Ind = 1:length(h1Bags)\n ll = h0Mix.logPdf(h1Bags{h1Ind});\n [~,ind] = min(ll);\n xH1(h1Ind,:) = h1Bags{h1Ind}(ind,:);\n end\n \n %H1 Kmeans\n idx1 = kmeans(xH1,self.K1,'Replicates',1,'EmptyAction','singleton','MaxIter',100);\n uIds = unique(idx1);\n \n pi = [];\n for idx = 1:length(uIds)\n rvH1struct(idx).mean = mean(xH1(idx1 == idx,:),1);\n \n try\n rvH1struct(idx).cov = cov(xH1(idx0 == idx,:));\n chol(rvH1struct(idx).cov);\n catch ME\n rvH1struct(idx).cov = diag(var(xH1)) + eye(size(xH1,2));\n end\n \n rvH1(idx) = prtRvMvn('mu',rvH1struct(idx).mean,'sigma',rvH1struct(idx).cov);\n pi(idx) = sum(idx1 == idx)./length(idx1);\n \n end\n pi = pi./sum(pi);\n h1Mix = prtRvGmm('nComponents',length(rvH1),'mixingProportions',pi,'components',rvH1);\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/multipleInstance/prtClassMilVbDpGmm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.682573734412324, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.34928431383371716}}
{"text": "function x = rstepHess(obj,x0,dx,grad0)\nalpha = sqrt(eps);\nx = x0 + alpha*dx;\n[y,deriv] = obj(x);\ng = deriv();\nx = (g-grad0)/alpha;\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/MV2DF/deriv_approx/rstepHess.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3492843072252301}}
{"text": "function [ y,dzdy ] = pad_data_1d( I,P,dzdy)\n%PAD_DATA Summary of this function goes here\n% Detailed explanation goes here\n\n if(length(P)==1)\n P=ones(1,2)*P;\n end\n \n \n if isempty(dzdy)\n %%forward\n original_size=size(I);\n new_size=original_size;\n new_size(1)=new_size(1)+P(1)+P(2);\n y=zeros(new_size,'like',I);\n y(1+P(1):P(1)+original_size(1),:,:)=I;\n\n else\n %backward\n new_size=size(dzdy);\n original_size=new_size;\n original_size(1)=original_size(1)-P(1)-P(2);\n y=I(1+P(1):P(1)+original_size(1),:,:);\n dzdy=dzdy(1+P(1):P(1)+original_size(1),:,:);\n \n end\n\nend\n\n", "meta": {"author": "yechengxi", "repo": "LightNet", "sha": "5dc29cefccf1ea6d9377aa90732581337408ce73", "save_path": "github-repos/MATLAB/yechengxi-LightNet", "path": "github-repos/MATLAB/yechengxi-LightNet/LightNet-5dc29cefccf1ea6d9377aa90732581337408ce73/CoreModules/util/pad_data_1d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.3491914116821351}}
{"text": "function [cl,cd] = bpolar(BladeState,AC)\n% To make your own bpolar:\n% BladeState is the state of the blade element with matrix components:\n% BladeState =\n% M: Mach number\n% alpha: angle of attack (radians)\n% r: radius location (nondimensional)\n% psi: azimuth location (radians)\n% alphadot: rate of change of angle of attack (rad/s)\n% Re: Reynolds number\n% all components on BladeState inputs are m x n, where n is the number of\n% blade elements, and m is the uniformly distributed number of azimuth\n% elements.\n%\n% NB: this function should run VERY fast, so avoid loops and extensive\n% interpolation.\n% see also lininterp1f\n%\n% AC is a structure with AC data (see documentation)\n%\n% cl and cd are the m x n arrays containing each blade element's lift and\n% drag coefficients.\n% note that output coefficients will be non-dimensionalized by a constant\n% blade chord, typically the average blade chord.\n%\n% The blade polar function is responsible for capturing all important rotor\n% phenomena, including reverse flow, retreating blade stall, and advancing\n% tip critical mach number.\n%\n% to capture reverse flow effects, the drag polar should be able to handle\n% alphas +/- 360 deg\n%\n% critical mach drag rise and stall should also be modeled.\n\n% This file is an example of using wind tunnel data (NACA 0012), very fast\n% interpolation, and a critical mach drag rise approximation.\n\n\n% Drag Coefficient data\n%from http://www.cyberiad.net\n% -------------------------------- REYNOLDS NUMBER -----------------------\n\n% RE = [5000000] ;\n\nDragData = [ 0.0064\n 0.0064\n 0.0066\n 0.0068\n 0.0072\n 0.0076\n 0.0081\n 0.0086\n 0.0092\n 0.0098\n 0.0106\n 0.0118\n 0.0130\n 0.0143\n 0.0159\n 0.0177\n 0.0198\n 0.0229\n 0.1480\n 0.2740\n 0.2970\n 0.3200\n 0.3440\n 0.3690\n 0.3940\n 0.4200\n 0.4460\n 0.4730\n 0.5700\n 0.7450\n 0.9200\n 1.0750\n 1.2150\n 1.3450\n 1.4700\n 1.5750\n 1.6650\n 1.7350\n 1.7800\n 1.8000\n 1.8000\n 1.7800\n 1.7500\n 1.7000\n 1.6350\n 1.5550\n 1.4650\n 1.3500\n 1.2250\n 1.0850\n 0.9250\n 0.7550\n 0.5750\n 0.4200\n 0.3200\n 0.2300\n 0.1400\n 0.0550\n 0.0250\n 0.0550\n 0.1400\n 0.2300\n 0.3200\n 0.4200\n 0.5750\n 0.7550\n 0.9250\n 1.0850\n 1.2250\n 1.3500\n 1.4650\n 1.5550\n 1.6350\n 1.7000\n 1.7500\n 1.7800\n 1.8000\n 1.8000\n 1.7800\n 1.7350\n 1.6650\n 1.5750\n 1.4700\n 1.3450\n 1.2150\n 1.0750\n 0.9200\n 0.7450\n 0.5700\n 0.4730\n 0.4460\n 0.4200\n 0.3940\n 0.3690\n 0.3440\n 0.3200\n 0.2970\n 0.2740\n 0.1480\n 0.0229\n 0.0198\n 0.0177\n 0.0159\n 0.0143\n 0.0130\n 0.0118\n 0.0106\n 0.0098\n 0.0092\n 0.0086\n 0.0081\n 0.0076\n 0.0072\n 0.0068\n 0.0066\n 0.0064\n 0.0064];\nLiftData =[ 0\n 0.1100\n 0.2200\n 0.3300\n 0.4400\n 0.5500\n 0.6600\n 0.7700\n 0.8800\n 0.9900\n 1.1000\n 1.1842\n 1.2673\n 1.3242\n 1.3423\n 1.3093\n 1.2195\n 1.0365\n 0.9054\n 0.8412\n 0.8233\n 0.8327\n 0.8563\n 0.8903\n 0.9295\n 0.9718\n 1.0193\n 1.0680\n 0.9150\n 1.0200\n 1.0750\n 1.0850\n 1.0400\n 0.9650\n 0.8750\n 0.7650\n 0.6500\n 0.5150\n 0.3700\n 0.2200\n 0.0700\n -0.0700\n -0.2200\n -0.3700\n -0.5100\n -0.6250\n -0.7350\n -0.8400\n -0.9100\n -0.9450\n -0.9450\n -0.9100\n -0.8500\n -0.7400\n -0.6600\n -0.6750\n -0.8500\n -0.6900\n 0\n 0.6900\n 0.8500\n 0.6750\n 0.6600\n 0.7400\n 0.8500\n 0.9100\n 0.9450\n 0.9450\n 0.9100\n 0.8400\n 0.7350\n 0.6250\n 0.5100\n 0.3700\n 0.2200\n 0.0700\n -0.0700\n -0.2200\n -0.3700\n -0.5150\n -0.6500\n -0.7650\n -0.8750\n -0.9650\n -1.0400\n -1.0850\n -1.0750\n -1.0200\n -0.9150\n -1.0680\n -1.0193\n -0.9718\n -0.9295\n -0.8903\n -0.8563\n -0.8327\n -0.8233\n -0.8412\n -0.9054\n -1.0365\n -1.2195\n -1.3093\n -1.3423\n -1.3242\n -1.2673\n -1.1842\n -1.1000\n -0.9900\n -0.8800\n -0.7700\n -0.6600\n -0.5500\n -0.4400\n -0.3300\n -0.2200\n -0.1100\n 0];\nAlpha =[0\n 1\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n 9\n 10\n 11\n 12\n 13\n 14\n 15\n 16\n 17\n 18\n 19\n 20\n 21\n 22\n 23\n 24\n 25\n 26\n 27\n 30\n 35\n 40\n 45\n 50\n 55\n 60\n 65\n 70\n 75\n 80\n 85\n 90\n 95\n 100\n 105\n 110\n 115\n 120\n 125\n 130\n 135\n 140\n 145\n 150\n 155\n 160\n 165\n 170\n 175\n 180\n 185\n 190\n 195\n 200\n 205\n 210\n 215\n 220\n 225\n 230\n 235\n 240\n 245\n 250\n 255\n 260\n 265\n 270\n 275\n 280\n 285\n 290\n 295\n 300\n 305\n 310\n 315\n 320\n 325\n 330\n 333\n 334\n 335\n 336\n 337\n 338\n 339\n 340\n 341\n 342\n 343\n 344\n 345\n 346\n 347\n 348\n 349\n 350\n 351\n 352\n 353\n 354\n 355\n 356\n 357\n 358\n 359\n 360]*pi/180;\nmodinpcount = 0;\nwhile any(BladeState.alpha(:)<0)\n ind = BladeState.alpha<0;\n BladeState.alpha(ind) = BladeState.alpha(ind)+2*pi;\n modinpcount=modinpcount+1;\nend\nif modinpcount>2\n disp('crazy stuff going on in bpolar - very very negative alphas')\nend\nmodinpcount = 0;\nwhile any(BladeState.alpha(:)>2*pi)\n ind = BladeState.alpha>2*pi;\n BladeState.alpha(ind) = BladeState.alpha(ind)-2*pi;\n modinpcount=modinpcount+1;\nend\nif modinpcount>1\n disp('crazy stuff going on in bpolar - very very positive alphas')\nend\ncd = mylerp1(Alpha,DragData,BladeState.alpha);%,'linear');\ncl = mylerp1(Alpha,LiftData,BladeState.alpha);%,'linear');\nif any(isnan([cd(:);cl(:)]));\n disp(' check this out')\nend\n% Data from http://adg.stanford.edu/aa241/drag/dragrise.html\n% at Cl of .3\n% M-Mcrit:\nMdiff0 =[ -1\n -0.15\n -0.125\n -0.1\n -0.075\n -0.05\n -0.025\n 0\n 0.025\n 0.05\n 0.075\n 0.1\n 0.125\n 0.15\n 0.175\n 0.2\n 0.225\n 10000.225];\n\nCdinvisc =[0\n 0\n 0\n 0.000025\n 0.00005\n 0.00015\n 0.0005\n 0.002\n 0.0052\n 0.0103\n 0.0173\n 0.026\n 0.037\n 0.048\n 0.068\n 0.1\n 0.148\n 20000];\n\nMcrit = max(.55,-.02002*abs(BladeState.alpha)+.765);\n% from ESDU AERO W.00.03.01\n% Critical Mach number for high speed aerofoil sections.\n\ncd = cd + mylerp1(Mdiff0,Cdinvisc,abs(BladeState.M)-Mcrit);\n\n%tip loss\nind = BladeState.r>.97;\ncl(ind)=cl(ind).*(1-(BladeState.r(ind)-.97)/.03);\n\n%% root cutout\ncl(BladeState.r<.15) = 0;\ncd(BladeState.r<.15) = .1;\n\nif any([isnan(cl(:)) isnan(cd(:))])\n disp('NaN in bpolar function')\n cd(isnan(cd)) = 1;\n cl(isnan(cl)) = 1;\nend\n\nend\n\nfunction yi = mylerp1(x,y,xi)\n% Y = interp1(x,y,X,'linear');\n\ntoreshape = size(xi);\nxi = xi(:);\nyi = lininterp1f(x,y,xi,NaN); %mex .dll function\nyi = reshape(yi,toreshape);\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/toolbox/bpolar_0012.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.3491559019158495}}
{"text": "function Problem = ITERmodify_LB_X0_UB(Problem)\nX0 = Problem.x0(:);\nLB = Problem.lb(:);\nUB = Problem.ub(:);\nXLabels = Problem.XLabels;\n\nrepeat = true;\nwhile repeat\n disp(' ')\n BOUNDS = {'Index', 'Parameter'};\n for ii = 1:length(X0)\n BOUNDS{ii+1,1} = ii;\n BOUNDS{ii+1,2} = XLabels{ii};\n end\n disp(BOUNDS);\n LB_X0_UB = [LB X0 UB];\n openvar('LB_X0_UB');\n disp (' ');\n disp('[LB X0 UB] available for editing in array editor.')\n disp('Close array editor and type ''return'' in command window when finished editing')\n keyboard;\n LB = LB_X0_UB(:,1); UB = LB_X0_UB(:,3); X0 = LB_X0_UB(:,2);\n disp('LB, X0, and UB overwritten by edited values')\n repeat = false;\n if any(UBUB)\n disp('One or more seed values outside bounds. What would you like to do?')\n k = txtmenu([],'Edit in array editor',...\n 'Trim seed to bounds','Expand bounds to seed');\n if k\n lowind = X0UB;\n if k == 1\n X0(lowind) = LB(lowind);\n X0(hiind) = UB(hiind);\n elseif k ==2\n LB(lowind) = X0(lowind);\n UB(hiind) = X0(hiind);\n end\n else\n repeat = true;\n end\n end\nend\n\nProblem.x0 = X0;\nProblem.lb = LB;\nProblem.ub = UB;\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/ITERmodify_LB_X0_UB.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.34915237353242456}}
{"text": "function [OffDec,OffMask] = Operator(Problem,ParentDec,ParentMask,Fitness)\n% The operator of SparseEA2\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 [N,~] = size(ParentDec);\n Parent1Dec = ParentDec(1:floor(end/2),:);\n Parent2Dec = ParentDec(floor(end/2)+1:floor(end/2)*2,:);\n Parent1Mask = ParentMask(1:floor(end/2),:);\n Parent2Mask = ParentMask(floor(end/2)+1:floor(end/2)*2,:);\n \n %% Crossover and mutation for dec\n if any(Problem.encoding~=4)\n [OffDec,groupIndex,chosengroups] = GLP_OperatorGAhalf(Problem,Parent1Dec,Parent2Dec,4);\t% 4 -- numberofgroups\n OffDec(:,Problem.encoding==4) = 1;\n else\n OffDec = ones(size(Parent1Dec));\n end\n \n %% Crossover for mask\n OffMask = Parent1Mask;\n for i = 1 : N/2\n if rand < 0.5\n index = find(Parent1Mask(i,:)&~Parent2Mask(i,:));\n index = index(TS(-Fitness(index)));\n OffMask(i,index) = 0;\n else\n index = find(~Parent1Mask(i,:)&Parent2Mask(i,:));\n index = index(TS(Fitness(index)));\n OffMask(i,index) = Parent2Mask(i,index);\n end\n end\n \n %% Mutation for mask\n if any(Problem.encoding~=4)\n chosenindex = groupIndex == chosengroups;\n for i = 1 : N/2\n if rand < 0.5\n index = find(OffMask(i,:)&chosenindex(i,:));\n index = index(TS(-Fitness(index)));\n OffMask(i,index) = 0;\n else\n index = find(~OffMask(i,:)&chosenindex(i,:));\n index = index(TS(Fitness(index)));\n OffMask(i,index) = 1;\n end\n end \n end \nend\n\nfunction index = TS(Fitness)\n% Binary tournament selection\n if isempty(Fitness)\n index = [];\n else\n index = TournamentSelection(2,1,Fitness);\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/SparseEA2/Operator.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3491523698675708}}
{"text": "%DATASETS Info on the dataset class construction for PRTools\n%\n% This is not a command, just an information file.\n%\n% Datasets in PRTools are in the MATLAB language defined as objects of the\n% class PRDATASET. Below, the words 'object' and 'class' are used in the pattern \n% recognition sense.\n%\n% A dataset is a set consisting of M objects, each described by K features. \n% In PRTools, such a dataset is represented by a M x K matrix: M rows, each\n% containing an object vector of K elements. Usually, a dataset is labeled.\n% An example of a definition is:\n%\n% DATA = [RAND(3,2) ; RAND(3,2)+0.5];\n% LABS = ['A';'A';'A';'B';'B';'B'];\n% A = PRDATASET(DATA,LABS)\n%\n% which defines a [6 x 2] dataset with 2 classes.\n%\n% The [6 x 2] data matrix (6 objects given by 2 features) is accompanied by\n% labels, assigning each of the objects to one of the two classes A and B.\n% Class labels can be numbers or strings and should always be given as rows\n% in the label list. A lable may also have the value NaN or may be an empty\n% string, indicating an ulabeled object. If the label list is not given, \n% all objects are marked as unlabeled.\n%\n% Various other types of information can be stored in a dataset. The most\n% simple way to get an overview is by typing:\n%\n% STRUCT(A)\n%\n% which for the above example displays the following:\n%\n% DATA: [6x2 double]\n% LABLIST: [2x1 double]\n% NLAB: [6x1 double]\n% LABTYPE: 'crisp'\n% TARGETS: []\n% FEATLAB: [2x1 double]\n% FEATDOM: {1x2 cell}\n% PRIOR: []\n% COST: []\n% OBJSIZE: 6\n% FEATSIZE: 2\n% IDENT: {6x1 cell}\n% VERSION: {1x2 cell}\n% NAME: []\n% USER: []\n%\n% These fields have the following meaning:\n% \n% DATA : an array containing the objects (the rows) represented by \n% features (the columns). In the software and help-files, the number\n% of objects is usually denoted by M and the number of features is\n% denoted by K. So, DATA has the size of [M,K]. This is also defined \n% as the size of the entire dataset.\n% LABLIST : The names of the classes, stored row-wise. These class names\n% should be integers, strings or cells of strings. Mixtures of\n% these are not supported. LABLIST has as many rows as there are \n% classes. This number is usually denoted by C. LABLIST is\n% constructed from the set of LABELS given in the DATASET command\n% by determining the unique names while ordering them alphabetically.\n% NLAB : an [M x 1] vector of integers between 1 and C, defining for each\n% of the M objects its class. They are indexing LABLIST.\n% LABTYPE : 'CRISP', 'SOFT' or 'TARGETS' are the three possible label types.\n% In case of 'CRISP' labels, a unique class, defined by NLAB, is\n% assigned to each object, pointing to the class names given in\n% LABLIST.\n% For 'SOFT' labels, each object has a corresponding vector of C \n% numbers between 0 and 1 indicating its membership (or confidence \n% or posterior probability) of each of the C classes. These numbers\n% are stored in the array TARGETS of the size M x C. They don't\n% necessarily sum to one for individual row vectors.\n% Labels of type 'TARGETS' are in fact no labels, but merely target\n% vectors of length C. The values are again stored in TARGETS and\n% are not restricted in value.\n% TARGETS : [M,C] array storing the values of the soft labels or targets.\n% FEATLAB : A label list (like LABLIST) of K rows storing the names of the\n% features.\n% FEATDOM : A cell array describing for each feature its domain.\n% PRIOR : Vector of length C storing the class prior probabilities. They \n% should sum to one. If PRIOR is empty ([]) it is assumed that the\n% class prior probabilities correspond to the class frequencies.\n% COST : Classification cost matrix. COST(I,J) are the costs\n% of classifying an object from class I as class J. Column C+1\n% generates an alternative reject class and may be omitted, \n% yielding a size of [C,C]. An empty cost matrix, COST = [] \n% (default) is interpreted as COST = ONES(C) - EYE(C) (identical\n% costs of misclassification).\n% OBJSIZE : The number of objects, M. In case the objects are related to a\n% n-dimensional structure, OBJSIZE is a vector of length n, storing\n% the size of this structure. For instance, if the objects are pixels\n% in a [20 x 16] image, then OBJSIZE = [20,16] and M = 320.\n% FEATSIZE : The number of features, K. In case the features are related to \n% an n-dimensional structure, FEATSIZE is a vector of length n, \n% storing the size of this structure. For instance, if the features\n% are pixels in a [20 x 16] image, then FEATSIZE = [20,16] and \n% K = 320.\n% IDENT : A cell array of M elements storing indicators of the M objects.\n% They are initialized by integers 1:M.\n% VERSION : Some information related to the version of PRTools used for\n% defining the dataset.\n% NAME : A character string naming the dataset, possibly used to annotate\n% related graphics.\n% USER : Free field for the user, not used by PRTools.\n%\n%\n% The fields can be set by commands like SETDATA, SETFEATLAB, SETLABELS,\n% see below for a complete list.\n% Note that there is no field LABELS in the DATASET definition. Labels are\n% converted to NLAB and LABLIST. The command SETLABELS however exists and\n% takes care of the conversion.\n%\n% The data and information stored in a dataset can be retrieved as follows:\n%\n% - By DOUBLE(A) and by +A, the content of A.DATA is returned.\n% - [N,LABLIST] = CLASSSIZES(A); \n% It returns the numbers of objects per class and the class names stored \n% in LABLIST.\n% - By DISPLAY(A), it writes the size of the dataset, the number of classes \n% and the label type on the terminal screen.\n% - By SIZE(A), it returns the size of A.DATA: numbers of objects and features.\n% - By SCATTERD(A), it makes a scatter plot of a dataset.\n% - By SHOW(A), it may be used to display images that are stored as features \n% or as objects in a dataset. \n% - By commands like: GETDATA, GETFEATLAB, etcetera, see below. With some\n% exceptions they point to a single dataset field. E.g. GETSIZE(A) returns \n% [M,K,C]. A aet of commands does not return data, but instead they return \n% indices to objects that have specific identifiers, labels or class indices:\n% FINDIDENT, FINDLABELS, FINDNLAB.\n%\n% Many standard MATLAB operations and a number of general MATLAB commands have \n% been overloaded for variables of the DATASET type.\n%\n% SEE ALSO (PRTools Guide)\n% PRDATASET, DATA2IM, OBJ2FEAT, FEAT2OBJ, IM2FEAT, IM2OBJ, DATAIM \n% SETDATA, SETFEATLAB, SETFEATDOM, SETFEATSIZE, SETIDENT, SETLABELS, \n% SETLABLIST, SETLABTYPE, SETNAME, SETNLAB, SETOBJSIZE, SETPRIOR, SETCOST, \n% SETTARGETS, SETUSER, SETLABLISTNAMES, SETVERSION\n% GETDATA, GETFEATLAB, GETFEATDOM, GETFEATSIZE, GETIDENT, GETLABELS, \n% GETLABLIST, GETLABTYPE, GETNAME, GETNLAB, GETOBJSIZE, GETPRIOR, GETCOST, \n% GETSIZE, GETTARGETS, GETUSER, GETVERSION, GETCLASSI, GETLABLISTNAMES,\n% FINDIDENT, FINDLABELS, FINDNLAB\n\n% Copyright: R.P.W. Duin, r.p.w.duin@37steps.com\n% Faculty EWI, Delft University of Technology\n% P.O. Box 5031, 2600 GA Delft, The Netherlands\n\n", "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/datasets.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3491523698675708}}
{"text": "%Program for random permuting the share generation\n\n%Author : Athi Narayanan S\n%M.E, Embedded Systems,\n%K.S.R College of Engineering\n%Erode, Tamil Nadu, India.\n%http://sites.google.com/site/athisnarayanan/\n%s_athi1983@yahoo.co.in\n\n%Program Description\n%This program generates the share 1 & share 2 randomly for each pixel. \n\nfunction out = generateShare(a,b)\n\na1 = a(1);\na2 = a(2);\nb1 = b(1);\nb2 = b(2);\n\nin = [a\n b];\nout = zeros(size(in));\nrandNumber = floor(1.9*rand(1));\n\nif (randNumber == 0)\n out = in;\nelseif (randNumber == 1)\n a(1) = a2;\n a(2) = a1;\n b(1) = b2;\n b(2) = b1;\n out = [a\n b]; \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/24981-visual-cryptography/Visual_Cryptography/generateShare.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3490428696386238}}
{"text": "function g = dnetOutputGrad(model, X)\n\n% DNETOUTPUTGRAD Evaluate derivatives of dnet model outputs with respect to parameters.\n% FORMAT\n% DESC evaluates the derivates of a density network's\n% outputs with respect to the parameters of the mapping function.\n% ARG model : the model for which the derivatives are to be\n% computed.\n% ARG X : the input data locations where the gradients are to be\n% computed.\n% RETURN g : the gradient of the outputs of the density network\n% perceptron with respect to each of the parameters. The size of\n% the matrix is number of data x number of parameters x number of\n% outputs of the model.\n%\n% SEEALSO : modelOutputGrad, dnetCreate\n%\n% COPYRIGHT : Neil D. Lawrence, 2008\n\n% MLTOOLS\n\n g = modelOutputGrad(model.mapping, X);\n % Add output gradient wrt beta.\n g(:, end+1, :) = 0;\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/mltools/dnetOutputGrad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3490428696386238}}
{"text": "% Remove bad tracking coordinates (position jumps)\n%\n% A position \"jump\" correspond to position samples that imply that the rat is\n% moving quicker than physical possible.\n%\n%\nfunction [x, y] = removePosJumps(x, y, threshold, stdThreshold)\n N = length(x);\n % Indexes to position samples that are to be removed\n remInd = zeros(N,1);\n remCounter = 0;\n\n diffX = diff(x);\n diffY = diff(y);\n diffR = sqrt(diffX.^2 + diffY.^2);\n ind = find(diffR > threshold);\n\n if isempty(ind)\n return;\n end\n\n if ind(end) == length(x)\n offset = 2;\n else\n offset = 1;\n end\n\n for ii = 1:length(ind)-offset\n if ind(ii+1) == ind(ii)+1\n % A single sample position jump, tracker jumps out one sample and\n % then jumps back to path on the next sample. Remove bad sample.\n remCounter = remCounter + 1;\n remInd(remCounter) = ind(ii)+1;\n ii = ii+1;\n continue\n else\n % Not a single jump. 2 possibilities:\n % 1. Tracker jumps out, and stay out at the same place for several\n % samples and then jumps back.\n % 2. Tracker just has a small jump before path continues as normal,\n % unknown reason for this. In latter case the samples are left\n % untouched.\n idx = find(x(ind(ii)+1:ind(ii+1)+1)==x(ind(ii)+1));\n if length(idx) == length(x(ind(ii)+1:ind(ii+1)+1));\n n = ind(ii+1)+1 - ind(ii);\n remInd(remCounter+1:remCounter+n) = (ind(ii)+1:ind(ii+1)+1)';\n remCounter = remCounter + n;\n end\n end\n end\n\n remInd = remInd(1:remCounter);\n\n % Remove the samples\n x(remInd) = NaN;\n y(remInd) = NaN;\n\n % there could be tracking outliers. They are commonly several values between longer list of\n % NaNs. These values lie far away from 'good' points, so discard everything that is\n % further than 2.5*STD\n med(1) = nanmin(x) + (nanmax(x) - nanmin(x))/2; % roughy middle point of the arena, better\n med(2) = nanmin(y) + (nanmax(y) - nanmin(y))/2; % than median or mean since it's less biased\n std = nanstd([x, y]);\n lowerBound = med - (stdThreshold*std);\n upperBound = med + (stdThreshold*std);\n\n x(x < lowerBound(1)) = nan;\n x(x > upperBound(1)) = nan;\n\n y(y < lowerBound(2)) = nan;\n y(y > upperBound(2)) = nan;\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/+general/removePosJumps.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.5273165233795672, "lm_q1q2_score": 0.3490428626050725}}
{"text": "% Scrip: mcgrid.m\n% Calculates Magnitude shift map for two specific time periods\n% Uses view_mcgrid to plot the results\n%\n% J. Woessner\n% last update: 22.01.04\n\nreport_this_filefun(mfilename('fullpath'));\n\n\nglobal no1 bo1 inb1 inb2 valeg valeg2 CO valm1\n\nvaleg = 1;\nvalm1 = min(a.Magnitude);\nprf = NaN;\nif sel == 'in'\n % Set the grid parameter\n %Initial values\n dx = 1;\n dy = 1;\n ni = 150;\n Nmin = 150;\n ra = 50;\n fMaxRadius = 5;\n fSplitTime = 2000.4;\n\n % cut catalog at mainshock time:\n% l = a.Date > maepi(1,3);\n% a = a.subset(l);\n\n % cat at selecte magnitude threshold\n l = a.Magnitude < valm1;\n a(l,:) = [];\n newt2 = a;\n\n ho2=true;\n timeplot\n ho2=false;\n\n\n %The definitions in the following line were present in the initial bvalgrid.m file.\n %stan2 = NaN; stan = NaN; prf = NaN; av = NaN;\n\n % make the interface\n % creates a dialog box to input grid parameters\n %\n figure_w_normalized_uicontrolunits(...\n 'Name','Grid Input Parameter',...\n 'NumberTitle','off', ...\n 'MenuBar','none', ...\n 'NextPlot','new', ...\n 'units','points',...\n 'Visible','off', ...\n 'Position',[ wex+200 wey-200 650 250]);\n axis off\n% labelList2=[' Automatic Mcomp (max curvature) | Fixed Mc (Mc = Mmin) | Automatic Mcomp (90% probability) | Automatic Mcomp (95% probability) | Best (?) combination (Mc95 - Mc90 - max curvature) | Constant Mc'];\n% labelPos = [0.2 0.8 0.6 0.08];\n% hndl2=uicontrol(...\n% 'Style','popup',...\n% 'Position',labelPos,...\n% 'Units','normalized',...\n% 'String',labelList2,...\n% 'Callback','inb2 =get(hndl2,''Value''); ');\n%\n% set(hndl2,'value',5);\n\n\n % creates a dialog box to input grid parameters\n %\n\n oldfig_button = uicontrol('BackGroundColor',[.60 .92 .84], ...\n 'Style','checkbox','string','Plot in Current Figure',...\n 'Position',[.78 .7 .20 .08],...\n 'Units','normalized');\n\n set(oldfig_button,'value',1);\n\n\n freq_field=uicontrol('Style','edit',...\n 'Position',[.30 .60 .12 .08],...\n 'Units','normalized','String',num2str(ni),...\n 'Callback','ni=str2double(get(freq_field,''String'')); set(freq_field,''String'',num2str(ni));set(tgl2,''value'',0); set(tgl1,''value'',1)');\n\n\n freq_field0=uicontrol('Style','edit',...\n 'Position',[.30 .50 .12 .08],...\n 'Units','normalized','String',num2str(ra),...\n 'Callback','ra=str2double(get(freq_field0,''String'')); set(freq_field0,''String'',num2str(ra)) ; set(tgl2,''value'',1); set(tgl1,''value'',0)');\n\n freq_field2=uicontrol('Style','edit',...\n 'Position',[.30 .40 .12 .08],...\n 'Units','normalized','String',num2str(dx),...\n 'Callback','dx=str2double(get(freq_field2,''String'')); set(freq_field2,''String'',num2str(dx));');\n\n freq_field3=uicontrol('Style','edit',...\n 'Position',[.30 .30 .12 .080],...\n 'Units','normalized','String',num2str(dy),...\n 'Callback','dy=str2double(get(freq_field3,''String'')); set(freq_field3,''String'',num2str(dy));');\n\n freq_field4=uicontrol('Style','edit',...\n 'Position',[.6 .30 .12 .080],...\n 'Units','normalized','String',num2str(fSplitTime),...\n 'Callback','fSplitTime=str2double(get(freq_field4,''String'')); set(freq_field4,''String'',num2str(fSplitTime));');\n\n freq_field7=uicontrol('Style','edit',...\n 'Position',[.30 .20 .12 .080],...\n 'Units','normalized','String',num2str(Nmin),...\n 'Callback','Nmin=str2double(get(freq_field7,''String'')); set(freq_field7,''String'',num2str(Nmin));');\n\n freq_field8=uicontrol('Style','edit',...\n 'Position',[.6 .60 .12 .080],...\n 'Units','normalized','String',num2str(fMaxRadius),...\n 'Callback','fMaxRadius=str2double(get(freq_field8,''String'')); set(freq_field8,''String'',num2str(fMaxRadius));');\n\n tgl1 = uicontrol('Style','radiobutton',...\n 'string','Number of Events:',...\n 'Position',[.05 .60 .2 .0800], 'Callback','set(tgl2,''value'',0)',...\n 'Units','normalized');\n\n set(tgl1,'value',0);\n\n tgl2 = uicontrol('Style','radiobutton',...\n 'string','OR: Constant Radius',...\n 'Position',[.05 .50 .2 .080], 'Callback','set(tgl1,''value'',0)',...\n 'Units','normalized');\n set(tgl2,'value',1);\n\n create_grid = uicontrol('Style','radiobutton',...\n 'string','Calculate a new grid', 'Callback','set(load_grid,''value'',0), set(prev_grid,''value'',0)','Position',[.78 .55 .2 .080],...\n 'Units','normalized');\n\n set(create_grid,'value',1);\n\n prev_grid = uicontrol('Style','radiobutton',...\n 'string','Reuse the previous grid', 'Callback','set(load_grid,''value'',0),set(create_grid,''value'',0)','Position',[.78 .45 .2 .080],...\n 'Units','normalized');\n\n\n load_grid = uicontrol('Style','radiobutton',...\n 'string','Load a previously saved grid', 'Callback','set(prev_grid,''value'',0),set(create_grid,''value'',0)','Position',[.78 .35 .2 .080],...\n 'Units','normalized');\n\n save_grid = uicontrol('Style','checkbox',...\n 'string','Save selected grid to file',...\n 'Position',[.78 .22 .2 .080],...\n 'Units','normalized');\n\n\n\n close_button=uicontrol('Style','Pushbutton',...\n 'Position',[.60 .05 .15 .12 ],...\n 'Units','normalized','Callback','close;done','String','Cancel');\n\n go_button1=uicontrol('Style','Pushbutton',...\n 'Position',[.20 .05 .15 .12 ],...\n 'Units','normalized',...\n 'Callback','tgl1 =get(tgl1,''Value'');tgl2 =get(tgl2,''Value'');prev_grid = get(prev_grid,''Value'');create_grid = get(create_grid,''Value''); load_grid = get(load_grid,''Value''); save_grid = get(save_grid,''Value''); oldfig_button = get(oldfig_button,''Value''); close,sel =''ca'', mc_grid',...\n 'String','Go');\n\n text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[0.10 0.98 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.l ,...\n 'FontWeight','bold',...\n 'String','Please choose an Mc estimation option ');\n txt3 = text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[0.30 0.75 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.l ,...\n 'FontWeight','bold',...\n 'String',' Grid Parameter');\n txt5 = text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[-0.1 0.4 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String','Spacing in x (dx) in deg:');\n\n txt6 = text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[-0.1 0.3 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String','Spacing in y (dy) in deg:');\n\n txt7 = text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[-0.1 0.18 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String','Min. No. of events > Mc:');\n\n txt9 = text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[0.42 0.28 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.s ,...\n 'FontWeight','bold',...\n 'String','Time window:');\n\n txt11 = text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[0.42 0.62 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.s ,...\n 'FontWeight','bold',...\n 'String','Max. Radius /[km]:');\n\n set(gcf,'visible','on');\n watchoff\n\nend % if nargin ==0\n\n% get the grid-size interactively and\n% calculate the b-value in the grid by sorting\n% thge seimicity and selectiong the ni neighbors\n% to each grid point\n\nif sel == 'ca'\n\n\n\n %In the following line, the program .m is called, which creates a rectangular grid from which then selects,\n %on the basis of the vector ll, the points within the selected poligon.\n\n % get new grid if needed\n if load_grid == 1\n [file1,path1] = uigetfile(['*.mat'],'previously saved grid');\n if length(path1) > 1\n think\n load([path1 file1])\n end\n plot(newgri(:,1),newgri(:,2),'k+')\n elseif load_grid ==0 && prev_grid == 0\n selgp\n if length(gx) < 2 || length(gy) < 2\n errordlg('Selection too small! (Dx and Dy are in degreees! ');\n return\n end\n elseif prev_grid == 1\n plot(newgri(:,1),newgri(:,2),'k+')\n end\n % end\n\n gll = ll;\n\n if save_grid == 1\n\n sFile = ['*.mat'];\n sPath = pwd;\n [file1,path1] = uiputfile([sFile], 'Grid File Name?');\n sSaveFile = [path1 file1];\n save(sSaveFile, 'newgri', 'dx', 'dy', 'gx', 'gy', 'xvect', 'yvect', 'tmpgri', 'll', 'fSplitTime', 'Nmin', 'ra', 'a');\n end\n\n % selgp\n itotal = length(newgri(:,1));\n% if length(gx) < 4 | length(gy) < 4\n% errordlg('Selection too small! (Dx and Dy are in degreees! ');\n% return\n% end\n\n zmap_message_center.set_info(' ','Running... ');think\n % make grid, calculate start- endtime etc. ...\n %\n t0b = min(a.Date) ;\n n = a.Count;\n teb = a(n,3) ;\n tdiff = round((teb - t0b)*365/par1);\n loc = zeros(3, length(gx)*length(gy));\n\n % loop over all points\n %\n i1 = 0.;\n mRes =[];\n mResult = [];\n allcount = 0.;\n wai = waitbar(0,' Please Wait ... ');\n set(wai,'NumberTitle','off','Name','Rate change grid - percent done');\n drawnow\n\n % loop over all points\n for i= 1:length(newgri(:,1))\n i/length(newgri(:,1));\n % Grid node point\n x = newgri(i,1);y = newgri(i,2);\n allcount = allcount + 1.;\n\n\n % calculate distance from center point and sort with distance\n l = sqrt(((a.Longitude-x)*cos(pi/180*y)*111).^2 + ((a.Latitude-y)*111).^2) ;\n [s,is] = sort(l);\n mCat = a(is(:,1),:) ; % re-orders matrix to agree row-wise\n % Use Radius to determine grid node catalogs\n l3 = l <= ra;\n mCat = a.subset(l3); % new data per grid point (mCat) is sorted in distance\n\n\n % % Select earthquakes in non-overlapping rectangles\n % vSel = (a.Longitude >= (newgri(i,1)-dx/2)) & (a.Longitude < (newgri(i,1)+dx/2)) &...\n % (a.Latitude >= (newgri(i,2)-dy/2)) & (a.Latitude < (newgri(i,2)+dy/2));\n % % Select earthquakes in overlapping rectangles\n % vSel = (a.Longitude >= (newgri(i,1)-dx)) & (a.Longitude < (newgri(i,1)+dx)) &...\n % (a.Latitude >= (newgri(i,2)-dy)) & (a.Latitude < (newgri(i,2)+dy));\n % mCat = a.subset(vSel);\n\n % Initialize\n fMinTime = min(mCat(:,3));\n fMaxTime = max(mCat(:,3));\n\n % Select data from 2 time periods\n vSelT = mCat(:,3) < fSplitTime;\n mCat1 = mCat(vSelT,:);\n mCat2 = mCat(~vSelT,:);\n % Length of catalog (resolution)\n nNumevents1 = length(mCat1(:,1));\n nNumevents2 = length(mCat2(:,1));\n\n % Minimum bin: essential for computing difference in FMD\n fMinBin = roundn(min(mCat(:,6)),-1);\n fMaxBin = roundn(max(mCat(:,6)),-1);\n\n if (length(mCat1(:,1)) >=Nmin & length(mCat2(:,1)) >= Nmin)\n % Compute change in FMD normalized by time period\n % Time periods\n fPeriod1 = max(mCat1(:,3))-min(mCat1(:,3));\n fPeriod2 = max(mCat2(:,3))-min(mCat2(:,3));\n [vFMD1, vBin1] = hist(mCat1(:,6),fMinBin:0.1:fMaxBin);\n [vFMD2, vBin2] = hist(mCat2(:,6),fMinBin:0.1:fMaxBin);\n fChFMD = max(cumsum(abs(vFMD2./fPeriod2-vFMD1./fPeriod1)));\n % Calculate shift\n [fMshift, fProbability, fAICc, mProblikelihood, bH] = calc_loglikelihood_dM2(mCat1, mCat2);\n % Check for validity of model using KS-Test result to produce validated result of magnitude shift\n if (bH == 1 | fMshift == 0)\n fMshift_valid = NaN;\n else\n fMshift_valid = fMshift;\n end\n % Calculate Mc\n [mResult1, fMls1, fMc1, fMu1, fSigma1, mDatPredBest1,...\n vPredBest1, fBvalue1, fAvalue1, bH1] = calc_McEMR_kstest(mCat1, 0.1);\n [mResult2, fMls2, fMc2, fMu2, fSigma2, mDatPredBest2,...\n vPredBest2, fBvalue2, fAvalue2, bH2] = calc_McEMR_kstest(mCat2, 0.1);\n % Mc change\n fdMc = fMc2-fMc1;\n if (bH1 ==0 && bH2 == 0)\n fdMc_val = fdMc;\n else\n fdMc_val = NaN;\n end\n % Calculate Utsu-Test\n [dA, fProbEqual, fProbDifferent] = calc_Utsu(fBvalue1, fBvalue2, nNumevents1, nNumevents2);\n % Create result matrix\n mResult = [mResult; i fMshift fProbability fAICc bH nNumevents1 nNumevents2 fMshift_valid fChFMD fMc1 fMc2 fdMc fdMc_val dA fProbEqual fProbDifferent bH1 fBvalue1 fAvalue1 bH2 fBvalue2 fAvalue2];\n else\n % Create result matrix\n mResult = [mResult; i NaN NaN NaN NaN nNumevents1 nNumevents2 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN];\n end\n waitbar(allcount/itotal)\n end % for newgr\n\n % Save the data to rcval_grid.mat\n save mcgrid.mat mResult gx gy dx dy par1 tdiff t0b teb a main faults mainfault coastline yvect xvect tmpgri ll bo1 newgri gll ra maepi fSplitTime\n disp('Saving data to mcgrid.mat in current directory')\n\n close(wai)\n watchoff\n\n normlap2=ones(length(tmpgri(:,1)),1)*nan;\n % Magnitude shift\n normlap2(ll)= mResult(:,2);\n mMagShift = reshape(normlap2,length(yvect),length(xvect));\n\n\n % KS-Test-Value\n normlap2(ll)= mResult(:,5);\n mHkstest = reshape(normlap2,length(yvect),length(xvect));\n\n %%% Resolution parameters\n % Number of events per grid node in first time period\n normlap2(ll)= mResult(:,6);\n mNumevents1 = reshape(normlap2,length(yvect),length(xvect));\n\n % Number of events per grid node in first time period\n normlap2(ll)= mResult(:,7);\n mNumevents2 = reshape(normlap2,length(yvect),length(xvect));\n\n % Validated magnitude shift\n normlap2(ll)= mResult(:,8);\n mMagShift_valid = reshape(normlap2,length(yvect),length(xvect));\n\n % Absolute FMD difference\n normlap2(ll)= mResult(:,9);\n mChFMD = reshape(normlap2,length(yvect),length(xvect));\n\n % Mc Periode 1\n normlap2(ll)= mResult(:,10);\n mMc1 = reshape(normlap2,length(yvect),length(xvect));\n\n % Mc Periode 2\n normlap2(ll)= mResult(:,11);\n mMc2 = reshape(normlap2,length(yvect),length(xvect));\n\n % Mc change\n normlap2(ll)= mResult(:,12);\n mdMc = reshape(normlap2,length(yvect),length(xvect));\n\n % Mc change validated by KS-Test\n normlap2(ll)= mResult(:,13);\n mdMc_val = reshape(normlap2,length(yvect),length(xvect));\n\n % Difference of AIC for Utsu-Test\n normlap2(ll)= mResult(:,14);\n mdAIC_Utsu = reshape(normlap2,length(yvect),length(xvect));\n\n % Probability of stationarity (favoring stationarity)\n normlap2(ll)= mResult(:,15);\n mStationary1_Utsu = reshape(normlap2,length(yvect),length(xvect));\n\n % Probability of stationarity (favoring non-stationarity)\n normlap2(ll)= mResult(:,16);\n mStationary2_Utsu = reshape(normlap2,length(yvect),length(xvect));\n\n % Data to plot first map\n re3 = mMagShift;\n lab1 = 'Magnitude shift';\n\n\n % View the map\n view_mcgrid\n\nend % if sel = na\n\n% Load exist b-grid\nif sel == 'lo'\n [file1,path1] = uigetfile(['*.mat'],'b-value gridfile');\n if length(path1) > 1\n think\n load([path1 file1])\n\n normlap2=ones(length(tmpgri(:,1)),1)*nan;\n\n % Magnitude shift\n normlap2(ll)= mResult(:,2);\n mMagShift = reshape(normlap2,length(yvect),length(xvect));\n\n % KS-Test-Value\n normlap2(ll)= mResult(:,5);\n mHkstest = reshape(normlap2,length(yvect),length(xvect));\n\n %%% Resolution parameters\n % Number of events per grid node in first time period\n normlap2(ll)= mResult(:,6);\n mNumevents1 = reshape(normlap2,length(yvect),length(xvect));\n\n % Number of events per grid node in first time period\n normlap2(ll)= mResult(:,7);\n mNumevents2 = reshape(normlap2,length(yvect),length(xvect));\n\n try\n % Validated magnitude shift\n normlap2(ll)= mResult(:,8);\n mMagShift_valid = reshape(normlap2,length(yvect),length(xvect));\n\n % Absolute FMD difference\n normlap2(ll)= mResult(:,9);\n mChFMD = reshape(normlap2,length(yvect),length(xvect));\n % Mc Periode 1\n normlap2(ll)= mResult(:,10);\n mMc1 = reshape(normlap2,length(yvect),length(xvect));\n\n % Mc Periode 2\n normlap2(ll)= mResult(:,11);\n mMc2 = reshape(normlap2,length(yvect),length(xvect));\n\n % Mc change\n normlap2(ll)= mResult(:,12);\n mdMc = reshape(normlap2,length(yvect),length(xvect));\n\n % Mc change\n normlap2(ll)= mResult(:,13);\n mdMc_val = reshape(normlap2,length(yvect),length(xvect));\n\n % Difference of AIC for Utsu-Test\n normlap2(ll)= mResult(:,14);\n mdAIC_Utsu = reshape(normlap2,length(yvect),length(xvect));\n\n % Probability of stationarity (favoring stationarity)\n normlap2(ll)= mResult(:,15);\n mStationary1_Utsu = reshape(normlap2,length(yvect),length(xvect));\n\n % Probability of stationarity (favoring non-stationarity)\n normlap2(ll)= mResult(:,16);\n mStationary2_Utsu = reshape(normlap2,length(yvect),length(xvect));\n\n catch\n disp('Validated magnitude shift map not available');\n end\n % Initial map set to relative rate change\n re3 = mMagShift;\n lab1 = 'Magnitude shift';\n\n old = re3;\n % Plot\n view_mcgrid;\n else\n return\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/zmap_deprecated/orphaned/src/jochen/Scriptlab/mc_grid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.34904286260507245}}
{"text": "function [t,z] = plotDNLS(prob,opts,xb,confStats,tspan)\n%plotDNLS Plot Parameter Estimation Problem\n\n% Copyright (C) 2013 Jonathan Currie (IPL)\n\nif(nargin < 5), tspan = []; end\nif(nargin < 4), confStats = []; end\n\n%Measurement Plot Color\nmeasC = [0.4 0.4 0.4];\n%Measurement Plot Style\nmeasS = 'o';\n%Initial Condition plot style\nicS = 'sq';\n\n%Plot confidence lines if present\nif(~isempty(confStats))\n plot(NaN,NaN); %hack to prevent patch removing outer borders\n plotConfReg(confStats);\n hold on;\nend\n\n% Insert initial conditions if also solved\nind = isnan(prob.odez0);\nif(any(ind))\n len = sum(ind);\n estZ0 = xb(end-len+1:end);\n prob.odez0(ind) = estZ0;\n xb = xb(1:end-len);\nend\n\n% Generate smooth plot \ndopts = optidynset(opts.dynamicOpts);\nif(isempty(tspan))\n tspan = [prob.xdata(1) prob.xdata(end)];\nend\node = @(t,z) prob.ode(t,z,xb);\nswitch(dopts.integrator)\n case 'ode45'\n [t,z] = ode45(ode,tspan,prob.odez0,dopts.odeOpts);\n case 'ode15s'\n [t,z] = ode15s(ode,tspan,prob.odez0,dopts.odeOpts);\n case 'ode23'\n [t,z] = ode23(ode,tspan,prob.odez0,dopts.odeOpts);\n case 'ode113'\n [t,z] = ode113(ode,tspan,prob.odez0,dopts.odeOpts);\n case 'ode23t'\n [t,z] = ode23t(ode,tspan,prob.odez0,dopts.odeOpts);\n case 'ode23tb'\n [t,z] = ode23tb(ode,tspan,prob.odez0,dopts.odeOpts);\n case 'ode23s'\n [t,z] = ode23s(ode,tspan,prob.odez0,dopts.odeOpts);\n case 'ode15i'\n [t,z] = ode15i(ode,tspan,prob.odez0,dopts.odeOpts);\n otherwise\n optiwarn('OPTI:Plot','Unknown integrator chosen! Using ode45.');\n [t,z] = ode45(ode,tspan,prob.odez0,dopts.odeOpts);\nend\nif(nargout > 1), return; end %just for evaluating above\n\n%Plot smooth sim\nplot(t,z);\ntitle('Dynamic Parameter Estimation Solution');\nxlabel('time'); ylabel('z');\nhold on;\n\n%Plot Solved Initial Conditions\nif(any(ind))\n for i = 1:sum(ind)\n plot(tspan(1),estZ0(i),icS,'Color',measC);\n end\nend\n\n%If we have xdata_old, then should be in cell format, plot each cell\nif(isfield(prob.misc,'xdata_orig') && ~isempty(prob.misc.xdata_orig))\n if(iscell(prob.misc.xdata_orig) && iscell(prob.misc.ydata_orig))\n for i = 1:length(prob.misc.xdata_orig)\n plot(prob.misc.xdata_orig{i},prob.misc.ydata_orig{i},measS,'Color',measC);\n end \n elseif(~iscell(prob.misc.xdata_orig) && ~iscell(prob.misc.ydata_orig))\n for i = 1:size(prob.misc.ydata_orig,2)\n plot(prob.misc.xdata_orig,prob.misc.ydata_orig(:,i),measS,'Color',measC); \n end\n else\n error('Expected misc.xdata_orig and misc.ydata_orig to be cell arrays');\n end \nelse\n %Otherwise reshape ydata (always a column in OPTI) and plot\n if(~isempty(dopts.stateIndex))\n nstates = length(prob.odez0(dopts.stateIndex));\n else\n nstates = length(prob.odez0);\n end\n ydata = reshape(prob.ydata,length(prob.xdata),nstates);\n %Plot\n plot(prob.xdata,ydata,measS,'Color',measC);\nend\n\nhold off;", "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/opti/Utilities/opti/plotDNLS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.34904286260507245}}
{"text": "function plotRegionOverlapScript\n\nload('~/data/occlusion/labelme/results/result_LM_region_mean_covering.mat');\n\n%% Plot by area\narea_vals = [0.0025 0.005 0.01 0.2 0.4 1];\n\nareas = cat(2, cover_occ1.area)';\n\n% assign index for largest area_vals that area is less than or equal to\narea_ind = zeros(size(areas));\nfor k = 1:numel(area_vals)\n area_ind = area_ind + (areas > area_vals(k));\nend\narea_ind = area_ind+1;\n\nnames = {'Pb+ucm', 'globalPb+ucm', 'occ_1', 'occ_{final}'};\narea_hist = zeros(numel(area_vals), 4);\novmax{1} = cat(1, cover_ucm1.maxov);\novmax{2} = cat(1, cover_ucm2.maxov);\novmax{3} = cat(1, cover_occ1.maxov);\novmax{4} = cat(1, cover_occave.maxov);\n\narea_hist = zeros(numel(area_vals), numel(ovmax));\nfor k = 1:numel(ovmax)\n for k2 = 1:numel(area_vals)\n area_hist(k2, k) = mean(ovmax{k}(area_ind==k2));\n end \nend\n\nna = numel(area_vals);\nnl = numel(ovmax);\nfigure(1), hold off;\nstyle = {'--', '--', '-', '-' ,'-'};\nmarkers = {'+', 'x', 'o', '+', 'x'};\nfor k = 1:numel(ovmax)\n plot(area_hist(:, k), 'LineStyle', style{k}, 'MarkerSize', 12, 'Marker', markers{k}, 'LineWidth', mod(k,3)+2, 'Color', hsv2rgb(k/nl, 1, k/nl)); hold on;\nend\nxlabels = strtokAll(num2str(area_vals), ' '); \nxlabels = [[{'0'} ; xlabels(1:end-1)] repmat({'-'}, na, 1) xlabels(:) [repmat({'|'}, na-1, 1) ; {' '}]]';\naxis([1 6 0 1]); set(gca, 'XTick', 1:na, 'XTickLabel', cat(2, xlabels{:}), 'FontSize', 16); \nlegend(names, 'Location', 'NorthWest')\nxlabel('Region Area', 'FontSize', 18); ylabel('Average Overlap', 'FontSize', 18)\nprint -f1 -depsc ~/data/occlusion/labelme/figs/plots/overlap_comparison_by_area.eps\n\n%% Cumulative overlap\nfigure(2), hold off, \nind = true(size(areas));\nfor k = 1:numel(ovmax)\n y = sort(ovmax{k}(ind), 'descend');\n plot((1:numel(y))/numel(y), y, 'LineStyle', style{k}, 'LineWidth', mod(k,3)+2, 'Color', hsv2rgb(k/nl, 1, k/nl)); hold on;\nend\naxis([0 1 0 1]); set(gca, 'XTick', 0:0.1:1, 'FontSize', 16); \nlegend(names, 'Location', 'NorthEast')\nxlabel('Recall', 'FontSize', 18); ylabel('Overlap', 'FontSize', 18)\nprint -f2 -depsc ~/data/occlusion/labelme/figs/plots/overlap_overall_comparison.eps\n\n%% Cumulative overlap by area\nfigure(3), hold off, \nfor k = 1:na-1\n ind = areas>=area_vals(k);\n y = sort(ovmax{end}(ind), 'descend');\n plot((1:numel(y))/numel(y),y, 'LineStyle', style{k}, 'LineWidth', mod(k,3)+2, 'Color', hsv2rgb(k/(na-1), 1, k/(na-1))); hold on;\nend\naxis([0 1 0 1]); set(gca, 'XTick', 0:0.1:1, 'FontSize', 16); \nfor k = 1:na-1, lstr{k} = [' >' num2str(area_vals(k))]; end\nlegend(lstr, 'Location', 'SouthWest')\nxlabel('Recall', 'FontSize', 18); ylabel('Overlap', 'FontSize', 18);\nprint -f3 -depsc ~/data/occlusion/labelme/figs/plots/overlap_occlusion.eps", "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/occlusion/plotRegionOverlapScript.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347362, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.34902656926909287}}
{"text": "function failed_bug2359\n\n% MEM 2gb\n% WALLTIME 00:30:00\n% DEPENDENCY ft_prepare_mesh ft_prepare_sourcemodel\n\ncd(dccnpath('/home/common/matlab/fieldtrip/data/test/bug2359'));\n\ncortex = ft_read_headshape('cortex_20484.surf.gii');\niskull = ft_read_headshape('iskull_2562.surf.gii');\noskull = ft_read_headshape('oskull_2562.surf.gii');\nscalp = ft_read_headshape('scalp_2562.surf.gii');\n\nfigure\nft_plot_mesh(cortex, 'facecolor', 'b');\nft_plot_mesh(iskull, 'facecolor', [0.5 0.5 0.5], 'edgecolor', 'none', 'facealpha', 0.5);\n\n%% PART 1, implement the correction of the cortical sheet by moving points that are too close to the surface inward\n\n% usually the \"moveinward\" cortex modification would be done for EEG-BEM, but it is\n% easier to test it for a MEG singleshell model (for which it is actually not\n% needed).\n\ncfg = [];\ncfg.method = 'singleshell';\nvol = ft_prepare_headmodel(cfg, iskull);\n\ncfg = [];\ncfg.headmodel = vol;\ncfg.sourcemodel = cortex; % this is in mm\ncfg.inwardshift = 0; % this should be expressed in the units consistent with cfg.unit\ncfg.moveinward = 0;\ngridorig = ft_prepare_sourcemodel(cfg);\n\ncfg = [];\ncfg.headmodel = vol;\ncfg.sourcemodel = cortex; % this is in mm\ncfg.inwardshift = -5; % outward shifted\ncfg.moveinward = 0;\ngridoutward = ft_prepare_sourcemodel(cfg);\n\ncfg = [];\ncfg.headmodel = vol;\ncfg.sourcemodel = cortex; % this is in mm\ncfg.inwardshift = 5; % inward shifted\ncfg.moveinward = 0;\ngridinward = ft_prepare_sourcemodel(cfg);\n\ncfg = [];\ncfg.headmodel = vol;\ncfg.sourcemodel = cortex; % this is in mm\ncfg.inwardshift = 0; % keep this at the original place\ncfg.moveinward = 5; % dipoles moved inwards\ngridcorrect = ft_prepare_sourcemodel(cfg);\n\nassert(isempty(gridorig.outside));\nassert(isempty(gridoutward.outside));\nassert(~isempty(gridinward.outside)); % this should have a few vertices outside the inward shifted surface\nassert(isempty(gridcorrect.outside))\n\nfigure\nft_plot_mesh(iskull, 'facecolor', [0.5 0.5 0.5], 'edgecolor', 'none', 'facealpha', 0.5);\nft_plot_mesh(gridorig.pos(gridinward.outside,:), 'vertexcolor', 'b');\nft_plot_mesh(gridcorrect.pos(gridinward.outside,:), 'vertexcolor', 'r');\n\n%% PART 2, implement the spherify of the cortical sheet\n\nmesh = cat(1, iskull, oskull, scalp);\n\ncfg = [];\ncfg.method = 'concentricspheres';\nvol = ft_prepare_headmodel(cfg, mesh);\n\n\ncfg = [];\ncfg.headmodel = vol;\ncfg.sourcemodel = cortex; % this is in mm\ncfg.spherify = 'yes';\ngridsphere = ft_prepare_sourcemodel(cfg);\n\nassert(isempty(gridsphere.outside));\n\nfigure\nft_plot_headmodel(vol, 'edgecolor', 'none', 'facecolor', 'skin', 'facealpha', 0.5);\nft_plot_mesh(gridsphere)\n\n%% this is a weird modification, I am just curious to see how it works\n\ncfg = [];\ncfg.method = 'singlesphere';\nvol = ft_prepare_headmodel(cfg, iskull);\n\ncfg = [];\ncfg.headmodel = vol;\ncfg.sourcemodel.xgrid = -200:10:200; % this is in mm\ncfg.sourcemodel.ygrid = -200:10:200; % this is in mm\ncfg.sourcemodel.zgrid = -50:10:150; % this is in mm\ncfg.spherify = 'yes';\ngridsphere = ft_prepare_sourcemodel(cfg);\n\nfigure\nft_plot_headmodel(vol, 'edgecolor', 'none', 'facecolor', 'skin', 'facealpha', 0.5);\nft_plot_mesh(gridsphere)\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_bug2359.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3490265628749381}}
{"text": "function net = res_finetune_init(imdb, n)\nnet = sprintf('imagenet-resnet-%d-dag', n); \n\nif ischar(net), \n net_path = fullfile('data','models',[net '.mat']);\n if ~exist(net_path,'file'), \n fprintf('Downloading model (%s) ...', net) ;\n vl_xmkdir(fullfile('data','models')) ;\n urlwrite(fullfile('http://www.vlfeat.org/matconvnet/models', ...\n [net '.mat']), net_path) ;\n fprintf(' done!\\n');\n end\n net = dagnn.DagNN.loadobj(load(net_path));\nend\n\nnet.meta.trainOpts.weightDecay = 0.0001 ;\nnet.meta.trainOpts.momentum = 0.9;\nnet.meta.trainOpts.batchSize = 256 ;\nnet.meta.classes.name = imdb.meta.classes;\nnet.meta.classes.description = imdb.meta.classes;\n\n% remove 'prob'\nnet.removeLayer(net.layers(end).name);\n\n[h,w,in,out] = size(zeros(net.layers(end).block.size));\nout = numel(net.meta.classes.name); \n% remove 'fc'\nlName = net.layers(end).name;\nnet.removeLayer(net.layers(end).name);\n\npName = net.layers(end).name;\nblock = dagnn.Conv('size', [h,w,in,out], 'hasBias', true, ...\n 'stride', 1, 'pad', 0);\nnet.addLayer(lName, block, pName, lName, {[lName '_f'], [lName '_b']});\n%net.params(net.layers(end).paramIndexes(1)).value = init_weight(opts, h, w, in, out, 'single');\n%net.params(net.layers(end).paramIndexes(2)).value = zeros(out, 1, 'single');\np = net.getParamIndex(net.layers(end).params) ;\nparams = net.layers(end).block.initParams() ;\nparams = cellfun(@gather, params, 'UniformOutput', false) ;\n[net.params(p).value] = deal(params{:}) ;\n\nlName = net.layers(end).name;\nnet.addLayer('softmax', dagnn.SoftMax(), lName, 'softmax'); \nnet.addLayer('loss', dagnn.Loss('loss', 'log'), {'softmax', 'label'}, 'loss');\nnet.addLayer('error', dagnn.Loss('loss', 'classerror'), {'softmax','label'}, 'error') ;\nnet.addLayer('error5', dagnn.Loss('loss', 'topkerror', 'opts', {'topK', 5}), ...\n {'softmax','label'}, 'error5') ;\n\nnet.meta.augmentation.rgbVariance = zeros(0,3) ;\nnet.meta.augmentation.transformation = 'stretch' ;\n\nend\n", "meta": {"author": "zhanghang1989", "repo": "ResNet-Matconvnet", "sha": "247d5f6896638e773bb23f295f27833f66808866", "save_path": "github-repos/MATLAB/zhanghang1989-ResNet-Matconvnet", "path": "github-repos/MATLAB/zhanghang1989-ResNet-Matconvnet/ResNet-Matconvnet-247d5f6896638e773bb23f295f27833f66808866/init/res_finetune_init.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.34902656287493805}}
{"text": "% VBRFA2011_TESTBED_PLOT - Make the Testbed plots for the VBRFA journal\n% paper.\n\n% Last modified 2011-06-15\n% Copyright (c) Jaakko Luttinen (jaakko.luttinen@aalto.fi)\n\nfunction data = vbrfa2011_testbed_plot(model)\n\n% Result files\nfolder = '/share/climate/jluttine/testbed';\n%files = {'testbed_results_ind-t_D=30_20110616'};\nfiles = {'testbed_results_gaussian_D=30_20110617', ...\n 'testbed_results_multi-t_D=30_20110617', ...\n 'testbed_results_ind-t_D=30_20110617', ...\n 'testbed_results_laplace_D=30_20110617'};\n\n% Pick stations from: 12 13 20 21 28 48 57 59\ncorrupted = [12 13 20 21 28 48 57 59];\nstations = [5 corrupted([8 7 6 1 3])];\n\n%\n% PLOT DATA OBSERVATIONS\n%\n\ndata = testbed_loaddata();\ndata = testbed_preprocess(data);\nreturn\nplot_timeseries(data.time, ...\n data.observations(stations,:));\n%return\n\nprint('-depsc2', '-loose', ...\n '/home/jluttine/papers/rpca_journal/fig_testbed_timeseries_data');\n%\n% PLOT RESULTS FOR EACH METHOD\n%\n\nsuffix = {'gaussian', 'multi-t', 'ind', 'laplace'};\n\n% Plot\nif nargin < 1\n model = 1:length(files);\nend\nfor n=model\n fprintf('Loading results from file:\\n%s\\n', files{n});\n Q = load(files{n}, 'W', 'X', 'W_struct');\n% $$$ plot_loadings(Q,suffix{n});\n plot_reconstructions(Q,stations,suffix{n});\n %figure, semilogy(Q.W_struct.alpha)\n %fprintf('alpha(%d): %.4e\\n', [1:length(Q.w); Q.w(:)']);\nend\n\n% $$$ %\n% $$$ % PLOT THE STATIONS\n% $$$ %\n% $$$ \n% $$$ fig = figure();\n% $$$ \n% $$$ % Plot the research area on the map of Finland\n% $$$ hax(1) = subplot(1,2,1);\n% $$$ testbed_plot_finland();\n% $$$ \n% $$$ % Plot the stations on a topographic map\n% $$$ hax(2) = subplot(1,2,2);\n% $$$ set(hax(2), 'FontSize', 9);\n% $$$ testbed_plot_topography();\n% $$$ hold on;\n% $$$ testbed_coast();\n% $$$ map_grid();\n% $$$ testbed_plot_stations(data.coordinates);\n% $$$ hcb = colorbar('peer',hax(2),'FontSize',9);\n% $$$ \n% $$$ % Set layout\n% $$$ bottom = 0.07;\n% $$$ top = 0.92;\n% $$$ set(hax(1), 'Units','Normalized', 'Position',[0.0 bottom 0.22 (top-bottom)]);\n% $$$ set(hax(2), 'Units','Normalized', 'Position',[0.27 bottom 0.63 (top-bottom)]);\n% $$$ set(hcb, 'Units','Normalized', 'Position',[0.91 bottom 0.02 (top-bottom)]);\n% $$$ set_figure_size(15,6.3,fig);\n% $$$ \n% $$$ % $$$ % Print\n% $$$ % $$$ print('-depsc2', '-loose', ...\n% $$$ % $$$ '/home/jluttine/papers/vbrfa/figures_journal/fig_testbed_stations');\n% $$$ \n% $$$ \n\nfunction plot_timeseries(time,Y)\n\n% Plot timeseries\nhax = tsplot(time, Y, 'k');\n\n% Set the range of the x-axis\nN = length(hax);\nset(hax, 'xlim', [min(time), max(time)]);\n\n% Put date ticks on x-axis\ndateticks(hax, 'x', 'mmmyy', 'keeplimits');\nset(hax(1:(N-1)), 'xticklabel', []);\nset_ticks_fontsize(hax,9);\nxtick = get(hax(end), 'xtick');\nset(hax, 'xtick', xtick(2:end));\n\n% Remove ticks from y-axis\nset(hax, 'ylim', [-50 50], 'yticklabel', [], 'ytick', []);\n\n% Set the layout of the subplots\nset_subplot_positions(hax, N, 1, [0.01 0.01 0.01 0.07], [0.02 0.02]);\nset_figure_size(15,9)\n\nfunction plot_reconstructions(Q,stations,suffix)\n\n% Reconstructions\nYh = Q.W(:,stations)' * Q.X;\n\n% Remove time instances with no observations to make the plot more clear\ndata = load(['/share/climate/jluttine/testbed/' ...\n 'testbed_vbrfa2011_traindata']);\n% $$$ data = testbed_loaddata();\n% $$$ data = testbed_preprocess(data);\nind = sum(~isnan(data.observations),1) == 0;\nYh(:,ind) = nan;\n\n% Plotplotplot\nplot_timeseries(data.time, Yh);\n\n% Print figure\nprint('-depsc2', '-loose', ...\n ['/home/jluttine/papers/rpca_journal/fig_testbed_timeseries_', ...\n suffix]);\n\nfunction plot_loadings(Q,suffix)\n\n%\n% Plot spatial components\n%\n\ndata = testbed_loaddata();\ndata = testbed_preprocess(data);\n\ncomponents = 1:4;\nhax = testbed_loadings(Q.W(components,:)', ...\n data.coordinates, ...\n 'resolution', [200 150], ...\n 'method', 'rbf');\n% Subplot layout\nset_subplot_positions(hax, 2, 2, [0.01 0.01 0.08 0.06], [0.08 0.1]);\n% Colorbar layout\ncolorbars(hax, ...\n 'Size', 0.02, ...\n 'Separation', 0.0, ...\n 'Location', 'EastOutside', ...\n 'FontSize', 9);\n% X-labels (and layout)\nfor n=1:numel(components)\n xlabels(hax(n),sprintf('(%d)', components(n)), 'Separation',0.03, 'FontSize', 9);\nend\n% Print figure\nset_figure_size(15,8.5)\n% $$$ print('-depsc2', '-loose', ...\n% $$$ ['/home/jluttine/papers/vbrfa/figures_journal/fig_testbed_loadings_', ...\n% $$$ suffix]);\n\n% Plot reconstructions of problematic stations\n%testbed_rcplot(Q, 'stations', [12 13 20 21 28 48 57 59]);\n\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/publications/vbrfa2011/vbrfa2011_testbed_plot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3490149188820786}}
{"text": "function disp(c)\n \n % CORRELATION/DISPLAY Command window display of a correlation object\n % See help correlation for fields\n \n % Author: Michael West, Geophysical Institute, Univ. of Alaska Fairbanks\n % $Date$\n % $Revision$\n \n \n \n disp(' ');\n disp([inputname(1),' = '])\n disp(' ');\n %\n showline('WAVEFORMS', c.traces, 'vector');\n showline('TRIG', c.trig, 'vector');\n showline('CORR', c.corrmatrix, 'square matrix');\n showline('LAG', c.lags, 'square matrix');\n showline('STAT', c.stat, 'matrix');\n showline('LINK', c.link, 'matrix');\n showline('CLUST', c.clust, 'vector');\nend\n\nfunction showline(fname, value, desc)\n fprintf('%11s: %s %s\\n',fname, getsizestr(value), desc);\nend\n\nfunction s = getsizestr(val)\n s = num2str(size(val),'%dx');\n s(s == ' ') = [];\n s = s(1:end-1);\nend\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/dev/@NewCorrelation/disp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.34901491032977594}}
{"text": "classdef CumMomentAnalysisWindow < AnalysisWindow\n % CUMMOMENTANALYSISWINDOW shows cumulative moment release\n properties\n end\n methods\n function obj=CumMomentAnalysisWindow(ax)\n obj@AnalysisWindow(ax);\n end\n \n function prepare_axes(obj)\n % prepare the moment release axes\n if isempty(obj.ax.Tag)\n obj.ax.Tag = 'dvMoment';\n end\n obj.ax.Title.String='Cum Moment Release';\n obj.ax.XLabel.String='time';\n obj.ax.YLabel.String='Cumulative Moment [N m]'; %units as per calc_moment\n end\n \n function [x,y]=calculate(~,catalog)\n if ~isa(catalog,'ZmapCatalog')\n catalog=catalog.Catalog;\n end\n % return the datetime and cumulative-moment for each event in the catalog\n x=catalog.Date;\n [~, y, ~] = calc_moment(catalog);\n end\n \n end\nend", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/CumMomentAnalysisWindow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3489737138901228}}
{"text": "function [A, b, Aeq, beq, lb, ub] = snd_l_constraints(k, net_load_data, varargin)\n\n u0_ref = cell2mat(varargin(2));\n f = 1.05;\n g = 0.95;\n p = 1.2;\n A = []; %A*u<=b\n b = [];\n Aeq = [1 1 1]; %A*u = b\n beq = net_load_data(k);\n \n if k ~= 12\n if u0_ref(1,k) * u0_ref(1,k+1) <= 0\n if u0_ref(1,k)>0\n ub = [u0_ref(1,k)*1.05];\n lb = [u0_ref(1,k+1)*1.05];\n else\n ub = [u0_ref(1,k+1)*1.05];\n lb = [u0_ref(1,k)*1.05];\n end\n elseif u0_ref(1,k)>0 && u0_ref(1,k+1)>0\n if u0_ref(1,k)>u0_ref(1,k+1)\n ub = [u0_ref(1,k)*1.05];\n lb = [u0_ref(1,k+1)*0.95];\n else\n ub = [u0_ref(1,k+1)*1.05];\n lb = [u0_ref(1,k)*0.95];\n end\n elseif u0_ref(1,k)<0 && u0_ref(1,k+1)<0\n if u0_ref(1,k)>u0_ref(1,k+1)\n ub = [u0_ref(1,k)*0.95];\n lb = [u0_ref(1,k+1)*1.05];\n else\n ub = [u0_ref(1,k+1)*0.95];\n lb = [u0_ref(1,k)*1.05];\n end\n end\n else\n if u0_ref(1,k) >=0\n ub = [u0_ref(1,k)*1.05];\n lb = [u0_ref(1,k)*0.95];\n else\n ub = [u0_ref(1,k)*0.95];\n lb = [u0_ref(1,k)*1.05];\n end\n \n end\n\n if u0_ref(2,k)>0 %\n ub = [ub, u0_ref(2,k)*1.1, 10]; \n lb = [lb, 0, -10]; \n else\n ub = [ub, 0, 10]; \n lb = [lb, u0_ref(2,k)*1.1, -10];\n end\n\n\nend", "meta": {"author": "juchengquan", "repo": "Two_Layer_EMS", "sha": "48864a80e10fe32e566181ebd5e2394ab2c6e1a7", "save_path": "github-repos/MATLAB/juchengquan-Two_Layer_EMS", "path": "github-repos/MATLAB/juchengquan-Two_Layer_EMS/Two_Layer_EMS-48864a80e10fe32e566181ebd5e2394ab2c6e1a7/constraints/Copy_of_snd_l_constraints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3489708056480583}}
{"text": "function [coords, data] = dtiRoiGrow2d(data, xformToAcpc, seedAcpc, ax, tol, thick)\n%\n% [selectedCoords, data] = dtiRoiGrow2d(data, xformToAcpc, seedAcpc, ax, tol, [thick=1])\n%\n% data is either an image volume (scalar or dt6) or the data struct\n% returned after calling this function once (useful if you want to iterate\n% with the same image volume, just chaning the tolerance).\n%\n% seedAcpc: the seed point, in ac-pc coords\n%\n% ax: the axis to grow in (1,2 or 3). E.g., ax=1 will grow in the slice\n% X=seedAcpc(1), ax=2 will grow in Y=seedAcpc(2), and ax=3 in\n% Z=seedAcpc(3).\n%\n% tol: the tolerance (between 0 and 1, with lower values including fewer\n% voxels).\n%\n% thick: the thickness of the resulting coordinates. The algorithm grows in\n% a single slice. thick > 1 will replicate the selected coords in adjacent\n% slices for you.\n%\n% E.g.:\n% dt = dtiLoadDt6('dti06trilinrt/dt6');\n% seedAcpc = [-36 -28 26];\n% ax = 3;\n% tol = .20;\n% [coords, data] = dtiRoiGrow2d(dt.dt6, dt.xformToAcpc, seedAcpc, ax, tol);\n% % Show the delta image with the selected coords overlaid\n% figure; image(data.x(:), data.y(:), data.img); axis equal tight xy;\n% hold on; plot(coords(:,1),coords(:,2),'k.'); hold off;\n%\n% % do it again with stricter tol and passing the pre-processed data:\n% coords = dtiRoiGrow2d(data, dt.xformToAcpc, seedAcpc, ax, 0.10);\n% figure; image(data.x(:), data.y(:), data.img); axis equal tight xy;\n% hold on; plot(coords(:,1),coords(:,2),'k.'); hold off;\n%\n% HISTORY\n% 2009.08.26 RFD: pulled code from dtiFiberUI so that we can easily scrip it.\n%\n\nif(~exist('thick','var')||isempty(thick))\n thick = 1;\nend\n\nif(~isstruct(data))\n if(ndims(data)==3)\n [img,x,y,z] = dtiGetSlice(xformToAcpc, data, ax, seedAcpc(ax), [], 'n');\n if(ax==2), yseed = find(x(:,1)>seedAcpc(1)-.5&x(:,1)<=seedAcpc(1)+.5);\n else yseed = find(y(:,1)>seedAcpc(2)-.5&y(:,1)<=seedAcpc(2)+.5); end\n if(ax==3), xseed = find(x(1,:)>seedAcpc(1)-.5&x(1,:)<=seedAcpc(1)+.5);\n else xseed = find(z(1,:)>seedAcpc(3)-.5&z(1,:)<=seedAcpc(3)+.5); end\n elseif(ndims(data)==4)\n % Then it's a dt6 (tensor). We'll create a map of the angle between the\n % seed point PDD and each image voxel PDD.\n [dt6,x,y,z] = dtiGetSlice(xformToAcpc, data, ax, seedAcpc(ax), [], 'n');\n if(ax==2), yseed = find(x(:,1)>seedAcpc(1)-.5&x(:,1)<=seedAcpc(1)+.5);\n else yseed = find(y(:,1)>seedAcpc(2)-.5&y(:,1)<=seedAcpc(2)+.5); end\n if(ax==3), xseed = find(x(1,:)>seedAcpc(1)-.5&x(1,:)<=seedAcpc(1)+.5);\n else xseed = find(z(1,:)>seedAcpc(3)-.5&z(1,:)<=seedAcpc(3)+.5); end\n [eigVec,eigVal] = dtiEig(dt6);\n seedPdd = squeeze(eigVec(yseed,xseed,:,1));\n % dot(eigVec(1,:),[1 0 0]) = eigVec(1,1) and dot(eigVec(1,:),[0 1 0]) = eigVec(1,2)\n img = eigVec(:,:,1,1).*seedPdd(1)+eigVec(:,:,2,1).*seedPdd(2)+eigVec(:,:,3,1).*seedPdd(3);\n img(img>1) = 1; img(img<-1) = -1;\n img = acos(img);\n % Reflect about pi/2 for angles > pi/2 (diffusion is symmetric along the eigenvector axis)\n img(img>pi/2) = pi/2-(img(img>pi/2)-pi/2);\n img = img./(pi/2);\n % FA an MD should matter too, since we usually don't want to grow\n % into regions with very different anisotropy from our seed. But-\n % should it get equal weighting to our angle measure? Maybe make it a\n % parameter?\n [fa,md] = dtiComputeFA(eigVal);\n maxMd = md(yseed,xseed)*3;\n md(md>maxMd) = maxMd;\n md = md./maxMd;\n %img = 0.5*img + 0.5*abs(fa-fa(yseed,xseed));\n img = cat(3, img, abs(fa-fa(yseed,xseed)), abs(md-md(yseed,xseed)));\n %figure;imagesc(img);axis image xy; colormap gray\n end\n clear data;\n data.img = img;\n data.x = x;\n data.y = y;\n data.z = z;\n data.xseed = xseed;\n data.yseed = yseed;\nend\n\nbinImg = magicwand1(data.img, data.yseed, data.xseed, tol);\nind = find(binImg);\ncoords = [data.x(ind), data.y(ind), data.z(ind)];\nfor(ii=[1:thick-1,-1:-1:-(thick-1)])\n\tnewLayer = coords; \n newLayer(:,ax) = newLayer(:,ax)+ii;\n coords = [coords; newLayer];\nend\ncoords = unique(coords, 'rows');\nreturn;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrDiffusion/roi/dtiRoiGrow2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3489708056480583}}
{"text": "function [lf] = eeg_halfspace_dipole(dippos, elc, vol)\n\n% EEG_HALFSPACE_DIPOLE calculate the leadfield on electrode positions elc\n% for a dipole at position dippos. The halfspace solution requires a plane dividing a\n% conductive zone (cond > 0), from a non-coductive zone (cond = 0).\n%\n% Use as\n% [lf] = eeg_halfspace_dipole(dippos, elc, vol)\n%\n% See also EEG_INFINITE_DIPOLE, EEG_INFINITE_MONOPOLE, EEG_HALFSPACE_MONOPOLE\n\n% Copyright (C) 2011, Cristiano Micheli and Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\nif isfield(vol, 'pos')\n % this is for forward/backward compatibility\n vol.pnt = vol.pos;\n vol = rmfield(vol, 'pos');\nend\n\nsiz = size(dippos);\nif any(siz==1)\n % positions are specified as a single vector\n Ndipoles = prod(siz)/3;\n dippos = dippos(:)'; % 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 dippos = dippos';\n dippos = dippos(:)'; % ensure that it is a row vector\nelse\n ft_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 = dippos((1:3) + 3*(i-1));\n \n % find the position of a mirror dipole symmetric to the plane\n dip2 = get_mirror_pos(dip1, vol);\n \n % compute the potential of the original and the mirror dipole\n lf1 = eeg_infinite_dipole(dip1, elc, vol);\n lf2 = eeg_infinite_dipole(dip2, elc, vol);\n \n % the z-direction of the mirror dipole should be swapped\n lf2(:,3) = -lf2(:,3);\n \n % take the sum of the two dipoles\n lf = lf1 + lf2;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SUBFUNCTION\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction P2 = get_mirror_pos(P1,vol)\n% calculates the position of a point symmetric to pnt with respect to a plane\n\n% define the plane\npnt = vol.pnt;\nori = vol.ori; % already normalized\n\nif abs(dot(P1-pnt,ori))0;\n ind_neg = label<0;\n ind_pos = ind_pos(:);\n ind_neg = ind_neg(:);\n n_pos = sum(ind_pos);\n n_neg = sum(ind_neg);\n ind_select = ones(n_pos,n_neg)>0;\n pos_use = sum(ind_select,2);\n neg_use = sum(ind_select,1);\n% instance_weight = 1./(pos_use*neg_use+eps);\n instance_weight = ones(n_pos,n_neg);\n n_pairs = sum(ind_select(:));\n sz_in = size(score);\n try\n batch_size = sz_in(4);\n catch\n batch_size = 1;\n end\n% out = 0;\n if isa(score,'gpuArray')\n in0 = gpuArray.zeros([n_pairs,2,batch_size],classUnderlying(score)) ;\n instance_weight =gpuArray(instance_weight );\n else\n in0 = zeros([n_pairs,2,batch_size],'single');\n end \n \n \n for i = 1:batch_size\n tmp_s = score(:,:,:,i); \n pos = tmp_s(ind_pos);\n neg = tmp_s(ind_neg);\n% ef1 = exp(pos); ef2 = exp(neg);\n pos_m = repmat(pos,1,n_neg).*instance_weight;\n neg_m = repmat(neg',n_pos,1).*instance_weight;\n pos_v = pos_m(ind_select);\n neg_v = neg_m(ind_select);\n if size(pos_v,1)==1\n pos_v = pos_v'; neg_v = neg_v';\n end\n in0(:,:,i) = [pos_v,neg_v]; \n end \n in0 = reshape(in0,[1,n_pairs,2,batch_size]);\n% switch obj.label_type\n% case 'form1'\n% label0 = obj.zerosLike(in0);\n% label0(:,:,1,:) = 1;\n% case 'form2'\n% label0 = ones(1,n_pairs,1,batch_size,'single');\n% otherwise\n% \n% end\n \n outputs{1} = in0;\n% outputs{2} = label0;\n% sz_in = size(inputs{1});\n% n = prod(sz_in(1:3));\n% ef1 = exp(inputs{1});\n% ef2 = exp(inputs{2});\n% out = 2*(ef2./(ef1+ef2+eps)).^2 ;\n% outputs{1} = sum(out(:))/n;\n% n = obj.numAveraged ;\n% m = n + size(inputs{1},4) ;\n% obj.average = (n * obj.average + gather(outputs{1})) / m ;\n% obj.numAveraged = m ;\n end\n\n function [derInputs, derParams] = backward(obj, inputs, params, derOutputs)\n score = inputs{1};\n label = inputs{2};\n ind_pos = label>0;\n ind_neg = label<0;\n ind_pos = ind_pos(:);\n ind_neg = ind_neg(:);\n n_pos = sum(ind_pos);\n n_neg = sum(ind_neg);\n ind_select0 = ones(n_pos,n_neg,'single');\n ind_select = ind_select0>0;\n pos_use = sum(ind_select,2);\n neg_use = sum(ind_select,1);\n% instance_weight = 1./(pos_use*neg_use+eps);\n instance_weight = ones(n_pos,n_neg);\n if isa(score,'gpuArray')\n ind_select0 = gpuArray(ind_select0);\n instance_weight =gpuArray(instance_weight );\n end\n% n_pairs = sum(ind_select(:));\n sz_in = size(score);\n try\n batch_size = sz_in(4);\n catch\n batch_size = 1;\n end\n der1 = squeeze(derOutputs{1});\n \n% out = 0;\n derIn0 = obj.zerosLike(score);\n% derOutputs{1} = derOutputs{1}/n_pairs;\n for i = 1:batch_size\n tmp = obj.zerosLike(ind_select0);\n tmp(ind_select) = der1(:,1,i);\n tmp = tmp .*instance_weight;\n tmp_s = score(:,:,:,i);\n der_tmp = obj.zerosLike(tmp_s);\n der_tmp(ind_pos) = sum(tmp,2);\n \n tmp = obj.zerosLike(ind_select0);\n tmp(ind_select) = der1(:,2,i);\n tmp = tmp .*instance_weight;\n% der_tmp = obj.zerosLike(tmp_s);\n der_tmp(ind_neg) = sum(tmp,1);\n derIn0(:,:,1,i) = reshape(der_tmp,size(tmp_s));\n \n% pos = tmp_s(ind_pos);\n% neg = tmp_s(ind_neg);\n% ef1 = exp(pos); ef2 = exp(neg);\n% ef1_m = repmat(ef1,1,n_neg).*ind_select;\n% ef2_m = repmat(ef2',n_pos,1).*ind_select;\n% derIn1 = -4.*ef2_m.^2./((ef1_m+ef2_m).^3+eps).*derOutputs{1};\n% der_tmp(ind_pos) = sum(derIn1,2);\n% derIn2 = derIn1 *(-1).* ef1_m;\n% der_tmp(ind_neg) = sum(derIn2);\n% derIn0(:,:,1,i) = reshape(der_tmp,size(tmp_s));\n end \n derInputs{1} = derIn0;\n derInputs{2} = [];\n% sz_in = size(inputs{1});\n% n = prod(sz_in(1:3));\n% derOutputs{1} = derOutputs{1}/n;\n% ef1 = exp(inputs{1});\n% ef2 = exp(inputs{2}); \n% derInputs{1} = -4.*ef2.^2./((ef1+ef2).^3+eps).*derOutputs{1};\n% derInputs{2} = derInputs{1}*(-1).* ef1;\n derParams = {} ;\n end\n\n% function reset(obj)\n% obj.average = 0 ;\n% obj.numAveraged = 0 ;\n% end\n\n function outputSizes = getOutputSizes(obj, inputSizes, paramSizes)\n outputSizes{1} = [1 1 1 inputSizes{1}(4)] ;\n end\n\n function rfs = getReceptiveFields(obj)\n % the receptive field depends on the dimension of the variables\n % which is not known until the network is run\n rfs(1,1).size = [NaN NaN] ;\n rfs(1,1).stride = [NaN NaN] ;\n rfs(1,1).offset = [NaN NaN] ;\n rfs(2,1) = rfs(1,1) ;\n end\n\n function obj = select_pairs(varargin)\n obj.load(varargin) ;\n end\n end\nend\n", "meta": {"author": "shenjianbing", "repo": "TripletTracking", "sha": "b4ed538f2189b94bf3bc13fcca879b7fd12ad93a", "save_path": "github-repos/MATLAB/shenjianbing-TripletTracking", "path": "github-repos/MATLAB/shenjianbing-TripletTracking/TripletTracking-b4ed538f2189b94bf3bc13fcca879b7fd12ad93a/util_triplet/select_pairs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7090191214879991, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.34897079959557453}}
{"text": "function grid = reshapeGrid(~, grid)\n%RESHAPEGRID Add the repeated endpoint to a 1D periodic grid.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Note: We use periodic discretizations in 1D/2D/3D. These discretizatioins \n% do not include the repeated endpoints. Before plotting data with \n% SPINOPERATOR/INITIALIZEMOVIE, we add these repeated endpoints to the grid. \n\n% Get the points:\nxx = grid{1};\n\n% Add the endpoint:\nxx = [xx; 2*xx(end) - xx(end-1)];\n\n% Output the new grid:\ngrid{1} = xx;\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@spinop/reshapeGrid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3488913482066966}}
{"text": "function u = ldivide(a,b)\n%LDIVIDE Slope elementwise left division a .\\ b\n%\n\n% written 11/02/05 S.M. Rump\n%\n\n u = b ./ a;\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/ldivide.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3488913482066966}}
{"text": "function [GrainBoundaryX,GrainBoundaryY]=IdentifyGrainBoundary(x,y,state)\n\ncount=1;\nfor i=1:size(x,1)-1\n for j=1:(size(x,1)-1)\n if state(i,j)~=state(i,j+1)\n GrainBoundaryX(1,count)=x(i,j);\n GrainBoundaryY(1,count)=y(i,j);\n count=count+1;\n end\n if state(i,j)~=state(i+1,j)\n GrainBoundaryX(1,count)=x(i,j);\n GrainBoundaryY(1,count)=y(i,j);\n count=count+1;\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/34784-monte-carlo-simulation-of-two-dimensional-grain-growth-code-version-no-1-basic/Monte Carlo Simulation Q-state Potts model 2D square-lattice - microstructure/IdentifyGrainBoundary.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3488913482066966}}
{"text": "function [f,g,h] = fminunc_wrapper(x,F,G,H)\n% [f,g,h] = fminunc_wrapper( x, F, G, H )\n% for use with Matlab's \"fminunc\"\nf = F(x);\nif nargin > 2 && nargout > 1\n g = G(x);\nend\nif nargin > 3 && nargout > 2\n h = H(x);\nend\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/Train_LBFGS/Matlab/fminunc_wrapper.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3487678348649093}}
{"text": "function [ ] = convertPLY( openDir, saveDir )\n%CONVERTPLY Summary of this function goes here\n% Detailed explanation goes here\n \n % For KITTI Dataset\n\n fileExt = '*.bin';\n files = dir(fullfile(openDir,fileExt)); \n \n for i=0:length(files)-1\n i\n \n fileID = sprintf('%06d', i);\n fileName = [openDir, fileID, '.bin' ];\n \n xyz = readVelodyne(fileName);\n xyz = xyz';\n xyz = xyz(:,1:3);\n \n pt = pointCloud(xyz);\n \n saveName = [saveDir, num2str(i), '.ply'];\n pcwrite(pt, saveName);\n \n end\n\nend\n\n", "meta": {"author": "HuanYin94", "repo": "map_compression", "sha": "3c126a5cc832bf51f0c313c6ad8aa58a2930312c", "save_path": "github-repos/MATLAB/HuanYin94-map_compression", "path": "github-repos/MATLAB/HuanYin94-map_compression/map_compression-3c126a5cc832bf51f0c313c6ad8aa58a2930312c/prepare/convertPLY.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.34876783486490925}}
{"text": "function out = chebcoeffs(f, varargin)\n%CHEBCOEFFS Chebyshev polynomial coefficients of a CLASSICFUN.\n% CHEBCOEFFS(F) returns the Chebyshev coefficients of F.ONEFUN.\n%\n% See also LEGPOLY, TRIGCOEFFS.\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 CHEBCOEFFS() of the .ONEFUN:\nout = chebcoeffs(f.onefun, 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/@classicfun/chebcoeffs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.34876783486490914}}
{"text": "classdef PdeVariableToPrintGetter < handle\n \n properties (Access = private)\n physicalProblem\n end\n \n methods (Access = public)\n \n function obj = PdeVariableToPrintGetter(cParams)\n obj.init(cParams)\n end\n \n function v = compute(obj)\n p = obj.physicalProblem;\n if isempty(p.variables)\n p.computeChomog();\n end\n v.stress = p.variables.stress;\n v.strain = p.variables.strain;\n% v.u = obj.splitDisplacement(p.variables.d_u,p.getDimensions().ndimf);\n v.u = p.variables.d_u;\n v.quad = p.getQuadrature();\n end\n \n end\n \n methods (Access = private)\n \n function init(obj,cParams)\n obj.physicalProblem = cParams.physicalProblem;\n end\n \n end\n \n methods (Access = private, Static)\n \n function uM = splitDisplacement(u,nu)\n nnode = round(length(u)/nu);\n nodes = 1:nnode;\n uM = zeros(nnode,nu);\n for idim = 1:nu\n dofs = nu*(nodes-1)+idim;\n uM(:,idim) = u(dofs);\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/PostProcess/Printer/GiD/ResultsPrinter/CompositesPrinters/ShapePrinters/PdeVariableToPrintGetter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.34876783486490914}}
{"text": "function plot_time(catalogObject)\n %CATALOG.PLOT_TIME Plot magnitude and depth against time\n % catalogObject.plot_time()\n\n % Glenn Thompson 2014/06/01\n\n symsize = get_symsize(catalogObject); \n timerange = catalogObject.gettimerange();\n xlims = [floor(timerange(1)) ceil(timerange(2))];\n\n % time-depth\n if all(isnan(catalogObject.depth))\n warning('No depth data to plot');\n else\n figure;\n set(gcf,'Color', [1 1 1]);\n subplot(2,1,1);\n scatter(catalogObject.otime, catalogObject.depth, symsize);\n set(gca, 'XLim', xlims);\n datetick('x');\n xlabel('Date');\n ylabel('Depth (km)');\n set(gca, 'YDir', 'reverse');\n grid on;\n\n % time-mag\n subplot(2,1,2);\n end\n if all(isnan(catalogObject.mag))\n warning('No magnitude data to plot');\n else\n scatter(catalogObject.otime, catalogObject.mag, symsize);\n %stem(catalogObject.otime, catalogObject.mag);\n set(gca, 'XLim', xlims);\n datetick('x');\n xlabel('Date');\n ylabel('Magnitude');\n grid on;\n end\nend\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/@Catalog/plot_time.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.3487678266313717}}
{"text": "function [map,data] = PhaseMango(spikes,phases,varargin)\n\n%PhaseMango - Compute phase as a function of spike rate and acceleration.\n%\n% Compute spike phase as a function of spike rate and acceleration, as in\n% Harris et al. (2002). The name of the function refers to the aspect of\n% the resulting phase plot.\n%\n% USAGE\n%\n% [map,data] = PhaseMango(spikes,phases,)\n%\n% spikes spike timestamps\n% phases phase samples (see Phase)\n% optional list of property-value pairs (see table below)\n%\n% =========================================================================\n% Properties Values\n% -------------------------------------------------------------------------\n% 'smooth' smoothing size in bins (0 = no smoothing, default = 2)\n% 'nBins' number of horizontal and vertical bins (default = [50 50])\n% 'limits' [maxRate minAccel maxAccel] (default = [8 -2 2])\n% 'maxGap' time gaps between successive position samples exceeding\n% this threshold (e.g. undetects) will not be interpolated\n% (default = 100 ms)\n% 'boundaries' onset and offset for single-lap phase precession can be\n% determined either automatically based on spike count\n% ('count', default) or using explicit firing field\n% boundaries ([Xstart Xstop], where each X is in [0..1])\n% =========================================================================\n%\n% OUTPUT\n%\n% map.x x bins\n% map.y y bins\n% map.phase phase map\n% map.count count map\n%\n% data.rate spike rate for each cycle\n% data.acceleration spike acceleration for each cycle\n% data.phase mean spike phase (in radians) for each cycle\n%\n% SEE\n%\n% See also Phase, PhasePrecession, PlotPhaseMango.\n\n% Copyright (C) 2004-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\n% Default values\nmaxGap = 0.1;\nsmooth = 2;\nnBins = 50;\nlimits = [8 -2 2];\n\n% Check number of parameters\nif nargin < 2 | mod(length(varargin),2) ~= 0,\n error('Incorrect number of parameters (type ''help PhaseMango'' for details).');\nend\n\n% Check parameter sizes\nif ~isdvector(spikes),\n\terror('Parameter ''spikes'' is not a vector (type ''help PhaseMango'' for details).');\nend\nif size(phases,2) ~= 2,\n\terror('Parameter ''phases'' is not a Nx2 matrix (type ''help PhaseMango'' for details).');\nend\nisradians(phases(:,2));\n\n% Parse options\nfor i = 1:2:length(varargin),\n\tif ~ischar(varargin{i}),\n\t\terror(['Parameter ' num2str(i+2) ' is not a property (type ''help PhaseMango'' for details).']);\n\tend\n\tswitch(lower(varargin{i})),\n\t\tcase 'smooth',\n\t\t\tsmooth = varargin{i+1};\n\t\t\tif ~isdvector(smooth,'>=0') || length(smooth) > 2,\n\t\t\t\terror('Incorrect value for property ''smooth'' (type ''help PhaseMango'' for details).');\n\t\t\tend\n\t\tcase 'nbins',\n\t\t\tnBins = varargin{i+1};\n\t\t\tif ~isivector(nBins,'>0') || length(nBins) > 2,\n\t\t\t\terror('Incorrect value for property ''nBins'' (type ''help PhaseMango'' for details).');\n\t\t\tend\n\t\tcase 'limits',\n\t\t\tlimits = varargin{i+1};\n\t\t\tif ~isivector(limits,'#3') || limits(1) <0 || limits(3) < limits(2),\n\t\t\t\terror('Incorrect value for property ''limits'' (type ''help PhaseMango'' for details).');\n\t\t\tend\n\t\tcase 'maxgap',\n\t\t\tmaxGap = varargin{i+1};\n\t\t\tif ~isdscalar(maxGap,'>0'),\n\t\t\t\terror('Incorrect value for property ''maxGap'' (type ''help PhaseMango'' for details).');\n\t\t\tend\n\t\totherwise,\n\t\t\terror(['Unknown property ''' num2str(varargin{i}) ''' (type ''help PhaseMango'' for details).']);\n\tend\nend\n\n% Default values\ndata.time = [];\ndata.rate = [];\ndata.acceleration = [];\ndata.phase = [];\nmap.x = [];\nmap.y = [];\nmap.phase = [];\nmap.count = [];\n\n% Compute spike phases\nif isempty(spikes), return; end\nspikePhases = Interpolate(phases,spikes,'trim','off','type','circular');\nspikePhases = exp(j*spikePhases(:,2));\nif isempty(spikePhases), return; end\n\n% Determine theta cycles (start/stop)\nphases(:,2) = wrap(phases(:,2),1); % in [-pi,pi]\nstart = phases(ZeroCrossings(phases),1);\nstop = start(2:end);\nstart = start(1:end-1);\ndata.time = start;\n\n% Determine to which theta cycle each spike belongs\n[~,spikeCycles] = InIntervals(spikes,[start stop]);\npartialCycles = spikeCycles==0;\nspikeCycles(partialCycles) = [];\n\n% Compute number of spikes in each cycle\nnSpikes = Accumulate(spikeCycles,1,size(start));\n\n% Compute average phase in each cycle\nspikePhases(partialCycles) = [];\ndata.phase = angle(Accumulate(spikeCycles,spikePhases,size(start))./nSpikes);\n\nphase = Accumulate(spikeCycles,spikePhases,size(start))./nSpikes;\nphase(nSpikes==0) = 0;\nkernel = ones(7,1)/7;\ndata.phase = angle(conv(phase,kernel,'same'));\n\n% Estimate spike rate and acceleration in each cycle\n\n% Rate = average number of spikes over 7 surrounding cycles, which can be\n% efficiently computed as the convolution of nSpikes with the kernel (1/7,..,1/7)\nkernel = ones(7,1)/7;\ndata.rate = conv(nSpikes,kernel,'same');\n% Acceleration = slope of linear regression over 7 surrounding cycles\n% The general formula is b = (E[xy]-E[x]E[y]) / (E[x\u00b2]-E[x]\u00b2)\n% To compute this efficiently, we first note that the slope is unchanged\n% by translations along x the axis: we choose x in {-3..3}, so that E[x]=0.\n% We then compute E[x\u00b2] = 4, and end up with b = 1/4 E[xy], which can be\n% computed as the convolution of y with the kernel (3,2,1,0,-1,-2,-3)/7.\nkernel = (3:-1:-3)/7;\ndata.acceleration = conv(nSpikes,kernel,'same')/4;\n\n% Number of bins for x and y\nnBinsX = nBins(1);\nif length(nBins) == 1,\n\tnBinsY = nBinsX;\n\tnBins(2) = nBins;\nelse\n\tnBinsY = nBins(2);\nend\n\n% Min and max speed and acceleration\nxLims = [0 limits(1)];\nyLims = limits(2:3);\n\n% Bin rate and acceleration\nrate = Bin(data.rate,xLims,nBinsX);\nacceleration = Bin(data.acceleration,yLims,nBinsY);\n\n% Compute phase map\nmap.phase = angle(Smooth(Accumulate([rate acceleration],exp(j*data.phase),[nBinsX nBinsY]),smooth))';\nmap.count = Smooth(Accumulate([rate acceleration],1,[nBinsX nBinsY]),smooth)';\n\n% Bins\nmap.x = linspace(xLims(1),xLims(2),nBinsX);\nmap.y = linspace(yLims(1),yLims(2),nBinsY);\n\n\n% figure;\n% hold on;\n% PlotXY(phases);\n% PlotTicks(spikes,'size',1,'k');\n% plot(start,nSpikes,'b*');\n% plot(start,data.rate,'r*');\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/FMAToolbox/Analyses/PhaseMango.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3487603642072085}}
{"text": "function Psi0 = biasVardistPsi0Compute(biaskern, vardist)\n\n% BIASVARDISTPSI0COMPUTE one line description\n% FORMAT\n% DESC description\n% RETURN Psi0 : description\n% ARG biasKern : the kernel structure associated with the white kernel.\n% ARG vardist : description\n%\n%\n% SEEALSO : others\n%\n%\n% COPYRIGHT : Michalis K. Titsias, 2009\n%\n\n% VARGPLVM\n\nPsi0 = vardist.numData*biaskern.variance; \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/biasVardistPsi0Compute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3487603565866375}}
{"text": "function option = femoption(option)\n%% FEMOPTION provides default options for femPoisson\n%\n% option = femoption(option)\n%\n% - options.elemType: type of finite element\n% - options.maxIt \n% - options.maxN\n% - options.L0\n% - options.refType mesh refinement type \n% - options.printlevel\n% - options.plotflag\n% - options.rateflag\n% - options.dispflag\n% - options.tol\n% - options.lumpflag\n\n\nif ~isfield(option,'elemType')\n option.elemType = 'P1'; \nend\n\nif ~isfield(option,'maxIt')\n option.maxIt = 4; \nend\n\nif ~isfield(option,'maxN')\n option.maxN = 2e5; \nend\n\nif ~isfield(option,'L0')\n option.L0 = 0; \nend\n\nif ~isfield(option,'refType')\n option.refType = 'red';\nend\n\nif ~isfield(option,'printlevel')\n option.printlevel = 1; \nend\n\nif ~isfield(option,'plotflag')\n option.plotflag = 1; \nend\n\nif ~isfield(option,'rateflag')\n option.rateflag = 1; \nend\n\nif ~isfield(option,'dispflag')\n option.dispflag = 1; \nend\n\nif ~isfield(option,'tol')\n option.tol = 1e-8; \nend\n\nif ~isfield(option,'lumpflag') % mass lumping\n option.lumpflag = 0; % no mass lumping\nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/fem/femoption.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3487603565866375}}
{"text": "function make3plots(X1, Y1, Y2, Y3)\n%CREATEFIGURE1(X1,Y1,Y2,Y3)\n% X1: vector of x data\n% Y1: vector of y data\n% Y2: vector of y data\n% Y3: vector of y data\n\n% Auto-generated by MATLAB on 14-Feb-2007 22:38:36\n\n% Create figure\nfigure1 = figure;\n\n% Create subplot\nsubplot1 = subplot(3,1,1,'Parent',figure1,'YGrid','on','XGrid','on');\nbox('on');\nhold('all');\n\n% Create plot\nplot(X1,Y1,'Parent',subplot1,'LineWidth',2,'Color',[0 0 0]);\n\n% Create ylabel\nylabel('Plunge (in)','FontWeight','demi','FontSize',12);\n\n% Create title\ntitle('Closed-Loop Response','FontWeight','demi','FontSize',12);\n\n% Create subplot\nsubplot2 = subplot(3,1,2,'Parent',figure1,'YGrid','on','XGrid','on');\nbox('on');\nhold('all');\n\n% Create plot\nplot(X1,Y2,'Parent',subplot2,'LineWidth',2,'Color',[0 0 0]);\n\n% Create ylabel\nylabel('Pitch (deg)','FontWeight','demi','FontSize',12);\n\n% Create subplot\nsubplot3 = subplot(3,1,3,'Parent',figure1,'YGrid','on','XGrid','on');\nbox('on');\nhold('all');\n\n% Create plot\nplot(X1,Y3,'Parent',subplot3,'LineWidth',2,'Color',[0 0 0]);\n\n% Create xlabel\nxlabel('Time (s)','FontWeight','demi','FontSize',12);\n\n% Create ylabel\nylabel('TE Pos (deg)','FontWeight','demi','FontSize',12);\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/3938-flutter-analysis-model/make3plots.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.3487603565866375}}
{"text": "function exact = p06_exact ( )\n\n%*****************************************************************************80\n%\n%% P06_EXACT returns the exact integral for problem 6.\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 = 0.00056103711148387120640;\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/p06_exact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.3487603489660664}}
{"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 createfigure_returns(x,y1, y2, y3,tit,legend1,legend2,legend3)\n%CREATEFIGURE(X1,YMATRIX1)\n% x: vector of xvalue data\n% y1,y2,y3: vectors of densities yvalue data\n\n% Create figure\nfigure('PaperSize',[20.98 29.68],...\n 'Name',tit,'Color',[1 1 1]);\n\n% Create axes\nbox('on');\nhold('all');\n\nylow = min(min(y2),min(y3)); ylow = min(ylow,min(y1));\nyhigh = max(max(y2),max(y3)); yhigh = max(yhigh, max(y1));\n\n%ylow = -0.1;\n%yhigh = 0.1;\n\nsubplot(3,1,1); plot(x,y1, 'black','DisplayName',legend1); xlabel('Time'); ylabel('Return Value');ylim([ylow yhigh]);title(legend1);\nsubplot(3,1,2); plot(x,y2, 'black', 'DisplayName',legend2); xlabel('Time'); ylabel('Return Value');ylim([ylow yhigh]);title(legend2);\nsubplot(3,1,3); plot(x,y3, 'black', 'DisplayName',legend3); xlabel('Time'); ylabel('Return Value');ylim([ylow yhigh]);title(legend3);\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/37618-monte-carlo-simulation-and-derivatives-pricing/StandardMonteCarlo/createfigure_returns.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.3487603489660664}}
{"text": "% Image Reconstruction With Directional Sensors Example\n%\n% This example demonstrates how the directionality of sensor elements can\n% give rise to artefacts in time reversal photoacoustic image\n% reconstruction. It builds on the Sensor Element Directivity in 2D and 2D\n% Time Reversal Reconstruction For A Line Sensor examples.\n%\n% author: Bradley Treeby & Ben Cox\n% date: 18th 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\nPML_size = 20; % size of the PML in grid points\nNx = 128 - 2*PML_size; % number of grid points in the x (row) direction\nNy = 256 - 2*PML_size; % number of grid points in the y (column) direction\ndx = 0.1e-3; % grid point spacing in the x direction [m]\ndy = 0.1e-3; % grid point spacing in the y direction [m]\nkgrid = makeGrid(Nx, dx, Ny, dy);\n\n% define the properties of the propagation medium\nmedium.sound_speed = 1500;\t% [m/s]\n\n% create initial pressure distribution using makeDisc\ndisc_magnitude = 5; % [au]\ndisc_x_pos = 60; % [grid points]\ndisc_y_pos = 140; \t% [grid points]\ndisc_radius = 5; % [grid points]\ndisc_2 = disc_magnitude*makeDisc(Nx, Ny, disc_x_pos, disc_y_pos, disc_radius);\n\ndisc_x_pos = 30; % [grid points]\ndisc_y_pos = 110; \t% [grid points]\ndisc_radius = 8; % [grid points]\ndisc_1 = disc_magnitude*makeDisc(Nx, Ny, disc_x_pos, disc_y_pos, disc_radius);\n\n% smooth the initial pressure distribution and restore the magnitude\np0 = smooth(kgrid, disc_1 + disc_2, true);\n\n% assign to the source structure\nsource.p0 = p0;\n\n% define a four-sided, square sensor\nsensor.mask = zeros(kgrid.Nx, kgrid.Ny);\nsensor.mask(1, :) = 1;\nsensor.mask(end, :) = 1;\nsensor.mask(:, 1) = 1;\nsensor.mask(:, end) = 1;\n\n% create the time array\n[kgrid.t_array, dt] = makeTime(kgrid, medium.sound_speed);\n\n% set the input arguements\ninput_args = {'PMLInside', false, 'PMLSize', PML_size, 'PlotPML', false, 'Smooth', false};\n\n% run the simulation for omnidirectional detector elements\nsensor_data = kspaceFirstOrder2D(kgrid, medium, source, sensor, input_args{:});\n\n% define the directionality of the sensor elements\nsensor.directivity_angle = zeros(kgrid.Nx, kgrid.Ny);\nsensor.directivity_angle(1, :) = 0; \t % max sensitivity in x direction\nsensor.directivity_angle(end, :) = 0; \t % max sensitivity in x direction\nsensor.directivity_angle(:, 1) = pi/2; % max sensitivity in y direction\nsensor.directivity_angle(:, end) = pi/2; % max sensitivity in y direction\n\n% define the directivity size\nsensor.directivity_size = 20*kgrid.dx;\n\n% run the simulation with directional elements\nsensor_data_directional = kspaceFirstOrder2D(kgrid, medium, source, sensor, input_args{:});\n\n% reset the initial pressure\nsource.p0 = 0;\n\n% assign the time reversal data for the omnidirectional case\nsensor.time_reversal_boundary_data = sensor_data;\n\n% run the time reversal reconstruction\np0_recon = kspaceFirstOrder2D(kgrid, medium, source, sensor, input_args{:});\n\n% assign the time reversal data for the directional case\nsensor.time_reversal_boundary_data = sensor_data_directional;\n\n% run the time reversal reconstruction with directional elements\np0_recon_directional = kspaceFirstOrder2D(kgrid, medium, source, sensor, input_args{:});\n\n% =========================================================================\n% VISUALISATION\n% =========================================================================\n\n% plot the initial pressure and sensor distribution\nfigure;\nimagesc(kgrid.y_vec*1e3, kgrid.x_vec*1e3, p0 + sensor.mask*disc_magnitude, [-disc_magnitude disc_magnitude]);\ncolormap(getColorMap);\nylabel('x-position [mm]');\nxlabel('y-position [mm]');\naxis image;\ncolorbar;\n\n% plot the reconstructed initial pressure \nfigure;\nimagesc(kgrid.y_vec*1e3, kgrid.x_vec*1e3, p0_recon, [-disc_magnitude disc_magnitude]);\ncolormap(getColorMap);\nylabel('x-position [mm]');\nxlabel('y-position [mm]');\naxis image;\ncolorbar;\n\n% plot the reconstructed initial pressure with directivity\nfigure;\nimagesc(kgrid.y_vec*1e3, kgrid.x_vec*1e3, p0_recon_directional, [-disc_magnitude disc_magnitude]);\ncolormap(getColorMap);\nylabel('x-position [mm]');\nxlabel('y-position [mm]');\naxis image;\ncolorbar;\n\n% plot a profile for comparison\nfigure;\nplot(kgrid.y_vec*1e3, p0(disc_x_pos, :), 'k-',...\n kgrid.y_vec*1e3, p0_recon(disc_x_pos, :), 'r--',...\n kgrid.y_vec*1e3, p0_recon_directional(disc_x_pos, :), 'b:');\nxlabel('y-position [mm]');\nylabel('Pressure');\nlegend('True', 'Omnidirectional','Directional');\naxis tight;\nset(gca, 'YLim', [0 5.1]);\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/K-wave/k-Wave/examples/example_pr_2D_TR_directional_sensors.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784220301064, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.34860324839554585}}
{"text": "function nc2010_plot_compexperiment(flatW, datatype, convergence)\n\nn = 200;\nm = 50;\nd = 10;\n\nmodel = 'vbpca';\nif flatW\n stringW = 'flatW';\nelse\n stringW = 'hierW';\nend\n\n% SELECT THE SEED\nseed = 4132\ndatasets = 10\n% Initialise variables\nnorottime = zeros(m,datasets);\nnorotloglike = zeros(m,datasets);\nrottime = zeros(m,datasets);\nrotloglike = zeros(m,datasets);\nfor ncomps = 1:m\n for ind = 1:datasets\n rotstring = 'rotate=0';\n norotfilename = sprintf(['/home/jluttine/matlab/neurocomputing2010/' ...\n 'nc2010_%s_compexperiment_%s_subspace=%s_n=%d_m=' ...\n '%d_d=%d_ncomps=%d_%s_seed=%d_datasetindex=%d.mat'], ...\n model,stringW,datatype,n,m,d, ncomps, rotstring, ...\n seed, ind);\n\n rotstring = 'rotate=1';\n rotfilename = sprintf(['/home/jluttine/matlab/neurocomputing2010/' ...\n 'nc2010_%s_compexperiment_%s_subspace=%s_n=%d_m=' ...\n '%d_d=%d_ncomps=%d_%s_seed=%d_datasetindex=%d.mat'], ...\n model,stringW,datatype,n,m,d, ncomps, rotstring, ...\n seed, ind);\n norot = load(norotfilename, 'duration', 'cost', 'rmse', 'rmse_test');\n rot = load(rotfilename, 'duration', 'cost', 'rmse', 'rmse_test');\n %plot_results(norot, rot,ncomps);\n \n % Find the point of convergence\n switch 2\n case 1 % by relative change in loglikelihood\n len = length(norot.cost);\n dcost = diff(norot.cost);\n dstep = abs(dcost ./ norot.cost(1:(len-1)));\n norotind = find(dstep < convergence, 1, 'first');\n len = length(rot.cost);\n dcost = diff(rot.cost);\n dstep = abs(dcost ./ rot.cost(1:(len-1)));\n rotind = find(dstep < convergence, 1, 'first');\n case 2 % being inside a threshold compared to converged loglikelihood\n convind = find(~isnan(norot.cost), 1, 'last');\n dif = abs((norot.cost - norot.cost(convind))/norot.cost(convind));\n norotind = find(dif < convergence, 1, 'first');\n convind = find(~isnan(rot.cost), 1, 'last');\n dif = abs((rot.cost - rot.cost(convind))/rot.cost(convind));\n rotind = find(dif < convergence, 1, 'first');\n end\n \n \n % norotind = find(~isnan(norot.cost), 1, 'last');\n % rotind = find(~isnan(rot.cost), 1, 'last');\n norottime(ncomps,ind) = norot.duration(norotind);\n norotloglike(ncomps,ind) = norot.cost(norotind);\n rottime(ncomps,ind) = rot.duration(rotind);\n rotloglike(ncomps,ind) = rot.cost(rotind);\n end\nend\n\nfigure\nnorotmedian = prctile(norottime,50,2);\nnorot90 = prctile(norottime,100,2);\nnorot10 = prctile(norottime,0,2);\n%norotmean = mean(norottime,2);\n%rotmean = mean(rottime,2);\nrotmedian = prctile(rottime,50,2);\nrot90 = prctile(rottime,100,2);\nrot10 = prctile(rottime,0,2);\nsemilogy(1:ncomps, norotmedian(:), 'r-');\nhold on\nx = [1:ncomps, ncomps:-1:1]';\ny = [rot10(:); rot90(end:-1:1)];\nc = [0.75 0.75 0.75];\nfill(x,y,c,'EdgeColor',c);\n%patch(x,y, [0.6 0.6 0.6]); \n% $$$ semilogy(1:ncomps, rot90(:), 'k:', 'linewidth', 1);\n% $$$ semilogy(1:ncomps, rot10(:), 'k:', 'linewidth', 1);\nsemilogy(1:ncomps, norotmedian(:), 'r-');\nsemilogy(1:ncomps, norot90(:), 'r-');\nsemilogy(1:ncomps, norot10(:), 'r-');\nsemilogy(1:ncomps, rotmedian(:), 'k:', 'linewidth', 2);\n%semilogy(1:ncomps, rot90(:), 'k:', 'linewidth', 1);\n%semilogy(1:ncomps, rot10(:), 'k:', 'linewidth', 1);\n%[norotloglike(:) - rotloglike(:)];\nxlabel('number of components, D')\nylabel('time (seconds)')\nxlim([1 m]);\n\nreturn \n\n% $$$ \n% $$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% $$$ function plot_results(norot, rot,ncomps)\n% $$$ \n% $$$ % $$$ norot.cost(norot.cost==-inf) = -1e10;\n% $$$ % $$$ rot.cost(rot.cost==-inf) = -1e10;\n% $$$ %suffix = sprintf(' (n=%d m=%d d=%d ncomps=%d)',n,m,d,ncomps);\n% $$$ \n% $$$ figure\n% $$$ subplot(1,3,1)\n% $$$ semilogx([norot.duration(:), rot.duration(:)], -[norot.cost(:), rot.cost(:)])\n% $$$ %title(['Negative loglikelihood', suffix]);\n% $$$ %filename = sprintf('fig_cost_n=%d_m=%d_d=%d_ncomps=%d', n,m,d,ncomps);\n% $$$ % $$$ set(gcf, 'units', 'centimeters', 'paperunits', 'centimeters');\n% $$$ % $$$ pos = get(gcf, 'position');\n% $$$ % $$$ set(gcf, 'position', [pos(1:2), 8,8]);\n% $$$ % $$$ pos = get(gcf, 'paperposition');\n% $$$ % $$$ set(gcf, 'paperposition', [pos(1:2),8,8])\n% $$$ \n% $$$ %figure\n% $$$ subplot(1,3,2)\n% $$$ semilogx([norot.duration(:), rot.duration(:)], [norot.rmse(:), rot.rmse(:)])\n% $$$ % $$$ %title(['Training set RMSE', suffix]);\n% $$$ % $$$ %filename = sprintf('fig_rmse_n=%d_m=%d_d=%d_ncomps=%d', n,m,d,ncomps);\n% $$$ % $$$ set(gcf, 'units', 'centimeters', 'paperunits', 'centimeters');\n% $$$ % $$$ pos = get(gcf, 'position');\n% $$$ % $$$ set(gcf, 'position', [pos(1:2), 8,8]);\n% $$$ % $$$ pos = get(gcf, 'paperposition');\n% $$$ % $$$ set(gcf, 'paperposition', [pos(1:2),8,8])\n% $$$ \n% $$$ \n% $$$ %figure\n% $$$ subplot(1,3,3)\n% $$$ semilogx([norot.duration(:), rot.duration(:)], [norot.rmse_test(:), rot.rmse_test(:)])\n% $$$ % $$$ %title(['Test set RMSE', suffix]);\n% $$$ % $$$ %filename = sprintf('fig_rmsetest_n=%d_m=%d_d=%d_ncomps=%d', n,m,d,ncomps);\n% $$$ % $$$ set(gcf, 'units', 'centimeters', 'paperunits', 'centimeters');\n% $$$ % $$$ pos = get(gcf, 'position');\n% $$$ % $$$ set(gcf, 'position', [pos(1:2), 8,8]);\n% $$$ % $$$ pos = get(gcf, 'paperposition');\n% $$$ % $$$ set(gcf, 'paperposition', [pos(1:2),8,8])\n% $$$ \n% $$$ ", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/publications/neurocomputing2010/nc2010_plot_compexperiment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.34860323953727723}}
{"text": "function gpcf = gpcf_squared(varargin)\n%GPCF_SQUARED Create a squared (dot product) covariance function\n%\n% Description\n% GPCF = GPCF_SQUARED('PARAM1',VALUE1,'PARAM2,VALUE2,...) creates\n% a squared (dot product) covariance function structure in which\n% the named parameters have the specified values. Any unspecified\n% parameters are set to default values. The squared covariance function\n% corresponds to x.^2 mean function and the respective covariance matrix\n% is given as C = x.^2*diag(gpcf.coeffSigma2)*(x'.^2);\n%\n% GPCF = GPCF_SQUARED(GPCF,'PARAM1',VALUE1,'PARAM2,VALUE2,...) \n% modify a covariance function structure with the named\n% parameters altered with the specified values.\n% \n% Parameters for squared (dot product) covariance function\n% interactions - twoway interactions (default off)\n% coeffSigma2 - prior variance for regressor coefficients [10]\n% This can be either scalar corresponding\n% to a common prior variance or vector\n% defining own prior variance for each\n% coefficient.\n% coeffSigma2_prior - prior structure for coeffSigma2 [prior_logunif]\n% selectedVariables - vector defining which inputs are used [all]\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% See also\n% GP_SET, GPCF_*, PRIOR_*, MEAN_*\n%\n% Copyright (c) 2007-2016 Jarno Vanhatalo\n% Copyright (c) 2008-2010 Jaakko Riihim\u00e4ki\n% Copyright (c) 2010 Aki Vehtari\n% Copyright (c) 2014 Arno Solin\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 = 'GPCF_SQUARED';\n ip.addOptional('gpcf', [], @isstruct);\n ip.addParamValue('interactions', 'off', @(x) ismember(x,{'on' 'off'}))\n ip.addParamValue('coeffSigma2',10, @(x) isvector(x) && all(x>0));\n ip.addParamValue('coeffSigma2_prior',prior_logunif, @(x) isstruct(x) || isempty(x));\n ip.addParamValue('selectedVariables',[], @(x) isvector(x) && all(x>0));\n ip.parse(varargin{:});\n gpcf=ip.Results.gpcf;\n\n if isempty(gpcf)\n init=true;\n gpcf.type = 'gpcf_squared';\n else\n if ~isfield(gpcf,'type') && ~isequal(gpcf.type,'gpcf_squared')\n error('First argument does not seem to be a valid covariance function structure')\n end\n init=false;\n end\n \n if init || ~ismember('interactions',ip.UsingDefaults)\n gpcf.interactions=ip.Results.interactions;\n end\n \n % Initialize parameter\n if init || ~ismember('coeffSigma2',ip.UsingDefaults)\n gpcf.coeffSigma2=ip.Results.coeffSigma2;\n end\n\n % Initialize prior structure\n if init\n gpcf.p=[];\n end\n if init || ~ismember('coeffSigma2_prior',ip.UsingDefaults)\n gpcf.p.coeffSigma2=ip.Results.coeffSigma2_prior;\n end\n if ~ismember('selectedVariables',ip.UsingDefaults)\n selectedVariables=ip.Results.selectedVariables;\n if ~isempty(selectedVariables)\n gpcf.selectedVariables = selectedVariables;\n end\n end\n \n if init\n % Set the function handles to the subfunctions\n gpcf.fh.pak = @gpcf_squared_pak;\n gpcf.fh.unpak = @gpcf_squared_unpak;\n gpcf.fh.lp = @gpcf_squared_lp;\n gpcf.fh.lpg = @gpcf_squared_lpg;\n gpcf.fh.cfg = @gpcf_squared_cfg;\n gpcf.fh.cfdg = @gpcf_squared_cfdg;\n gpcf.fh.cfdg2 = @gpcf_squared_cfdg2;\n gpcf.fh.ginput = @gpcf_squared_ginput;\n gpcf.fh.ginput2 = @gpcf_squared_ginput2;\n gpcf.fh.ginput3 = @gpcf_squared_ginput3;\n gpcf.fh.ginput4 = @gpcf_squared_ginput4;\n gpcf.fh.cov = @gpcf_squared_cov;\n gpcf.fh.trcov = @gpcf_squared_trcov;\n gpcf.fh.trvar = @gpcf_squared_trvar;\n gpcf.fh.recappend = @gpcf_squared_recappend;\n gpcf.fh.cf2ss = @gpcf_squared_cf2ss;\n end \n\nend\n\nfunction [w, s, h] = gpcf_squared_pak(gpcf, w)\n%GPCF_squared_PAK Combine GP covariance function parameters into one vector\n%\n% Description\n% W = GPCF_squared_PAK(GPCF) takes a covariance function\n% structure GPCF and combines the covariance function\n% parameters and their hyperparameters into a single row\n% vector W. This is a mandatory subfunction used for \n% example in energy and gradient computations.\n%\n% w = [ log(gpcf.coeffSigma2)\n% (hyperparameters of gpcf.coeffSigma2)]'\n%\n% See also\n% GPCF_squared_UNPAK\n \n w = []; s = {}; h =[];\n if ~isempty(gpcf.p.coeffSigma2)\n w = log(gpcf.coeffSigma2);\n if numel(gpcf.coeffSigma2)>1\n s = [s; sprintf('log(squared.coeffSigma2 x %d)',numel(gpcf.coeffSigma2))];\n else\n s = [s; 'log(squared.coeffSigma2)'];\n end\n h = [h ones(1, numel(gpcf.coeffSigma2))];\n % Hyperparameters of coeffSigma2\n [wh, sh, hh] = gpcf.p.coeffSigma2.fh.pak(gpcf.p.coeffSigma2);\n sh=strcat(repmat('prior-', size(sh,1),1),sh);\n w = [w wh];\n s = [s; sh];\n h = [h 1+hh];\n end\nend\n\nfunction [gpcf, w] = gpcf_squared_unpak(gpcf, w)\n%GPCF_squared_UNPAK Sets the covariance function parameters \n% into the structure\n%\n% Description\n% [GPCF, W] = GPCF_squared_UNPAK(GPCF, W) takes a covariance\n% function structure GPCF and a hyper-parameter vector W, and\n% returns a covariance function structure identical to the\n% input, except that the covariance hyper-parameters have been\n% set to the values in W. Deletes the values set to GPCF from\n% W and returns the modified W. This is a mandatory subfunction \n% used for example in energy and gradient computations.\n%\n% Assignment is inverse of \n% w = [ log(gpcf.coeffSigma2)\n% (hyperparameters of gpcf.coeffSigma2)]'\n%\n% See also\n% GPCF_squared_PAK\n \n gpp=gpcf.p;\n\n if ~isempty(gpp.coeffSigma2)\n i2=length(gpcf.coeffSigma2);\n i1=1;\n gpcf.coeffSigma2 = exp(w(i1:i2));\n w = w(i2+1:end);\n \n % Hyperparameters of coeffSigma2\n [p, w] = gpcf.p.coeffSigma2.fh.unpak(gpcf.p.coeffSigma2, w);\n gpcf.p.coeffSigma2 = p;\n end\nend\n\nfunction lp = gpcf_squared_lp(gpcf)\n%GPCF_squared_LP Evaluate the log prior of covariance function parameters\n%\n% Description\n% LP = GPCF_squared_LP(GPCF) takes a covariance function\n% structure GPCF and returns log(p(th)), where th collects the\n% parameters. This is a mandatory subfunction used for example \n% in energy computations.\n%\n% See also\n% GPCF_squared_PAK, GPCF_squared_UNPAK, GPCF_squared_LPG, GP_E\n\n% Evaluate the prior contribution to the error. The parameters that\n% are sampled are from space W = log(w) where w is all the \"real\" samples.\n% On the other hand errors are evaluated in the W-space so we need take\n% into account also the Jacobian of transformation W -> w = exp(W).\n% See Gelman et al. (2013), Bayesian Data Analysis, third edition, p. 21.\n lp = 0;\n gpp=gpcf.p;\n\n if ~isempty(gpp.coeffSigma2)\n lp = gpp.coeffSigma2.fh.lp(gpcf.coeffSigma2, gpp.coeffSigma2) + sum(log(gpcf.coeffSigma2));\n end\nend\n\nfunction lpg = gpcf_squared_lpg(gpcf)\n%GPCF_squared_LPG Evaluate gradient of the log prior with respect\n% to the parameters.\n%\n% Description\n% LPG = GPCF_squared_LPG(GPCF) takes a covariance function\n% structure GPCF and returns LPG = d log (p(th))/dth, where th\n% is the vector of parameters. This is a mandatory subfunction \n% used for example in gradient computations.\n%\n% See also\n% GPCF_squared_PAK, GPCF_SQUARED_UNPAK, GPCF_SQUARED_LP, GP_G\n\n lpg = [];\n gpp=gpcf.p;\n \n if ~isempty(gpcf.p.coeffSigma2) \n lll=length(gpcf.coeffSigma2);\n lpgs = gpp.coeffSigma2.fh.lpg(gpcf.coeffSigma2, gpp.coeffSigma2);\n lpg = [lpg lpgs(1:lll).*gpcf.coeffSigma2+1 lpgs(lll+1:end)];\n end\nend\n\nfunction DKff = gpcf_squared_cfg(gpcf, x, x2, mask, i1)\n%GPCF_SQUARED_CFG Evaluate gradient of covariance function\n% with respect to the parameters\n%\n% Description\n% DKff = GPCF_SQUARED_CFG(GPCF, X) takes a covariance function\n% structure GPCF, a matrix X of input vectors and returns\n% DKff, the gradients of covariance matrix Kff = k(X,X) with\n% respect to th (cell array with matrix elements). This is a \n% mandatory subfunction used in gradient computations.\n%\n% DKff = GPCF_SQUARED_CFG(GPCF, X, X2) takes a covariance\n% function structure GPCF, a matrix X of input vectors and\n% returns DKff, the gradients of covariance matrix Kff =\n% k(X,X2) with respect to th (cell array with matrix\n% elements). This subfunction is needed when using sparse \n% approximations (e.g. FIC).\n%\n% DKff = GPCF_SQUARED_CFG(GPCF, X, [], MASK) takes a covariance\n% function structure GPCF, a matrix X of input vectors and\n% returns DKff, the diagonal of gradients of covariance matrix\n% Kff = k(X,X2) with respect to th (cell array with matrix\n% elements). This subfunction is needed when using sparse \n% approximations (e.g. FIC).\n%\n% DKff = GPCF_SQUARED_CFG(GPCF,X,X2,MASK,i) takes a covariance \n% function structure GPCF, a matrix X of input vectors and \n% returns DKff, the gradient of covariance matrix Kff = \n% k(X,X2), or k(X,X) if X2 is empty, with respect to ith \n% hyperparameter. This subfunction is needed when using\n% memory save option in gp_set.\n%\n% See also\n% GPCF_SQUARED_PAK, GPCF_SQUARED_UNPAK, GPCF_SQUARED_LP, GP_G\n\n if nargin>2 && ~isempty(x2)\n if size(x,2) ~= size(x2,2)\n error('gpcf_squared -> _cfg: the number of columns of X1 and X2 has to be same')\n end\n end\n\n if isfield(gpcf, 'selectedVariables')\n x = x(:,gpcf.selectedVariables);\n end\n [n, m] =size(x);\n h = x.^2;\n if isequal(gpcf.interactions,'on')\n for xi1=1:m\n for xi2=xi1+1:m\n h = [h x(:,xi1).*x(:,xi2)];\n end\n end\n end\n \n DKff = {};\n \n if nargin==5\n % Use memory save option\n savememory=1;\n if i1==0\n % Return number of hyperparameters\n DKff=0;\n if ~isempty(gpcf.p.coeffSigma2)\n DKff=length(gpcf.coeffSigma2);\n end\n return\n end\n else\n savememory=0;\n end\n \n % Evaluate: DKff{1} = d Kff / d coeffSigma2\n % NOTE! Here we have already taken into account that the parameters are transformed\n % through log() and thus dK/dlog(p) = p * dK/dp\n\n \n % evaluate the gradient for training covariance\n if nargin == 2 || (isempty(x2) && isempty(mask))\n \n if ~isempty(gpcf.p.coeffSigma2)\n if length(gpcf.coeffSigma2) == 1\n DKff{1}=gpcf.coeffSigma2*h*(h');\n else\n if isa(gpcf.coeffSigma2,'single')\n epsi=eps('single');\n else\n epsi=eps;\n end\n if ~savememory\n i1=1:length(gpcf.coeffSigma2);\n end\n DKff=cell(1,length(i1));\n for ii1=i1\n DD = gpcf.coeffSigma2(ii1)*h(:,ii1)*(h(:,ii1)');\n DD(abs(DD)<=epsi) = 0;\n DKff{ii1}= (DD+DD')./2;\n end\n end\n end\n \n \n % Evaluate the gradient of non-symmetric covariance (e.g. K_fu)\n elseif nargin == 3 || isempty(mask)\n \n error('this part of the subfunction has not been tested')\n \n if isfield(gpcf, 'selectedVariables')\n x2 = x2(:,gpcf.selectedVariables);\n end\n h2 = x2.^2;\n if isequal(gpcf.interactions,'on')\n for xi1=1:m\n for xi2=xi1+1:m\n h2 = [h2 x2(:,xi1).*x2(:,xi2)];\n end\n end\n end\n \n if ~isempty(gpcf.p.coeffSigma2)\n if length(gpcf.coeffSigma2) == 1\n DKff{1}=gpcf.coeffSigma2*h*(h2');\n else\n if ~savememory\n i1=1:m;\n end\n for ii1=i1\n DKff{ii1}=gpcf.coeffSigma2(ii1)*h(:,ii1)*(h2(:,ii1)');\n end\n end\n end\n % Evaluate: DKff{1} = d mask(Kff,I) / d coeffSigma2\n % DKff{2...} = d mask(Kff,I) / d coeffSigma2\n elseif nargin == 4 || nargin == 5\n \n error('this part of the subfunction has not been tested')\n \n if ~isempty(gpcf.p.coeffSigma2)\n if length(gpcf.coeffSigma2) == 1\n DKff{1}=gpcf.coeffSigma2*sum(h.^2,2); % d mask(Kff,I) / d coeffSigma2\n else\n if ~savememory\n i1=1:m;\n end\n for ii1=i1\n DKff{ii1}=gpcf.coeffSigma2(ii1)*(h(:,ii1).^2); % d mask(Kff,I) / d coeffSigma2\n end\n end\n end\n end\n if savememory\n DKff=DKff{i1};\n end\nend\n\nfunction DKff = gpcf_squared_cfdg(gpcf, x, x2, dims)\n%GPCF_SQUARED_CFDG Evaluate gradient of covariance function, of\n% which has been taken partial derivative with\n% respect to x, with respect to parameters.\n%\n% Description\n% DKff = GPCF_SQUARED_CFDG(GPCF, X) takes a covariance function\n% structure GPCF, a matrix X of input vectors and returns\n% DKff, the gradients of derivatived covariance matrix\n% dK(df,f)/dhyp = d(d k(X,X)/dx)/dhyp, with respect to the\n% parameters\n%\n% Evaluate: DKff{1:m} = d Kff / d coeffSigma2\n% m is the dimension of inputs. This subfunction is needed when using\n% derivative observations.\n%\n% Note! When coding the derivatives of the covariance function, remember\n% to double check them. See gp_cov for lines of code to check the\n% matrices\n%\n% See also\n% GPCF_SQUARED_GINPUT\n\n[~,m]=size(x);\nif nargin<3\n x2=x;\nend\nif nargin < 4 || isempty(dims)\n dims = 1:m;\nend\nii1=0;\nDKff={};\nif isfield(gpcf,'selectedVariables')\n selVars = gpcf.selectedVariables;\nelse\n selVars = 1:m;\nend\nc = gpcf.coeffSigma2;\n\nh = x.^2;\nh2 = x2.^2;\n\nii1=0;\nDKff={};\nif ~isempty(gpcf.p.coeffSigma2)\n if length(gpcf.coeffSigma2)==1\n % One coeffSigma2\n for i1=dims\n if isfield(gpcf, 'selectedVariables') && sum(gpcf.selectedVariables==i1)==0\n DK{i1}=zeros(size(x,1),size(x2,1));\n else\n DK{i1}=c(1).*2*x(:,i1)*h2(:,i1)';\n if isequal(gpcf.interactions,'on')\n for xi2=selVars\n if xi2~=i1\n DK{i1} = DK{i1} + c(1)*x(:,xi2)*(x2(:,i1).*x2(:,xi2))';\n end\n end\n end\n end\n end\n ii1=ii1+1;\n DKff{ii1}=cat(1,DK{1:end});\n else\n % vector of coeffSigma2s\n for i1=1:length(selVars)\n for j=dims\n if selVars(i1)~=j %|| (isfield(gpcf, 'selectedVariables') && sum(gpcf.selectedVariables==i1)==0)\n DK{j}=zeros(size(x,1),size(x2,1));\n else\n DK{j}=c(i1).*2*x(:,j)*h2(:,j)';\n end\n end\n ii1=ii1+1;\n DKff{ii1}=cat(1,DK{1:end});\n end\n if isequal(gpcf.interactions,'on')\n for xi1=1:length(selVars)\n for xi2=xi1+1:length(selVars)\n i1=i1+1;\n for j=dims\n if j==xi1 \n DK{j} = c(i1)*x(:,xi2)*(x2(:,xi1).*x2(:,xi2))';\n elseif j==xi2\n DK{j} = c(i1)*x(:,xi1)*(x2(:,xi1).*x2(:,xi2))';\n else\n DK{j}=zeros(size(x,1),size(x2,1));\n end\n end\n ii1=ii1+1;\n DKff{ii1}=cat(1,DK{1:end});\n end\n end\n end\n end\nend\n\nend\n\nfunction DKff = gpcf_squared_cfdg2(gpcf, x, x2, dims1, dims2)\n%GPCF_SQUARED_CFDG2 Evaluate gradient of covariance function, of which has\n% been taken partial derivatives with respect to both\n% input variables x, with respect to parameters.\n%\n% Description\n% DKff = GPCF_SQUARED_CFDG2(GPCF, X) takes a covariance\n% function structure GPCF, a matrix X of input vectors and\n% returns DKff, the gradients of derivative covariance matrix\n% dK(df,df)/dhyp = d(d^2 k(X1,X2)/dX1dX2)/dhyp with respect to\n% the parameters\n%\n% Evaluate: DKff{1:m} = d K(df,df) / d coeffSigma\n% m is the dimension of inputs. This subfunction is needed when using\n% derivative observations.\n%\n% Note! When coding the derivatives of the covariance function, remember\n% to double check them. See gp_cov for lines of code to check the\n% matrices\n%\n% See also\n% GPCF_SQUARED_GINPUT, GPCF_SQUARED_GINPUT2\n\n\n[~, m] =size(x);\nif nargin <3 || isempty(x2)\n x2=x;\nend\nif nargin < 4 || isempty(dims1)\n %dims1 = 1:m;\n error('dims1 needs to be given')\nend\nif nargin < 5 || isempty(dims2)\n %dims2 = 1:m;\n error('dims2 needs to be given')\nend\nif isfield(gpcf,'selectedVariables')\n selVars = gpcf.selectedVariables;\nelse\n selVars = 1:m;\nend\n% NOTICE. AS OF NOW we assume that dims1 and dims2 are scalars\n\nii1=0;\nif length(gpcf.coeffSigma2)==1\n c=repmat(gpcf.coeffSigma2,1,(1+length(selVars))*length(selVars)/2);\nelse\n c=gpcf.coeffSigma2;\nend\nif length(gpcf.coeffSigma2)==1\n % One coeffSigma2\n if dims1~=dims2 %|| (isfield(gpcf, 'selectedVariables') && (sum(gpcf.selectedVariables==j)==0 || sum(gpcf.selectedVariables==k)==0))\n DK=zeros(size(x,1),size(x2,1));\n if isequal(gpcf.interactions,'on') && (sum(selVars==dims1)>0 || sum(selVars==dims2)>0)\n DK = c(1)*x(:,dims1)*x2(:,dims2)';\n end\n else\n if sum(selVars==dims1)==0\n DK=zeros(size(x,1),size(x2,1));\n else\n DK=c(1).*4.*x(:,dims1)*x2(:,dims2)';\n end\n if isequal(gpcf.interactions,'on') && sum(selVars==dims1)>0\n for xi2=selVars\n if xi2~=dims1\n DK = DK + c(1)*x(:,xi2)*x2(:,xi2)';\n end\n end\n end\n end\n ii1=ii1+1;\n DKff{ii1}=DK;\nelse\n % vector of coeffSigma2s\n for i1=1:length(selVars)\n if dims1~=dims2 || dims2~=selVars(i1)\n DK=zeros(size(x,1),size(x2,1));\n else\n DK=c(i1).*4.*x(:,dims1)*x2(:,dims2)';\n end\n ii1=ii1+1;\n DKff{ii1}=DK;\n end\n if isequal(gpcf.interactions,'on')\n for xi1=1:length(selVars)\n for xi2=xi1+1:length(selVars)\n i1=i1+1;\n %if k==xi1 && j==xi2\n if dims1==xi1 && dims2==xi2\n DK = c(i1)*x(:,xi2)*x2(:,xi1)';\n %elseif k==xi2 && j==xi1\n elseif dims1==xi2 && dims2==xi1\n DK = c(i1)*x(:,xi1)*x2(:,xi2)';\n %elseif k==j && k==xi1\n elseif dims1==dims2 && dims1==xi1 \n DK = c(i1)*x(:,xi2)*x2(:,xi2)';\n %elseif k==j && k==xi2\n elseif dims1==dims2 && dims1==xi2\n DK = c(i1)*x(:,xi1)*x2(:,xi1)';\n else\n DK=zeros(size(x,1),size(x2,1));\n end\n ii1=ii1+1;\n DKff{ii1}=DK;\n end\n end\n end\nend\n\nend\n\n\nfunction DKff = gpcf_squared_ginput(gpcf, x, x2, i1)\n%GPCF_SQUARED_GINPUT Evaluate gradient of covariance function with \n% respect to x.\n%\n% Description\n% DKff = GPCF_SQUARED_GINPUT(GPCF, X, X2) takes a covariance function\n% structure GPCF, a matrix X of input vectors and returns DKff, the\n% gradients of covariance matrix Kff = k(X,X2) with respect to X (cell\n% array with matrix elements). If called with only two inputs\n% GPCF_SQUARED_GINPUT(GPCF, X), X2=X. This subfunction is needed when\n% computing gradients with respect to inducing inputs in sparse\n% approximations. \n%\n% DKff = GPCF_SQUARED_GINPUT(GPCF, X, X2, i) takes a covariance\n% function structure GPCF, a matrix X of input vectors and\n% returns DKff, the gradients of covariance matrix Kff =\n% k(X,X2) with respect to ith covariate in X (matrix).\n% This subfunction is needed when using memory save option\n% in gp_set.\n%\n% Note! When coding the derivatives of the covariance function, remember\n% to double check them. See gp_cov for lines of code to check the\n% matrices\n%\n% See also\n% GPCF_SQUARED_PAK, GPCF_SQUARED_UNPAK, GPCF_SQUARED_LP, GP_G \n \nif isfield(gpcf, 'selectedVariables') \n error('The selectedVariables option has not yet been implemented for gpcf_squared with derivobs=''on'' ')\n % notice, some parts of the code already take into account the\n % selectedVariables but the code has not been checked\nend\n\n[n, m] =size(x);\n\nif nargin==4\n % Use memory save option\n savememory=1;\n if i1==0\n % Return number of covariates\n DKff=m;\n return\n end\nelse\n savememory=0;\nend\n\nif nargin == 2 || isempty(x2)\n \n xx = x.^2;\n if length(gpcf.coeffSigma2)==1\n s=gpcf.coeffSigma2.*ones(1,(1+m)*m/2);\n else\n s=gpcf.coeffSigma2;\n end\n ii1 = 0;\n if nargin<4\n i1=1:m;\n end\n for j = 1:n\n for i=i1\n DK = zeros(n);\n DK(j,:)=2*s(i)*x(j,i)*xx(:,i)';\n if isequal(gpcf.interactions,'on')\n for xi2=i1\n if xi2~=i\n DK(j,:) = DK(j,:) + s(i)*x(j,xi2).*(x(:,i).*x(:,xi2))';\n end\n end\n end\n DK = DK + DK';\n ii1 = ii1 + 1;\n DKff{ii1} = DK;\n end\n end\n \nelseif nargin == 3 || nargin == 4\n \n xx2 = x2.^2;\n if length(gpcf.coeffSigma2)==1\n s=gpcf.coeffSigma2.*ones(1,(1+m)*m/2);\n else\n s=gpcf.coeffSigma2;\n end\n ii1 = 0;\n if ~savememory\n i1=1:m;\n end\n for j = 1:n\n for i=i1\n DK = zeros(n, size(x2,1));\n DK(j,:)=2*s(i)*x(j,i)*xx2(:,i)';\n if isequal(gpcf.interactions,'on')\n for xi2=i1\n if xi2~=i\n DK(j,:) = DK(j,:) + s(i)*x(j,xi2).*(x2(:,i).*x2(:,xi2))';\n end\n end\n end\n ii1 = ii1 + 1;\n DKff{ii1} = DK;\n end\n end\nend\n\nend\n\nfunction DKff = gpcf_squared_ginput2(gpcf, x, x2, dims,takeOnlyDiag)\n%GPCF_SQUARED_GINPUT2 Evaluate gradient of covariance function with\n% respect to both input variables x and x2 in\n% same dimension.\n%\n% Description\n% DKff = GPCF_SQUARED_GINPUT2(GPCF, X, X2) takes a covariance\n% function structure GPCF, a matrix X of input vectors and\n% returns DKff, the gradients of twice derivatived covariance\n% matrix K(df,df) = dk(X1,X2)/dX1dX2 (cell array with matrix\n% elements). Input variable's dimensions are expected to be\n% same. This subfunction is needed when using derivative \n% observations.\n% \n% Note! When coding the derivatives of the covariance function, remember\n% to double check them. See gp_cov for lines of code to check the\n% matrices\n%\n% See also\n% GPCF_SQUARED_GINPUT, GPCF_SQUARED_GINPUT2, GPCF_SQUARED_CFDG2 \n\n[~,m]=size(x);\nii1=0;\nif nargin<4 || isempty(dims)\n dims=1:m;\nend\nif length(gpcf.coeffSigma2)==1\n c=repmat(gpcf.coeffSigma2,1,(1+m)*m/2);\nelse\n c=gpcf.coeffSigma2;\nend\nif isfield(gpcf, 'selectedVariables')\n sv = gpcf.selectedVariables;\nelse \n sv = 1:m;\nend\n\nif nargin==5 && isequal(takeOnlyDiag,'takeOnlyDiag')\n for i1=dims\n if ~any(sv==i1)%isfield(gpcf, 'selectedVariables') && sum(gpcf.selectedVariables==i1)==0\n DK=zeros(size(x,1),1);\n else\n DK=c(i1).*4.*(x(:,i1).*x2(:,i1));\n if isequal(gpcf.interactions,'on')\n i2=length(sv);\n for xi1=1:length(sv)\n for xi2=xi1+1:length(sv)\n if any(sv==xi1) && any(sv==xi2)\n i2=i2+1;\n if i1==xi1\n DK = DK + c(i2)*x(:,xi2).*x2(:,xi2);\n elseif i1==xi2\n DK = DK + c(i2)*x(:,xi1).*x2(:,xi1);\n end\n end\n end\n end\n end\n end\n ii1=ii1+1;\n DKff{ii1}=DK;\n end\nelse\n for i1=dims\n if ~any(sv==i1)%isfield(gpcf, 'selectedVariables') && sum(gpcf.selectedVariables==i1)==0\n DK=zeros(size(x,1),size(x2,1));\n else\n DK=c(i1).*4.*(x(:,i1)*x2(:,i1)');\n if isequal(gpcf.interactions,'on')\n i2=length(sv);\n for xi1=1:length(sv)\n for xi2=xi1+1:length(sv)\n if any(sv==xi1) && any(sv==xi2)\n i2=i2+1;\n if i1==xi1\n DK = DK + c(i2)*x(:,xi2)*x2(:,xi2)';\n elseif i1==xi2\n DK = DK + c(i2)*x(:,xi1)*x2(:,xi1)';\n end\n end\n end\n end\n end\n end\n ii1=ii1+1;\n DKff{ii1}=DK;\n end\nend\nend\n\nfunction DKff = gpcf_squared_ginput3(gpcf, x, x2, dims1, dims2)\n%GPCF_SQUARED_GINPUT3 Evaluate gradient of covariance function with\n% respect to both input variables x and x2 (in\n% different dimensions).\n%\n% Description\n% DKff = GPCF_SQUARED_GINPUT3(GPCF, X, X2) takes a covariance\n% function structure GPCF, a matrix X of input vectors and\n% returns DKff, the gradients of twice derivatived covariance\n% matrix K(df,df) = dk(X1,X2)/dX1dX2 (cell array with matrix\n% elements). The derivative is calculated in multidimensional\n% problem between input's observation dimensions which are not\n% same. This subfunction is needed when using derivative \n% observations.\n%\n% DKff is a cell array with the following elements:\n% DKff{1} = dk(X1,X2)/dX1_1dX2_2\n% DKff{2} = dk(X1,X2)/dX1_1dX2_3\n% ... \n% DKff{m-1} = dk(X1,X2)/dX1_1dX2_m\n% DKff{m} = dk(X1,X2)/dX1_2dX2_3\n% ...\n% DKff{m} = dk(X1,X2)/dX1_(m-1)dX2_m\n% where _m denotes the input dimension with respect to which the\n% gradient is calculated.\n%\n% Note! When coding the derivatives of the covariance function, remember\n% to double check them. See gp_cov for lines of code to check the\n% matrices\n% \n% See also\n% GPCF_SQUARED_GINPUT, GPCF_SQUARED_GINPUT2, GPCF_SQUARED_CFDG2 \n\n\n[~,m]=size(x);\nif nargin < 3\n error('Needs at least 3 input arguments')\nend\nif nargin<4 || isempty(dims1)\n dims1=1:m;\nend\nif nargin<5 || isempty(dims2)\n dims2=1:m;\nend\nif isfield(gpcf, 'selectedVariables')\n sv = gpcf.selectedVariables;\nelse \n sv = 1:m;\nend\n\nii1=0;\nif length(gpcf.coeffSigma2)==1\n c=repmat(gpcf.coeffSigma2,1,(1+m)*m/2);\nelse\n c=gpcf.coeffSigma2;\nend\nDK=zeros(size(x,1),size(x2,1));\ni2=m;\nfor i=dims1\n for j=dims2\n ii1=ii1+1;\n if isequal(gpcf.interactions,'on') && any(sv==i) && any(sv==j)\n i2 = min(i,j)*length(sv) - 0.5*min(i,j)*(min(i,j)-1) + max(i,j)-min(i,j);\n DKff{ii1} = c(i2)*x(:,j)*x2(:,i)';\n else\n DKff{ii1}=DK;\n end\n end\nend\n\n% i2=m;\n% for i=1:m-1\n% for j=i+1:m\n% i2=i2+1;\n% if any(dims1==i) && any(dims2==j)\n% ii1=ii1+1;\n% if isequal(gpcf.interactions,'on') && any(sv==i) && any(sv==j)\n% % if isequal(gpcf.interactions,'on') &&...\n% % ~(isfield(gpcf, 'selectedVariables') && (sum(gpcf.selectedVariables==i)==0 || sum(gpcf.selectedVariables==j)==0))\n% DKff{ii1} = c(i2)*x(:,j)*x2(:,i)';\n% else\n% DKff{ii1}=DK;\n% end\n% end\n% end\n% end\n\nend\n\nfunction DKff = gpcf_squared_ginput4(gpcf, x, x2, dims)\n%GPCF_SQUARED_GINPUT Evaluate gradient of covariance function with respect\n% to x. Simplified and faster version of squared_ginput,\n% returns full matrices. \n%\n% Description\n% DKff = GPCF_SQUARED_GINPUT4(GPCF, X, X2) takes a covariance function\n% structure GPCF, matrices X and X2 of input vectors and returns DKff,\n% the gradients of covariance matrix Kff = k(X,X2) with respect to X\n% (whole matrix); that is d k(X,X2)/dX. If called with only two inputs\n% GPCF_SQUARED_GINPUT4(GPCF, X), X2=X.\n%\n% This subfunction is needed when using derivative observations. \n%\n% Note! When coding the derivatives of the covariance function, remember\n% to double check them. See gp_cov for lines of code to check the\n% matrices\n%\n% See also\n% GPCF_SQUARED_PAK, GPCF_SQUARED_UNPAK, GPCF_SQUARED_LP, GP_G\n\n\n% if isfield(gpcf, 'selectedVariables') \n% error('The selectedVariables option has not yet been implemented for gpcf_squared with derivobs=''on'' ')\n% % notice, some parts of the code already take into account the\n% % selectedVariables but the code has not been checked\n% end\n% \n% if isfield(gpcf, 'selectedVariables')\n% m = length(gpcf.selectedVariables);\n% sv = gpcf.selectedVariables;\n% else \n% [~,m]=size(x);\n% sv = 1:m;\n% end\n% if nargin==2\n% x2=x;\n% end\n% if nargin<4\n% dims=1:size(x,2);\n% end\n% if length(gpcf.coeffSigma2)==1 \n% c=repmat(gpcf.coeffSigma2,1,(1+m)*m/2);\n% else\n% % If coeffSigma is vector, we trust it is of rigth length\n% c=gpcf.coeffSigma2;\n% end\n% h2=x2.^2;\n% ii1=0;\n% for i=dims\n% if ~any(sv==i) %isfield(gpcf, 'selectedVariables') && sum(gpcf.selectedVariables==i)==0\n% DK=zeros(size(x,1),size(x2,1));\n% else\n% DK=c(i).*2.*x(:,i)*h2(:,i)';\n% if isequal(gpcf.interactions,'on')\n% i2=m;\n% for xi1=sv\n% sv2 = sv(sv>xi1);\n% for xi2=sv2 %xi1+1:m\n% i2 = i2+1;\n% if i==xi1\n% DK = DK + c(i2)*x(:,xi2)*(x2(:,i).*x2(:,xi2))';\n% elseif i==xi2\n% DK = DK + c(i2)*x(:,xi1)*(x2(:,i).*x2(:,xi1))';\n% end\n% end\n% end\n% end\n% end\n% ii1=ii1+1;\n% DKff{ii1}=DK;\n% end\n\n[n,m]=size(x);\nif nargin<4\n dims=1:m;\nend\nif isfield(gpcf, 'selectedVariables')\n sv = gpcf.selectedVariables;\nelse \n sv = 1:m;\nend\nii1=0;\nif nargin==2\n x2=x;\nend\nh2=x2.^2;\nif length(gpcf.coeffSigma2)==1\n c=repmat(gpcf.coeffSigma2,1,(1+m)*m/2);\nelse\n c=gpcf.coeffSigma2;\nend\nfor i=dims\n if ~any(sv==i) % isfield(gpcf, 'selectedVariables') && sum(gpcf.selectedVariables==i)==0\n DK=zeros(size(x,1),size(x2,1));\n else\n DK=c(i).*2.*x(:,i)*h2(:,i)';\n if isequal(gpcf.interactions,'on')\n i2=length(sv);\n for xi1=1:length(sv)\n for xi2=xi1+1:length(sv)\n if any(sv==xi1) && any(sv==xi2)\n i2=i2+1;\n% i2 = min(i,j)*length(sv) - 0.5*min(i,j)*(min(i,j)-1) + max(i,j)-min(i,j)\n if i==xi1\n DK = DK + c(i2)*x(:,xi2)*(x2(:,i).*x2(:,xi2))';\n elseif i==xi2\n DK = DK + c(i2)*x(:,xi1)*(x2(:,i).*x2(:,xi1))';\n end\n end\n end\n end\n end\n end\n ii1=ii1+1;\n DKff{ii1}=DK;\nend\nend\n\nfunction C = gpcf_squared_cov(gpcf, x1, x2, varargin)\n%GP_SQUARED_COV Evaluate covariance matrix between two input vectors\n%\n% Description \n% C = GP_SQUARED_COV(GP, TX, X) takes in covariance function of\n% a Gaussian process GP and two matrixes TX and X that contain\n% input vectors to GP. Returns covariance matrix C. Every\n% element ij of C contains covariance between inputs i in TX\n% and j in X. This is a mandatory subfunction used for example in\n% prediction and energy computations.\n%\n% See also\n% GPCF_SQUARED_TRCOV, GPCF_SQUARED_TRVAR, GP_COV, GP_TRCOV\n \n if isempty(x2)\n x2=x1;\n end\n [n1,m1]=size(x1);\n [n2,m2]=size(x2);\n if m1~=m2\n error('the number of columns of X1 and X2 has to be same')\n end\n if isfield(gpcf, 'selectedVariables')\n x1 = x1(:,gpcf.selectedVariables);\n x2 = x2(:,gpcf.selectedVariables);\n end\n h1 = x1.^2;\n h2 = x2.^2;\n if isequal(gpcf.interactions,'on')\n m=size(x1,2);\n for xi1=1:m\n for xi2=xi1+1:m\n h1 = [h1 x1(:,xi1).*x1(:,xi2)];\n h2 = [h2 x2(:,xi1).*x2(:,xi2)];\n end\n end\n end\n C = h1*diag(gpcf.coeffSigma2)*(h2');\n C(abs(C)<=eps) = 0;\n \nend\n\nfunction C = gpcf_squared_trcov(gpcf, x)\n%GP_SQUARED_TRCOV Evaluate training covariance matrix of inputs\n%\n% Description\n% C = GP_SQUARED_TRCOV(GP, TX) takes in covariance function of\n% a Gaussian process GP and matrix TX that contains training\n% input vectors. Returns covariance matrix C. Every element ij\n% of C contains covariance between inputs i and j in TX. This \n% is a mandatory subfunction used for example in prediction and \n% energy computations.\n%\n% See also\n% GPCF_SQUARED_COV, GPCF_SQUARED_TRVAR, GP_COV, GP_TRCOV\n\n \n if isfield(gpcf, 'selectedVariables')\n x = x(:,gpcf.selectedVariables);\n end\n h = x.^2;\n if isequal(gpcf.interactions,'on')\n m=size(x,2);\n for xi1=1:m\n for xi2=xi1+1:m\n h = [h x(:,xi1).*x(:,xi2)];\n end\n end\n end\n C = h*diag(gpcf.coeffSigma2)*(h');\n C(abs(C)<=eps) = 0;\n C = (C+C')./2;\n \nend\n\n\nfunction C = gpcf_squared_trvar(gpcf, x)\n%GP_SQUARED_TRVAR Evaluate training variance vector\n%\n% Description\n% C = GP_SQUARED_TRVAR(GPCF, TX) takes in covariance function\n% of a Gaussian process GPCF 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 is a mandatory \n% subfunction used for example in prediction and energy computations.\n%\n%\n% See also\n% GPCF_SQUARED_COV, GP_COV, GP_TRCOV\n\n \n if isfield(gpcf, 'selectedVariables')\n x = x(:,gpcf.selectedVariables);\n end\n h = x.^2;\n if isequal(gpcf.interactions,'on')\n m=size(x,2);\n for xi1=1:m\n for xi2=xi1+1:m\n h = [h x(:,xi1).*x(:,xi2)];\n end\n end\n end\n if length(gpcf.coeffSigma2) == 1\n C=gpcf.coeffSigma2.*sum(h.^2,2);\n else\n C=sum(repmat(gpcf.coeffSigma2, size(x,1), 1).*h.^2,2);\n end\n C(abs(C) RECAPPEND\n\n if nargin == 2\n % Initialize the record\n reccf.type = 'gpcf_squared';\n \n % Initialize parameters\n reccf.coeffSigma2= [];\n\n % Set the function handles\n reccf.fh.pak = @gpcf_squared_pak;\n reccf.fh.unpak = @gpcf_squared_unpak;\n reccf.fh.lp = @gpcf_squared_lp;\n reccf.fh.lpg = @gpcf_squared_lpg;\n reccf.fh.cfg = @gpcf_squared_cfg;\n reccf.fh.cfdg = @gpcf_squared_cfdg;\n reccf.fh.cfdg2 = @gpcf_squared_cfdg2;\n reccf.fh.ginput = @gpcf_squared_ginput;\n reccf.fh.ginput2 = @gpcf_squared_ginput2;\n reccf.fh.ginput3 = @gpcf_squared_ginput3;\n reccf.fh.ginput4 = @gpcf_squared_ginput4;\n reccf.fh.cov = @gpcf_squared_cov;\n reccf.fh.trcov = @gpcf_squared_trcov;\n reccf.fh.trvar = @gpcf_squared_trvar;\n reccf.fh.recappend = @gpcf_squared_recappend;\n reccf.p=[];\n reccf.p.coeffSigma2=[];\n if ~isempty(ri.p.coeffSigma2)\n reccf.p.coeffSigma2 = ri.p.coeffSigma2;\n end\n\n else\n % Append to the record\n gpp = gpcf.p;\n \n reccf.interactions = gpcf.interactions;\n \n % record coeffSigma2\n reccf.coeffSigma2(ri,:)=gpcf.coeffSigma2;\n if isfield(gpp,'coeffSigma2') && ~isempty(gpp.coeffSigma2)\n reccf.p.coeffSigma2 = gpp.coeffSigma2.fh.recappend(reccf.p.coeffSigma2, ri, gpcf.p.coeffSigma2);\n end\n \n if isfield(gpcf, 'selectedVariables')\n reccf.selectedVariables = gpcf.selectedVariables;\n end\n end\nend\n\nfunction [F,L,Qc,H,Pinf,dF,dQc,dPinf,params] = gpcf_squared_cf2ss(gpcf,x)\n%GPCF_SQUARED_CF2SS Convert the covariance function to state space form\n%\n% Description\n% Convert the covariance function to state space form such that\n% the process can be described by the stochastic differential equation\n% of the form:\n% df(t)/dt = F f(t) + L w(t),\n% where w(t) is a white noise process. The observation model now \n% corresponds to y_k = H f(t_k) + r_k, where r_k ~ N(0,sigma2).\n%\n%\n\n % Check arguments\n if nargin < 2 || isempty(x), x = 0; end\n\n % Scaling\n x0 = min(x);\n \n % Define the model\n F = [0 1; 0 0]; \n L = [0; 1]; \n Qc = 0; \n H = [1 0];\n Pinf = [x0^2 x0; x0 1]*gpcf.coeffSigma2;\n dF = zeros(2,2,1);\n dQc = zeros(1,1,1);\n dPinf = [x0^2 x0; x0 1];\n params = {};\n\n % Set params\n params.stationary = false;\n \n % Check which parameters are optimized\n if isempty(gpcf.p.coeffSigma2), ind(1) = false; else ind(1) = true; end\n \n % Return only those derivatives that are needed\n dF = dF(:,:,ind);\n dQc = dQc(:,:,ind);\n dPinf = dPinf(:,:,ind);\n \nend", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/gp/gpcf_squared.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3486032395372771}}
{"text": "% loadtxt() - load ascii text file into numeric or cell arrays\n%\n% Usage:\n% >> array = loadtxt( filename, 'key', 'val' ...);\n%\n% Inputs:\n% filename - name of the input file\n%\n% Optional inputs\n% 'skipline' - number of lines to skip {default:0}. If this number is\n% negative the program will only skip non-empty lines \n% (can be usefull for files transmitted from one platform\n% to an other, as CR may be inserted at every lines).\n% 'convert' - 'on' standard text conversion, see note 1\n% 'off' no conversion, considers text only\n% 'force' force conversion, NaN are returned \n% for non-numeric inputs {default:'on'}\n% 'delim' - ascii character for delimiters. {default:[9 32]\n% i.e space and tab}. It is also possible to enter \n% strings, Ex: [9 ' ' ','].\n% 'blankcell' - ['on'|'off'] extract blank cells {default:'on'}\n% 'verbose' - ['on'|'off'] {default:'on'}\n% 'convertmethod' - ['str2double'|'str2num'] default is 'str2double'\n% 'nlines' - [integer] number of lines to read {default: all file}\n%\n% Outputs:\n% array - cell array. If the option 'force' is given, the function\n% retrun a numeric array.\n%\n% Notes: 1) Since it uses cell arrays, the function can handle text input.\n% The function reads each token and then try to convert it to a \n% number. If the conversion is unsucessfull, the string itself\n% is included in the array.\n% 2) The function adds empty entries for rows that contains\n% fewer columns than others.\n%\n% Author: Arnaud Delorme, CNL / Salk Institute, 29 March 2002\n\n% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 29 March 2002\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 array = loadtxt( filename, varargin );\n\nif nargin < 1\n\thelp loadtxt;\n\treturn;\nend;\t\nif ~isempty(varargin)\n try, g = struct(varargin{:});\n catch, disp('Wrong syntax in function arguments'); return; end;\nelse\n g = [];\nend;\n\ng = finputcheck( varargin, { 'convert' 'string' { 'on';'off';'force' } 'on';\n 'skipline' 'integer' [0 Inf] 0;\n 'verbose' 'string' { 'on';'off' } 'on';\n 'uniformdelim' 'string' { 'on';'off' } 'off'; \n 'blankcell' 'string' { 'on';'off' } 'on';\n 'convertmethod' 'string' { 'str2double';'str2num' } 'str2double';\n 'delim' { 'integer';'string' } [] [9 32];\n 'nlines' 'integer' [] Inf });\nif isstr(g), error(g); end;\nif strcmpi(g.blankcell, 'off'), g.uniformdelim = 'on'; end;\ng.convert = lower(g.convert);\ng.verbose = lower(g.verbose);\ng.delim = char(g.delim);\n\n% open the file\n% -------------\nif exist(filename) ~=2, error( ['file ' filename ' not found'] ); end; \nfid=fopen(filename,'r','ieee-le');\nif fid<0, error( ['file ' filename ' found but error while opening file'] ); end; \n\nindex = 0;\nwhile index < abs(g.skipline)\n tmpline = fgetl(fid); \n if g.skipline > 0 | ~isempty(tmpline)\n index = index + 1;\n end; \nend; % skip lines ---------\n\ninputline = fgetl(fid);\nlinenb = 1;\nif strcmp(g.verbose, 'on'), fprintf('Reading file (lines): '); end;\nwhile isempty(inputline) | inputline~=-1\n colnb = 1;\n if ~isempty(inputline)\n tabFirstpos = 1;\n \n % convert all delimiter to the first one\n if strcmpi(g.uniformdelim, 'on')\n for index = 2:length(g.delim)\n inputline(find(inputline == g.delim(index))) = g.delim(1);\n end;\n end;\n \n while ~isempty(deblank(inputline))\n if strcmpi(g.blankcell,'off'), inputline = strtrim(inputline); end;\n if tabFirstpos && length(inputline) > 1 && all(inputline(1) ~= g.delim), tabFirstpos = 0; end;\n [tmp inputline tabFirstpos] = mystrtok(inputline, g.delim, tabFirstpos);\n switch g.convert\n case 'off', array{linenb, colnb} = tmp;\n case 'on', \n if strcmpi(g.convertmethod, 'str2double')\n tmp2 = str2double(tmp);\n if isnan( tmp2 ) , array{linenb, colnb} = tmp;\n else array{linenb, colnb} = tmp2;\n end;\n else\n tmp2 = str2num(tmp);\n if isempty( tmp2 ) , array{linenb, colnb} = tmp;\n else array{linenb, colnb} = tmp2;\n end;\n end;\n case 'force', array{linenb, colnb} = str2double(tmp);\n end;\n colnb = colnb+1;\n end;\n\t linenb = linenb +1;\n end;\n inputline = fgetl(fid);\n if linenb > g.nlines\n inputline = -1;\n end;\n if ~mod(linenb,10) & strcmp(g.verbose, 'on'), fprintf('%d ', linenb); end;\nend; \nif strcmp(g.verbose, 'on'), fprintf('%d\\n', linenb-1); end;\nif strcmp(g.convert, 'force'), array = [ array{:} ]; end;\nfclose(fid); \n\n% problem strtok do not consider tabulation\n% -----------------------------------------\nfunction [str, strout, tabFirstpos] = mystrtok(strin, delim, tabFirstpos);\n % remove extra spaces at the beginning\n while any(strin(1) == delim) && strin(1) ~= 9 && strin(1) ~= ','\n strin = strin(2:end);\n end;\n % for tab and coma, consider empty cells\n if length(strin) > 1 && any(strin(1) == delim)\n if tabFirstpos || any(strin(2) == delim)\n str = '';\n strout = strin(2:end);\n if strin(2) ~= 9 && strin(2) ~= ','\n tabFirstpos = 0;\n strout = strtrim(strout);\n end;\n else\n [str, strout] = strtok(strin, delim);\n end;\n else\n [str, strout] = strtok(strin, delim);\n 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/eeglab14_0_0b/functions/sigprocfunc/loadtxt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.3486032395372771}}
{"text": "function [ output_meta ] = meta2sicd_s1noise( domnode, meta_product )\n%META2SICD_S1NOISE Converts Sentinel-1 noise XML file into SICD format\n%\n% Written by: Wade Schwartzkopf, NGA Research\n%\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED ///\n% //////////////////////////////////////////\n\n% Setup\nxp=javax.xml.xpath.XPathFactory.newInstance.newXPath();\n\n% Compute the first line of each burst in overall TIFF file\nfirst_line = zeros(numel(meta_product),1);\nfor i = 1:(numel(meta_product)-1)\n first_line(i+1) = first_line(i) + meta_product{i}.ImageData.NumCols;\nend\n% Read noise parameters from XML\nn_str = 'noise';\nnum_noise_vecs=str2double(xp.evaluate(...\n ['count(noise/' n_str 'VectorList/' n_str 'Vector)'],domnode));\nif num_noise_vecs == 0 % Data after March 2018 had different format\n n_str = 'noiseRange';\n num_noise_vecs=str2double(xp.evaluate(...\n ['count(noise/' n_str 'VectorList/' n_str 'Vector)'],domnode));\nend\nnoisevals = cell(num_noise_vecs,1);\npixel = cell(num_noise_vecs,1);\nnoise_line = zeros(num_noise_vecs,1);\nfor i = 1:num_noise_vecs\n noise_line(i) = str2double(xp.evaluate(...\n ['noise/' n_str 'VectorList/' n_str 'Vector[' num2str(i) ']/line'],...\n domnode));\n pixel{i} = str2num(xp.evaluate(...\n ['noise/' n_str 'VectorList/' n_str 'Vector[' num2str(i) ']/pixel'],...\n domnode));\n noisevals{i} = str2num(xp.evaluate(...\n ['noise/' n_str 'VectorList/' n_str 'Vector[' num2str(i) ']/' n_str 'Lut'],...\n domnode));\nend\nmode = char(xp.evaluate('noise/adsHeader/mode',domnode));\nfit_tolerance = 0.1; % Simple 1D data for IW should fit quite tightly\nnoisepoly_order = 6; % For IW, this fits quite tightly\nif upper(mode(1))=='S'\n % Average all of the noise values across azimuth for a single 1D\n % polynomial that varies in range. They are roughly similar. A\n % precise solution would include a 2D fit.\n pixel = {cell2mat(pixel)};\n noisevals = {cell2mat(noisevals)};\n noise_line = 0;\n % Allow for more slop for SM since we have 2D noise values, but aren't\n % doing a full 2D fit. Because we average across all azimuth, there is\n % no reason to attempt a tight fit, since it won't match across all\n % lines for any fit.\n fit_tolerance = 0.5;\n noisepoly_order = 3;\n% Double check our assumptions about the noise data\nelseif any(mod(noise_line(1:(end-1)), ...\n double(meta_product{1}.ImageData.NumCols))~=0)\n warning('META2SICD_S1NOISE:UNEXPECTED_LINE','Expected noise values at beginning of each burst.');\n return;\nend\n% Compute SICD noise polynomials\noutput_meta = cell(numel(meta_product),1);\nfor i = 1:numel(meta_product) % First and last are usually outside bursts\n % Which noise values should we use for this burst? We use the ones\n % that correspond to the first column of the burst.\n line_ind = find(noise_line>=first_line(i) & ...\n noise_line<(first_line(i)+meta_product{i}.ImageData.NumCols),1);\n if isempty(line_ind), continue, end\n coords_rg_m = (double(0:(meta_product{i}.ImageData.NumRows-1)) - ...\n double(meta_product{i}.ImageData.SCPPixel.Row)) * ...\n meta_product{i}.Grid.Row.SS;\n coords_rg_m = coords_rg_m(pixel{line_ind}(:)+1);\n old_state = warning('off','MATLAB:polyfit:RepeatedPointsOrRescale');\n noisepoly = polyfit(coords_rg_m(:), 10*log10(noisevals{line_ind}(:)), noisepoly_order);\n warning(old_state);\n if any(polyval(noisepoly, coords_rg_m(:)) - ...\n 10*log10(noisevals{line_ind}(:)) > fit_tolerance)\n warning('META2SICD_S1NOISE:NOISE_TOLERANCE', ...\n 'Noise model does not appear to fit data tightly.'); \n end\n % These are typically very close across all bursts, but we compute for\n % each bursts independently anyway.\n output_meta{i}.Radiometric.NoiseLevel.NoiseLevelType = 'ABSOLUTE';\n output_meta{i}.Radiometric.NoiseLevel.NoisePoly = noisepoly(end:-1:1).';\nend\n% Throw warning for old, potentially inaccurate data\nlast_az_time = xp.evaluate(...\n ['noise/' n_str 'VectorList/' n_str 'Vector[' num2str(num_noise_vecs) ']/azimuthTime'],...\n domnode);\nif datenum(char(last_az_time),'yyyy-mm-ddTHH:MM:SS')\n P = inv(V); \n filters = [filters V(:,[1:args.patterns end-args.patterns+1:end])];\n patterns = [patterns P([1:args.patterns end-args.patterns+1:end],:)'];\n end\n model = struct('filters',{filters},'patterns',{patterns},'time_args',{time_args},'freq_args',{freq_args},'chanlocs',{args.signal.chanlocs});\n end\n \n function features = feature_extract(self,signal,featuremodel)\n W = length(featuremodel.freq_args);\n F = size(featuremodel.filters,2);\n T = size(signal.data,3);\n features = zeros(T,F);\n for w = 1:W\n % filter data in time & frequency\n data = exp_eval_optimized(flt_spectrum('signal',flt_window('signal',signal,featuremodel.time_args{w}),featuremodel.freq_args{w}));\n inds = (w-1)*(F/W)+(1:(F/W));\n for t=1:T\n features(t,inds) = log(var(data.data(:,:,t)' * featuremodel.filters(:,inds))); end\n end\n end\n \n function visualize_model(self,varargin) %#ok<*INUSD>\n args = arg_define([0 3],varargin, ...\n arg_norep({'myparent','Parent'},[],[],'Parent figure.'), ...\n arg_norep({'featuremodel','FeatureModel'},[],[],'Feature model. This is the part of the model that describes the feature extraction.'), ...\n arg_norep({'predictivemodel','PredictiveModel'},[],[],'Predictive model. This is the part of the model that describes the predictive mapping.'), ...\n arg({'patterns','PlotPatterns'},true,[],'Plot patterns instead of filters. Whether to plot spatial patterns (forward projections) rather than spatial filters.'), ...\n arg({'weight_scaled','WeightScaled'},false,[],'Scaled by weight. Whether to scale the patterns by weight.'));\n arg_toworkspace(args);\n \n % find the relevant components\n scores = predictivemodel.model.w;\n scores = sqrt(abs(scores));\n % optionally remove the bias if included in w\n if length(scores) == size(featuremodel.patterns,2)+1\n scores = scores(1:end-1); end \n % frequency labels\n % titles = repmat({'delta','theta','alpha','beta','gamma'},8,1); titles = titles(:);\n % extract relevant patterns\n patterns = featuremodel.patterns(:,find(scores)); %#ok\n filters = featuremodel.filters(:,find(scores)); %#ok\n % plot them\n if args.weight_scaled\n if args.patterns\n topoplot_grid(patterns,featuremodel.chanlocs,'scales',scores(find(scores))/max(scores)*1);\n else\n topoplot_grid(filters,featuremodel.chanlocs,'scales',scores(find(scores))/max(scores)*1);\n end\n else\n if args.patterns\n topoplot_grid(patterns,featuremodel.chanlocs);\n else\n topoplot_grid(filters,featuremodel.chanlocs);\n end\n end\n % figure;\n end\n \n function layout = dialog_layout_defaults(self)\n % define the default configuration dialog layout\n layout = {'SignalProcessing.Resampling.SamplingRate', 'SignalProcessing.EpochExtraction', '', ...\n 'Prediction.FeatureExtraction.FreqWindows', 'Prediction.FeatureExtraction.TimeWindows', ...\n 'Prediction.FeatureExtraction.WindowFunction', '', 'Prediction.FeatureExtraction.PatternPairs', '', ...\n 'Prediction.MachineLearning.Learner'};\n end\n \n function tf = needs_voting(self)\n tf = true;\n end\n end\nend\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/code/paradigms/ParadigmFBCSP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.34853896456110484}}
{"text": "%% Copyright (C) 2011-2012 by Jun He, Laura Balzano, and Arthur Szlam\n% \n% This file is part of the GRASTA library.\n% It is provided without any warranty of fitness\n% for any purpose. You can redistribute this file\n% and/or modify it under the terms of the GNU\n% Lesser General Public License (LGPL) as published\n% by the Free Software Foundation, either version 3\n% of the License or (at your option) any later version.\n% (see http://www.opensource.org/licenses for more info)\n\nfunction [ Unew, STATUSnew, OPTSnew ] = grasta_stream( y_Omega, idx, U0, STATUS,OPTIONS, OPTS)\n% grasta_stream is the streaming version of GRASTA which can be used for\n% online data processing\n%\n% [1] Jun He, Laura Balzano, and John C.S. Lui. Online Robust Subspace Tracking from Partial Information\n% http://arxiv.org/abs/1109.3827\n% [2] Jun He, Laura Balzano, and Arthur Szlam. Incremental gradient on the grassmannian for online foreground \n% and background separation in subsampled video. In IEEE Conference on Computer Vision and Pattern Recognition \n% (CVPR), June 2012.\n%\n% Usage:\n% [ Unew, STATUSnew, OPTSnew ] = grasta_stream( y_Omega, idx, U0, STATUS, OPTIONS, OPTS)\n% Inputs:\n% y_Omega: current partial observation of a full data vector\n% idx: the observed indices of y_Omega\n% U0: the current estimated subspace\n% STATUS: the current status of GRASTA\n% last_mu: \\mu_{t-1} for adaptive step rule\n% step_scale: the estimated step_scale constant for adaptive\n% step-size rule\n% lelve: the current level of the \"Multi-Level\" adaptive rule\n% last_gamma and last_w: previous gradient = last_gamma*last_w'\n%\n% OPTIONS: the options of GRASTA \n% CONSTANT_STEP: default 0, will use multi-level step-size rule; > 0 will\n% use constant step-size rule\n% DIM_M : the ambient dimension\n% RANK : the estimated low-rank of the underlying system\n% rho : ADMM constant step \n% ITER_MAX: the max_iter for ADMM solver\n% TOL : the stopping tolerance of admm_srp / mex_srp\n%\n% OPTS: the current options for the subproblem of GRASTA\n% refer to mex_srp.cpp or admm_srp.m\n% Outputs:\n% Unew: the updated subspace \n% STATUSnew: the updated running status\n% OPTSnew: the updated options for the subproblem of GRASTA\n%\n% Author: Jun He, Laura Balzano\n% Email: hejun.zz@gmail.com, sunbeam@ece.wisc.edu\n% Date: Sept. 01, 2012\n%\n%\n\nLEVEL_FACTOR = 2;\n\nif isfield(OPTIONS,'MIN_MU'),\n MIN_MU = OPTIONS.MIN_MU;\nelse\n MIN_MU = 1;\nend\n\nif isfield(OPTIONS,'MAX_MU'),\n MAX_MU = OPTIONS.MAX_MU;\nelse\n MAX_MU = 15;\nend\n\n\nif isfield(OPTIONS,'USE_MEX'),\n USE_MEX = OPTIONS.USE_MEX;\nelse\n USE_MEX = 1;\nend\n\nif isfield(OPTIONS,'CONSTANT_STEP'),\n CONSTANT_STEP = OPTIONS.CONSTANT_STEP;\nelse\n CONSTANT_STEP = 0;\nend\n\n\nif isfield(OPTIONS,'DIM_M'),\n DIM_M = OPTIONS.DIM_M;\nelse\n error('Should specify OPTIONS.DIM_M data ambient dimension!!!\\n');\nend\n\nif isfield(OPTIONS,'ITER_MIN'),\n MIN_ITER = OPTIONS.ITER_MIN;\nelse\n MIN_ITER = 5;\nend\n\nif isfield(OPTIONS,'ITER_MAX'),\n ITER_MAX = OPTIONS.ITER_MAX;\nelse\n ITER_MAX = 60;\nend\n\nif isfield(OPTIONS,'TOL'),\n TOL = OPTIONS.TOL;\nelse\n TOL = 1e-6;\nend\n\n\nif isfield(OPTIONS,'MAX_LEVEL'),\n MAX_LEVEL = OPTIONS.MAX_LEVEL;\nelse\n MAX_LEVEL = 20;\nend\n\n\n\nif isfield(OPTIONS,'RANK'),\n RANK = OPTIONS.RANK;\nelse\n error('Should specify OPTIONS.RANK!!!\\n');\nend\n\nif isfield(OPTIONS,'QUIET'),\n QUIET = OPTIONS.QUIET;\nelse\n QUIET = 0;\nend\n\nDEFAULT_MU_HIGH = (MAX_MU-1)/2; \nDEFAULT_MU_LOW = MIN_MU + 2;\n\n\n% If we first call GRASTA_stream then do the following initilization \nif STATUS.init == 0, \n STATUS.init = 1; % Do not enter this initial part any longer \n STATUS.curr_iter = 0; % For debug\n \n STATUS.last_mu = MIN_MU; \n STATUS.level = 0;\n STATUS.step_scale = 0;\n STATUS.last_w = zeros(RANK,1);\n STATUS.last_gamma = zeros(DIM_M,1);\n\n OPTS.TOL = TOL;\n OPTS.MAX_ITER = MIN_ITER; % the max iteration of ADMM at level=0\n OPTS.QUIET = 1; \n\n if isfield(OPTIONS,'rho'),\n OPTS.RHO = OPTIONS.rho;\n else\n OPTS.RHO = 1.8;\n end\n \n U0 = orth(randn(DIM_M,RANK));\nend\n\n%%%%%%%%%%%%%%%\n% main framework of GRASTA\nU_Omega = U0(idx,:);\n\nif USE_MEX,\n [s_t, w, ldual] = mex_srp(U_Omega, y_Omega, OPTS);\nelse\n [s_t, w, ldual] = admm_srp(U_Omega, y_Omega, OPTS);\nend\n\ngamma_1 = ldual;% + OPTS.RHO*(U_Omega*w + s_t - y_Omega);\nUtDual_omega = U_Omega' * gamma_1;\ngamma_2 = U0 * UtDual_omega;\ngamma = zeros(DIM_M,1);\ngamma(idx) = gamma_1;\ngamma = gamma - gamma_2;\n\ngamma_norm = norm(gamma);\nw_norm = norm(w);\nsG = gamma_norm * w_norm;\n\n\n% Here we use the adaptive step-size rule for SGD. The adaptive can work\n% well for both dynamic and static subspace tracking tasks\n\n% 1. determine the step scale from the first observation\nif ~STATUS.step_scale,\n STATUS.step_scale = 0.5*pi*(1+MIN_MU)/sG;\n \n if ~QUIET,\n fprintf('Level 0: %.2e\\n',STATUS.step_scale);\n end\nend\n\n% 2. inner product of previous grad and current grad\ngrad_ip = trace(STATUS.last_w * (STATUS.last_gamma' * gamma) * w');\n\n%%% avoid inner product too large\nnormalization = norm(STATUS.last_gamma * STATUS.last_w','fro') * norm(gamma * w','fro');\nif normalization == 0,\n grad_ip_normalization = 0;\nelse\n grad_ip_normalization = grad_ip/normalization;\nend\n%%%\n\n\n% 3. if the two consecutive grad in the same direction, we take a larger\n% step along the gradient direction, otherwise take a small step along the\n% gradient direction\nSTATUS.last_mu = max(STATUS.last_mu + sigmoid(-grad_ip_normalization) , MIN_MU);\n\nif CONSTANT_STEP > 0,\n t = CONSTANT_STEP;\nelse\n % should not take a step larger than pi/2\n t = STATUS.step_scale * LEVEL_FACTOR^(-STATUS.level) * sG / (1+STATUS.last_mu);\n if t>=pi/3,\n t = pi/3;\n end\n \n % Adjust the level\n bShrUpd = 0;\n if STATUS.last_mu <= MIN_MU,\n if STATUS.level > 1,\n bShrUpd = 1;\n STATUS.level = STATUS.level - 1;\n \n if ~QUIET,\n fprintf('multi-level adaption - decreasing, t:%.2e, vectors: %d, level: %d\\n',...\n t,STATUS.curr_iter, STATUS.level);\n end\n STATUS.curr_iter = 0;\n end\n \n STATUS.last_mu = DEFAULT_MU_LOW;\n elseif STATUS.last_mu > MAX_MU,\n if STATUS.level < MAX_LEVEL,\n bShrUpd = 1;\n STATUS.level = STATUS.level + 1;\n \n if ~QUIET,\n fprintf('multi-level adaption - increasing, t:%.2e, vectors: %d, level: %d\\n',...\n t, STATUS.curr_iter, STATUS.level);\n end\n STATUS.curr_iter = 0;\n STATUS.last_mu = DEFAULT_MU_HIGH;\n else\n STATUS.last_mu = MAX_MU;\n end\n end\n \n if bShrUpd,\n if STATUS.level>=0 && STATUS.level <4, % [0,4)\n OPTS.MAX_ITER = MIN_ITER;\n elseif STATUS.level>=4 && STATUS.level <7, % [4,7)\n OPTS.MAX_ITER = min(MIN_ITER*2, ITER_MAX);\n elseif STATUS.level>=7 && STATUS.level <10, % [7,10)\n OPTS.MAX_ITER = min(MIN_ITER*4, ITER_MAX);\n elseif STATUS.level>=10 && STATUS.level <14, % [10,14)\n OPTS.MAX_ITER = min(MIN_ITER*8, ITER_MAX);\n else\n OPTS.MAX_ITER = ITER_MAX; % [14,...)\n end\n \n if ~QUIET,\n fprintf('Will use %d ADMM iterations in level %d\\n',OPTS.MAX_ITER, STATUS.level);\n end\n end\n \nend\n\n% 4. update the gradient for further step size update\nSTATUS.last_gamma = gamma;\nSTATUS.last_w = w;\n\nSTATUS.grad_ip = grad_ip_normalization; % just for debugging\n\n\n% Take the gradient step along Grassmannian geodesic.\nalpha = w/w_norm;\nbeta = gamma/gamma_norm;\nstep = (cos(t)-1)*U0*(alpha*alpha') - sin(t)*beta*alpha';\n\nU0 = U0 + step;\n\n%%\n\nSTATUS.s_t = s_t;\nSTATUS.w = w;\nSTATUS.ldual = ldual;\nSTATUS.SCALE = 1;\nSTATUS.curr_iter = STATUS.curr_iter + 1;\n\nSTATUS.grasta_t = t;\n\n%\n%%%%%%%%%%%%%%%%%%%%%%\n\nUnew = U0;\nSTATUSnew = STATUS;\nOPTSnew = OPTS;\nend\n\n\n%% Function of Sigmoid\n\nfunction fval = sigmoid(x)\nFMIN = -1; FMAX = 1;\nomega = 0.1;\n\nfval = FMIN + (FMAX - FMIN)/(1 - (FMAX/FMIN)*exp(-x/omega));\nend", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/st/GRASTA/grasta_stream.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3485389645611048}}
{"text": "function [predict_label,accuracy] = jdrf(x_train,y_train,x_test,y_test,n_trees)\n%%jdrf:packaged TreeBagger from Matlab,just for easier use.\n%%==============================================================================\n%%input:\n%%------x_train,...,y_test : training and testing sets. [required]\n%%------n_trees : number of trees,default is 10. [not required]\n\n%%output:\n%%------predict_label : predicted label vector for test case.\n%%------accuracy : accuracy\n%%==============================================================================\n\tpredict_label = [];\n accuracy = 0;\n switch nargin\n case 4\n tree_para = 10;\n case 5\n tree_para = n_trees;\n otherwise\n fprintf('++++++Fatal error!Please check the input!');\n return\n\tend\n\tfactor = TreeBagger(tree_para,x_train,y_train);\n [predict_labels,scores] = predict(factor,x_test);\n predictY = str2num(char(predict_labels));\n accuracy = mean(predictY == y_test);\n predict_label = predictY;\nend", "meta": {"author": "jindongwang", "repo": "activityrecognition", "sha": "33687803886d4a184e0b285e3ec7ab73a8f86355", "save_path": "github-repos/MATLAB/jindongwang-activityrecognition", "path": "github-repos/MATLAB/jindongwang-activityrecognition/activityrecognition-33687803886d4a184e0b285e3ec7ab73a8f86355/code/percom18_stl/base/classifier/jdrf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.34853895731816215}}
{"text": "function view = fixPhase(view, scanNum, sliceNum, shift, scale)\n%\n% function view = fixPhase(view, [scanNum], [sliceNum], [shift], [scale])\n%\n%\n% Adds specified offset and scale to the phases of the specified coranal.\n% Will prompt for offset & scale if not given of empty.\n% The current slice will be used if sliceNum not given or empty.\n%\n% HISTORY:\n% 2002.03.08 RFD (bob@white.stanford.edu) wrote it.\n\nglobal dataTYPES;\n\nif(~exist('scanNum','var') | isempty(scanNum))\n scanNum = getCurScan(view);\nend\n\nif(~exist('sliceNum','var') | isempty(sliceNum))\n sliceNum = viewGet(view, 'Current Slice');\nend\n\noldShift = dataTYPES(view.curDataType).atlasParams(scanNum).phaseShift(sliceNum);\noldScale = dataTYPES(view.curDataType).atlasParams(scanNum).phaseScale(sliceNum);\n\noldPh = view.ph;\n% undo the old shift & scale so that we can start anew\nview.ph{scanNum}(:,:,sliceNum) = mod((view.ph{scanNum}(:,:,sliceNum) - oldShift)/oldScale, 2*pi);\n%refreshView(view);\n\nif(~exist('shift','var')) shift = []; end\nif(~exist('scale','var')) scale = []; end\nif(isempty(shift) | isempty(scale))\n if(isempty(shift))\n def{1} = num2str(oldShift);\n else\n def{1} = num2str(shift);\n end\n if(isempty(scale))\n def{2} = num2str(oldScale);\n else\n def{2} = num2str(scale);\n end\n \n ok = 0;\n while(~ok)\n answer = inputdlg({'Phase shift:','Scale Factor:'}, 'Fix Phase', 1, def);\n if(isempty(answer))\n % Cancel all changes\n view.ph = oldPh;\n refreshView(view);\n ok = 1;\n return;\n end\n shift = eval(answer{1});\n scale = eval(answer{2});\n view.ph{scanNum}(:,:,sliceNum) = view.ph{scanNum}(:,:,sliceNum) * scale + shift;\n view.ph{scanNum}(:,:,sliceNum) = phaseStandardize(view.ph{scanNum}(:,:,sliceNum));\n view.ph{scanNum}(:,:,sliceNum) = mod(view.ph{scanNum}(:,:,sliceNum), 2*pi);\n refreshView(view);\n ans = questdlg('Is this OK?', ...\n 'Confirm Phase Adjustment', ...\n 'Yes','No- try again','Cancel all changes','Yes');\n \n switch ans,\n case 'Yes', \n saveCorAnal(view);\n ok = 1;\n case 'No- try again',\n refreshView(view);\n def = answer;\n ok = 0;\n case 'Cancel all changes',\n view.ph = oldPh;\n refreshView(view);\n ok = -1;\n return;\n end % switch\n end\nelse\n view.ph{scanNum}(:,:,sliceNum) = view.ph{scanNum}(:,:,sliceNum) * scale + shift;\n view.ph{scanNum}(:,:,sliceNum) = phaseStandardize(view.ph{scanNum}(:,:,sliceNum));\n view.ph{scanNum}(:,:,sliceNum) = mod(view.ph{scanNum}(:,:,sliceNum), 2*pi);\n refreshView(view);\n saveCorAnal(view);\nend\ndataTYPES(view.curDataType).atlasParams(scanNum).phaseShift(sliceNum) = shift;\ndataTYPES(view.curDataType).atlasParams(scanNum).phaseScale(sliceNum) = scale;\nsaveSession;\nreturn;\n\nfunction ph = phaseStandardize(ph)\n% wrap neagative phases back up to the 2pi end\n\nl = ph<0;\nif(~isempty(l))\n ph(l) = ph(l)+2*pi;\nend\nreturn;", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Analysis/VisualField/fixPhase.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.34853895731816203}}
{"text": "% difftopo - compute and plot component decomposition for the difference ERP \n% between two EEG datasets. Plots into the current axis (gca); \n% plot into a new empty figure as below.\n% Usage:\n% >> figure; difftopo(ALLEEG,eeg1,eeg2,interval);\n% Inputs:\n% ALLEEG - array of leaded EEG datasets\n% eeg1 - index of subtrahend (+) dataset\n% eeg2 - index of minuend (-) dataset\n% interval - [minms maxms] latency interval in which to find \n% and plot largest contributing components {default: whole epoch}\n% limits - [stms endms] latenc plotting limits (in ms) {default|0: whole epoch}\n% subcomps - array of component indices to remove from data \n% (e.g. eye movement components) {default|0: none}\n%\n% Outputs: none\n%\n% Author: Scott Makeig, SCCN/INC/UCSD 3/28/05\n\n% Copyright (C) Scott Makeig, SCCN/INC/UCSD 3/28/05\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\nfunction difftopo(ALLEEG,eeg1,eeg2,interval,limits,subcomps);\n\nif nargin < 3\n help difftopo\n return\nend\nif eeg1 < 1 | eeg1 > length(ALLEEG)\n help difftopo\n return\nend\nif eeg2 < 1 | eeg2 > length(ALLEEG)\n help difftopo\n return\nend\nif eeg1 == eeg2\n help difftopo\n return\nend\nif ndims(ALLEEG(eeg1).data) ~=3 | ndims(ALLEEG(eeg2).data) ~=3\n error('EEG datasets must be epoched data');\nend\n\nif nargin < 4\n interval = [ALLEEG(eeg1).xmin*999.9 ALLEEG(eeg1).xmax*999.9];\nend\nif nargin < 5\n limits = 0; % [ALLEEG(eeg1).xmin*1000 ALLEEG(eeg1).xmax*1000];\nend\nif nargin < 6\n subcomps = [];\nend\n\nif ~isfield(ALLEEG(eeg1),'icaweights')\n error('EEG datasets must have icaweights');\nend\nif length(interval) ~= 2\n help difftopo\n return\nend\n\nif ALLEEG(eeg1).pnts ~= ALLEEG(eeg1).pnts\n error('EEG datasets must have the same number of frames per epoch');\nend\n\nset(gcf,'Name','difftopo()');\ndiff = mean(ALLEEG(eeg1).data,3) - mean(ALLEEG(eeg2).data,3);\n\nplottitle = [ ALLEEG(eeg1).setname ' - ' ALLEEG(eeg2).setname];\nenvtopo(diff,ALLEEG(eeg1).icaweights*ALLEEG(eeg1).icasphere,...\n 'chanlocs',ALLEEG(eeg1).chanlocs, ...\n 'timerange',[ALLEEG(eeg1).xmin*1000 ALLEEG(eeg1).xmax*1000],...\n 'limits',limits,...\n 'limcontrib',interval,...\n 'title',plottitle, ...\n 'subcomps',subcomps);\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/functions/miscfunc/difftopo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548511303336, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.348538957318162}}
{"text": "function [formula, protons] = getFormulaFromInChI(InChI)\n% Extracts the chemical formula of a given compound from\n% the InChI string provided\n%\n% USAGE:\n%\n% [formula, protons] = getFormulaFromInChI(InChI)\n%\n% INPUT:\n% InChI: The Inchi String of the chemical formula (e.g. InChI=\n% extract formula from `InChI = 1S/C3H4O3/c1-2(4)3(5)6/h1H3, (H,5,6)/p-1` for pyruvate\n%\n% OUTPUTS:\n% formula: The chemical formula (including the protonation state\n% protons: The total number of protons\n\n[token,rem] = strtok(InChI, '/');\nformula=strtok(rem, '/');\n\n%This could be a composite formula, so combine it.\ntokens = strsplit(formula,'.');\n\n%The protonation state can also modify the formula! To get it, we remove\n%any reconstruction fields, as they do not influence it.\nInChI = regexprep(InChI,'/r.*','');\np_layer = regexp(InChI,'/p(.*?)/|/p(.*?)$','tokens');\nprotonationProtons = 0;\nif ~isempty(p_layer)\n individualProtons = cellfun(@(x) {strsplit(x{1},';')},p_layer);\n protonationProtons = cellfun(@(x) sum(cellfun(@(y) eval(y) , x)), individualProtons);\nend\n\n%Calc the coefs for all formulas\nif (numel(tokens) > 1) || (~isempty(regexp(formula,'(^[0-9]+)'))) || (~isempty(p_layer))\n CoefLists = cellfun(@(x) calcFormula(x), tokens,'UniformOutput',0);\n if ~isempty(p_layer)\n %CoefLists = [CoefLists;{{'H';protonationProtons}}];%was crashing\n %with formula C62H90N13O14P.Co.H2O\n CoefLists{end+1} = {'H';protonationProtons};\n end\n %and now, combine them.\n Elements = {};\n Coefficients = [];\n for i = 1:numel(CoefLists)\n if isempty(CoefLists{i})\n %This should only happen, if there was no actual formula.\n continue\n end\n currentForm = CoefLists{i};\n Elements = [Elements,setdiff(currentForm(1,:),Elements)];\n current_coefs = cell2mat(currentForm(2,:));\n [A,B] = ismember(Elements,currentForm(1,:));\n %Extend the coefficients if necessary\n Coefficients(end+1:numel(Elements)) = 0;\n Coefficients(A) = Coefficients(A)+current_coefs;\n end\n\n Coefs = num2cell(Coefficients);\n Coefs(cellfun(@(x) x == 1, Coefs)) = {[]};\n Coefs = cellfun(@(x) num2str(x) , Coefs,'UniformOutput',0);\n if nargout > 1\n protons = Coefficients(ismember(Elements,'H'));\n end\n formula = strjoin([Elements , {''}],Coefs);\nelse\n %had to add this for some inchi, e.g.\n %InChI=1/C21H30O4/c1-19-8-5-14(23)11-13(19)3-4-15-16(19)6-9-20(2)17(15)7-10-21(20,25)18(24)12-22/h11,15-17,22,25H,3-10,12H2,1-2H3/t15-,16+,17+,19+,20+,21+/m1/s1\n protons = numAtomsOfElementInFormula(formula, 'H',0);\nend\n\nzero='0';\nindZero=strfind(formula,zero);\nif ~isempty(indZero)\n if isletter(formula(indZero-1))\n if 0\n warning('Formula contains a zero with a letter preceeding it, replacing with letter.')\n fprintf('%s%s\\n','Formula before:, ', formula)\n end\n formula = strrep(formula, formula(indZero-1:indZero), formula(indZero-1));\n if 0\n fprintf('%s%s\\n','Formula after:, ', formula)\n end\n end\nend\n\nend\n\n\nfunction [CoefList] = calcFormula(Formula)\nmultiplier = 1;\nisReplicated = regexp(Formula,'(^[0-9]+)','tokens');\nElementTokens = regexp(Formula,'([A-Z][a-z]?)([0-9]*)','tokens');\nElements = cellfun(@(x) x{1}, ElementTokens,'UniformOutput',0);\nCoefs = cellfun(@(x) str2num(x{2}), ElementTokens,'UniformOutput',0);\nCoefs(cellfun(@isempty, Coefs)) = {1};\n\nif ~isempty(isReplicated)\n multiplier = str2num(isReplicated{1}{1});\n Coefs = cellfun(@(x) x*multiplier, Coefs,'UniformOutput',0);\nend\n\nCoefList = [Elements;Coefs];\nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/dataIntegration/chemoInformatics/inchi/getFormulaFromInChI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.34852083267109213}}
{"text": "function [returns,interval] = realized_return_filter(price,time,timeType,samplingType,samplingInterval,subsamples)\n% THESE COMMENTS ARE WRONG!!!\n% Computes the Quantile Realized Variance of Christensen, Oomen and Podolskij (2008),\n% the MinRV and MedRV estimator of Andersen, Dobrev and Shaumberg and the\n% general symmetrized version suggested by Sheppard in a discussion of COP\n%\n% USAGE:\n% [RETURN,INTERVAL] = realized_return_filter(PRICE,TIME,TIMETYPE,SAMPLINGTYPE,SAMPLINGINTERVAL,SUBSAMPLES)\n%\n% INPUTS:\n% PRICE - m by 1 vector of high frequency prices\n% TIME - m by 1 vector of times where TIME(i) corresponds to PRICE(i)\n% TIMETYPE - String describing the way times are measured\n% 'wall' 24-hour clock of the form HHMMSS, e.g. 101543 or 153217\n% 'seconds' Time measured in seconds past midnight on the first day.\n% 'unit' Unit normalized date format, e.g. .1, .234, .9\n% Unit normalized times are more general than the other types and can be\n% applied to data from more than one calendar day\n% SAMPLINGTYPE - String describing the type of sampling to use when\n% filtering PRICE\n% 'CalendarTime' - Sample in calendar time using observations separated by\n% SAMPLINGINTERVAL seconds\n% 'CalendarUniform' - Sample in calendar time using SAMPLINGINTERVAL\n% observations spread uniformly between TIME(1) and TIME(m)\n% 'BusinessTime' - Sample in business (tick) time using observation separated\n% by SAMPLINGINTERVALticks\n% 'BusinessUniform' - Sample in business (tick) time using observations\n% uniformly spaced in business time.\n% 'Fixed' - Sample at specific points in time. When using fixed,\n% SAMPLINGINTERVAL must be a n by 1 vector of times with the same TIMETYPE\n% as TIME (i.e. seconds if TIME is in seconds)\n% SAMPLINGINTERVAL - Scalar integer or n by 1 vector whose meaning depends on the selected SAMPLINGTYPE\n% SUBSAMPLES - [OPTIONAL] Integer value containing the number of subsamples to use when\n% computing RRSS. It must be the case that SUBSAMPLE0 will produce an estimator based on jittering the starting\n% point over floor(linspace(0,(SUBSAMPLES)/(SUBSAMPLES+1),SUBSAMPLES+1)*SAMPLESPERBIN)+1\n% For example, if SUBSAMPLES = 3 and SAMPLESPERBIN = 20, then the starting\n% points for the four RR estimators will be observations 1, 6, 11 and 16. If\n% omitted SUBSAMPLE = 0 and RRSS=RR.\n%\n% OUTPUTS:\n% RETURNS - Quantile realized variance vector (k by 1) corresponding to the values in QUANTILES\n% INTERVAL - Subsample based version of RQ. RQSS = RQ if SUBSAMPLES = 0\n%\n% COMMENTS:\n%\n% EXAMPLES:\n%\n%\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 1 Date: 5/1/2008\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% InputChecking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif nargin<5 || nargin>6\n error('Seven or eight inputs required.')\nend\n\nif size(price,2)>size(price,1)\n price=price';\nend\nif size(price,2)>1\n error('PRICE must be a m by 1 vector.')\nend\nif size(time,2)>size(time,1)\n time=time';\nend\nif any(diff(time)<0)\n error('TIME must be sorted and increasing')\nend\nif size(time,2)>1 || length(time)~=length(price)\n error('TIME must be a m by 1 vector.')\nend\n% Inserted to protect against inputing integer times\ntime = double(time);\n\ntimeType=lower(timeType);\nif ~ismember(timeType,{'wall','seconds','unit'})\n error('TIMETYPE must be one of ''wall'', ''seconds'' or ''unit''.');\nend\nsamplingType=lower(samplingType);\nif ~ismember(samplingType,{'calendartime','calendaruniform','businesstime','businessuniform','fixed'})\n error('SAMPLINGTYPE must be one of ''CalendarTime'', ''CalendarUniform'', ''BusinessTime'', ''BusinessUniform'' or ''Fixed''.');\nend\n\nm=size(price,1);\nt0=time(1);\ntT=time(m);\nif ismember(samplingType,{'calendartime','calendaruniform','businesstime','businessuniform'})\n % Must be a scalar integer\n if ~isscalar(samplingInterval) || floor(samplingInterval)~=samplingInterval || samplingInterval<1\n error('SAMPLINGINTERVAL must be a positive integer for the SAMPLINGTYPE selected.')\n end\nelse\n if size(samplingInterval,2)>size(samplingInterval,1)\n samplingInterval=samplingInterval';\n end\n if ~(any(samplingInterval>=t0) && any(samplingInterval<=tT))\n error('At least one sampling interval must be between min(TIME) and max(TIME) when using ''Fixed'' as SAMPLINGTYPE.')\n end\n if any(diff(samplingInterval)<=0)\n error('When using ''Fixed'' as SAMPLINGTYPE the vector of sampling times in SAMPLINGINTERVAL must be sorted and strictly increasing.')\n end\nend\n\n% SUBSAMPLES\nif nargin==6 && ~isempty(subsamples)\n if ~isscalar(subsamples) || subsamples<0 || floor(subsamples)~=subsamples\n error('SUBSAMPLES must be a non-negative integer.')\n end\nelse\n subsamples=0;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Convert if wall to compute the interval\nif strcmp(timeType,'wall')\n time=wall2seconds(time);\n timeType = 'seconds';\nend\n\n% Initialize the return cell arrays and the interval vector\nreturns=cell(subsamples+1,1);\ninterval=zeros(subsamples+1,1);\n% 1. Filter the price\nlogPrice = log(price);\n[filteredLogPrice,filteredTimes] = realized_price_filter(logPrice ,time,timeType,samplingType,samplingInterval);\nreturns{1} = diff(filteredLogPrice);\ninterval(1) = 1;\n\n\nif subsamples>0\n % Initialize the place holder for rvSS and rvAdjustment\n % Get the number of filtered times\n n = size(filteredTimes,1);\n % Compute the length of time used in computing the realized variance to\n % bias adjust the subsample RVs\n baseDifference = filteredTimes(n) - filteredTimes(1);\n switch lower(samplingType)\n case {'calendartime','calendaruniform','fixed'}\n % Uniform sampling in CT so the gap is constant\n gap=diff(filteredTimes);\n % The stepsize is constant\n step = gap /(subsamples+1);\n if ismember(samplingType,{'calendartime','calendaruniform'})\n step = [step;mean(step)];\n else\n step = [step;step(length(step))];\n end\n for i=1:subsamples\n thisSampleTime = filteredTimes;\n % Need to compute times for this subsample\n thisSampleTime = thisSampleTime(1:n)+i*step;\n % Use these times to filter the price\n filteredLogPrice = realized_price_filter(logPrice,time,'unit','fixed',thisSampleTime);\n % Compute returns\n returns{i+1} = diff(filteredLogPrice);\n % Compute the ith subsample RV\n % The adjustment depends on the amount of time used in this\n % subsample relative to the full sample RV\n interval(i+1) = (thisSampleTime(n-1)-thisSampleTime(1))/baseDifference;\n end\n case {'businesstime', 'businessuniform'}\n % Uniform sampling in business time\n if strcmp(samplingType,'businesstime')\n % If BT then samplingInterval contains the number of ticks to skip\n originalIndices = 1:samplingInterval:m;\n if ~ismember(m,originalIndices)\n originalIndices = [originalIndices m];\n end\n gap=samplingInterval;\n else\n % If businessuniform then gap will be average\n originalIndices = floor(linspace(1,m,samplingInterval));\n if ~ismember(m,originalIndices)\n originalIndices = [originalIndices m];\n end\n gap = m/samplingInterval;\n end\n % The step size is constant\n step = gap/(subsamples+1);\n for i=1:subsamples\n % The indices indicate which points to use since the\n % sampling is linear in ticks\n indices = floor(originalIndices + step*i);\n indices(indices>m) = m;\n returns{i+1} = diff(logPrice(indices));\n interval(i+1) = (time(max(indices))-time(min(indices)))/baseDifference;\n end\n end\nend", "meta": {"author": "bashtage", "repo": "mfe-toolbox", "sha": "9622b6c546bc6d649fd9bf0a36a7fcd53872e04a", "save_path": "github-repos/MATLAB/bashtage-mfe-toolbox", "path": "github-repos/MATLAB/bashtage-mfe-toolbox/mfe-toolbox-9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/realized/realized_return_filter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.34852082649161226}}
{"text": "report_this_filefun(mfilename('fullpath'));\n\n[lat,lon] = meshgrat(tmap,tmapleg);\n%gx = rex(1,:);\n%gy = rey(:,1)';\n\n% tmap = km2deg(tmap/1);\n% [X , Y] = meshgrid(gx,gy);\n\nren = interp2(XB,YB,ZB,lon,lat);\n\nl = ren < -8.8; ren(l) = -8.8;\nmi = min(min(ren));\n\nl = isnan(ren);\nren(l) = mi-2;\n\n\nfigure_w_normalized_uicontrolunits('pos',[150 100 600 500])\n\nhold on; axis off\naxm1 = axesm('MapProjection','eqaconic','MapParallels',[],...\n 'MapLatLimit',[s4_south s3_north],'MapLonLimit',[s2_west s1_east])\n\nmeshm(ren,tmapleg,size(tmap),tmap);\n\ndaspectm('m',3);\ntightmap\nview([0 90])\ncamlight; lighting phong\nset(gca,'projection','perspective');\n\nload worldlo\n%h = displaym(POline); set(h(1),'color',[0.9 0.9 0.9],'Linewidth',1.7)\n% h2 = displaym(PPpoint);\n% h = displaym(PPtext); trimcart(h);\n\npl = plotm(ms(:,1), ms(:,2),'ow','Linewidth',1.4);\nset(pl,'LineWidth',1,'MarkerSize',3,...\n 'MarkerFaceColor',[0.8 0.8 0.8 ],'MarkerEdgeColor',[ 0.8 0.8 0.8 ])\n\n\nplmag = 4.\nl = a.Date > t0+4/365 & a.Date < t0+34/365 & a.Magnitude >= plmag & a.Magnitude < 5;\n\npl = plotm(a(l,2),a(l,1),'ow','Markersize',9);\nset(pl,'LineWidth',1,'MarkerSize',6,...\n 'MarkerFaceColor',[1 1 1 ],'MarkerEdgeColor',[ 0 0 0 ])\n\n\nl = a.Date > t0+4/365 & a.Date < t0+34/365 & a.Magnitude >= 5.0 ;\npl = plotm(a(l,2),a(l,1),'^w','Markersize',9);\nset(pl,'LineWidth',1,'MarkerSize',10,...\n 'MarkerFaceColor',[1 1 1 ],'MarkerEdgeColor',[ 0 0 0 ])\n\n\n\n% pl = plotm(a.Latitude,a.Longitude,'+k');\n%set(pl,'LineWidth',0.5,'MarkerSize',2,...\n% 'MarkerFaceColor','k','MarkerEdgeColor','k')\npl = plotm(main(:,2),main(:,1),'hw');\nset(pl,'LineWidth',1,'MarkerSize',20,...\n 'MarkerFaceColor','w','MarkerEdgeColor','k')\n\n\nzdatam(handlem('allline'),2000) % keep line on surface\n%zdatam(handlem('alltext'),10000) % keep line on surface\ncaxis([0.0 0.22])\nj = hsv;\n%j = j(64:-1:1,:);\nj = [ [ 0.9 0.9 0.9] ; j];\n\ncolormap(j); brighten(0.0);\n\naxis off; set(gcf,'color','w')\n\nsetm(gca,'ffacecolor','w')\nsetm(gca,'fedgecolor','k','flinewidth',3);\nsetm(gca,'mlabellocation',0.25)\nsetm(gca,'meridianlabel','on')\nsetm(gca,'plabellocation',0.25)\nsetm(gca,'parallellabel','on')\nsetm(gca,'Fontcolor','k','Fontweight','normal','FontSize',10,'Labelunits','dm')\n\nh5 = colorbar;\nset(h5,'position',[0.71 0.44 0.017 0.45],'TickDir','out','Ycolor','k','Xcolor','k',...\n 'Fontweight','bold','FontSize',14,'Ticklength',[0.02 0.08],'Yticklabel',[]);\nset(gcf,'Inverthardcopy','off');\n\nsc = scaleruler('RulerStyle','lines','MajorTick',0:15:30,'Linewidth',1,'color','k',...\n 'MajorTickLength',2,'XLoc',-0.003,'YLoc',0.5663,'Zloc',40000,'FontSize',9,'Fontweight','normal',...\n 'MinorTick',0:5:10,'color',[0 0 0 ],'TickDir','down')\n\n\nreturn\n\nscaleruler\n\nsetm(handlem('scaleruler'),'XLoc',-0.0,'YLoc',0.566,'Zloc',4000)\nsetm(handlem('scaleruler'),'MajorTick',0:10:30,...\n 'MinorTick',0:5:10,'TickDir','down',...\n 'MajorTickLength',(3),...\n 'MinorTickLength',(3),'Linewidth',8)\n%setm(handlem('scaleruler'),'RulerStyle','ruler')\nsetm(handlem('scaleruler1'),'RulerStyle','lines')\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/dramaphec2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.34852082649161226}}
{"text": "function [pE,pC] = spm_L_priors(dipfit,pE,pC)\n% prior moments for the lead-field parameters of ERP models\n% FORMAT [pE,pC] = spm_L_priors(dipfit)\n%\n% dipfit - forward model structure:\n%\n% dipfit.type - 'ECD', 'LFP' or 'IMG'\n% dipfit.symmetry - distance (mm) for symmetry constraints (ECD)\n% dipfit.location - allow changes in source location (ECD)\n% dipfit.Lpos - x,y,z source positions (mm) (ECD)\n% dipfit.Nm - number of modes (IMG)\n% dipfit.Ns - number of sources\n% dipfit.Nc - number of channels\n%\n% pE - prior expectation\n% pC - prior covariance\n%\n% adds spatial parameters\n%--------------------------------------------------------------------------\n% pE.Lpos - position - ECD\n% pE.L - orientation - ECD\n% coefficients of local modes - Imaging\n% gain of electrodes - LFP\n% pE.J - contributing states (length(J) = number of states per source\n%\n%__________________________________________________________________________\n%\n% David O, Friston KJ (2003) A neural mass model for MEG/EEG: coupling and\n% neuronal dynamics. NeuroImage 20: 1743-1755\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: spm_L_priors.m 7409 2018-08-27 11:39:00Z bernadette $\n\n\n\n% defaults\n%--------------------------------------------------------------------------\ntry, model = dipfit.model; catch, model = 'LFP'; end\ntry, type = dipfit.type; catch, type = 'LFP'; end\ntry, location = dipfit.location; catch, location = 0; end\ntry, pC; catch, pC = []; end\n\n\n% number of sources\n%--------------------------------------------------------------------------\ntry\n n = dipfit.Ns;\n m = dipfit.Nc;\ncatch\n n = dipfit;\n m = n;\nend\n\n% location priors (4 mm)\n%--------------------------------------------------------------------------\nif location, V = 2^2; else, V = 0; end\n\n% parameters for electromagnetic forward model\n%==========================================================================\nswitch type\n \n case{'ECD'} % mean and variance\n %------------------------------------------------------------------\n pE.Lpos = dipfit.Lpos; pC.Lpos = ones(3,n)*V; % positions\n pE.L = zeros(3,n); pC.L = ones(3,n)*64; % orientations\n \n Sc = find(~cellfun(@isempty,dipfit.silent_source)); % silence sources for CSD\n if(Sc); pC.L(:,Sc) = pC.L(:,Sc)*0; end\n \n case{'IMG'}\n %------------------------------------------------------------------\n m = dipfit.Nm; % number modes\n pE.Lpos = sparse(3,0); pC.Lpos = sparse(3,0); % positions\n pE.L = zeros(m,n); pC.L = ones(m,n)*64; % modes\n \n Sc = find(~cellfun(@isempty,dipfit.silent_source)); % silence sources for CSD\n if(Sc); pC.L(:,Sc) = pC.L(:,Sc)*0; end\n \n case{'LFP'}\n %------------------------------------------------------------------\n pE.Lpos = sparse(3,0); pC.Lpos = sparse(3,0); % positions\n pE.L = ones(1,m); pC.L = ones(1,m)*64; % gains\n \n otherwise\n warndlg('Unknown spatial model')\n \nend\n\n% contributing states (encoded in J)\n%==========================================================================\nif ischar(model), mod.source = model; model = mod; end\npE.J = {};\npC.J = {};\n\nfor i = 1:numel(model)\n \n switch upper(model(i).source)\n \n case{'ERP','SEP'}\n %--------------------------------------------------------------\n pE.J{end + 1} = sparse(1,9,1,1,9); % 9 states\n pC.J{end + 1} = sparse(1,[1 7],1/32,1,9);\n \n case{'CMC','TFM'}\n %--------------------------------------------------------------\n pE.J{end + 1} = sparse(1,3,1,1,8); % 8 states\n pC.J{end + 1} = sparse(1,[1 7],1/32,1,8);\n \n case{'LFP'}\n %--------------------------------------------------------------\n pE.J{end + 1} = sparse(1,9,1,1,13); % 13 states\n pC.J{end + 1} = sparse(1,[1 7],1/32,1,13);\n \n case{'NMM'}\n %--------------------------------------------------------------\n pE.J{end + 1} = sparse(1,3,1,1,9); % 9 states\n pC.J{end + 1} = sparse(1,[1,2],1/32,1,9);\n \n case{'NMDA'}\n %--------------------------------------------------------------\n pE.J{end + 1} = sparse(1,3,1,1,12); % 12 states\n pC.J{end + 1} = sparse(1,[1,2],1/32,1,12);\n \n case{'CMM'}\n %--------------------------------------------------------------\n pE.J{end + 1} = sparse(1,2,1,1,12); % 12 states\n pC.J{end + 1} = sparse(1,[3,4],1/32,1,12);\n \n case{'CMM_NMDA'}\n %--------------------------------------------------------------\n pE.J{end + 1} = sparse(1,2,1,1,16); % 12 states\n pC.J{end + 1} = sparse(1,[3,4],1/32,1,16);\n \n case{'MFM'}\n %--------------------------------------------------------------\n pE.J{end + 1} = sparse(1,3,1,1,36); % 36 (9 + 27)\n pC.J{end + 1} = sparse(1,[1,2],1/32,1,36); % states\n \n case{'DEM','NFM'}\n %--------------------------------------------------------------\n pE.J{end + 1} = []; % null\n pC.J{end + 1} = [];\n \n case{'BGT'}\n %--------------------------------------------------------------\n %assuming data are from STN\n pE.J{end + 1} = sparse(1,5,1,1,10); % 10 states\n pC.J{end + 1} = sparse(1,10);\n \n case{'MMC'}\n %--------------------------------------------------------------\n pE.J{end + 1} = sparse(1,[1 3 7],[.2 .2 .6],1,8); % 8 states\n pC.J{end + 1} = sparse(1,8);\n \n case{'NULL'}\n %--------------------------------------------------------------\n nx = size(pE.A,1)/m;\n pE.J{end + 1} = ones(1,nx); % nx states\n pC.J{end + 1} = ones(1,nx);\n \n otherwise\n warndlg('Unknown neural model')\n \n end\n \n % Cardinal sources\n %----------------------------------------------------------------------\n if isfield(model(i),'J')\n if numel(model(i).J)\n pE.J{i} = spm_zeros(pE.J{i});\n pE.J{i}(model(i).J) = 1;\n end\n end\n \n % subsidiary (free) sources\n %----------------------------------------------------------------------\n if isfield(model(i),'K')\n if numel(model(i).K)\n pC.J{i} = spm_zeros(pE.J{i});\n pC.J{i}(model(i).K) = 1/32;\n end\n end\n \nend\n\n% replace J with a vector if there is only one sort of model\n%--------------------------------------------------------------------------\nif numel(pE.J) == 1\n pE.J = pE.J{:};\n pC.J = pC.J{:};\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_L_priors.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.34844248858936344}}
{"text": "function [ objects ] = rectangle2hypothesis( xyzBox, rule, room_points )\n%RECTANGLE2HYPOTHESIS Popup rectangles to cuboids\n% Detailed explanation goes here\nCOUNTER_CLOCKWISE = true;\nFITTINGRULES;\nuni_room_points = zeros(8,3);\nuni_room_points(POINTMAPPING{3},1) = room_points(:,1);\nuni_room_points(POINTMAPPING{3},2) = room_points(:,2);\nuni_room_points(POINTMAPPING{3},3) = room_points(:,3);\n\nI = find(uni_room_points(1:4,1)<0 & uni_room_points(1:4,2)<0);\nID = rem([I I+1 I+2 I+3]-1,4) + 1;\nuni_room_points = uni_room_points([ID ID+4],:);\nwall_points = zeros(4,3,6);\nwall_points(:,:,1) = uni_room_points([1 4 8 5],:);\nwall_points(:,:,2) = uni_room_points([3 2 6 7],:);\nwall_points(:,:,3) = uni_room_points([2 1 5 6],:);\nwall_points(:,:,4) = uni_room_points([4 3 7 8],:);\nwall_points(:,:,5) = uni_room_points([1 2 3 4],:);\nwall_points(:,:,6) = uni_room_points([8 7 6 5],:);\n\nLRDU_SURF = zeros(6,4);\nLRDU_SURF(1,:) = [3 4 5 6];\nLRDU_SURF(2,:) = [4 3 5 6];\nLRDU_SURF(3,:) = [2 1 5 6];\nLRDU_SURF(4,:) = [1 2 5 6];\nLRDU_SURF(5,:) = [1 2 4 3];\nLRDU_SURF(6,:) = [1 2 3 4];\n\nnormals = [1 0 0; -1 0 0; 0 1 0; 0 -1 0; 0 0 1; 0 0 -1];\nnormal_ids = [1 1 2 2 3 3];\nmain_angle = [pi/2 -pi/2 -pi 0 0];\n\nobjects = repmat(struct('out_points_w',[],'name',[],'type',[],'points',[],'x_w',[]),0,1);\nobject = struct('out_points_w',[],'name','other','type',[],'points',[],'x_w',zeros(7,1));\nxyzBox = reshape(xyzBox', 3, 4)';\n\n%% if left two points in lhs wall, add a hypothesis\n[inside,~,~] = insideCone( wall_points(:,:,LRDU_SURF(rule,1)), xyzBox([1 4],:), 0 );\nif all(inside) \n LID = LRDU_SURF(rule,1);\n wall_point = wall_points(:,:,LID);\n point4 = LineFaceIntersection(wall_point(1,:), normals(LID,:), [0 0 0], xyzBox(1,:));\n point3 = LineFaceIntersection(wall_point(1,:), normals(LID,:), [0 0 0], xyzBox(4,:));\n point1 = LineFaceIntersection(point4, normals(rule,:), [0 0 0], xyzBox(2,:));\n point2 = LineFaceIntersection(point3, normals(rule,:), [0 0 0], xyzBox(3,:));\n point5 = point1; point6 = point2;\n point5(normal_ids(rule)) = wall_points(1,normal_ids(rule),rule);\n point6(normal_ids(rule)) = wall_points(1,normal_ids(rule),rule);\n \n object.out_points_w = [point1; point2; point3; point4; point5; point6];\n object.type = 9;\n object.points = object.out_points_w ./ repmat(sqrt(sum(object.out_points_w.^2,2)),1,3);\n object.x_w(1:3) = point3;\n object.x_w(4) = norm(point2-point3);\n object.x_w(5) = norm(point6-point2);\n object.x_w(6) = norm(point4-point3);\n object.x_w(7) = main_angle(rule);\n objects(end+1,1) = object;\nend\n\n%% if right two points in rhs wall, add a hypothesis\n[inside,~,~] = insideCone( wall_points(:,:,LRDU_SURF(rule,2)), xyzBox([2 3],:), 0 );\nif all(inside)\n RID = LRDU_SURF(rule,2);\n wall_point = wall_points(:,:,RID);\n point5 = LineFaceIntersection(wall_point(1,:), normals(RID,:), [0 0 0], xyzBox(2,:));\n point6 = LineFaceIntersection(wall_point(1,:), normals(RID,:), [0 0 0], xyzBox(3,:));\n point1 = LineFaceIntersection(point5, normals(rule,:), [0 0 0], xyzBox(1,:));\n point2 = LineFaceIntersection(point6, normals(rule,:), [0 0 0], xyzBox(4,:));\n point4 = point1; point3 = point2;\n point4(normal_ids(rule)) = wall_points(1,normal_ids(rule),rule);\n point3(normal_ids(rule)) = wall_points(1,normal_ids(rule),rule);\n \n object.out_points_w = [point1; point2; point3; point4; point5; point6];\n object.type = 9;\n object.points = object.out_points_w ./ repmat(sqrt(sum(object.out_points_w.^2,2)),1,3);\n object.x_w(1:3) = point3;\n object.x_w(4) = norm(point2-point3);\n object.x_w(5) = norm(point6-point2);\n object.x_w(6) = norm(point4-point3);\n object.x_w(7) = main_angle(rule); \n objects(end+1,1) = object;\nend\n\n%% if bottom two points in floor, add a hypothesis\n[inside,~,~] = insideCone( wall_points(:,:,LRDU_SURF(rule,3)), xyzBox([4 3],:), 0 );\nif all(inside)\n DID = LRDU_SURF(rule,3);\n wall_point = wall_points(:,:,DID);\n point3 = LineFaceIntersection(wall_point(1,:), normals(DID,:), [0 0 0], xyzBox(4,:));\n point2 = LineFaceIntersection(wall_point(1,:), normals(DID,:), [0 0 0], xyzBox(3,:));\n point4 = LineFaceIntersection(point3, normals(rule,:), [0 0 0], xyzBox(1,:));\n point1 = LineFaceIntersection(point2, normals(rule,:), [0 0 0], xyzBox(2,:));\n point5 = point4; point6 = point1;\n point5(normal_ids(rule)) = wall_points(1,normal_ids(rule),rule);\n point6(normal_ids(rule)) = wall_points(1,normal_ids(rule),rule);\n \n object.out_points_w = [point1; point2; point3; point4; point5; point6];\n object.type = 13;\n object.points = object.out_points_w ./ repmat(sqrt(sum(object.out_points_w.^2,2)),1,3);\n object.x_w(1:3) = point3;\n object.x_w(4) = norm(point2-point3);\n object.x_w(5) = norm(point5-point4);\n object.x_w(6) = norm(point4-point3);\n object.x_w(7) = main_angle(rule); \n objects(end+1,1) = object;\nend\n\n%% if all four points inside the wall, add a rectangle\n[inside,~,~] = insideCone( wall_points(:,:,rule), xyzBox, 0 );\nif all(inside)\n wall_point = wall_points(:,:,rule);\n point4 = LineFaceIntersection(wall_point(1,:), normals(rule,:), [0 0 0], xyzBox(1,:));\n point1 = LineFaceIntersection(wall_point(1,:), normals(rule,:), [0 0 0], xyzBox(2,:));\n point2 = LineFaceIntersection(wall_point(1,:), normals(rule,:), [0 0 0], xyzBox(3,:));\n point3 = LineFaceIntersection(wall_point(1,:), normals(rule,:), [0 0 0], xyzBox(4,:));\n point5 = point4;\n point8 = point1;\n point7 = point2;\n point6 = point3;\n \n object.out_points_w = [point1; point2; point3; point4; point5; point6; point7; point8];\n object.type = 1;\n object.points = object.out_points_w ./ repmat(sqrt(sum(object.out_points_w.^2,2)),1,3);\n object.x_w(1:3) = point3;\n object.x_w(4) = norm(point2-point3);\n object.x_w(5) = norm(point7-point2);\n object.x_w(6) = norm(point4-point3);\n object.x_w(7) = main_angle(rule); \n objects(end+1,1) = object;\nend\n\nend\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/ObjectHypothesisGeneration/Rectangle2Hypothesis/rectangle2hypothesis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3484424776715494}}
{"text": "%--- help for statespace/estimate ---\n%\n% ESTIMATE Maximum likelihood parameter estimation of state-space models \n% \n% Syntax:\n% \n% [EstMdl,estParams,EstParamCov,logL,Output] = estimate(Mdl,Y,params0)\n% [EstMdl,estParams,EstParamCov,logL,Output] = estimate(Mdl,Y,params0,\n% name,value,...)\n% \n% Description:\n% \n% For observation vector y(t) and state vector x(t), estimate parameters \n% of the following general state-space model by maximum likelihood:\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% For models created explicitly by specifying coefficients A, B, C, and D,\n% unknown parameters to estimate are identified by the presence of NaNs in\n% these model coefficients. Unknown parameters identified by the presence \n% of NaNs in the mean vector (Mean0) and covariance matrix (Cov0) of initial\n% states x(0) are optionally estimated as well.\n% \n% For models created implicitly by specifying a parameter mapping function \n% ParamMap, the mapping function is responsible for managing the presence \n% and placement of unknown parameters. In the implicit approach, the mapping\n% function alone defines the model, and is particularly convenient for \n% estimating complex models and for imposing certain parameter constraints. \n% Moreover, in more general settings in which the initial states are also \n% determined by unknown parameters, ParamMap may include additional output \n% arguments; refer to the SSM/DSSM constructor for more details.\n% \n% Input Arguments:\n% \n% Mdl - A state-space model with unknown parameters to estimate, created \n% by the SSM/DSSM constructor.\n% \n% Y - Observed response data to which the model is fit. For time-invariant \n% models in which the length of each observation vector (n) is the same, \n% Y is a T-by-n matrix. For time-varying models in which the length of \n% the observation vector changes, Y is a T-by-1 cell array in which \n% each element contains a time-varying n-element vector of observations, \n% y(t), associated with the corresponding period. The last observation \n% is the most recent.\n% \n% params0 - A vector containing the initial values of unknown \n% parameters associated with model coefficients A, B, C, and D, and \n% optionally the mean vector (Mean0) and covariance matrix (Cov0) of \n% initial states x(0), estimated by maximum likelihood. For models created \n% explicitly, parameters mapped to NaN values are found by a column-wise \n% search of A, followed by B, then C, then D, and finally Mean0 and Cov0. \n% For models created implicitly, the parameter function ParamMap is \n% solely responsible for mapping the initial parameter vector into model \n% coefficients A, B, C, and D, as well as additional information \n% regarding initial states and types if necessary. \n% \n% Optional Input Name/Value Pairs:\n% \n% 'Univariate' Logical value indicating whether to use the univariate \n% treatment of a multivariate series. The default is false.\n% \n% 'SquareRoot' Logical value indicating whether to use the square-root \n% filter. The default is false.\n% SSM only. No effects on DSSM.\n% \n% 'Tolerance' A small, non-negative variance tolerance that controls \n% whether an observed series is ignored if its forecast\n% uncertainty falls below this threshold. Setting tolerance \n% to a small number, say 1e-15, may help overcome numerical \n% problems of the filter. The default is 0.\n% \n% 'Predictors' 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% 'Beta0' d-by-n matrix of initial values of regression coefficients \n% associated with predictors (see above). If the model contains\n% a regression component, coefficients are estimated along \n% with other unknown parameters in A, B, C, D, Mean0, and \n% Cov0; the default initial values are obtained by ordinary \n% least squares (OLS) by regressing Y on the explanatory \n% variables.\n% \n% 'SwitchTime' a positive integer that specifies the date after which the\n% diffuse filter switches to the standard filter.\n% The default is the earliest date when the smoothed\n% initial states have a full-rank covariance matrix.\n% DSSM only. No effects on SSM.\n% \n% 'CovMethod' String or character vector indicating the method for\n% computing the asymptotic parameter error covariance\n% matrix of estimated parameters. Values are:\n% \n% VALUE METHOD\n% \n% o 'hessian' Negative inverted Hessian matrix\n% o 'opg' Outer product of gradients (default)\n% o 'sandwich' Both Hessian and outer product of gradients\n% \n% 'Options' Optimization options created with OPTIMOPTIONS. If \n% specified, default optimization parameters are replaced \n% by those in options. The default OPTIMOPTIONS object depends\n% on the optimization function used to estimate parameters.\n% For constrained optimization, FMINCON is called and the \n% algorithm used is interior point; for unconstrained \n% optimization, FMINUNC is called and the algorithm is \n% quasi-Newton. See documentation for OPTIMOPTIONS, FMINCON, \n% and FMINUNC for details.\n% \n% 'Display' String vector or cell vector of character vectors\n% indicating what information to display in the command\n% window. Values are:\n% \n% VALUE DISPLAY\n% \n% o 'off' No display to the command window. \n% \n% o 'params' Display maximum likelihood parameter \n% estimates, standard errors, and t statistics.\n% This is the default.\n% \n% o 'iter' Display iterative optimization information.\n% \n% o 'diagnostics' Display optimization diagnostics.\n% \n% o 'full' Display 'params', 'iter', and 'diagnostics'. \n% \n% The following optional name/value pairs are related to constrained\n% optimization performed by FMINCON (see FMINCON for details):\n% \n% 'Aineq' Linear inequality matrix, such that for solution vector X \n% Aineq*X <= bineq. The number of rows is determined by the \n% number of constraints, and the number of columns by the number \n% of estimated parameters. Columns are ordered by estimated \n% parameters in A, B, C, D, Mean0, Cov0, and finally regression \n% coefficients for models with a regression component.\n% \n% 'bineq' Linear inequality column vector, such that for solution vector\n% X Aineq*X <= bineq. \n% \n% 'Aeq' Linear equality matrix, such that for solution vector X \n% Aeq*X = beq. The number of rows is determined by the \n% number of constraints, and the number of columns by the number \n% of estimated parameters. Columns are ordered by estimated \n% parameters in A, B, C, D, Mean0, Cov0, and finally regression \n% coefficients for models with a regression component.\n% \n% 'beq' Linear equality column vector, such that for solution vector X \n% Aeq*X = beq. \n% \n% 'lb' Lower bounds column vector on estimated parameters. Vector \n% elements are ordered by estimated parameters in A, B, C, D, \n% Mean0, Cov0, and finally regression coefficients for models with \n% a regression component.\n% \n% 'ub' Upper bounds column vector on estimated parameters. Vector \n% elements are ordered by estimated parameters in A, B, C, D, \n% Mean0, Cov0, and finally regression coefficients for models with \n% a regression component.\n% \n% Output Arguments:\n% \n% EstMdl - A fitted state-space model with estimated model coefficients. \n% Provided the optimization converged successfully, the model is explicit \n% in its coefficients A, B, C, D, Mean0, and Cov0 regardless of whether \n% the input model (Mdl) was created explicitly or implicitly.\n% \n% estParams - Vector of estimated parameter. The elements are ordered such\n% that any estimated parameters in A appear first, then B, then C, then\n% D, and finally Mean0 and Cov0. Additionally, if the observation equation\n% includes a regression component, then estimates of any regression \n% coefficients appear last.\n% \n% EstParamCov - Variance-covariance matrix of estimated parameters. The\n% rows/columns are ordered such that variances/covariances of any \n% estimated parameters in A appear first, then B, then C, then D, and \n% finally Mean0 and Cov0. Additionally, if the observation equation\n% includes a regression component, then variances/covariances of any \n% estimated regression coefficients appear last.\n% \n% logL - Log-likelihood of the observations.\n% \n% Output - Output structure with the following fields:\n% \n% o ExitFlag - Optimization exit flag that describes the exit condition.\n% See FMINCON or FMINUNC for additional details.\n% \n% o Options - Optimization options, created with OPTIMOPTIONS, and used\n% by the optimizer.\n% \n% Notes:\n% \n% o Missing observations in Y are indicated by NaNs.\n% \n% o Although creating a model explicitly by directly specifying parameters\n% (A, B, C, D, etc.) with NaN placeholders to indicate parameters to \n% estimate is more convenient than specifying a user-defined mapping \n% function ParamMap, the utility of an explicit approach is limited in \n% that each estimated parameter affects and is uniquely associated with \n% a single element of a coefficient matrix. \n% \n% o The option of univariate treatment requires a diagonal D(t)*D(t)'.\n% \n% o The state-space model itself does not store regression data or \n% coefficients. Instead, a regression component is used to deflate the \n% observations, such that the deflated data is given by y(t) - z(t)*b. \n% \n% o Regression coefficients in the observation equation are estimated along \n% with other unknown parameters, and so parameter constraints may be \n% placed on regression coefficients as well other parameters by specifying \n% appropriate entries in 'Aineq', 'bineq', etc.\n% \n% o If observations are multivariate, then the same regressors apply to all.\n% \n% o If the state equation requires predictors, or each individual component \n% of the observation equation requires a set of distinct predictors, try\n% one of the following methods:\n% \n% o Expand the states by a constant one.\n% o Expand the states by predictors.\n% o Return 8 output arguments from the user-supplied function \n% ParamMap, the last of which is the deflated observation data.\n% \n% o Regression components in the observation equation are allowed only for\n% time-invariant observations, in which the input observation series Y\n% is of constant length and specified as a T-by-n matrix. Y specified as\n% a T-by-1 cell array indicates a time-varying observation series whose \n% length may change over time. If the length of each observation y(t)\n% changes, then it is unclear which regression coefficients are needed\n% to deflate a given observation.\n% \n% o If no constraints are specified, FMINUNC is used; otherwise, FMINCON \n% is used for constrained optimization. Therefore, when specifying the \n% input Options, the input should be consistent with the solver (see \n% OPTIMOPTIONS, FMINCON, and FMINUNC for details).\n% \n% Whenever possible, it is recommended to avoid equality/inequality \n% constraints by reparameterizing the model. For example, various \n% parameters may be exponentiated using EXP to ensure positivity.\n% \n% o The observations in the starting periods are treated as if they were\n% presample data for exact initialization of the diffuse initial\n% states. We define the likelihood function as the joint density\n% of the observations after the algorithm is switched to\n% the standard Kalman filter. The variable 'SwitchTime' determines when\n% the standard Kalman filter starts.\n% \n% See also SSM, DSSM, FILTER, SMOOTH, FORECAST, SIMULATE, SIMSMOOTH.\n%\n% Other functions named estimate\n%\n% abstvar/estimate garch/estimate\n% arima/estimate generic/estimate\n% conjugateblm/estimate gjr/estimate\n% customblm/estimate regARIMA/estimate\n% diffuseblm/estimate semiconjugateblm/estimate\n% dsge/estimate ssm/estimate\n% dssm/estimate varm/estimate\n% egarch/estimate vecm/estimate\n% empiricalblm/estimate\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/@dsge/estimate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.3484424776715493}}
{"text": "%COLORNAME Map between color names and RGB values\n%\n% RGB = COLORNAME(NAME) is the RGB-tristimulus value (1x3) corresponding to\n% the color specified by the string NAME. If RGB is a cell-array (1xN) of\n% names then RGB is a matrix (Nx3) with each row being the corresponding\n% tristimulus.\n%\n% XYZ = COLORNAME(NAME, 'xyz') as above but the XYZ-tristimulus value \n% corresponding to the color specified by the string NAME.\n%\n% XY = COLORNAME(NAME, 'xy') as above but the xy-chromaticity coordinates \n% corresponding to the color specified by the string NAME.\n%\n% NAME = COLORNAME(RGB) is a string giving the name of the color that is \n% closest (Euclidean) to the given RGB-tristimulus value (1x3). If RGB is\n% a matrix (Nx3) then return a cell-array (1xN) of color names.\n%\n% NAME = COLORNAME(XYZ, 'xyz') as above but the color is the closest (Euclidean)\n% to the given XYZ-tristimulus value.\n%\n% NAME = COLORNAME(XYZ, 'xy') as above but the color is the closest (Euclidean)\n% to the given xy-chromaticity value with assumed Y=1.\n%\n% Notes::\n% - Color name may contain a wildcard, eg. \"?burnt\"\n% - Based on the standard X11 color database rgb.txt.\n% - Tristimulus values are in the range 0 to 1\n\n\n\n% Copyright (C) 1993-2014, 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 = colorname(a, varargin)\n\n opt.color = {'rgb', 'xyz', 'xy'};\n opt = tb_optparse(opt, varargin);\n\n persistent rgbtable;\n \n mvtb_present = exist('tristim2cc');\n \n % ensure that the database is loaded\n if isempty(rgbtable)\n % load mapping table from file\n fprintf('loading rgb.txt\\n');\n f = fopen('private/rgb.txt', 'r');\n k = 0;\n rgb = [];\n names = {};\n xy = [];\n \n while ~feof(f),\n line = fgets(f);\n if line(1) == '#',\n continue;\n end\n \n [A,count,errm,next] = sscanf(line, '%d %d %d');\n if count == 3\n k = k + 1;\n rgb(k,:) = A' / 255.0;\n names{k} = lower( strtrim(line(next:end)) );\n if mvtb_present\n xy = tristim2cc( colorspace('RGB->XYZ', rgb) );\n end\n end\n end\n s.rgb = rgb;\n s.names = names;\n if mvtb_present\n s.xy = xy;\n end\n rgbtable = s;\n end\n \n if isstr(a)\n % map name to rgb/xy\n if a(1) == '?' \n % just do a wildcard lookup\n r = namelookup(rgbtable, a(2:end), opt);\n else\n r = name2rgb(rgbtable, a, opt);\n end\n elseif iscell(a)\n % map multiple names to rgb\n r = [];\n for name=a,\n rgb = name2rgb(rgbtable, name{1}, opt.xy);\n if isempty(rgb)\n warning('Color %s not found', name{1});\n end\n r = [r; rgb];\n end\n else\n % map values to strings\n switch opt.color\n case 'rgb'\n if numel(a) == 3\n r = rgb2name(rgbtable, a(:)');\n elseif numcols(a) ~= 3\n error('RGB data must have 3 columns');\n else\n r = {};\n for i=1:numrows(a)\n r{i} = rgb2name(rgbtable, a(i,:));\n end\n end\n \n case 'xyz'\n if numel(a) == 3\n rgb = colorspace('XYZ->RGB', a(:)');\n r = rgb2name(rgbtable, rgb);\n elseif numcols(a) ~= 3\n error('XYZ data must have 3 columns');\n else\n rgb = colorspace('XYZ->RGB', a);\n \n r = {};\n for i=1:numrows(a)\n r{i} = rgb2name(rgbtable, rgb(i,:));\n end\n end\n \n case 'xy'\n if numel(a) == 2\n Y = 1; XYZ = 1/a(2);\n X = a(1) * XYZ;\n Z = (1-a(1)-a(2)) * XYZ;\n rgb = colorspace('XYZ->RGB', [X Y Z]);\n r = rgb2name(rgbtable, rgb);\n elseif numcols(a) ~= 2\n error('xy data must have 2 columns');\n else\n Y = ones(numrows(a),1); XYZ = 1./a(:,2);\n X = a(:,1) .* XYZ;\n Z = (1-a(:,1)-a(:,2)) .* XYZ;\n rgb = colorspace('XYZ->RGB', [X Y Z]);\n \n r = {};\n for i=1:numrows(a)\n r{i} = rgb2name(rgbtable, rgb(i,:));\n end\n end\n end\n \n\n end\nend\n \nfunction r = namelookup(table, s)\n s = lower(s); % all matching done in lower case\n \n r = {};\n count = 1;\n for k=1:length(table.names),\n if ~isempty( findstr(table.names{k}, s) )\n r{count} = table.names{k};\n count = count + 1;\n end\n end\nend\n\nfunction out = name2rgb(table, s, opt)\n\n s = lower(s); % all matching done in lower case\n \n for k=1:length(table.names),\n if strcmp(s, table.names(k)),\n rgb = table.rgb(k,:);\n switch opt.color\n case 'rgb'\n out = rgb;\n case 'xy'\n XYZ = colorspace('RGB->XYZ', r);\n out = tristim2cc(XYZ);\n case 'xyz'\n out = colorspace('RGB->XYZ', rgb);\n end\n return;\n end\n end\n out = [];\nend\n\nfunction r = rgb2name(table, v)\n d = table.rgb - ones(numrows(table.rgb),1) * v;\n n = colnorm(d');\n [z,k] = min(n);\n r = table.names{k};\nend\n\nfunction r = xy2name(table, v)\n d = table.xy - ones(numrows(table.xy),1) * v;\n n = colnorm(d');\n [z,k] = min(n);\n r = table.names{k};\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/common/colorname.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3484376933599228}}
{"text": "classdef VademecumPtensorComputer < VademecumVariablesComputer\n \n properties (Access = private)\n pNorm \n end\n \n methods (Access = public)\n \n function obj = VademecumPtensorComputer(d)\n obj.init(d);\n obj.pNorm = d.pNorm;\n end \n \n end\n \n methods (Access = protected)\n \n function computeAmplificators(obj,imx,imy)\n obj.createAmplificatorInput();\n d = obj.amplificatorInput;\n d.pNorm = obj.pNorm;\n ga = AmplificatorComponentsCalculator(d);\n ga.compute();\n obj.vademecumData.variables{imx,imy}.Ptensor = ga.Phomog; \n obj.vademecumData.monomials = ga.monom;\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/VademecumPtensorComputer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.34843768662603863}}
{"text": "function dlY = model(dlX,parameters,hyperparameters,doTraining)\n\nnumBlocks = hyperparameters.NumBlocks;\ndropoutFactor = hyperparameters.DropoutFactor;\n\ndlY = dlX;\n\n% Residual blocks.\nfor k = 1:numBlocks\n dilationFactor = 2^(k-1);\n parametersBlock = parameters.(\"Block\"+k);\n \n dlY = residualBlock(dlY,dilationFactor,dropoutFactor,parametersBlock,doTraining);\nend\n\n% Fully connect\nweights = parameters.FC.Weights;\nbias = parameters.FC.Bias;\ndlY = fullyconnect(dlY,weights,bias,'DataFormat','CBT');\n\nend", "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/model.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3484376866260385}}
{"text": "function [pairs,pOri,cOri] = getP2CPairs(job,varargin)\n% \n\n% all parent - child neighbors\npairs = neighbors(job.grains);\n\nisParent = ismember(pairs, job.grains.id(job.isParent));\nisChild = ismember(pairs, job.grains.id(job.isChild));\n\nind = any(isParent,2) & any(isChild,2);\npairs = pairs(ind,:);\n\n% ensure parent is first\ndoFlip = isChild(ind,1);\npairs(doFlip,:) = fliplr(pairs(doFlip,:));\n\nif check_option(varargin,'quick') && length(pairs) > 10000\n ind = unique(randi(length(pairs),10000,1));\n pairs = pairs(ind,:);\nend\n\n% maybe there is nothing to do\nif isempty(pairs)\n pOri = orientation(job.csParent);\n cOri = orientation(job.csChild);\n return\nend\n\n% compute the corresponding mean orientations\nif job.useBoundaryOrientations \n \n % identify boundaries by grain pairs\n [gB,pairId] = job.grains.boundary.selectByGrainId(pairs);\n \n % extract boundary child orientations\n % TODO: this can be done faster\n pOri = job.ebsd('id',gB.ebsdId(:,1)).orientations; \n cOri = job.ebsdPrior('id',gB.ebsdId(:,2)).orientations;\n \n % average child orientations along the boundaries\n pOri = accumarray(pairId,pOri);\n cOri = accumarray(pairId,cOri);\n \nelse \n \n % simply the mean orientations of the grains\n pOri = job.grains('id',pairs(:,1)).meanOrientation;\n cOri = job.grains('id',pairs(:,2)).meanOrientation;\n \nend\n\n% translate to index if required\nif check_option(varargin,'index'), pairs = job.grains.id2ind(pairs); end\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/EBSDAnalysis/@parentGrainReconstructor/private/getP2CPairs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3484376866260385}}
{"text": "function output = fourier2crsspctrm(cfg, freq)\n\n% FOURIER2CRSSPCTRM transforms a fourier-containing freq-structure \n% into a crsspctrm-containing freq-structure, in which the\n% powerspectra are also contained in the cross-spectra, being a \n% channelcombination of a channel with itself.\n%\n% Use as\n% [freq] = fourier2crsspctrm(cfg, freq)\n%\n% where you have the following configuration options:\n% cfg.channel = cell-array with selection of channels,\n% see CHANNELSELECTION for details\n% cfg.channelcmb = cell-array with selection of combinations between\n% channels, see CHANNELCOMBINATION for details\n% cfg.keeptrials = 'yes' or 'no' (default)\n% cfg.foilim = 2-element vector defining your frequency limits of \n% interest. By default the whole frequency range of the \n% input is taken.\n%\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 ~isfield(cfg, 'channel'), cfg.channel = {'all'}; end\nif ~isfield(cfg, 'channelcmb'), cfg.channelcmb = {}; end\nif ~isfield(cfg, 'foilim'), cfg.foilim = [freq.freq(1) freq.freq(end)]; end\nif ~isfield(cfg, 'keepfourier'), cfg.keepfourier = 'no'; end\nif ~isfield(cfg, 'feedback'), cfg.feedback = 'text'; end\n\n%select the channels on which the power-spectra will be computed\nchn = ft_channelselection(cfg.channel,freq.label);\nfor j = 1:length(chn)\n chnindx(j,1) = find(strcmp(chn(j), freq.label));\n %chnindx(j,1) = find(strcmp(chn{j}, freq.label));\nend\n\n%convert the channelcombinations to indices\nchncmb = ft_channelcombination(cfg.channelcmb, freq.label);\ncmbindx = zeros(size(chncmb,1),2);\nfor j = 1:size(chncmb,1)\n cmbindx(j,1) = find(strcmp(chncmb(j,1), freq.label));\n cmbindx(j,2) = find(strcmp(chncmb(j,2), freq.label));\n %cmbindx(j,1) = find(strcmp(chncmb{j,1}, freq.label));\n %cmbindx(j,2) = find(strcmp(chncmb{j,2}, freq.label));\nend\n\n%dimensionality of the input data\nNrpt = length(freq.cumtapcnt);\nNfrq = size(freq.fourierspctrm,3);\nNtim = size(freq.fourierspctrm,4);\nNchn = length(chnindx);\nNcmb = size(cmbindx,1);\n\n%%FIXME\n%if Ntim>1, ft_error('correct handling of time-frequency data is not yet implemented, no information about tapers is available'); end\n\n%keeping track of the tapers\n%in the case of tfr fourier-data cumtapcnt is highly redundant; for each frequency\n%the number of tapers is equal, as well as for each trial, thus it is sufficient to\n%reduce the original cumtapcnt to a vector of Ntrlx1 containing the number of tapers\ncumtapcnt = freq.cumtapcnt;\nif ~isempty(strfind(freq.dimord, 'time')),\n %cumtapcnt is NtrlxNfrqxNtim; create just one column-vector\n cumtapcnt = ones(size(cumtapcnt,1),1).*unique(cumtapcnt(~isnan(cumtapcnt(:))));\nend\nsumtapcnt = cumsum([0; cumtapcnt(:)]);\n\npowspctrm = zeros(Nrpt, Nchn, Nfrq, Ntim);\nprogress('init', cfg.feedback, 'computing single-trial power-spectral densities');\nfor j = 1:Nrpt\n progress(j/Nrpt, 'trial %d/%d\\n', j, Nrpt);\n tmp1 = freq.fourierspctrm([1+sumtapcnt(j):sumtapcnt(j+1)], chnindx, :, :);\n tmp2 = freq.fourierspctrm([1+sumtapcnt(j):sumtapcnt(j+1)], chnindx, :, :);\n powspctrm(j, :, :, :) = squeeze(sum( tmp1 .* conj(tmp2), 1) ./ size(tmp1,1));\nend\nprogress('close');\n\ncrsspctrm = complex(zeros(Nrpt, Ncmb, Nfrq, Ntim), zeros(Nrpt, Ncmb, Nfrq, Ntim));\nprogress('init', cfg.feedback, 'computing single-trial cross-spectral densities');\nfor j = 1:Nrpt\n progress(j/Nrpt, 'trial %d/%d\\n', j, Nrpt);\n tmp1 = freq.fourierspctrm([1+sumtapcnt(j):sumtapcnt(j+1)], cmbindx(:,1), :, :);\n tmp2 = freq.fourierspctrm([1+sumtapcnt(j):sumtapcnt(j+1)], cmbindx(:,2), :, :);\n crsspctrm(j, :, :, :) = squeeze(sum( tmp1 .* conj(tmp2), 1) ./ size(tmp1,1));\nend\nprogress('close');\n\noutput.dimord = freq.dimord;\noutput.freq = freq.freq;\noutput.label = chn;\noutput.labelcmb(:,1) = freq.label(cmbindx(:,1));\noutput.labelcmb(:,2) = freq.label(cmbindx(:,2));\noutput.cumtapcnt = freq.cumtapcnt;\ntry, output.grad = freq.grad; end\ntry, output.time = freq.time; end\noutput.powspctrm = powspctrm;\noutput.crsspctrm = crsspctrm;\nif strcmp(cfg.keepfourier, 'yes'), output.fourierspctrm = freq.fourierspctrm; end \n\nif isempty(output.crsspctrm), output = rmfield(output, 'crsspctrm'); end\nif isempty(output.labelcmb ), output = rmfield(output, 'labelcmb' ); end\n\n% add information about the version of this function to the configuration\ncfg.version.name = mfilename('fullpath');\ncfg.version.id = '$Id$';\n\n% remember the configuration details of the input data\ntry, cfg.previous = freq.cfg; end\n\n% remember the exact configuration details in the output \noutput.cfg = cfg;\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/fourier2crsspctrm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3484376866260385}}
{"text": "%INITCAMERAMATRIX2D Finds an initial camera matrix from 3D-2D point correspondences\n%\n% cameraMatrix = cv.initCameraMatrix2D(objectPoints, imagePoints, imageSize)\n% [...] = cv.initCameraMatrix2D(..., 'OptionName', optionValue, ...)\n%\n% ## Input\n% * __objectPoints__ Vector of vectors of the calibration pattern points in\n% the calibration pattern coordinate space. Cell array of cell array of\n% 3-element vectors are accepted `{{[x,y,z],...}, ...}`.\n% * __imagePoints__ Vector of vectors of the projections of the calibration\n% pattern points. Cell array of cell array of 2-element vectors are accepted\n% `{{[x,y],...}, ...}`.\n% * __imageSize__ Image size in pixels used to initialize the principal point\n% `[w,h]`.\n%\n% ## Output\n% * __cameraMatrix__ Camera matrix 3x3, `A = [fx 0 cx; 0 fy cy; 0 0 1]`\n%\n% ## Options\n% * __AspectRatio__ If it is zero or negative, both `fx` and `fy` are\n% estimated independently. Otherwise, `fx = fy * AspectRatio`. default 1.0\n%\n% The function estimates and returns an initial camera matrix for the\n% camera calibration process. Currently, the function only supports planar\n% calibration patterns, which are patterns where each object point has\n% z-coordinate=0.\n%\n% See also: cv.calibrateCamera\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/initCameraMatrix2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.34843767989215424}}
{"text": "function parseOut = parser(lexIn)\n%STRCONVPARSER LL(1) parser for mathematical expressions\n% PARSEOUT = STRCONVPARSER(LEXIN) returns a syntax tree of expressions so that\n% it can be converted to a format Chebfun is able to work with. The input,\n% LEXIN, is the output of the method STRCONVLEXER(), and is a cell array of\n% strings, containaining the tokens of strings.\n%\n% This method implements a LL(1) parser, a technique from compiler theory. For\n% more details, see e.g.,\n% [1] Aho, Sethi, Ullman, Compilers: Principles, Techniques, and Tools,\n% Addison-Wesley, 1986.\n%\n% See also: STRINGPARSER, STRINGPARSER/STR2ANON, STRINGPARSER/LEXER.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers. \n% See http://www.chebfun.org/ for Chebfun information.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Developers note: Usually, a parser relies on having access to pointers, which\n% is not possible in MATLAB. We get around this issue using global variables.\n%\n% TODO: Can we now get around this? See #515.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Initialize all global variables\nglobal NEXT\nglobal COUNTER\nglobal LEX\nglobal STACK\n\n% Enter the main routine\nparseMain(lexIn);\n\n% Return the stored stack\nparseOut = STACK;\n\n% Clear all global variables\nNEXT = [];\nCOUNTER = [];\nLEX = [];\nSTACK = [];\n\nend\n\nfunction parseMain(lexIn)\n%PARSEMAIN The main parsing routine, starts the recursive parsing.\n\nglobal NEXT\nglobal STACK\nglobal LEX\nglobal COUNTER\n\nCOUNTER = 1;\nLEX = lexIn;\nNEXT = char(LEX(COUNTER, 2));\nSTACK = [];\n\n% Our expression can only start with certain labels, make sure we are\n% starting with one of them.\nvalidTypes = {'NUM', 'VAR', 'INDVAR', 'PDEVAR', 'LAMBDA',...\n 'FUNC1', 'FUNC2', 'FUNC3', 'UN-', 'UN+', 'LPAR'};\n\nif ( any(strcmp(NEXT, validTypes)) )\n \n % Enter the recursion and check for successful termination.\n parseExpA();\n \n % We've put a $ at the end of the lexer output. Hence, we have only\n % successfully parsed our string if the only remaining token left is a\n % $ sign.\n success = match('$');\n \n if ( ~success )\n reportError('Parse:end', ...\n 'Input expression ended in unexpected manner.');\n end\n \nelse\n \n reportError('Parse:start', 'Input field started with unaccepted symbol.');\n \nend\n\nend\n\n% The following is the allowed grammar of mathematical expressions in the\n% chebgui (\u00ac denotes an empty symbol):\n%\n% ExpA -> ExpA COMMA Exp0\n% ExpA -> Exp0\n% Exp0 -> Exp0 OP= Exp05\n% Exp0 -> Exp05\n% Exp05 -> Exp05 OPREL Exp1 where OPREL can be OP>, OP>=, OP<, OP<=\n% Exp05 -> Exp1\n% Exp1 -> Exp1 OP+ Exp2\n% Exp1 -> Exp1 OP- Exp2\n% Exp1 -> Exp2\n% Exp2 -> Exp2 OP* Exp3\n% Exp2 -> Exp2 OP/ Exp3\n% Exp2 -> Exp3\n% Exp3 -> Exp3 OP^ Exp4\n% Exp3 -> Exp4\n% Exp4 -> UN+ Exp4\n% Exp4 -> UN- Exp4\n% Exp4 -> Exp5\n% Exp5 -> NUM\n% Exp5 -> INDVAR\n% Exp5 -> PDEVAR\n% Exp5 -> LAMBDA\n% Exp5 -> VAR\n% Exp5 -> VAR ExpDer\n% Exp5 -> VAR LPAR ExpList RPAR\n% Exp5 -> VAR ExpDer LPAR ExpList RPAR\n% Exp5 -> FUNC1 LPAR Exp1 RPAR\n% Exp5 -> FUNC2 LPAR Exp1 COMMA Exp1 RPAR]\n% Exp5 -> FUNC3 LPAR Exp1 COMMA Exp1 COMMA Exp1 RPAR\n% Exp5 -> LPAR Exp1 RPAR\n% ExpDer -> DER\n% ExpDer -> \u00ac\n% ExpList -> Exp1\n% ExpList -> Exp1 COMMA STR\n\nfunction parseExpA()\n\nparseExp0();\nparseExpApr();\n\nend\n\nfunction parseExp0()\n\nparseExp05();\nparseExp0pr();\n\nend\n\nfunction parseExp05()\n\nparseExp1();\nparseExp05pr();\n\nend\n\nfunction parseExp1()\n\nparseExp2();\nparseExp1pr();\n\nend\n\nfunction parseExp2()\n\nparseExp3();\nparseExp2pr();\n\nend\n\nfunction parseExp3()\n\nparseExp4();\nparseExp3pr();\n\nend\n\nfunction parseExp4()\n\nparseExp5();\n\nend\n\nfunction parseExp5()\n\nglobal NEXT\nglobal COUNTER\nglobal LEX\n\n% We begin by checking whether we have hit a terminal case. In that case,\n% we push that into the stack. We need to treat variables with _ in the\n% names separately, as we only allow certain operators around the time\n% derivative.\nif ( strcmp(NEXT, 'VAR') )\n % Create a new tree for later use, corresponding to the dependent\n % variable\n tempLeaf = struct('center', {{char(LEX(COUNTER)), char(NEXT)}}, ...\n 'pdeflag', 0);\n \n % Push the variable onto the stack so that we can take the correct\n % actions if we have derivatives or expressions on the form u(...)\n % involved. If not, we'll simply pop it later.\n push(tempLeaf);\n\n % Begin by advancing as usual.\n advance();\n \n % If there follows a derivative symbol, ', we parse that\n parseExpDer();\n \n % If we then have a u(3) or u(3,left) situation (or u'(3) etc.), we\n % parse that as required\n parseExpList();\n \nelseif ( any(strcmp(NEXT, {'NUM', 'INDVAR', 'LAMBDA', 'STR'})) )\n newLeaf = struct('center', {{char(LEX(COUNTER)), char(NEXT)}}, ...\n 'pdeflag', 0);\n push(newLeaf);\n advance();\n \nelseif ( strcmp(NEXT, 'PDEVAR') )\n newLeaf = struct('center', {{char(LEX(COUNTER)), char(NEXT)}}, ...\n 'pdeflag', 1);\n push(newLeaf);\n advance();\n \nelseif ( strcmp(NEXT, 'FUNC1') ) % Functions which take one argument\n parseFunction1();\n \nelseif ( strcmp(NEXT, 'FUNC2') ) % Functions which take two arguments\n parseFunction2();\n \nelseif ( strcmp(NEXT, 'FUNC3') ) % Functions which take three arguments\n parseFunction3();\n\nelseif ( strcmp(NEXT, 'LPAR') )\n advance();\n parseExp05();\n\n % Check if NEXT symbol is ')' as it should be. If not, there is a\n % parenthesis imbalance in the expression and we return an error.\n m = match('RPAR'); \n if ( ~m )\n reportError('Parse:parenths', 'Parenthesis imbalance in input fields.')\n end\n \nelseif ( strcmp(NEXT, 'UN-') || strcmp(NEXT, 'UN+') || ...\n strcmp(NEXT, 'OP-') || strcmp(NEXT,'OP+') )\n % If + or - reaches this far, we have an unary operator.\n % ['UN', char(NEXT(3))] determines whether we have UN+ or UN-.\n newCenterNode = {{char(LEX(COUNTER)), ['UN', char(NEXT(3))]}};\n advance();\n parseExp4();\n \n rightArg = pop();\n \n pdeflag = rightArg.pdeflag;\n\n newTree = struct('center', newCenterNode, 'right', rightArg, ...\n 'pdeflag',pdeflag);\n push(newTree);\nelse\n \n reportError('Parse:terminal', ...\n ['Unrecognized character in input field:', NEXT]);\nend\n\nend\n\nfunction parseFunction1()\n\nglobal COUNTER\nglobal LEX\n\nfunctionName = char(LEX(COUNTER));\nadvance();\n\nif ( match('LPAR') )\n parseExp1();\n \n if ( match('COMMA') )\n reportError('Parse:func1', ...\n ['Method ''', functionName, ''' only takes one input argument.']);\n elseif ( ~match('RPAR') )\n reportError('Parse:parenths', 'Parenthesis imbalance in input fields.')\n end\n \n rightArg = pop();\n if ( rightArg.pdeflag )\n error('CHEBFUN:STRINGPARSER:parser:PDE', ...\n 'Cannot use time derivative as function arguments.')\n end\n % Can assume no pde if we reach here\n newTree = struct('center', {{functionName, 'FUNC1'}}, ...\n 'right', rightArg, 'pdeflag', 0);\n push(newTree);\nelse\n reportError('Parse:parenths', ...\n 'Need parenthesis when using functions in input fields.')\nend\n\nend\n\nfunction parseFunction2()\n\nglobal NEXT\nglobal COUNTER\nglobal LEX\n\n% Function which allow one or two arguments\noneArgAllowed = {'diff', 'cumsum', 'airy', 'mean'};\nfunctionName = char(LEX(COUNTER));\nadvance();\n\n% Here we need ( as the next symbol\nif ( strcmp(NEXT, 'LPAR') )\n advance();\n parseExp1();\n \n firstArg = pop();\n if ( firstArg.pdeflag )\n error('CHEBFUN:STRINGPARSER:parser:PDE', ...\n 'Cannot use time derivative as function arguments.')\n end\n \n % Check whether we have a comma, if so, continue as normal\n if ( match('COMMA') )\n parseExp1();\n m = match('RPAR');\n if ( ~m )\n reportError('Parse:parenths', ...\n 'Parenthesis imbalance in input fields.')\n end\n \n secondArg = pop();\n if ( secondArg.pdeflag )\n error('CHEBFUN:STRINGPARSER:parser:PDE', ...\n 'Cannot use time derivative as function arguments.')\n end\n\n % Can assume no pde if we reach here\n newTree = struct('left', firstArg, ...\n 'center', {{functionName, 'FUNC2'}}, ...\n 'right', secondArg,'pdeflag',0);\n push(newTree);\n \n elseif ( match('RPAR') )\n if ( any(strcmp(functionName, oneArgAllowed)) )\n % Have hit a function which allows one or two args.\n\n % If we only had one argument, we convert the function to type\n % FUNC1. Can assume no PDE if we reach here\n newTree = struct('center', {{functionName, 'FUNC1'}}, ...\n 'right', firstArg, 'pdeflag', 0);\n push(newTree);\n else\n % We tried to call a method which requires two args with only one.\n reportError('Parse:func2', ['Method ''', functionName, ...\n ''' requires two input arguments.']);\n end\n \n else\n reportError('Parse:parenths', 'Parenthesis imbalance in input fields.')\n end\n \nelse\n reportError('Parse:parenths', ...\n 'Need parenthesis when using functions in input fields.')\nend\n\nend\n\nfunction parseFunction3()\n\nglobal NEXT\nglobal COUNTER\nglobal LEX\n\n% Function which allow one or two arguments\noneArgAllowed = {'sum', 'integral'};\ntwoArgAllowed = {'feval', 'fred', 'volt'};\nfunctionName = char(LEX(COUNTER));\nadvance();\n\n% Here we need ( as the next symbol\nif ( strcmp(NEXT, 'LPAR') )\n advance();\n parseExp1();\n firstArg = pop();\n if ( firstArg.pdeflag )\n error('CHEBFUN:STRINGPARSER:parser:PDE', ...\n 'Cannot use time derivative as function arguments.')\n end\n \n % Check whether we have a comma, if so, continue as normal\n if ( match('COMMA') )\n parseExp1();\n secondArg = pop();\n if ( secondArg.pdeflag )\n error('CHEBFUN:STRINGPARSER:parser:PDE', ...\n 'Cannot use time derivative as function arguments.')\n end\n\n if ( match('COMMA') ) % and again\n parseExp1();\n thirdArg = pop();\n\n % Define the new branch\n newTree = struct('left', firstArg, ...\n 'center', {{functionName, 'FUNC3'}}, ...\n 'right', secondArg, 'arg', thirdArg, 'pdeflag', 0);\n\n if ( ~match('RPAR') ) % Check the final parenthesis\n reportError('Parse:parenths', ...\n 'Parenthesis imbalance in input fields.')\n end\n elseif ( match('RPAR') && any(strcmp(functionName, twoArgAllowed)) )\n % This was actually a two argument function in disguise\n newTree = struct('left', firstArg, ...\n 'center', {{functionName, 'FUNC2'}},...\n 'right', secondArg, 'pdeflag', 0);\n else\n reportError('Parse:parenths', ...\n 'Parenthesis imbalance in input fields.')\n end\n push(newTree);\n \n elseif ( match('RPAR') )\n if ( any(strcmp(functionName,oneArgAllowed)) )\n % Have hit a function which allows one or two args.\n\n % If we only had one argument, convert the function to type FUNC1.\n % Can assume no PDE if we reach here.\n newTree = struct('center', {{functionName, 'FUNC1'}}, ...\n 'right', firstArg, 'pdeflag', 0);\n push(newTree);\n else\n % We tried to call a method which requires two args with only one.\n reportError('Parse:func2', ['Method ''', functionName, ...\n ''' requires two input arguments.']);\n end\n \n else\n reportError('Parse:parenths', 'Parenthesis imbalance in input fields.')\n end\n \nelse\n reportError('Parse:parenths', 'Need parenthesis when using functions in input fields.')\nend\n\nend\n\nfunction parseExp1pr()\n\nglobal NEXT\n\nif ( strcmp(NEXT, 'OP+') )\n\n advance();\n leftArg = pop();\n parseExp2();\n rightArg = pop();\n \n pdeflag = leftArg.pdeflag || rightArg.pdeflag;\n \n newTree = struct('left', leftArg, 'center', {{'+', 'OP+'}}, ...\n 'right', rightArg, 'pdeflag', pdeflag);\n push(newTree);\n parseExp1pr();\n \nelseif ( strcmp(NEXT, 'OP-') )\n advance();\n leftArg = pop();\n parseExp2();\n rightArg = pop();\n\n pdeflag = leftArg.pdeflag || rightArg.pdeflag;\n newTree = struct('left', leftArg, 'center', {{'-', 'OP-'}}, ...\n 'right', rightArg, 'pdeflag', pdeflag);\n push(newTree);\n parseExp1pr();\nelseif ( strcmp(NEXT, 'RPAR') || strcmp(NEXT, '$') || strcmp(NEXT, 'OP=') )\n\t% Do nothing\nelse % If we don't have ) or the end symbol now something has gone wrong.\n% reportError('Parse:end','Syntax error in input fields.')\nend\n\nend\n\n\nfunction parseExp2pr()\n\nglobal NEXT\n\nif ( strcmp(NEXT,'OP*') )\n leftArg = pop(); % Pop from the stack the left argument\n advance(); % Advance in the input\n parseExp3();\n rightArg = pop(); % Pop from the stack the right argument\n\n % Check whether we have _ variables\n if ( leftArg.pdeflag || rightArg.pdeflag )\n error('CHEBFUN:STRINGPARSER:parser:PDE','Cannot multiply time derivative')\n end\n\n % Can assume no PDE if we reach here\n newTree = struct('left', leftArg, 'center', {{'.*', 'OP*'}}, ...\n 'right', rightArg, 'pdeflag', 0);\n push(newTree);\n parseExp2pr();\n \nelseif ( strcmp(NEXT,'OP/') )\n leftArg = pop(); % Pop from the stack the left argument\n advance(); % Advance in the input\n parseExp3();\n rightArg = pop(); % Pop from the stack the right argument\n\n % Check whether we have _ variables\n if ( leftArg.pdeflag || rightArg.pdeflag )\n error('CHEBFUN:STRINGPARSER:parser:PDE','Cannot divide with time derivatives')\n end\n\n % Can assume no PDE if we reach here\n newTree = struct('left', leftArg, 'center', {{'./', 'OP/'}}, ...\n 'right', rightArg, 'pdeflag', 0);\n push(newTree);\n parseExp2pr();\nelse\n % Do nothing\nend\n\nend\n\nfunction parseExp3pr()\n\nglobal NEXT\n\nif ( strcmp(NEXT,'OP^') )\n leftArg = pop();\n advance(); \n parseExp4();\n rightArg = pop();\n\n % Check whether we have _ variables\n if ( leftArg.pdeflag || rightArg.pdeflag )\n error('CHEBFUN:STRINGPARSER:parser:PDE','Cannot take powers with time derivative')\n end\n\n % Can assume no pde if we reach here\n newTree = struct('left', leftArg, 'center', {{'.^', 'OP^'}}, ...\n 'right', rightArg, 'pdeflag', 0);\n push(newTree);\n parseExp3pr();\n \nelseif ( ~isempty(strfind(NEXT, 'DER')) )\n leftArg = pop();\n\n % Check whether we have _ variables\n if ( leftArg.pdeflag )\n error('CHEBFUN:STRINGPARSER:parser:PDE','Cannot differentiate time derivative')\n end\n\n newTree = struct('center', {{'D', NEXT}}, 'right', leftArg, 'pdeflag', 0);\n push(newTree);\n advance();\n parseExp3pr();\nelse\n % Do nothing\nend\n\nend\n\nfunction parseExpDer()\n% parseExpDer deals with ' denoting derivatives on the dependent variables\n% in the problem.\n\nglobal NEXT\n\nif ( ~isempty(strfind(NEXT, 'DER')) )\n leftArg = pop();\n\n % Check whether we have _ variables\n if ( leftArg.pdeflag )\n error('CHEBFUN:STRINGPARSER:parser:PDE','Cannot differentiate time derivative')\n end\n\n newTree = struct('center', {{'D', NEXT}}, 'right', leftArg, 'pdeflag', 0);\n push(newTree);\n advance();\nelse\n % Do nothing\nend\n\nend\n\nfunction parseExpList()\n% parseExpList deals with potential arguments to the dependent variables in\n% the problem, e.g. u(3,left).\n\nglobal NEXT\nglobal COUNTER\nglobal LEX\n\nif ( match('LPAR') ) % We are in a u(3) or u(3,left) situation\n % The first argument expression can only be of type EXP05 or higher\n % (no = or comma-dividers are allowed)\n parseExp1();\n % Check whether we are in in u(3) or u(3,left) situation. If we\n % have a match with ), we must have a feval with two arguments. If\n % we have a match with a comma, we must have a feval with three\n % arguments, but if there is no match, we have parenthesis\n % imbalance.\n if ( match('RPAR') )\n % Here we only had one argument in u(...), so we create a feval of type\n % FUNC2 (since the feval method has two input arguments)\n secondArg = pop();\n firstArg = pop();\n\n % Can assume no PDE if we reach here\n newTree = struct('left', firstArg, 'center', {{'feval', 'FUNC2'}}, ...\n 'right', secondArg,'pdeflag', 0);\n push(newTree);\n \n elseif ( match('COMMA') )\n % Here we only had two arguments in u(...), so we create a\n % feval of type FUNC3 (since the feval method has three input\n % arguments)\n \n % Check whether we have any of the allowed option type as the\n % second argument. If not, throw an error.\n if ( strcmp(NEXT,'STR') )\n % We got a match! But we also need to check for parenthesis\n % balance. Store the option as a temporary leaf\n optLeaf = struct('center', {{char(LEX(COUNTER)), char(NEXT)}}, ...\n 'pdeflag', 0);\n % Advance and check for parenth. balance\n advance();\n if ( match('RPAR') )\n % Create a feval of type FUNC3 (since the feval method\n % has three input arguments)\n secondArg = pop();\n firstArg = pop();\n thirdArg = optLeaf;\n\n % Can assume no pde if we reach here\n newTree = struct('left', firstArg, ...\n 'center', {{'feval', 'FUNC3'}}, 'right', secondArg, ...\n 'arg',thirdArg, 'pdeflag', 0);\n push(newTree);\n else\n reportError('Parse:parenths', ...\n 'Parenthesis imbalance in input fields.')\n end\n else\n reportError('Parse:secondArg', ...\n 'Invalid second argument to u(0,...) type of expression.')\n end\n \n else % There must be a parenthesis imbalance.\n reportError('Parse:parenths', 'Parenthesis imbalance in input fields.')\n end\nelse % We reach here for the default behaviour, e.g. u' = 1, no parentheses involved\n % Do nothing, since we've already pushed the variable onto the\n % stack.\nend\n\nend\n\nfunction parseExp0pr()\n\nglobal NEXT\n\nif ( strcmp(NEXT, 'OP=') )\n \n leftArg = pop();\n advance();\n parseExp05();\n\n rightArg = pop();\n\n pdeflag = leftArg.pdeflag || rightArg.pdeflag;\n\n newTree = struct('left', leftArg, 'center', {{'=', 'OP='}}, ...\n 'right', rightArg, 'pdeflag', pdeflag);\n push(newTree); \nelse\n\t% Do nothing\nend\n\nend\n\nfunction parseExpApr()\n\nglobal NEXT\n\nif ( strcmp(NEXT, 'COMMA') )\n \n advance();\n leftArg = pop();\n parseExpA();\n rightArg = pop();\n \n pdeflag = leftArg.pdeflag || rightArg.pdeflag;\n \n newTree = struct('left', leftArg, 'center', {{',', 'COMMA'}}, ...\n 'right', rightArg, 'pdeflag', pdeflag);\n push(newTree);\nelse\n\t% Do nothing\nend\n\nend\n\nfunction parseExp05pr()\n\nglobal NEXT\n\nif ( any(strcmp(NEXT, {'OP>', 'OP>=', 'OP<', 'OP<='})) )\n tempOpType = NEXT;\n tempOpLabel = tempOpType(3:end);\n \n advance();\n leftArg = pop();\n parseExp1();\n rightArg = pop();\n \n pdeflag = leftArg.pdeflag || rightArg.pdeflag;\n \n newTree = struct('left', leftArg, 'center', {{tempOpLabel, tempOpType}}, ...\n 'right', rightArg, 'pdeflag', pdeflag);\n push(newTree);\nelse\n\t% Do nothing\nend\n\nend\n\nfunction advance()\n%ADVANCE Move to the next token in the output from the lexer.\nglobal NEXT\nglobal COUNTER\nglobal LEX\n\nCOUNTER = COUNTER + 1;\nNEXT = char(LEX(COUNTER,2));\n\nend\n\n\n\nfunction m = match(label)\n\nglobal NEXT\nm = strcmp(label, NEXT);\n\n% If we found a match and are not at the end of output, we want to advance\n% to the NEXT symbol\nif ( m && ~strcmp(label, '$') )\n advance();\nend\n\nend\n\n\nfunction push(new)\n%PUSH Push a tree to the stack of syntax trees\nglobal STACK\n\nif ( ~stackRows() )\n STACK = new;\nelse\n % Ensure number of fields matches\n [STACK, new] = mergeFields(STACK, new);\n % Update the Stack\n STACK = [STACK ; new];\nend\n\nend\n\n\nfunction p = pop()\n%POP Pop a tree from the stack.\nglobal STACK\n\n% Throw a sensible error if we have an empty stack\nif ( isempty(STACK) )\n reportError('Parse:end', 'Syntax error in input expression (Empty stack)');\nend\n\np = STACK(end,:);\nSTACK(end,:) = [];\n\nend\n\nfunction m = stackRows()\n\nglobal STACK\n[m, n] = size(STACK); %#ok\n\nend\n\n% TODO: Can we get rid of this function entirely?\nfunction reportError(id, msg)\n\nerror(['CHEBFUN:', id], msg);\n% ME = MException(id,msg);\n% throw(ME);\n\nend\n\n\nfunction [a, b] = mergeFields(a, b)\n\naFields = fieldnames(a); \nbFields = fieldnames(b);\n\nfor k = 1:numel(aFields)\n if ( ~isfield(b, aFields{k}) )\n b.(aFields{k}) = [];\n end\nend\n\nfor k = 1:numel(bFields)\n if ( ~isfield(a, bFields{k}) )\n a.(bFields{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/@stringParser/parser.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.34839763850849137}}
{"text": "function show_per_class_table( soa, soa_ids, res_id, measure )\n\n% Pascal classes names\nclasses={'aeroplane', 'bicycle' , 'bird' , 'boat' ,...\n 'bottle' , 'bus' , 'car' , 'cat' ,...\n 'chair' , 'cow' , 'diningtable', 'dog' ,...\n 'horse' , 'motorbike', 'person' , 'pottedplant',...\n 'sheep' , 'sofa' , 'train' , 'tvmonitor' };\n\n% Allocate\nall_res = zeros(length(soa_ids),length(classes)+1);\nncands = zeros(length(res_id),1);\n\n% Fill\nfor ii=1:length(soa_ids)\n ncands(ii) = soa.(soa_ids{ii}).mean_n_masks(res_id(ii));\n for kk=1:length(classes)\n if strcmp(measure,'jaccard_object')\n res = soa.(soa_ids{ii}).per_class_results{kk}.meanmax;\n else\n res = soa.(soa_ids{ii}).per_class_results{kk}.global_J;\n end\n all_res(ii,kk) = res(res_id(ii));\n end\n res = soa.(soa_ids{ii}).(measure);\n all_res(ii,end) = res(res_id(ii));\nend\n\n% Get the maximums to set in boldface\n[~,max_ids] = max(all_res,[],1);\ndisp(['MCG is the best in ' num2str(sum(max_ids(1:end-1)==1)) ' categories'])\n\n% Show header\nto_disp = ' Method & NCands & ';\nfor kk=1:length(classes)\n to_disp = [to_disp sprintf('%14s',classes{kk}) ' & ']; %#ok\nend\nto_disp = [to_disp ' Global \\\\'];\ndisp(to_disp)\n\n% Show table\nfor ii=1:length(soa_ids)\n curr_n_reg = soa.(soa_ids{ii}).mean_n_masks(res_id(ii));\n to_disp = [sprintf('%10s', soa_ids{ii}) ' & ' sprintf('%4s%d',' ', round(curr_n_reg)) ' & '];\n for kk=1:length(classes)\n if (ii==max_ids(kk))\n to_disp = [to_disp sprintf('%13s',['\\textbf{' sprintf('%2.1f',100*all_res(ii,kk))]) '} & ']; %#ok\n else\n to_disp = [to_disp sprintf('%13s',sprintf('%2.1f',100*all_res(ii,kk))) ' & ']; %#ok\n end\n end\n if (ii==max_ids(end))\n to_disp = [to_disp sprintf('%13s',['\\textbf{' sprintf('%2.1f',100*all_res(ii,end))]) '} \\\\ ']; %#ok\n else\n to_disp = [to_disp sprintf('%13s',sprintf('%2.1f',100*all_res(ii,end))) ' \\\\']; %#ok\n end\n disp(to_disp)\nend\n\nend\n\n", "meta": {"author": "jponttuset", "repo": "mcg", "sha": "e72031d793abf8921e39a8ef3c20de2198c8b26f", "save_path": "github-repos/MATLAB/jponttuset-mcg", "path": "github-repos/MATLAB/jponttuset-mcg/mcg-e72031d793abf8921e39a8ef3c20de2198c8b26f/benchmark/src/aux/show_per_class_table.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3483976304384037}}
{"text": "function tdetx = tdet(x,K)\n% tdetx = tdet(x,K)\n%\n% TDET Computes twice determinant for Lorentz block\n%\n% ********** INTERNAL FUNCTION OF SEDUMI **********\n%\n% See also sedumi\n\n% This file is part of SeDuMi 1.1 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\nif isempty(K.q)\n tdetx = zeros(0,1);\nelse\n ix = K.mainblks;\n tdetx = x(ix(1):ix(2)-1).^2 - ddot(x(ix(2):ix(3)-1),x,K.qblkstart);\nend", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/sedumi/tdet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3483332715490145}}
{"text": "\nfunction Tr_Im=rotate3D(Im, T, R)\n% rotate 3D volume by T & R\n\n[row,col,layer] = size(Im);\nTr_Im = tformarray(Im, T, R, [1 2 3], [1 2 3], [row, col,layer], [], []);\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/Tran3D/rotate3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.34828943379113725}}
{"text": "classdef PoleFigure < dynProp & dynOption\n%\n% The class *PoleFigure* is used to store experimetnal pole figure\n% intensitied, i.e., XRD, synchrotron or neuron data. It provides several\n% as well as the\n% . Importing pole figure data is explained in .\n%\n% Input\n% h - crystal directions (@vector3d | @Miller)\n% r - specimen directions (@S2Grid)\n% intensities - diffraction counts (double)\n% CS,SS - crystal, specimen @symmetry\n%\n% Options\n% superposition - weights for superposed crystal directions\n% background - background intensities\n%\n% Class Properties\n% allH - cell of @Miller\n% allR - cell of @vector3d\n% allI - cell of diffraction intensities\n% c - structure coefficients\n% SS - specimen symmetry\n%\n% Dependent Class Properties\n% CS - @crystalSymmetry\n% h - @Miller direction of single pole figure\n% r - specimen directions\n% intensities - diffraction intensities\n% antipodal - \n%\n% See also\n% ImportPoleFigureData loadPoleFigure loadPoleFigure_generic\n% This section describes the class *PoleFigure* and gives an overview of\n% the functionality MTEX offers to analyze pole figure data.\n\n properties\n allH = {} % crystal directions\n allR = {} % specimen directions\n allI = {} % intensities\n c = {} % structure coefficients for superposed pole figures\n SS = specimenSymmetry % specimen symmetry\n end\n \n properties (Dependent = true)\n CS % crystal symmetry\n h % crystal direction of single pole figure\n r % specimen directions\n intensities % diffraction intensities\n antipodal\n end\n \n methods\n \n \n function pf = PoleFigure(h,r,intensities,varargin)\n % constructor\n \n if nargin == 0, return;end\n \n pf.allH = ensurecell(h);\n pf.allR = ensurecell(r);\n if numel(pf.allR) == 1, pf.allR = repmat(pf.allR,size(pf.allH));end\n if ~check_option(varargin,'complete'), pf.allR{1}.antipodal = true;end \n pf.allI = ensurecell(intensities);\n \n \n pf.c = ensurecell(get_option(varargin,'superposition',...\n cellfun(@(x) ones(1,length(x)),pf.allH,'uniformoutput',false)));\n \n % normalize structure coefficients\n %pf.c = cellfun(@(x) x./sum(x),pf.c,'uniformOutput',false);\n \n % extract symmetries\n pf.CS = getClass(varargin,'crystalSymmetry',pf.CS);\n pf.SS = getClass(varargin,'specimenSymmetry',pf.SS);\n \n end\n \n function pf = set.CS(pf,CS)\n \n for i = 1:length(pf.allH)\n pf.allH{i}.CS = CS;\n end\n end\n \n function CS = get.CS(pf)\n \n CS = pf.allH{1}.CS;\n \n end\n \n function h = get.h(pf)\n h = pf.allH;\n h = horzcat(h{:});\n end\n \n function r = get.r(pf)\n try\n r = [pf.allR{:}];\n catch\n for i = 1:numel(pf.allR)\n pf.allR{i} = pf.allR{i}(:);\n end\n r = vertcat(pf.allR{:});\n end\n end\n \n function i = get.intensities(pf)\n try\n i = [pf.allI{:}];\n catch\n for i = 1:numel(pf.allI)\n pf.allI{i} = pf.allI{i}(:);\n end\n i = vertcat(pf.allI{:});\n end\n end\n \n function pf = set.intensities(pf,i)\n \n if numel(i) == 1\n for ipf = 1:numel(pf.allI)\n \n pf.allI{ipf} = i*ones(size(pf.allI{ipf}));\n \n end\n else\n cs = cumsum([0,cellfun('prodofsize',pf.allI)]);\n \n for ipf = 1:numel(pf.allI)\n pf.allI{ipf} = reshape(i(cs(ipf)+1:cs(ipf+1)),size(pf.allI{ipf}));\n end\n end\n end\n\n function out = get.antipodal(pf)\n out = pf.allR{1}.antipodal;\n end\n \n function pf = set.antipodal(pf,value)\n for i = 1:pf.numPF\n pf.allR{i}.antipodal = value;\n end\n end\n \n function varargout = size(pf,varargin)\n [varargout{1:nargout}] = size(pf.r,varargin{:});\n end\n \n function varargout = length(pf,ip)\n if nargin == 2\n if isempty(ip)\n varargout{1} = cellfun(@length,pf.allR);\n else\n [varargout{1:nargout}] = length(pf.allR{ip});\n end\n else\n [varargout{1:nargout}] = length(pf.r);\n end\n end\n \n function n = numPF(pf)\n n = numel(pf.allH);\n end\n \n function e = end(pf,i,n)\n % overloaded end function\n\n if n==1\n e = numel(pf.r);\n else\n e = size(pf.r,i);\n end\n end\n \n end\n \n methods (Static = true)\n [pf,interface,options] = load(fname,varargin)\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/@PoleFigure/PoleFigure.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105587468141, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3482894268451718}}
{"text": "function y = residuals(fit,type)\n\n% Residuals (or a few other things) from a locfit() fit.\n%\n% Input arguments:\n% fit - the locfit() fit.\n% type (optional) type of residuals. Valid types are\n% 'dev' (deviance, the default)\n% 'd2' (deviance squared)\n% 'pearson'(Pearson)\n% 'raw' (observed - fitted)\n% 'ldot' (derivative of log-likelihood)\n% 'lddot' (second derivative)\n% 'fit' (fitted values - no transformation)\n% 'mean' (fitted values - with back transformation)\n%\n% Author: Catherine Loader.\n\nif (nargin<2) type = 'dev'; end;\n \ny = predict(fit,'d','restyp',type);\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/residuals.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3482894268451717}}
{"text": "function [vin, vout] = EdgeExtract(img, imgf)\n S = im2double(img);\n vin = [diff(S,1,1); S(1,:,:) - S(end,:,:)];\n img_filtered = im2double(imgf);\n S = im2double(img_filtered);\n vout = [diff(S,1,1); S(1,:,:) - S(end,:,:)];\nend\n\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/applications/deep_edge_aware_filters/utility/EdgeExtract.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.34828904686660667}}
{"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% load image matrix from system screenshot\n\nfunction MU_load_screenshot(handles)\n\ntry\n import java.awt.*;\n rob=Robot;\n t=java.awt.Toolkit.getDefaultToolkit();\n rec=java.awt.Rectangle(t.getScreenSize());\n img=rob.createScreenCapture(rec);\n filehandle=java.io.File('__scrnsht_temp.bmp');\n javax.imageio.ImageIO.write(img,'bmp',filehandle);\n imdata = imread('__scrnsht_temp.bmp','bmp'); % temporary file\n delete('__scrnsht_temp.bmp'); % temp file removed\n if ~MU_load_matrix('sns', imdata, 1)\n error('Loading image from screenshot failed!');\n end\n \ncatch me\n error_msg{1,1}='Error!!! Getting image information from system screenshot aborted.';\n error_msg{2,1}=me.message;\n errordlg(error_msg);\n return;\nend\n\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/Main/MU_load_screenshot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.34828903933149513}}
{"text": "function my_grad(V,F,u,k)\n%MY_GRAD Compute the numerical gradient operator for triangle meshes\n%\n% my_grad(V,F);\n%\n% Inputs:\n% V,F the input mesh for which to compute the gradient operator\n% Outputs:\n% G the sparse gradient matrix\n%\n\nG = ...\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/012_gradient/exercise/my_grad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.3482890393314951}}
{"text": "function [ res ] = pesq3( reference_sig, degraded_sig, Fs, fileNum )\n% A wrapper for the objective Perceptual Evaluation of Speech Quality measure\n% \n% Syntax:\t[ res ] = pesq3( reference_sig, degraded_sig, Fs, fileNum )\n% \n% Inputs: \n% \treference_sig - Reference (clean, talker, sender) speech signal\n% \tdegraded_sig - Degraded (noisy, listener, receiver) speech signal\n% \tFs - Sampling Frequency\n% fileNum - An ID number to append to the temporary audio files. Useful\n% when several instances are to be run together (in parallel).\n% \n% Outputs: \n% \tres - Raw PESQ result for narrowband and MOS-LQO result for wideband\n% \n% See also: pesq2mos.m\n\n% Author: Jacob Donley\n% University of Wollongong\n% Email: jrd089@uowmail.edu.au\n% Copyright: Jacob Donley 2017\n% Date: 03 October 2015 \n% Revision: 0.1\n% \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif nargin < 4\n fileNum = 0;\nend\ntemp_path = [pwd filesep '+Miscellaneous\\+Temporary\\'];\nref_path = [ 'tmp_ref' num2str(fileNum) '.wav'];\ndeg_path = [ 'tmp_deg' num2str(fileNum) '.wav'];\n\nif ~exist(temp_path,'dir'); mkdir(temp_path); end\n\nmax_val = max(abs([reference_sig(:); degraded_sig(:)]));\n\naudiowrite([temp_path ref_path], reference_sig / max_val, Fs);\naudiowrite([temp_path deg_path], degraded_sig / max_val, Fs);\n\nres = pesq2_mtlb(ref_path, ...\n deg_path, ...\n Fs, 'wb', [pwd filesep '+Tools\\pesq_NoResFile.exe'], ...\n temp_path);\n\nend\n\n", "meta": {"author": "jdonley", "repo": "SoundZone_Tools", "sha": "57f0135494435190f0323c46809f32e37e55b1a3", "save_path": "github-repos/MATLAB/jdonley-SoundZone_Tools", "path": "github-repos/MATLAB/jdonley-SoundZone_Tools/SoundZone_Tools-57f0135494435190f0323c46809f32e37e55b1a3/pesq3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.3482890393314951}}
{"text": "% dim_red_type: dimension reduction type: one of the strings: '', 'pca', 'ica'\n% new_dim: relevant only if dim_red_type is not ''\nfunction lmm(numClusters, is_sampled, dim_red_type, new_dim, numOfEMIter, numOfCpus)\n\n fv_init;\n\n if ~exist('numOfEMIter', 'var')\n numOfEMIter = 10;\n end\n \n if ~exist('numOfCpus', 'var')\n numOfCpus = 4;\n end\n\n word2vec_sqrt = false;\n \n mult_factor = LMM_HGLMM_MULT_FACTOR;\n \n output(1, 'LMM_HGLMM_MULT_FACTOR = %d\\n', LMM_HGLMM_MULT_FACTOR);\n\n vectors_file_name = add_data_dir_base('GoogleNews_vectors_norm.mat');\n output_file_name = add_data_dir_base(sprintf('GoogleNews_norm_lmm_%d.mat', numClusters));\n \n if word2vec_sqrt\n vectors_file_name = fname_concat(vectors_file_name, '_sqrt');\n output_file_name = fname_concat(output_file_name, '_sqrt');\n end\n \n if is_sampled\n vectors_file_name = fname_concat(vectors_file_name, '_sampled');\n output_file_name = fname_concat(output_file_name, '_sampled');\n end\n\n if strcmp(dim_red_type,'pca') || strcmp(dim_red_type,'ica')\n post_fix = sprintf('_%s_%d', dim_red_type, new_dim);\n vectors_file_name = fname_concat(vectors_file_name, post_fix);\n output_file_name = fname_concat(output_file_name, post_fix);\n end\n \n output(1, 'reading vectors file %s\\n', vectors_file_name);\n load(vectors_file_name);\n output(1, 'done\\n');\n\n output(1, 'Calculating LMM, %d clusters\\n', numClusters);\n \n % multiply by LMM_HGLMM_MULT_FACTOR=10 due to numerical issue\n % transpose because the rows should be the samples\n vectors_ = mult_factor * vectors_';\n\n % create a random initialization\n initPriors = (1.0 / numClusters) * ones(numClusters,1);\n muInit=vectors_(randsample(size(vectors_,1),numClusters),:);\n init_b=repmat(sum(abs(vectors_ - repmat(median(vectors_),size(vectors_,1),1))) / size(vectors_,1),numClusters,1);\n \n % calculate LMM\n\n output(1, 'numOfCpus = %d\\n', numOfCpus);\n output(1, 'numOfEMIter = %d\\n', numOfEMIter);\n \n [n_means,n_covariances,n_priors,samplesWeightsOut]=LMMMex(double(vectors_), double(muInit), double(init_b), double(initPriors), numOfEMIter, 0.01, numOfCpus);\n\n save(output_file_name, 'n_means', 'n_covariances', 'n_priors', 'mult_factor', '-v7.3');\n\n output(1, 'saved to file: %s\\n', output_file_name);\nend\n", "meta": {"author": "layumi", "repo": "Image-Text-Embedding", "sha": "58f858da887f12ca94301c4f44113e2464d414ee", "save_path": "github-repos/MATLAB/layumi-Image-Text-Embedding", "path": "github-repos/MATLAB/layumi-Image-Text-Embedding/Image-Text-Embedding-58f858da887f12ca94301c4f44113e2464d414ee/word2vector_matlab/hglmm_fv_v1.6/fv/lmm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3482890393314951}}
{"text": "\nclear\nclose all\n\nplotx2east\n\nload martensite_single_grain\n\n[grains,ebsd('indexed').grainId] =...\n calcGrains(ebsd('indexed'),'angle',3*degree);\n\ncond_grains = ismember(grains.id,unique(ebsd(ids_of_interest).grainId));\n\n%%\njob = parentGrainReconstructor(ebsd,grains) % define job\njob.useBoundaryOrientations = true;\nclearvars grains ebsd\n\njob.p2c = orientation.NishiyamaWassermann(job.p2c.CS,job.p2c.SS);\n\n%%\njob.calcHyperGraph2('threshold',5*degree,'c2c')\n\nnumIters = [3 10 50];\ngrainId = 1844;\n\nfor k = 1:length(numIters);\n if k == 1\n job.clusterHyperGraph2('numIter',numIters(k),'inflationPower',1,'keepGraph')\n graphplotfunc(job,cond_grains,grainId,k,numIters)\n else\n job.clusterHyperGraph2('numIter',numIters(k) - numIters(k-1),'inflationPower',1,'keepGraph')\n graphplotfunc(job,cond_grains,grainId,k,numIters)\n end\nend\n\nfor k = 1:length(numIters);\n if k == 1\n job.clusterHyperGraph2('numIter',numIters(k),'inflationPower',1.05,'keepGraph')\n graphplotfunc(job,cond_grains,grainId,k,numIters)\n else\n job.clusterHyperGraph2('numIter',numIters(k) - numIters(k-1),'inflationPower',1.05,'keepGraph')\n graphplotfunc(job,cond_grains,grainId,k,numIters)\n end\nend\n\n\n%%\nfunction graphplotfunc(job,cond_grains,grainId,k,numIters)\n\npOri = variants(job.p2c, job.grains.meanOrientation, job.votes.parentId(:,1));\n\nnextAxis\nplot(job.grains(cond_grains),...\n pOri(cond_grains))\nlims = job.ebsd.extent;\nxlim([lims(1) lims(2)])\nylim([lims(3) lims(4)])\n\ntext(lims(1)+5,lims(4)-10, [num2str(numIters(k)) ' iterations'],...\n 'HorizontalAlignment','left',...\n 'FontSize',20, 'FontWeight','bold','BackgroundColor', 'white')\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/userScripts/Tuomo/single_PAG_NW_12_iterations_result.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307806984445, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.34828903179638343}}
{"text": "function [weight] = corn_kernel(data, w, c)\n% This program output the final portfolio the CORN strategy on data\n% This version has one expert, thus straightforwardly go expert.\n%\n% function [weight] = corn_kernel(data, w, c)\n%\n% weight: final portfolio, used for next rebalance\n%\n% data: market sequence vectors\n% w: window size\n% c: correlation coefficient threshold\n%\n% Example: [weight] = corn_kernel(data, w, c);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This file is part of OLPS: http://OLPS.stevenhoi.org/\n% Original authors: Bin LI, Steven C.H. Hoi \n% Contributors:\n% Change log: \n% \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nweight = corn_expert(data, w, c);\n\n% if (size(weight, 1) == 1),\n% weight=weight';\n% end\n\nend", "meta": {"author": "OLPS", "repo": "OLPS", "sha": "9120783cd59a7966b0f78e2b5668030a4378b8af", "save_path": "github-repos/MATLAB/OLPS-OLPS", "path": "github-repos/MATLAB/OLPS-OLPS/OLPS-9120783cd59a7966b0f78e2b5668030a4378b8af/Strategy/corn_kernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.3481511269961152}}
{"text": "%Extracts the grid for the grid defined on\n%http://www.vision.ee.ethz.ch/~cwengert/calibration_toolbox.php\n%\n%Input: im The image to process\n% show 0 to not display any information graphically\n% minArea The minimum area a grid dot occupies\n% maxArea The minimum area a grid dot occupies\n%Output: success 1 if everything went ok\n% stats The processed blobs of this image\n% id0 The index of the main bar\n% id1 The index of the second main bar\n% searchPoints The potential grid points\n%\n%\n%Christian Wengert\n%Computer Vision Laboratory\n%ETH Zurich\n%Sternwartstrasse 7\n%CH-8092 Zurich\n%www.vision.ee.ethz.ch/cwengert\n%wengert@vision.ee.ethz.ch\n\n\nfunction [success, stats, cnt, id0, id1, searchPoints] = gridextractor(im, show, minArea, maxArea)\n %crop image\n if(nargin==1)\n show=0;\n end\n success = 0;\n stats = [];\n cnt = 0;\n searchPoints = [];\n %Indices for main bars\n idx = [];\n ids = [];\n id0 = -1;\n id1 = -1; \n x_ = [];\n X_ = []; \n %Show the image\n if(show)\n if(isfloat(im))\n imshow(im/255.0),hold on\n else\n imshow(im),hold on\n end\n end\n %Get the size of the image\n [h,w,bpp] = size(im);\n if(h<=0 & w<=0)\n return\n end\n if(bpp==3)\n img = rgb2gray(im);\n else\n img = im;\n end\n \n\n %used to filter for ellipticity\n minEllipticity = 1.95;\n maxEllipticity = 8;\n minSolidity = 0.80;\n %Used to filter by closeness to border->to close to border cannot be\n %correct\n borderRect = [0+50, 0+50, w-50, h-50];\n \n x0 = w/2;\n y0 = h/2; \n imc = im;\n for i=1:w\n for j=1:h\n r = sqrt((x0-i)*(x0-i) + (y0-j)*(y0-j));\n if(r>160)\n imc(j,i) = 0;\n end\n end\n end\n \n %Rather median filter\n imb = medfilt2(img,[3 3]); \n \n %Threshold\n h1 = fspecial('gaussian',100, 15);\n imf= (imfilter(im, h1));\n imt = ( imclose(medfilt2(imborderRect(1) & stats(i).Centroid(1) borderRect(2) & stats(i).Centroid(2) minArea & areas(i) minSolidity) \n idx = [idx;i]; \n %Filter on ellipticity\n if((majors(i)/minors(i))>minEllipticity & (majors(i)/minors(i))areas(ids(2)))\n id0 = ids(1); id1 = ids(2);\n else\n id0 = ids(2); id1 = ids(1);\n end \n %Test angle between main lines\n dir0 = (stats(id1).Centroid-stats(id0).Centroid);\n dir0 = dir0/norm(dir0);\n %get the orientation of main bar\n orientation = stats(id0).Orientation;\n y = tand(orientation);\n dir90 = [-1,y];\n dir90 = dir90/norm(dir90);\n %Check angle\n theta = acos((dir0*dir90')/(norm(dir0)*norm(dir90)))/pi*180;\n if(theta<70 | theta>110)\n disp('gridextractor:: Could not find both main bars, bar-count = 1. ')\n stats = [];\n searchPoints = [];\n success = 0;\n cnt = 0;\n id0 = 0;\n id1 = 0; \n else \n searchPoints = [areas(idx);...\n ptsx(idx);...\n ptsy(idx)]; \n success = 1;\n if(show)\n text(stats(id0).Centroid(1)+5,stats(id0).Centroid(2)+5,'0','Color','m');\n text(stats(id1).Centroid(1)+5,stats(id1).Centroid(2)+5,'1','Color','m');\n end\n end\n elseif(cnt>2)\n disp('gridextractor:: Found too many possible candidates, trying to choose the correct ones') \n %get the two blobs that are closest to each other!\n a = [];\n xb = [];\n %Sort by Area \n for i=1:length(ids)\n xb = [xb, [stats(ids(i)).Centroid(1);stats(ids(i)).Centroid(2)]];\n if(xb(1,i) > 50 | xb(1,i) < (w-50) | xb(2,i) > 50 | xb(2,i) < (h-50))\n a = [a;stats(ids(i)).Area];\n else \n a = [a;-1];\n end\n end \n\n [a,ixxx] = sort(a);\n %Take the two biggest ones\n id0 = ids(ixxx(end));\n id1 = ids(ixxx(end-1)); \n \n %Directions\n dir0 = (stats(id1).Centroid-stats(id0).Centroid);\n dir0 = dir0/norm(dir0);\n %get the orientation of main bar\n orientation = stats(id0).Orientation; \n y = tand(orientation); \n dir90 = [-1,y];\n dir90 = dir90/norm(dir90);\n %Check angle\n theta = acos((dir0*dir90')/(norm(dir0)*norm(dir90)))/pi*180;\n if(theta<80 | theta>100)\n id1 = ids(ixxx(end-2)); \n %Test again\n dir0 = (stats(id1).Centroid-stats(id0).Centroid);\n dir0 = dir0/norm(dir0);\n %get the orientation of main bar\n orientation = stats(id0).Orientation;\n y = tand(orientation);\n dir90 = [-1,y];\n dir90 = dir90/norm(dir90);\n %Check angle\n theta = acos((dir0*dir90')/(norm(dir0)*norm(dir90)))/pi*180;\n if(theta<80 | theta>100)\n disp('gridextractor:: Could not find both main bars, bar-count = 1. ')\n stats = [];\n searchPoints = [];\n success = 0;\n cnt = 0;\n id0 = 0;\n id1 = 0; \n end\n end\n \n if(show)\n text(stats(id0).Centroid(1)+5,stats(id0).Centroid(2)+5,'0','Color','y');\n text(stats(id1).Centroid(1)+5,stats(id1).Centroid(2)+5,'1','Color','y');\n end\n cnt = 2;\n success = 1;\n searchPoints = [areas(idx);...\n ptsx(idx);...\n ptsy(idx)]; \n else\n disp('gridextractor:: Could not find both main bars, bar-count = 1. ')\n stats = [];\n searchPoints = [];\n success = 0;\n cnt = 0;\n id0 = 0;\n id1 = 0; \n end \n catch \n disp('gridextractor:: Problems extracting the main bars. Please verify whether it is visible in this image.')\n s = lasterror;\n disp(['gridextractor:: ' s.message ' in function ' s.stack.name ' in ' s.stack.file ' @line ' num2str(s.stack.line)])\n stats = [];\n searchPoints = [];\n success = 0;\n cnt = 0;\n id0 = 0;\n id1 = 0;\n end \n \n\n", "meta": {"author": "christianwengert", "repo": "calib_toolbox_addon", "sha": "d4220bde1d17acc9ea03c88433f13eaad94ddccd", "save_path": "github-repos/MATLAB/christianwengert-calib_toolbox_addon", "path": "github-repos/MATLAB/christianwengert-calib_toolbox_addon/calib_toolbox_addon-d4220bde1d17acc9ea03c88433f13eaad94ddccd/gridextractor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.34807280659618606}}
{"text": "function geo_params = drawparticals(geo_param, pf_param)\ngeo_param = repmat(geo_param, [1,pf_param.p_num]);\ngeo_params = geo_param + randn(6,pf_param.p_num).*repmat(pf_param.affsig(:),[1,pf_param.p_num]);\nend", "meta": {"author": "scott89", "repo": "FCNT", "sha": "d2d9e72b13d2c0c1f5d13fdd40854be2a19aa188", "save_path": "github-repos/MATLAB/scott89-FCNT", "path": "github-repos/MATLAB/scott89-FCNT/FCNT-d2d9e72b13d2c0c1f5d13fdd40854be2a19aa188/util/drawparticals.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.3480284759003132}}
{"text": "function [z, logPrQ_z] = sampleStateSeq_PrecompSoftEv( ii, Etaii, LL, TargetPsi)\n\nlogPrQ_z = 0;\nT = size( LL,2 );\n\nif exist( 'TargetPsi', 'var' ) && ~isempty( TargetPsi )\n % Translate from TargetPsi's feature IDs to\n % corresponding IDs in F, theta, prevStateSeq, etc.\n z = TargetPsi.stateSeq(ii).z;\n for aa = 1:length( TargetPsi.activeFeatIDs )\n z( z == TargetPsi.activeFeatIDs(aa) ) = TargetPsi.externalFeatIDs(aa);\n end\n TargetPsi.stateSeq(ii).z = z;\nend\n\navailFeatIDs = Etaii.availFeatIDs;\nif length( availFeatIDs ) == 1\n z = availFeatIDs(1) * ones(1,T);\n return;\nend\npi_z = Etaii.eta;\npi_z = bsxfun( @rdivide, pi_z, sum(pi_z,2) );\n\npi_init = 1/length(pi_z)*ones( 1, length(pi_z) );\n\n\n% Safely convert provided *log* soft evidence matrix\n% into proper probabilities \n% (up to a prop. constant, so stays in range of CPU)\nnormC = max( LL, [], 1);\nLL = bsxfun( @minus, LL, normC );\nlikelihood = exp( LL );\n\nif ~exist( 'TargetPsi', 'var') || isempty( TargetPsi )\n % ------------------------------------------- Actually sample z(t)\n [js, logQ] = SampleHMMStateSeqWithQsC( pi_z, likelihood, pi_init, -1, randi([1 100000]) );\n z = availFeatIDs( js );\nelse % ----------------------------- Calc prob of moving to Target's z \n jseq = zeros(1,T);\n for jj = 1:length( availFeatIDs )\n jseq( TargetPsi.stateSeq(ii).z == availFeatIDs(jj) ) = jj;\n end\n [js,logQ] = SampleHMMStateSeqWithQsC( pi_z, likelihood, pi_init, jseq, randi([1 100000]) );\n z = availFeatIDs( js );\nend\n\nif nargout > 1\n if exist( 'logQ', 'var' )\n logPrQ_z = logPrQ_z + logQ;\n else\n logPrQ_z = logPrQ_z + sum( log( qs ) );\n end\nend\n\nend % main function\n\n% \n% % Initialize state and sub-state sequences:\n% qs = zeros(1,T);\n", "meta": {"author": "michaelchughes", "repo": "NPBayesHMM", "sha": "22e164b5eb68ea2b1e5ef38807a56fd8aa3660dd", "save_path": "github-repos/MATLAB/michaelchughes-NPBayesHMM", "path": "github-repos/MATLAB/michaelchughes-NPBayesHMM/NPBayesHMM-22e164b5eb68ea2b1e5ef38807a56fd8aa3660dd/code/BPHMM/sampler/SplitMergeSeq/sampleStateSeq_PrecompSoftEv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3479791625167263}}
{"text": "function [xc_incoherent_collapsed_pow xc_incoherent_collapsed_frq n_comb_xc n_comb_sp xc_incoherent_single xc_incoherent sp_incoherent sp] = ...\n xcorr_pss(capbuf,f_search_set,ds_comb_arm,fc,sampling_carrier_twist,k_factor,xc)\n\n% Copyright 2012 Evrytania LLC (http://www.evrytania.com)\n%\n% Written by James Peroulas \n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Affero 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 Affero General Public License for more details.\n%\n% You should have received a copy of the GNU Affero General Public License\n% along with this program. If not, see .\n\n% Perform the main correlations necessary to detect the PSS\n\nerror(nargchk(7,7,nargin));\nerror(chk_param(capbuf,'capbuf','vector','horizontal'));\nerror(chk_param(f_search_set,'f_search_set','vector','real'));\nerror(chk_param(ds_comb_arm,'ds_comb_arm','scalar','real','integer','>=',0));\nerror(chk_param(fc,'fc','scalar','real','>',0));\n\n% % Create the time domain pss signals\n% persistent pss_td\n% persistent pss_td_populated\n% if (isempty(pss_td_populated))\n% pss_td=NaN(3,128+9);\n% for t=0:2\n% temp=pss(t);\n% %temp=temp(6:67);\n% temp=[0 temp(32:end) zeros(1,65) temp(1:31)];\n% temp_td=idft(temp)*sqrt(128/62);\n% pss_td(t+1,:)=[temp_td(end-8:end) temp_td];\n% end\n% pss_td_populated=1;\n% end\n\nn_cap=length(capbuf);\nn_f=length(f_search_set);\n\n% % Correlate against the PSS\n% xc=NaN(3,n_cap-136,n_f);\n% for foi=1:n_f\n% % f_off=f_search_set(foi);\n% for t=1:3\n% % temp=conj(fshift(pss_td(t,:),f_off,fs_lte/16)/137);\n% % for k=1:n_cap-136\n% % xc(t,k,foi)=sum(temp.*capbuf(k:k+136));\n% % end\n% col_idx = (t-1)*n_f + foi;\n% xc(t,:,foi)=corr_store(1:(n_cap-136),col_idx);\n% end\n% end\n\n% Calculate the received power in the vicinity of the possible PSS\nsp=NaN(1,n_cap-136-137);\ncapbufx2=absx2(capbuf);\nsp(1)=sum(capbufx2(1:137*2));\nfor k=2:n_cap-136-137\n sp(k)=sp(k-1)-capbufx2(k-1)+capbufx2(k+137*2-1);\nend\nsp=sp/(137*2);\nassert(any(isnan(sp))==0);\n\n% Perform incoherent combining\nxc_incoherent=NaN(3,9600,n_f);\nxc_incoherent_single=NaN(3,9600,n_f);\nn_comb_xc=floor((size(xc,2)-100)/9600);\nfor foi=1:n_f\n \n if sampling_carrier_twist == 1\n f_off=f_search_set(foi);\n % fc*k_factor is the receiver's actual RX center frequency.\n k_factor=(fc-f_off)/fc;\n% else\n% k_factor = 1; % because it is already corrected outside\n end\n \n for t=1:3\n %xc_incoherent_single(t,:,foi)=sum(transpose(reshape(absx2(xc(t,1:n_comb_xc*9600,foi)),9600,n_comb_xc)),1)/n_comb_xc;\n %xc_incoherent_single(t,:,foi)=absx2(xc(t,1:9600,foi));\n xc_incoherent_single(t,:,foi)=zeros(1,9600);\n for m=1:n_comb_xc\n actual_time_offset=(m-1)*.005*k_factor;\n actual_start_index=round(actual_time_offset*fs_lte/16)+1;\n% xc_incoherent_single(t,:,foi)=xc_incoherent_single(t,:,foi)+absx2(xc(t,actual_start_index:actual_start_index+9599,foi));\n xc_incoherent_single(t,:,foi)=xc_incoherent_single(t,:,foi)+xc(t,actual_start_index:actual_start_index+9599,foi);\n end\n end\n xc_incoherent_single(:,:,foi)=xc_incoherent_single(:,:,foi)/n_comb_xc;\n % Combine adjacent samples that might be different taps from the same channel.\n xc_incoherent(:,:,foi)=xc_incoherent_single(:,:,foi);\n for t=1:ds_comb_arm\n for k=1:3\n xc_incoherent(k,:,foi)=xc_incoherent(k,:,foi)+tshift(xc_incoherent_single(k,:,foi),-t)+tshift(xc_incoherent_single(k,:,foi),t);\n end\n end\n xc_incoherent(:,:,foi)=xc_incoherent(:,:,foi)/(2*ds_comb_arm+1);\nend\nsp_incoherent=NaN(1,9600);\nn_comb_sp=floor(length(sp)/9600);\nsp_incoherent=sum(transpose(reshape(sp(1:n_comb_sp*9600),9600,n_comb_sp)),1)/n_comb_sp;\n\n% Align the correlations and the signal power measurements.\n% xc(:,1) represents the correlation from capture buffer offset 1 to 137.\n% sp(1) represents the signal power for samples 1 through 274.\n% Suppose capbuf(1) contains the first sample of an SSS and thus the PSS is\n% located from samples 138 to 274. The pss correlation peak will be located\n% at time sample 138. This PSS correlation peak must be compared against\n% the signal power for samples 1 through 274. Thus, the signal power must\n% be cyclically shifted right by 137 samples.\nsp_incoherent=tshift(sp_incoherent,137);\n\n% For each time offset and PSS index, find the peak correlation\n% among all the frequencies.\nxc_incoherent_collapsed_pow=NaN(3,9600);\nxc_incoherent_collapsed_frq=NaN(3,9600);\nfor t=1:3\n [pow frq]=max(transpose(shiftdim(xc_incoherent(t,:,:),1)),[],1);\n xc_incoherent_collapsed_pow(t,:)=pow;\n xc_incoherent_collapsed_frq(t,:)=frq;\nend\n\n", "meta": {"author": "JiaoXianjun", "repo": "rtl-sdr-LTE", "sha": "037a25f164f17b1a1d82e2eb02285550f50af9b9", "save_path": "github-repos/MATLAB/JiaoXianjun-rtl-sdr-LTE", "path": "github-repos/MATLAB/JiaoXianjun-rtl-sdr-LTE/rtl-sdr-LTE-037a25f164f17b1a1d82e2eb02285550f50af9b9/matlab/xcorr_pss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3479791625167263}}
{"text": "report_this_filefun(mfilename('fullpath'));\n\nl = isnan(tmap);\ntmap(l) = 1;\n\n\n\n%l = tmap< 0.1;\n%tmap(l) = nan;\n\n\n[lat,lon] = meshgrat(tmap,tmapleg);\n%[smap,smapleg] = country2mtx('switzerland',100);\n%[lat0, lon0] = meshgrat(smap,smapleg);\n\n\n% tmap = km2deg(tmap/1);\n[X , Y] = meshgrid(gx,gy);\n\n%sw = interp2(lon0,lat0,smap,lon,lat);\n\n\n\nren = interp2(X,Y,re4,lon,lat);\n\nmi = min(min(ren));\nl = isnan(ren);\nren(l) = mi-100;\n\n\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\n%h = displaym(POline); set(h(1),'color',[0.9 0.9 0.9],'Linewidth',1.7)\nh2 = displaym(PPpoint);\n%h = displaym(PPtext); trimcart(h);\nplotm(mainfault(:,2), mainfault(:,1),'m','Linewidth',4);\n\npl = plotm(ma(:,2),ma(:,1),'hw');\nset(pl,'LineWidth',1.5,'MarkerSize',12,...\n 'MarkerFaceColor','y','MarkerEdgeColor','k')\n\nzdatam(handlem('allline'),10000) % keep line on surface\n%zdatam(handlem('alltext'),10000) % keep line on surface\n\nj = jet;\nj = j(64:-1:1,:);\nj = [ [ 0.85 0.9 0.9] ; j];\ncaxis([ 95 2000]);\n\ncolormap(j); brighten(0.1);\n\naxis off; set(gcf,'color','k')\n\nsetm(gca,'ffacecolor','k')\nsetm(gca,'fedgecolor','w','flinewidth',3);\n\nsetm(gca,'mlabellocation',0.5)\nsetm(gca,'meridianlabel','on')\nsetm(gca,'plabellocation',0.5)\nsetm(gca,'parallellabel','on')\nsetm(gca,'Fontcolor','w','Fontweight','bold','FontSize',15,'Labelunits','dm')\n\nh5 = colorbar;\nset(h5,'position',[0.8 0.35 0.01 0.3],'TickDir','out','Ycolor','w','Xcolor','w',...\n 'Fontweight','bold','FontSize',15);\nset(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_hay.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3479791625167263}}
{"text": "% fig2: anat averages from paired regressors: sensory/motor correlations\n% plots a pair of regressors in a graded double colormap, saves as tiff\n% stacks, and also saves anat average plot as tiff file.\n% (compare to fig2A_correlation_1reg_with_hist for more details)\n\nclear all; close all; clc\n\noutputDir = GetOutputDataDir;\n\n%% Init load\nhfig = figure;\nInitializeAppData(hfig);\nResetDisplayParams(hfig);\n\n%% set params\nthres_reg_const = 0.5;\n% M_reg_thres = {0.5,0.5,0.5};\n\nisKeepTopPrct = 0; % init, can override\nisMotorseed = 0; % init, can override\n\nfor setflag = 9\n % reset\n ResetDisplayParams(hfig);\n \n switch setflag\n case 1 % Phototaxis\n % stimrange = 1;\n M_stimrange = GetStimRange('P');\n M_regtypeflag = [1,1,2]; % 0 for VAR, 1 for stim and 2 for motor\n M_reg_name = {'PT','HalfField','PT_SwimLR'};\n M_reg_range = {[3,2],[5,6],[1,3]};\n M_fishrange = {[1:18],[1:7],[1:3,5:18]};\n \n case 2 % OMR\n % stimrange = 2;\n M_stimrange = GetStimRange('O');\n M_regtypeflag = [1,1,2]; % 1 for stim and 2 for motor\n M_reg_name = {'OMR_FwBw','OMR_LR','OMR_SwimLR'};\n M_reg_range = {[7,6],[9,8],[1,3]};\n M_fishrange = {[8:18],[8:18],[8:18]};\n \n case 3 % Looming\n % stimrange = 5;\n M_stimrange = GetStimRange('L');\n M_regtypeflag = [1,2]; % 1 for stim and 2 for motor\n M_reg_name = {'Loom_LR','Loom_SwimLR'};\n M_reg_range = {[11,12],[1,3]};\n M_fishrange = {[9:15,17:18],[9:15,17:18]};\n \n case 4 % Dark Flash (black-white)\n % stimrange = 3;\n M_stimrange = GetStimRange('D');\n M_regtypeflag = [1,2]; % 1 for stim and 2 for motor\n M_reg_name = {'DF_BW','DF_SwimLR'};\n M_reg_range = {[1,4],[1,3]};\n M_fishrange = {[1:5,12:15,17:18],[12:15,17:18]}; % up till 7/10\n% M_fishrange = {[12:15,17:18],[12:15,17:18]}; % up till 7/10\n\n% % from VAR:\n\n case 5 % ABN\n M_regtypeflag = [0];\n M_stimrange = GetStimRange();%('2');\n% M_reg_name = {'ABN_top1%_defstimrange'};\n M_reg_name = {'ABN_reg0.5_defstimrange'};\n M_clus_range = {[12,1]};\n range = GetFishRange('e');%[1:8,11,12,14:17]\n M_fishrange = {range};%{[1:12,14:18]};\n\n% isKeepTopPrct = 1;\n% prct_const = 1;\n \n case 6 % Fw\n M_regtypeflag = [0];\n M_stimrange = GetStimRange();%('2');\n M_reg_name = {'Fw_seed_reg2%_defS'};\n% M_reg_name = {'Fw_reg0.5_defS'}; \n M_clus_range = {[11,4]};\n M_fishrange = {[1:3,5:18]}; \n\n isKeepTopPrct = 1;\n prct_const = 2;\n \n case 7 % HBO 4 stripes\n M_regtypeflag = [0,0];\n M_stimrange = GetStimRange();%('2');\n M_reg_name = {'HBO-L2_reg1%_tRes_defS','HBO-R2_reg1%_tRes_defS'}; \n M_clus_range = {[10,2],[10,3]};\n M_fishrange = {[1:3,5:18],[1:3,5:18]};\n\n isKeepTopPrct = 1;\n prct_const = 1;\n setappdata(hfig,'isTrialRes',1);\n \n case 8 % HBO 2 halves\n M_regtypeflag = [0,0];\n M_stimrange = GetStimRange();%('2');\n M_reg_name = {'HBO2_reg1%_tRes_defS'}; \n M_clus_range = {[10,5]};\n M_fishrange = {[1:3,5:18]};\n\n isKeepTopPrct = 1;\n prct_const = 1;\n setappdata(hfig,'isTrialRes',1);\n \n case 9 % spontaneous\n M_stimrange = GetStimRange('S'); % spontaneous\n M_regtypeflag = [2]; % 1 for stim and 2 for motor\n M_reg_name = {'spt_SwimLR_notmotorseed_top2%'};\n M_reg_range = {[1,3]}; % {[1,2]} for ismotorseed = 1\n M_fishrange = {[8:15,17:18]};\n \n isMotorseed = 0; % 1\n isKeepTopPrct = 1;\n prct_const = 2;\n end\n\n n_reg = length(M_reg_name);\n M_fishrange_im = M_fishrange;\n \n \n range = 1:18; % init,M_fishrange below specifies actual range #oldcode\n IM_full = cell(n_reg,18);\n \n %% \n \n% [M_fishrange_im,fishrange_load] = CheckIfLoadFish(M_fishrange,M_ClusterIDs,M_stimrange);\n% [cIX_load,gIX_load,M,stim,behavior,M_0] = LoadSingleFishDefault(i_fish,hfig,M_ClusterIDs{i_set},M_stimrange{i_set});\n for i_fish = range\n if ismember(i_fish,cell2mat(M_fishrange))\n ClusterIDs = [1,1];%GetClusterIDs('all');\n stimrange = M_stimrange{i_fish}; \n % load fish data\n if isempty(stimrange)\n [cIX_load,gIX_load,M,stim,behavior,M_0] = LoadSingleFishDefault(i_fish,hfig,ClusterIDs);\n else\n [cIX_load,gIX_load,M,stim,behavior,M_0] = LoadSingleFishDefault(i_fish,hfig,ClusterIDs,stimrange);\n end\n end\n \n %% Load stim/motor\n for i_set = 1:n_reg\n \n if ~ismember(i_fish,M_fishrange{i_set})\n continue;\n end\n \n reg_thres = thres_reg_const; %M_reg_thres{i_set};\n \n %% Get Regressors\n if M_regtypeflag(i_set)==0\n ClusterIDs = M_clus_range{i_set};%[12,1];% GetClusterIDs('all');\n [cIX,gIX] = LoadCluster_Direct(i_fish,ClusterIDs(1),ClusterIDs(2));\n M = UpdateIndices_Manual(hfig,cIX,gIX);\n Reg = FindClustermeans(gIX,M);\n \n elseif M_regtypeflag(i_set)==1\n fishset = getappdata(hfig,'fishset');\n [~,names,regressors] = GetStimRegressor(stim,fishset,i_fish);\n \n reg_range = M_reg_range{i_set}; % left/right pair\n Reg = regressors(reg_range,:);\n \n elseif M_regtypeflag(i_set)==2\n% isMotorseed = 0;\n setappdata(hfig,'isMotorseed',isMotorseed);\n [~,~,behavior] = UpdateTimeIndex(hfig); \n [~,names,regressors] = GetMotorRegressor(behavior,i_fish); \n \n reg_range = M_reg_range{i_set}; % left/right pair\n Reg = regressors(reg_range,:);\n end\n \n %% Regression\n % code adapted from 'best regressor regression' code 'AllRegsRegression'\n\n if isempty(Reg)\n M_fishrange_im{i_set} = setdiff(M_fishrange_im{i_set} ,i_fish);\n continue;\n end\n \n Corr = corr(Reg',M_0');\n \n if isKeepTopPrct\n % keep best regression only\n [Corr_rows,corr_max] = ConvertCorrToBestRegRows(Corr);\n \n % top x percentile\n nCells_total = size(M_0,1);\n% prct_const = 1;\n [CIX,RegThres] = ChooseTopPercentOfFish(nCells_total,prct_const,Corr_rows);\n \n if length(CIX)==1\n cIX = CIX{1};\n % get map color\n reg_thres = 0.25;\n gIX = MapXto1Dcolormap(corr_max(cIX),[reg_thres,1],64);\n else\n cIX1 = CIX{1};\n cIX2 = CIX{2};\n \n % get map color\n clrIX1 = MapXto1Dcolormap(corr_max(cIX1),[reg_thres,1],64);\n clrIX2 = MapXto1Dcolormap(corr_max(cIX2),[reg_thres,1],64);\n % clrIX1 = MapXto1Dcolormap(corr_max(cIX1),[reg_thres1,1],64);\n % clrIX2 = MapXto1Dcolormap(corr_max(cIX2),[reg_thres2,1],64);\n \n cIX = [cIX1;cIX2];\n % if isempty(cIX)\n % M_fishrange_im{i_set} = setdiff(M_fishrange_im{i_set} ,i_fish); %#ok\n % continue;\n % end\n \n clrIX = [clrIX1;clrIX2];\n gIX_offset = [ones(size(cIX1));2*ones(size(cIX2))];\n gIX = clrIX+(gIX_offset-1)*64;\n % gIX = [clrIX1;64+clrIX2];\n numK = length(unique(gIX));\n end\n \n else\n %%\n [corr_max,IX_regtype] = max(Corr,[],1);\n cIX = find(corr_max>reg_thres)';\n gIX_offset = IX_regtype(cIX)';\n clrIX = MapXto1Dcolormap(corr_max(cIX),[reg_thres,1],64);\n \n if isempty(cIX)\n M_fishrange_im{i_set} = setdiff(M_fishrange_im{i_set} ,i_fish);\n continue;\n end\n \n gIX = clrIX+(gIX_offset-1)*64;\n numK = length(unique(gIX));\n end\n \n %% make double colormap\n clr1 = [1,0,0];\n clr1_ = [0.7,0.5,0.5];\n clr2 = [0,1,1];\n clr2_ = [0.5,0.7,0.7];\n numC = 64;\n clrmap1 = Make1DColormap([clr1_;clr1],numC);\n clrmap2 = Make1DColormap([clr2_;clr2],numC);\n clrmap = [clrmap1;clrmap2];\n \n %% make figure\n I = LoadCurrentFishForAnatPlot(hfig,cIX,gIX,clrmap);\n [h,im_full] = DrawCellsOnAnat(I);\n \n % % add 2 colorbars\n % % AddColorbarToAnat(clrmap,cmin,cmax)\n % % colormap(clrmap1);\n % % caxis([reg_thres,1])\n % % colorbar('Location','manual','Position',[0.8,0.7,0.05,0.15],'Units','normalized')\n % ax = axes('Position',[0.75,0.8,0.05,0.15],'Units','normalized');\n % DrawCustomColorbar(clrmap1,[reg_thres,1],2,ax);\n %\n % ax = axes('Position',[0.9,0.8,0.05,0.15],'Units','normalized');\n % DrawCustomColorbar(clrmap2,[reg_thres,1],2,ax);\n %\n %% save figure\n close(h);\n IM_full{i_set,i_fish} = im_full;\n \n end\n end\n \n %% save as tiff stack\n for i_set = 1:n_reg\n range_im = M_fishrange_im{i_set};\n tiffdir = fullfile(outputDir,[M_reg_name{i_set},'_allfish.tiff']);\n IM = IM_full(i_set,range_im);\n \n SaveImToTiffStack(IM,tiffdir);\n end\n \n %% [for later] plot from tiff stack\n isPlotfromtiffstack = 0;\n \n if isPlotfromtiffstack\n IM_full = cell(n_reg,18);\n for i_set = 1:n_reg\n %% get tiff-stack path\n tiffdir = fullfile(outputDir,[M_reg_name{i_set},'_allfish.tiff']);\n \n %% load\n range_load = 1:17;\n for i_fish = range_load\n im = double(imread(tiffdir,i_fish))./255;\n IM_full{i_set,i_fish} = im;\n% IM_full{i_set,i_fish} = im(317:1236,1:621,:);\n end\n end\n end\n \n %% make average plots\n % M_k_scale = {1,1.5,1};\n % M_k_contrast = {1.2,1.5,1.2};\n \n for i_set = 1:n_reg\n range_im = M_fishrange_im{i_set};%[1:3,5:7];%[1:3,5:18];\n cellarray = IM_full(i_set,range_im);\n \n % adjust params for visualization\n k_scale = 0.7;%1/1.5;%M_k_scale{i_set};\n k_contrast = 1.1;%M_k_contrast{i_set};\n \n [h_anat,im_avr] = AverageAnatPlot(cellarray,k_contrast,k_scale);\n \n tiffdir = fullfile(outputDir,[M_reg_name{i_set},'_avr.tiff']);\n imwrite(im_avr, tiffdir, 'compression','none','writemode','overwrite');\n end\n \nend\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/Regression/fig2D_Batch_correlation_2regs_VARoption.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947425132314, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.34788622579622114}}
{"text": "function out = reconSpyr(coeff, filter)\n\n% Reconstruct the image from steerable pyramid\n% Input:\n% coeff: the cell structured pyramid\n% filter: filter, typically sp3.mat, sp1.mat, sp5.mat\n%\n% Output:\n% out: reconstructed image\n\nload(filter,'lo0filt','hi0filt','lofilt','bfilts');\n\nres = reconSpyrLevs(coeff(2:length(coeff)),lofilt, bfilts);\ntemp = upConv(res, lo0filt,[1 1]);\n\nhighpass = upConv( coeff{1}, hi0filt,[1 1]);\n\nout=highpass+temp;\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/36488-simplified-steerable-pyramid/Steerable/reconSpyr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3478862186402445}}
{"text": "function [hh] = plotEmissionParams( varargin )\n\nMAX_K = 12;\nMIN_THR = 0.01;\n\n% ================================================ Process User Input\nif isstruct( varargin{1} )\n if isfield( varargin{1}, 'ThetaM' )\n theta = varargin{1}.ThetaM.theta;\n elseif isfield( varargin{1}, 'theta' ) % || isprop(varargin{1},'theta')\n theta = varargin{1}.theta;\n else\n theta = varargin{1};\n end\n if isfield( varargin{1}, 'stateSeq' )\n stateSeq = varargin{1}.stateSeq;\n end\n \n for ll = 2:length( varargin )\n curArg = varargin{ll};\n if ishandle(curArg)\n figH = curArg;\n elseif isobject(curArg);\n data = curArg;\n end\n end\n \nelseif isobject( varargin{1} )\n if isprop( varargin{1}, 'theta' )\n theta = varargin{1}.theta;\n end\nelse\n jobID = varargin{1};\n taskID = varargin{2};\n DATA = loadSamplerOutput( jobID, taskID, {'iters', 'Psi'} );\n data = loadSamplerInfo( jobID, taskID, {'data'} );\n\n if length( varargin ) >= 3\n queryIter = varargin{3};\n [~, idx] = min( abs( queryIter - DATA.iters.Psi ) );\n else\n idx = length( DATA.Psi );\n end\n Psi = DATA.Psi( idx );\n theta = Psi.theta;\n stateSeq = Psi.stateSeq;\n \n if length( varargin ) >= 4\n objIDs = varargin{4};\n end\nend\n\nK = length( theta );\n\nif ~exist('figH','var')\n figH = gca;\nend\n\nif exist( 'stateSeq', 'var' )\n Zall = horzcat( stateSeq(:).z );\n N = length( Zall );\n [Zcounts, sortIDs] = sort( histc( Zall, 1:K ), 'descend' );\n sortIDs = sortIDs( Zcounts > 0 );\n K = length( sortIDs );\n K = min( K, MAX_K );\n theta = theta( sortIDs(1:K) );\nelse\n \n K = min( K, MAX_K );\n theta = theta( 1:K );\nend\n\nfNames = fieldnames(theta);\nif fNames{1} == 'mu'\n obsType = 'Gaussian';\nelseif fNames{1} == 'A'\n obsType = 'AR-Gaussian';\nelseif fNames{1} == 'logp'\n obsType = 'Multinomial';\nend\n\n\nswitch obsType\n case 'Multinomial'\n \n Px = exp( vertcat( theta(:).logp ) );\n set( gcf, 'Units', 'normalized', 'Position', [0 0.5 0.25 0.5] );\n imagesc( figH, Px, [0 0.01] );\n set( gca, 'Position', [0.1 0.1 0.8 0.06*K] );\n case 'Gaussian'\n\n if exist( 'data', 'var' )\n X = data.Xdata;\n plot(figH, X(1,:), X(2,:), 'k.' );\n end\n\n for kk = 1:K\n Mu(kk,:) = theta(kk).mu;\n invSigma(:,:,kk) = theta(kk).invSigma;\n end \n plotGauss( Mu, invSigma, 1, jet( MAX_K ), figH );\n\n B = 1.6;\n axis( [-B B -B B] );\n \n case 'AR-Gaussian'\n D = size( theta(1).A, 1);\n for kk = 1:K\n Mu(kk,:) = [ mean( diag( theta(kk).A ) ) zeros( 1, D-1) ];\n invSigma(:,:,kk) = theta(kk).invSigma;\n end \n plotGauss( Mu, 1000*invSigma, 1, jet(MAX_K), figH );\n \n case 'Bernoulli'\n error( 'TO DO' );\n case 'Multinomial'\n error( 'TO DO' );\nend\n\nhold off;\ndrawnow;", "meta": {"author": "michaelchughes", "repo": "NPBayesHMM", "sha": "22e164b5eb68ea2b1e5ef38807a56fd8aa3660dd", "save_path": "github-repos/MATLAB/michaelchughes-NPBayesHMM", "path": "github-repos/MATLAB/michaelchughes-NPBayesHMM/NPBayesHMM-22e164b5eb68ea2b1e5ef38807a56fd8aa3660dd/code/viz/plotEmissionParams.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.3478862186402444}}
{"text": "function [Ain, Cin, bin, fin, center] = initialize_components(Y, K, tau, options, P)\n\n% Initalize components using a greedy approach followed by hierarchical\n% alternative least squares (HALS) NMF. Optional use of spatio-temporal\n% downsampling to boost speed.\n\n%Input:\n%Y d1 x d2 x T movie, raw data\n%K number of neurons to extract (default value: 30)\n%tau standard deviation of neuron size (default value: 5)\n\n%options fine-tuning parameters (optional)\n% options.init_method: method of initialization ('greedy','sparse_NMF','HALS')\n% options.\n% options.nIter: number of iterations for shape tuning (default 5)\n% options.gSiz: size of kernel (default 2*tau + 1)\n% options.ssub: spatial downsampling factor (default 1)\n% options.tsub: temporal downsampling factor (default 1)\n% options.nb: rank of background component (default 1)\n% options.save_memory: flag for processing data in chunks to save memory (default 0)\n% options.windowSiz: size of spatial window when computing the median (default 32 x 32)\n% options.chunkSiz: number of timesteps to be processed simultaneously if on save_memory mode (default: 100)\n% options.med_app: number of timesteps to be interleaved for fast (approximate) median calculation (default: 1, no approximation)\n% options.rem_prct: percentile to be removed before initialization (default: 20)\n\n% P parameter struct used for normalization by noise and user feed component centroids (optional)\n\n%\n%Output:\n%Ain (d1*d2) x K matrix, location of each neuron\n%Cin T x K matrix, calcium activity of each neuron\n%center K x 2 matrix, inferred center of each neuron\n%bin (d1*d2) X nb matrix, initialization of spatial background\n%fin nb X T matrix, initalization of temporal background\n%res d1 x d2 x T movie, residual\n%\n%Authors: Eftychios A. Pnevmatikakis and Pengchen Zhou, with inputs from Weijian Yang\n\n\ndefoptions = CNMFSetParms;\nif nargin < 4 || isempty(options); options = defoptions; end\nif nargin < 2 || isempty(K)\n K = 30;\n fprintf('Number of components to be detected not specified. Using the default value 30. \\n');\nend\nif nargin < 3 || isempty(tau)\n options.gSig = 5;\n fprintf('Standard deviation for neuron not specified. Using the default value 5. \\n');\nelse options.gSig = tau;\nend\n\nif ~isfield(options,'init_method'); options.init_method = 'greedy'; end\nif ~isfield(options,'rem_prct') || isempty(options.rem_prct); options.rem_prct = defoptions.rem_prct; end\n% downsample the data\n\nif ~isfield(options, 'ssub'); options.ssub = 1; end; ssub = options.ssub;\nif ssub == 1; fprintf('No spatial downsampling is performed. Consider spatial downsampling if the field of view is very large. \\n'); end\nif ~isfield(options, 'tsub'), options.tsub = 1; end; tsub = options.tsub;\nif tsub == 1; fprintf('No temporal downsampling is performed. Consider temporal downsampling if the recording is very long. \\n'); end\n\nif ~isfield(options,'noise_norm') || isempty(options.noise_norm)\n options.noise_norm = defoptions.noise_norm; % normalization by noise (true if P is present)\nend\n\nif nargin < 5\n if options.noise_norm\n warning('Normalization by noise value is not performed since noise values are not provided. \\n');\n end\n options.noise_norm = false;\nend\n\nndimsY = ndims(Y)-1;\nsY = size(Y);\nd = sY(1:ndimsY);\nT = sY(end);\n\nif options.noise_norm\n mY = mean(Y,ndims(Y));\n norm_image = mY + median(mY(:)) + 1e-4;\n min_noise = norm_image;\n %min_noise = prctile(P.sn(P.sn>0),options.noise_norm_prctile);\n %Y = bsxfun(@times,Y,reshape(1./max(P.sn,min_noise),d));\n Y = bsxfun(@times,Y,reshape(1./double(min_noise),d));\nend\n\nds = d;\nds(1:2) = ceil(d(1:2)/ssub); % do not subsample along z axis\n%d1s = ceil(d1/ssub); %size of downsampled image\n%d2s = ceil(d2/ssub);\nTs = floor(T/tsub); %reduced number of frames\n% spatial downsampling\nfprintf('starting resampling \\n')\nif ssub~=1;\n if ndimsY == 2; Y_ds = imresize(Y, [ds(1), ds(2)], 'box'); end\n if ndimsY == 3;\n Y_ds = zeros([ds(1:2),T,ds(end)]);\n for z = 1:ds(3)\n Y_ds(:,:,:,z) = imresize(squeeze(Y(:,:,z,:)), [ds(1), ds(2)], 'box');\n end\n Y_ds = permute(Y_ds,[1,2,4,3]);\n end\nelse\n Y_ds = Y;\nend\n% temporal downsampling\nif tsub~=1\n if ndimsY == 2; Y_ds = squeeze(mean(reshape(Y_ds(:, :, 1:(Ts*tsub)),ds(1), ds(2), tsub, Ts), 3)); end\n if ndimsY == 3; Y_ds = squeeze(mean(reshape(Y_ds(:, :, :, 1:(Ts*tsub)),ds(1), ds(2), ds(3), tsub, Ts), 4)); end\nend\n\noptions_ds = options;\noptions_ds.d1 = ds(1);\noptions_ds.d2 = ds(2);\n\nif strcmpi(options.init_method,'greedy')\n % run greedy method\n if nargin < 5 || ~isfield(P,'ROI_list')\n ROI_list = [];\n else\n ROI_list = round(P.ROI_list/ssub);\n K = size(ROI_list,1);\n end\n fprintf('Initializing components with greedy method \\n');\n [Ain, Cin, bin, fin] = greedyROI(Y_ds, K, options, ROI_list);\nelseif strcmpi(options.init_method, 'greedy_corr')\n fprintf('Initializing components with greedy_corr method \\n');\n [Ain, Cin, bin, fin] = greedyROI_corr(Y_ds, K, options);\nelseif strcmpi(options.init_method,'sparse_NMF')\n % run sparse_NMF method\n fprintf('Initializing components with sparse NMF \\n');\n [Ain,Cin,bin,fin] = sparse_NMF_initialization(Y_ds,K,options_ds);\nelseif strcmpi(options.init_method,'HALS')\n fprintf('Initializing components with HALS \\n');\n [Ain,Cin,bin,fin] = HALS_initialization(Y_ds,K,options_ds);\nelse\n error('Unknown initialization method')\nend\n\n% refine with HALS\nfprintf('Refining initial estimates with HALS...');\n[Ain, Cin, bin, fin] = HALS(Y_ds, full(Ain), Cin, bin, fin, options_ds);\nfprintf(' done \\n');\n%% upsample Ain, Cin, bin, fin\nif nargout == 5\n if ndimsY == 2; center = ssub*com(Ain,ds(1),ds(2)); else center = ssub*com(Ain,ds(1),ds(2),ds(3)); end\nend\n\nAin = imresize(reshape(full(Ain), [ds(1),ds(2), size(Ain,2)*prod(ds)/ds(1)/ds(2)]),[d(1),d(2)]); %,prod(d)/d(1)/d(2)*sum(K)]);\nAin = max(sparse(reshape(Ain, prod(d), [])),0);\n\nbin = imresize(reshape(bin,[ds(1),ds(2), options.nb*prod(ds)/ds(1)/ds(2)]),[d(1),d(2)]);\nbin = max(double(reshape(bin,prod(d),[])),0);\n\nif options.noise_norm\n %Ain = bsxfun(@times,Ain,double(max(P.sn(:),min_noise)));\n %bin = bsxfun(@times,bin,max(P.sn(:),min_noise));\n Ain = bsxfun(@times,Ain,double(min_noise(:)));\n bin = bsxfun(@times,bin,double(min_noise(:)));\nend\nCin = max(imresize(Cin, [size(Cin, 1), Ts*tsub]),0);\nfin = max(imresize(fin, [options.nb, Ts*tsub]),0);\nif T ~= Ts*tsub\n Cin = padarray(Cin, [0, T-Ts*tsub], 'post');\n fin = padarray(fin, [0, T-Ts*tsub], fin(end), 'post');\nend\n", "meta": {"author": "flatironinstitute", "repo": "CaImAn-MATLAB", "sha": "49b7884e93348d50df7173e1619d7499468bb1f6", "save_path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB", "path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB/CaImAn-MATLAB-49b7884e93348d50df7173e1619d7499468bb1f6/initialize_components.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.3478862186402444}}
{"text": "init_fig;\n\n% c\naxes('position', [.05, .57, .95, .37]);\nhold on;\nplot(y, 'color', col{8}/255);\nalpha(.7);\nplot(true_c, 'color', col{3}/255, 'linewidth', 1.5);\nplot(c_oasis, '-.', 'color', col{5}/255);\nif plot_cvx && exist('c_cvx', 'var')\n plot(c_cvx, '-.', 'color', col{7}/255);\nend\naxis tight;\nxlim([0, 2000]);\nset(gca, 'xtick', [0, 25, 50, 75]*30);\nset(gca, 'xticklabel', []);\nset(gca, 'ytick', 0:2);\nylabel('Fluor.');\nbox off;\nif plot_cvx\n legend('Data', 'Truth', 'OASIS', 'CVX', 'location', 'northeast', 'orientation', 'horizental');\nelse\n legend('Data', 'Truth', 'OASIS', 'location', 'northeast', 'orientation', 'horizental');\nend\n% s\naxes('position', [.05, .18, .95, .37]);\nhold on;\nplot(true_s, 'color', col{3}/255, 'linewidth', 1.5);\nplot(s_oasis, '-.', 'color', col{5}/255);\nif plot_cvx && exist('s_cvx', 'var')\n plot(s_cvx, '-.', 'color', col{7}/255);\nend\naxis tight;\nxlim([0, 2000]);\nset(gca, 'xtick', [0, 25, 50, 75]*30);\nset(gca, 'xticklabel', get(gca, 'xtick')/30);\nset(gca, 'ytick', [0,1]);\nxlabel('Time [s]');\nylabel('Activity.');", "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/examples/show_results.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.3478638281366775}}
{"text": "classdef FourthOrderVoigtPlaneStressRotator < FourthOrderVoigtRotator\n\n methods (Access = public)\n \n function obj = FourthOrderVoigtPlaneStressRotator(angle,dir)\n obj.compute(angle,dir)\n end\n \n end\n \n methods (Access = protected,Static)\n \n function r = createStressRotator(a,d)\n r = StressVoigtPlaneStressRotator(a,d);\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/Homogenization/Sources/Rotator/FourthOrderVoigtPlaneStressRotator.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3478638269630346}}
{"text": "\naddpath Codes1D\naddpath Codes2D\naddpath Codes3D\naddpath ServiceRoutines\naddpath CFD1D\naddpath CFD2D\naddpath Grid/\naddpath Grid/CFD\naddpath Grid/3D\naddpath Grid/CNS2D\naddpath Grid/Euler2D\naddpath Grid/Maxwell2D\naddpath Grid/Other\n\ncpt = cputime;\n\nEulerDriver1D \nfigure; plot(x,Ener); drawnow; pause(.1); \n\nPoissonCDriver1D\nfigure; plot(x,u); drawnow; pause(.1); \n\nAdvecDriver1D \nfigure; plot(x,u); drawnow; pause(.1); \n\nBurgersDriver1D \nfigure; plot(x,u); drawnow; pause(.1); \n\nHeatDriver1D \nfigure; plot(x,u); drawnow; pause(.1); \n\nMaxwellDriver1D \nfigure; plot(x,E); drawnow; pause(.1); \n\n\nCurvedCNSDriver2D \nfigure; PlotField2D(N, x, y, Q(:,:,4)); drawnow; pause(.1); \n\nCurvedPoissonIPDGDriver2D\nfigure; PlotField2D(N, x, y, u); drawnow; pause(.1); \n\nCurvedEulerDriver2D \nfigure; PlotField2D(N, x, y, Q(:,:,4)); drawnow; pause(.1); \n\nMaxwellCurvedDriver2D\nfigure; PlotField2D(N, x, y, Ez); drawnow; pause(.1); \n\nCurvedINSDriver2D \nfigure; PlotField2D(N, x, y, PR); drawnow; pause(.1); \n\nMaxwellDriver2D\nfigure; PlotField2D(N, x, y, Ez); drawnow; pause(.1); \n\nEulerDriver2D \nfigure; PlotField2D(N, x, y, Q(:,:,4)); drawnow; pause(.1); \n\nMaxwellHNonConDriver2D\nfigure; PlotField2D(N, x, y, Ez); drawnow; pause(.1); \n\nEulerShockDriver2D \nfigure; PlotField2D(N, x, y, Q(:,:,4)); drawnow; pause(.1); \n\nPoissonDriver2D\nfigure; PlotField2D(N, x, y, u); drawnow; pause(.1); \n\nMaxwellPNonConDriver2D\n\nAdvecDriver3D\nfigure; PlotContour3D(N, u, linspace(0, 1, 5)); drawnow; pause(.1); \n\nMaxwellDriver3D\nfigure; PlotContour3D(3*N, Ez, linspace(-1, 1, 10)); drawnow; pause(.1); \n\nPoissonIPDGDriver3D\nfigure; PlotContour3D(3*N, u, linspace(.1, 1, 10)); drawnow; pause(.1); \nhold on\nPlotSlice3D(2*N, u, 'x', .4);\nhold off\n\nalldemostook = cputime-cpt\n\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/JSHesthaven&TWarburton/TestAll.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.3478638190587141}}
{"text": "function varargout = grSimplifyBranches(nodes, edges)\n%GRSIMPLIFYBRANCHES Replace branches of a graph by single edges\n%\n% [NODES2 EDGES2] = grSimplifyBranches(NODES, EDGES)\n% renvoie une version simplifiee d'un graphe, en ne gardant que les \n% points multiples et les aretes reliant les points multiples.\n%\n% -----\n%\n% author : David Legland \n% INRA - TPV URPOI - BIA IMASTE\n% created the 13/08/2003.\n%\n\n% HISTORY :\n% 10/02/2004 : doc\n% 17/01/2006 : uses faster method to find neighbour edges\n% 18/01/2006 : replace call to subfunctions by inlining -> faster\n\nMnodes = []; % size Nn*2 -> nodes coordinates\nSedges = []; % size Ne*2 -> indices of nodes\nMpoints = []; % size Nn*1 -> indices of Multiple points \n % in nodes input array\n\nbranch = []; % size Nb*2 (variable)\n\nNn = 0;\nNe = 0;\nNb = 0;\n\n% look for the first multiple point\np = 1;\nwhile length(find(edges(:,1) == p | edges(:,2) == p)) < 3\n p = p + 1;\nend\n\nMpoints(1) = p;\nMnodes(1, 1:2) = nodes(p, 1:2);\nNn = Nn + 1;\n\n% add the branches of the first multiple point\nneighbours = find(edges(:,1)==p | edges(:,2)==p);\nfor b = 1:length(neighbours)\n Nb = Nb+1;\n edge = edges(neighbours(b),:);\n if edge(1) == p\n branch(Nb, 1:2) = [p edge(2)]; %#ok\n else\n branch(Nb, 1:2) = [p edge(1)]; %#ok\n end\nend\n\n% process each branch, until there is no more branch to process.\n% b is index of current branch\nb = 0;\nwhile b < length(branch)\n b = b+1;\n \n % check if the branch is valid\n if branch(b, 1) == 0\n continue;\n end\n \n % initialize iteration\n pNode = branch(b, 1);\n node = branch(b,2);\n neighbours = find(edges(:,1) == node | edges(:,2) == node);\n \n% disp(sprintf('node %3d (%03d ; %03d) -> %3d (%03d ; %03d)', ... \n% Mnode, nodes(Mnode, 1), nodes(Mnode, 2), ...\n% node, nodes(node, 1), nodes(node, 2)));\n \n while length(neighbours) < 3\n % look for the next point on the current branch\n next = 0;\n for n = 1:length(neighbours)\n edge = edges(neighbours(n), :);\n if edge(1)~= node && edge(1)~= pNode\n next = edge(1);\n break;\n end\n if edge(2)~= node && edge(2)~= pNode\n next = edge(2);\n break;\n end\n end\n \n pNode = node;\n node = next;\n neighbours = find(edges(:,1) == node | edges(:,2) == node);\n end\n \n % node is now the next multiple point, and pNode contains the last\n % point of the branch.\n \n % check if the multiple point has already been processed\n index = find(Mpoints==node);\n if ~isempty(index)\n % find the branch starting with node, and with pNode has\n % second point, and set it to [0 0] to avoid it to be \n % processed again\n %disp('remove branch');\n for b2 = 1:Nb\n if branch(b2, 1) == node && branch(b2, 2) == pNode\n %disp('find branch');\n branch(b2, 1:2) = 0; %#ok\n break;\n end\n end\n \n else\n % add the multiple point to the list of points\n %disp('add point');\n Nn = Nn+1;\n Mnodes(Nn, 1:2) = nodes(node, 1:2); %#ok\n index = Nn;\n Mpoints(Nn) = node; %#ok\n \n % add each neighbour of the new multiple point (but not\n % the neighbour containing pNode) to the list of branches\n for n = 1:length(neighbours)\n edge = edges(neighbours(n), :);\n if edge(1) ~= pNode && edge(2) ~= pNode\n %disp('add a branch');\n Nb = Nb + 1;\n if edge(1) == node\n branch(Nb, 1:2) = [node edge(2)]; %#ok\n else\n branch(Nb, 1:2) = [node edge(1)]; %#ok\n end\n end\n end\n end\n \n %disp('add new Edge');\n Ne = Ne + 1;\n Sedges(Ne, 1:2) = [find(Mpoints == branch(b,1)), index]; %#ok\nend\n\n\n% process output depending on how many arguments are needed\nif nargout == 1\n out{1} = Mnodes;\n out{2} = Sedges;\n varargout{1} = out;\nend\n\nif nargout == 2\n varargout{1} = Mnodes;\n varargout{2} = Sedges;\nend\n\nreturn;\n\n", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/matGeom/graphs/grSimplifyBranches.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.34786381905871405}}
{"text": "function test_failed = test_libltfat_gabdual(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\nLarr = [12 15 120 120];\naarr = [3 3 10 10];\nMarr = [6 5 20 20];\n\nfor do_complex = 0:1\n complexstring = '';\n if do_complex, complexstring = 'complex'; end\n for idx = 1:numel(Larr)\n L = Larr(idx);\n a = aarr(idx);\n M = Marr(idx);\n \n if do_complex\n z = cast(randn(L,1)+1i*randn(L,1),flags.complexity);\n zi = complex2interleaved(z);\n zout = randn(size(zi),flags.complexity);\n \n ziPtr = libpointer(dataPtr,zi);\n zoutPtr = libpointer(dataPtr,zout);\n else\n z = cast(randn(L,1),flags.complexity);\n zi = z;\n zout = randn(size(zi),flags.complexity);\n \n ziPtr = libpointer(dataPtr,zi);\n zoutPtr = libpointer(dataPtr,zout);\n end\n \n trueres = gabdual(z,a,M);\n \n funname = makelibraryname('gabdual_long',flags.complexity,do_complex);\n status = calllib('libltfat',funname, ziPtr,L,a,M,zoutPtr);\n \n if do_complex\n res = norm(trueres - interleaved2complex(zoutPtr.Value));\n else\n res = norm(trueres - zoutPtr.Value);\n end\n \n [test_failed,fail]=ltfatdiditfail(res+status,test_failed);\n fprintf(['GABDUAL OP L:%3i, %s %s %s %s\\n'],L,flags.complexity,complexstring,ltfatstatusstring(status),fail);\n \n status = calllib('libltfat',funname,ziPtr,L,a,M,ziPtr);\n \n if do_complex\n res = norm(trueres - interleaved2complex(ziPtr.Value));\n else\n res = norm(trueres - ziPtr.Value);\n end\n \n [test_failed,fail]=ltfatdiditfail(res+status,test_failed);\n fprintf(['GABDUAL IP L:%3i, %s %s %s %s\\n'],L,flags.complexity,complexstring,ltfatstatusstring(status),fail);\n \n \n \n if do_complex\n z = cast(randn(M,1)+1i*randn(M,1),flags.complexity);\n zi = complex2interleaved(z);\n zout = randn(size(zi),flags.complexity);\n \n ziPtr = libpointer(dataPtr,zi);\n zoutPtr = libpointer(dataPtr,zout);\n else\n z = cast(randn(M,1),flags.complexity);\n zi = z;\n zout = randn(size(zi),flags.complexity);\n \n ziPtr = libpointer(dataPtr,zi);\n zoutPtr = libpointer(dataPtr,zout);\n end\n \n trueres = gabdual(z,a,M);\n \n funname = makelibraryname('gabdual_painless',flags.complexity,do_complex);\n status = calllib('libltfat',funname, ziPtr,M,a,M,zoutPtr);\n \n if do_complex\n res = norm(trueres - interleaved2complex(zoutPtr.Value));\n else\n res = norm(trueres - zoutPtr.Value);\n end\n \n [test_failed,fail]=ltfatdiditfail(res+status,test_failed);\n fprintf(['GABDUAL PAINLESS OP L:%3i, %s %s %s %s\\n'],L,flags.complexity,complexstring,ltfatstatusstring(status),fail);\n \n status = calllib('libltfat',funname,ziPtr,M,a,M,ziPtr);\n \n if do_complex\n res = norm(trueres - interleaved2complex(ziPtr.Value));\n else\n res = norm(trueres - ziPtr.Value);\n end\n \n [test_failed,fail]=ltfatdiditfail(res+status,test_failed);\n fprintf(['GABDUAL PANLESS IP L:%3i, %s %s %s %s\\n'],L,flags.complexity,complexstring,ltfatstatusstring(status),fail);\n \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_gabdual.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.34786381115439347}}
{"text": "% Helper function for decom.m, run DECOM method at regular time intervals.\n%\n% Octave compatible\n% \n% (please see decom.m for documentation and HOWTO_egg.m for a usage example)\n%\n%\n% Copyright (c) 2013 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 [Oqeggmess, f0mess, npicferms, npicouvers, atimes] = decom_sig(s, fs, f0s, method)\n\n if nargin<3; f0s=[]; f0=[]; end\n if nargin<4; method = []; end\n\n winLen=2*round(20/1000*fs /2)+1;\n winShift=round(5/1000*fs);\n\n % Do processing\n start=1;\n stop=start+winLen-1;\n cnt=1;\n\n while stop <= length(s)\n\n % Get windowed frame\n x_frame = s(start:stop);\n atimes(cnt) = (0.5*(stop+start))/fs;\n\n if ~isempty(f0s) && size(f0s,2)>1\n f0 = interp1(f0s(:,1), f0s(:,2), atimes(cnt), 'nearest', 'extrap');\n end\n\n [Oqeggmess(cnt), f0mess(cnt), npicferms(cnt), npicouvers(cnt)] = decom(x_frame, fs, f0, method);\n\n % Increment\n start=start+winShift-1;\n stop=start+winLen-1;\n cnt=cnt+1;\n end\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/glottalsource/egg/decom/decom_sig.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358548398982, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3477776834764116}}
{"text": "function [ a2, b2 ] = i4vec2_sorted_uniquely ( n1, a1, b1, n2 )\n\n%*****************************************************************************80\n%\n%% I4VEC2_SORTED_UNIQUELY copies unique elements from a sorted I4VEC2.\n%\n% Discussion:\n%\n% An I4VEC2 is a pair of I4VEC's.\n%\n% An I4VEC is a vector of I4's.\n%\n% Entry K of an I4VEC2 is the pair of values located\n% at the K-th entries of the two I4VEC's.\n%\n% Item I is stored as the pair A1(I), A2(I).\n%\n% The items must have been sorted, or at least it must be the\n% case that equal items are stored in adjacent vector locations.\n%\n% If the items were not sorted, then this routine will only\n% replace a string of equal values by a single representative.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 July 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N1, the number of items.\n%\n% Input, integer A1(N1), B1(N1), the array of items.\n%\n% Input, integer N2, the number of unique items.\n%\n% Output, integer A2(N2), B2(N2), the array of unique items.\n%\n a2 = zeros(n2,1);\n b2 = zeros(n2,1);\n\n i1 = 1;\n i2 = 1;\n a2(i2) = a1(i1);\n b2(i2) = b1(i1);\n\n for i1 = 2 : n1\n\n if ( a1(i1) ~= a2(i2) || b1(i1) ~= b2(i2) )\n\n i2 = i2 + 1;\n\n a2(i2) = a1(i1);\n b2(i2) = b1(i1);\n\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/st_to_cc/i4vec2_sorted_uniquely.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.3477776834764115}}
{"text": "filename='Gripping_quad_fine';\n ptype = 'MACRO';\nmethod = 'SIMPALL';\nmaterialType = 'ISOTROPIC';\ninitial_case = 'full';\ncost = {'nonadjoint_compliance'};\nweights = [1, 0.1];\nconstraint = {'volumeConstraint'};\nconstraint_case = 'INEQUALITY';\noptimizer = 'PROJECTED GRADIENT'; incrementFactor = 1;\nfilterType = 'P1';\n\nnsteps = 1;\nVfrac_final = 0.75;\noptimality_final = 1e-3;\nconstr_final =1e-3;\n\nVfrac_initial = 1;\noptimality_initial = 1e-3;\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/Gripping/GrippingQuadFine_Case_2_1_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.3477711491591614}}
{"text": "function [ mSynCat, vMain] = calc_SynCat(nNbkg,vSynCat,nSynCat_,nSynMode, vAfter,vEtas,mCatalog,bPSQ,vPSQ,mPSQ)\n % calculates a synthetic catalog with a backgroundrate based number of earthquakes in the catalog of the period before starting date.\n %\n % Example: [mSynCat, vMain] = calc_SynCat(2500,2.5,2.5,8,100,'January 1,1980','December 31,1990',6.5,1,0,a);\n %\n % This function (calc_SynCat) calculates a synthetic catalog with a\n % backgroundrate based number of earthquakes in the catalog of the period\n % before starting date. This function is doing the following:\n % 1) creates a synthetic catalog with background rate based on input parameters.\n % 2) calculate omori-type aftershock and add this to the background catalog,\n % that was created by the properties of the inputbackground catalog. Therefore\n % the program package ETESProject by karen Felzer was used.\n %\n % Author: van Stiphout, Thomas\n % Email: vanstiphout@sed.ethz.ch\n % Created: 2. Mar 2007\n % Changed: -\n %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Variables\n % Input:\n % nNbkg Number of events in background catalog during assigned period\n % vSynCat Vektor with contraints on synthetic catalog\n % 1-4: fMinLon fMaxLon fMinLat fMaxLat in degree\n % 5-6: fMinDepth fMaxDepth in km\n % 7-8: fMinTime fMaxTime (duration of catalog)\n % 9: fRate Reduction of earthquakes for entire catalog\n % (0.75 = 25% reduction) in period (fT-fTw) - fT\n % 10: fBValue b-value of the catalog\n % 11: fMc Magnitude of Completness (minimum Magnitude in Catalog)\n % 12: fIncMagnitude increment steps\n % nSynCat_ 1: only backgorund, 2: background + ETAS\n % nSynMode Type of synthetic catalog 0:homogeneous distr; 1:based\n % on real catalog 2:hypocenter based on real catalog, magnitude and focal\n % time is randomly computed\n % vAfter Definition/Constraints for Aftershocks\n % 1: Mmin: Minimum earthquake magnitude to report and simulate\n % 2: MminR: Minimum earthquake magnitude for reporting\n % in the output catalog\n % 3: maxm: Maximum earthquake magnitude\n % 4: DMax: Maximum distance for aftershocks\n % 5: magb: Cutoff magnitude for the point source vs. plane source\n % representation of the mainshock\n % vEtas Parameters for ETAS:[CX, P, A] standard=[0.095, 1.34, 0.008]\n % mCatalog Declustered catalog needed only for nSynMode=1\n % bPSQ with (1) or without (0) PSQ\n % vPSQ values for PSQ (lon, lat, N, Tw, T)\n %\n % Output:\n % SynCat Simulated ETES catalog [yr lon lat month day mag depth hrs min sec]\n % vMain Vector with assignments if main (true) or aftershock (false)\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n % initialize:\n clear FaultParam;\n \n % background:\n fBValue=vSynCat(10);\n fMc=vSynCat(11);\n fInc=vSynCat(12);\n fMinLat=vSynCat(3);\n fMaxLat=vSynCat(4);\n fMinLon=vSynCat(1);\n fMaxLon=vSynCat(2);\n fMinDepth=vSynCat(5);\n fMaxDepth=vSynCat(6);\n nRchange=vSynCat(9);\n [fYr1, nMn1, nDay1, nHr1, nMin1, nSec1]=decyear2mat(vSynCat(7));\n [fYr2, nMM2, nDD2, nHH2, nMN2, nSS2]=decyear2mat(vSynCat(8));\n \n \n % vAfter\n Mmin=vAfter(1);\n MminR=vAfter(2);\n maxm=vAfter(3);\n DMax=vAfter(4);\n magb=vAfter(5);\n FaultParam=[0 0 0 0 0 0 0];\n \n % vEtas\n CX=vEtas(1);\n P=vEtas(2);\n A=vEtas(3);\n \n switch nSynCat_\n case 1\n % create background rate\n mSynCat=syn_catalog(nNbkg, fBValue, fMc, fInc, fMinLat,fMaxLat,...\n fMinLon,fMaxLon,fMinDepth,fMaxDepth, fYr1,fYr2,nSynMode,...\n mCatalog);\n if bPSQ\n mSynCat=sr_makePSQ(mSynCat,vPSQ(2),vPSQ(3),vPSQ(4),...\n vPSQ(1),mPSQ);\n end\n % mSynCat(:,1)=mSynCat(randperm(size(mSynCat,1))',1);\n vMain=ones(nNbkg,1);\n case 2 % create background rate + ETAS\n nNbkgA=floor(nNbkg/(1+nRchange)*1);\n nNbkgB=ceil(nNbkg/(1+nRchange)*nRchange);\n if nRchange == 1\n mCat=syn_catalog(nNbkg, fBValue, fMc, fInc, fMinLat,fMaxLat,...\n fMinLon,fMaxLon,fMinDepth,fMaxDepth, fYr1,fYr2,nSynMode,...\n mCatalog);\n else\n mCatA=syn_catalog(nNbkgA, fBValue, fMc, fInc, fMinLat,fMaxLat,...\n fMinLon,fMaxLon,fMinDepth,fMaxDepth,fYr1,(fYr1+fYr2)/2,...\n nSynMode,mCatalog);\n mCatB=syn_catalog(nNbkgB, fBValue, fMc, fInc, fMinLat,fMaxLat,...\n fMinLon,fMaxLon,fMinDepth,fMaxDepth,(fYr1+fYr2)/2,fYr2,...\n nSynMode,mCatalog);\n mCat=[mCatA;mCatB];\n end\n % mCat(:,1)=mCat(randperm(size(mCat,1))',1);\n [Y,Idx]=sort(mCat(:,3),1);\n mCat=mCat(Idx,:);\n if bPSQ\n mCat=sr_makePSQ(mCat,vPSQ(2),vPSQ(3),vPSQ(4),...\n vPSQ(1),mPSQ);\n end\n mCat1=[fix(mCat(:,3)) mCat(:,4) mCat(:,5) mCat(:,8) mCat(:,9) rand(size(mCat,1),1)*60 mCat(:,2) mCat(:,1) mCat(:,7) mCat(:,6)];\n % mCat1(:,1)=mCat1(:,1)-(max(mCat1(:,1))-min(mCat1(:,1)));\n % [N,Mmax,catalog,IDAll,HistoryAll] = ETESProject2(cat1,RateGrid2,0.095,1.34,0.008,Mmin,MminR,maxm,DMax,sYr1,sYr2,6.5,FaultParam)\n [N,Mmax,catalog,IDAll,HistoryAll] = ETESProject3(mCat1,vEtas,vAfter,fYr1,fYr2,FaultParam);\n \n mSynCat(:,1) = catalog(:,8); % lon\n mSynCat(:,2) = catalog(:,7); % lat\n mSynCat(:,3) = catalog(:,1); % years\n mSynCat(:,4) = catalog(:,2); % month\n mSynCat(:,5) = catalog(:,3); % day\n mSynCat(:,6) = catalog(:,10); % mag\n mSynCat(:,7) = catalog(:,9); % depth\n mSynCat(:,8) = catalog(:,4); % hours\n mSynCat(:,9) = catalog(:,5); % minutes\n mSynCat(:,10) = catalog(:,6); % seconds\n \n mSynCat(:,3) = decyear([mSynCat(:,3) mSynCat(:,4) mSynCat(:,5) ...\n mSynCat(:,8) mSynCat(:,9) mSynCat(:,10)]); % yrs decimal\n size(mSynCat)\n vMain=(catalog(:,12)==0);\n end\n % disp('cat fertig')\nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/thomas/synthetic/calc_SynCat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.34755121315699955}}
{"text": "function [bnet, LL, engine] = learn_params_em(engine, evidence, max_iter, thresh)\n% LEARN_PARAMS_EM Set the parameters of each adjustable node to their ML/MAP values using batch EM.\n% [bnet, LLtrace, engine] = learn_params_em(engine, data, max_iter, thresh)\n%\n% data{i,l} is the value of node i in case l, or [] if hidden.\n% Suppose you have L training cases in an O*L array, D, where O is the num observed\n% scalar nodes, and N is the total num nodes.\n% Then you can create 'data' as follows, where onodes is the index of the observable nodes:\n% data = cell(N, L);\n% data(onodes,:) = num2cell(D);\n% Of course it is possible for different sets of nodes to be observed in each case.\n%\n% We return the modified bnet and engine.\n% To see the learned parameters for node i, use the construct\n% s = struct(bnet.CPD{i}); % violate object privacy\n% LLtrace is the learning curve: the vector of log-likelihood scores at each iteration.\n%\n% max_iter specifies the maximum number of iterations. Default: 10.\n%\n% thresh specifies the thresold for stopping EM. Default: 1e-3.\n% We stop when |f(t) - f(t-1)| / avg < threshold,\n% where avg = (|f(t)| + |f(t-1)|)/2 and f is log lik. \n\nif nargin < 3, max_iter = 10; end\nif nargin < 4, thresh = 1e-3; end\n\nverbose = 1;\n\nloglik = 0;\nprevious_loglik = -inf;\nconverged = 0;\nnum_iter = 1;\nLL = [];\n\nwhile ~converged & (num_iter <= max_iter)\n [engine, loglik] = EM_step(engine, evidence);\n if verbose, fprintf('EM iteration %d, ll = %8.4f\\n', num_iter, loglik); end\n num_iter = num_iter + 1;\n converged = em_converged(loglik, previous_loglik, thresh);\n previous_loglik = loglik;\n LL = [LL loglik];\nend\nif verbose, fprintf('\\n'); end\n\nbnet = bnet_from_engine(engine);\n\n%%%%%%%%%\n\nfunction [engine, loglik] = EM_step(engine, cases)\n\nbnet = bnet_from_engine(engine); % engine contains the old params that are used for the E step\nCPDs = bnet.CPD; % these are the new params that get maximized\nnum_CPDs = length(CPDs);\nadjustable = zeros(1,num_CPDs);\nfor e=1:num_CPDs\n adjustable(e) = adjustable_CPD(CPDs{e});\nend\nadj = find(adjustable);\nn = length(bnet.dag);\n\nfor e=adj(:)'\n CPDs{e} = reset_ess(CPDs{e});\nend\n\nloglik = 0;\nncases = size(cases, 2);\nfor l=1:ncases\n evidence = cases(:,l);\n [engine, ll] = enter_evidence(engine, evidence);\n loglik = loglik + ll;\n hidden_bitv = zeros(1,n);\n hidden_bitv(isemptycell(evidence))=1;\n for i=1:n\n e = bnet.equiv_class(i);\n if adjustable(e)\n fmarg = marginal_family(engine, i);\n CPDs{e} = update_ess(CPDs{e}, fmarg, evidence, bnet.node_sizes, bnet.cnodes, hidden_bitv);\n end\n end\nend\n\nfor e=adj(:)'\n CPDs{e} = maximize_params(CPDs{e});\nend\n\nengine = update_engine(engine, CPDs);\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/learning/learn_params_em.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3475470245753706}}
{"text": "function varargout = clipMeshVertices(v, f, b, varargin)\n%CLIPMESHVERTICES Clip vertices of a surfacic mesh and remove outer faces\n%\n% [V2, F2] = clipMeshVertices(V, F, B)\n% Clip a mesh represented by vertex array V and face array F, with the\n% box represented by B. The result is the set of vertices contained in\n% the box, and a new set of faces corresponding to original faces with\n% all vertices within the box.\n% \n% [V2, F2] = clipMeshVertices(..., 'shape','sphere') Specify the shape.\n% Default is 'box'. But it's also possible to use a 'sphere'.\n% \n% [V2, F2] = clipMeshVertices(..., 'inside',false) removes the inner \n% faces instead of the outer faces.\n%\n% Example\n% [v, f] = createSoccerBall;\n% f = triangulateFaces(f);\n% box = [0 2 -1 2 -.5 2];\n% [v2, f2] = clipMeshVertices(v, f, box, 'inside', false);\n% figure('color','w'); view(3); axis equal\n% drawMesh(v, f, 'faceColor', 'none', 'faceAlpha', .2);\n% drawBox3d(box)\n% drawMesh(v2, f2, 'faceAlpha', .7);\n%\n% See also\n% meshes3d, clipPoints3d\n%\n% ------\n% Author: David Legland, oqilipo\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2011-04-07, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011 INRA - Cepia Software Platform.\n\n% if input is given as a structure, parse fields\nif isstruct(v)\n if nargin > 2; varargin = [b, varargin]; end\n b = f;\n f = v.faces;\n v = v.vertices;\nend\n\nparser = inputParser;\nvalidStrings = {'box','sphere'};\naddParameter(parser,'shape','box',@(x) any(validatestring(x, validStrings)));\naddParameter(parser,'inside',true,@islogical);\nparse(parser,varargin{:});\n\n% clip the vertices\n[v2, indVertices] = clipPoints3d(v, b,...\n 'shape', parser.Results.shape, 'inside', parser.Results.inside);\n\n% create index array for face indices relabeling\nrefInds = zeros(size(indVertices));\nfor i = 1:length(indVertices)\n refInds(indVertices(i)) = i;\nend\n\n% select the faces with all vertices within the box\nif isnumeric(f)\n % Faces given as numeric array\n indFaces = sum(~ismember(f, indVertices), 2) == 0;\n f2 = refInds(f(indFaces, :));\n \nelseif iscell(f)\n % Faces given as cell array\n nFaces = length(f);\n indFaces = false(nFaces, 1);\n for i = 1:nFaces\n indFaces(i) = sum(~ismember(f{i}, indVertices), 2) == 0;\n end\n f2 = f(indFaces, :);\n \n % re-label indices of face vertices (keeping horizontal index array)\n for i = 1:length(f2)\n f2{i} = refInds(f2{i})';\n end\nend\n\nswitch nargout\n case 1\n mesh2.vertices=v2;\n mesh2.faces=f2;\n varargout{1}=mesh2;\n case 2\n varargout{1}=v2;\n varargout{2}=f2;\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/meshes3d/clipMeshVertices.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.34753584748593885}}
{"text": "function [p,r] = cs_scc (A) %#ok\n%CS_SCC strongly-connected components of a square sparse matrix.\n% [p,r] = cs_scc(A) finds a permutation p so that A(p,p) is permuted into\n% block upper triangular form. The diagonal of A is ignored. The kth block\n% is given by A (s,s) where s = r(k):r(k+1)-1. A must be square.\n% For bipartite or rectangular graphs, use cs_scc2.\n%\n% Example:\n% Prob = UFget ('HB/arc130') ; A = Prob.A ; [p r] = cs_scc (A) ;\n% cspy (A (p,p)) ;\n%\n% See also CS_DMPERM, DMPERM, CS_SCC2.\n\n% Copyright 2006-2007, Timothy A. Davis.\n% http://www.cise.ufl.edu/research/sparse\n\nerror ('cs_scc mexFunction not found') ;\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_scc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.34753584748593885}}
{"text": "function img = imMergeLabels(img, lbls, varargin)\n%IMMERGELABELS Merge regions in a labeled image\n%\n% Deprecated: replaced by the \"imMergeRegions\" function.\n%\n% Usage:\n% LBL2 = imMergeLabels(IMG, LABELS);\n% IMG is a label image, LABELS are the labels of the regions to be\n% merged. IMG can be 2D or 3D.\n% The indices of regions are set to the same value, and the boundary\n% between the regions is also merged to the new region, preserving\n% topology of adjacent regions.\n% The function uses morphologial operation, processing time can be\n% consuming.\n%\n% LBL2 = imMergeLabels(IMG, LABELS, SE);\n% Specify the structuring element used for morphological detection of the\n% boundary.\n%\n% Example:\n% lbl = [1 1 0 3 3;1 1 0 3 3;1 0 2 0 3;0 2 2 2 0];\n% lbl2 = imMergeLabels(lbl, [1 2])\n% lbl2 =\n% 1 1 0 3 3\n% 1 1 0 3 3\n% 1 1 1 0 3\n% 1 1 1 1 0\n%\n% See Also\n% imMergeRegions\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2007-08-07\n% Copyright 2007 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas.\n\n% simply call the new function\nimg = imMergeRegions(img, lbls, varargin{:});\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/imMergeLabels.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.6224593382055109, "lm_q1q2_score": 0.3475358422471228}}
{"text": "function tapas_sem_plot_fits(fits, dt)\n%% Plot the fits of the model.\n%\n% Input\n% data -- Structure of the data of a single subject.\n% fits -- Fits struct array\n% dt -- Factor to normalize the area\n% Output\n%\n\n% aponteeduardo@gmail.com\n% copyright (C) 2019\n%\n\nn = 1;\n\nn = n + 1;\nif nargin < n\n dt = 1;\nend\n\nnconds = numel(fits);\n\nfor i = 1:nconds\n\n ax = subplot(nconds, 2, (i - 1) * 2 + 1);\n hold on;\n\n plot(fits(i).t, fits(i).pro * dt, 'k', 'linewidth', 2)\n\n ax = subplot(nconds, 2, (i - 1) * 2 + 2);\n hold on;\n plot(fits(i).t, fits(i).anti * dt, 'k', 'linewidth', 2)\nend\n\n\nend\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/sem/plotting/tapas_sem_plot_fits.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.3475358396652779}}
{"text": "% This subroutine assigns creates a grid with\n% spacing dx,dy (in degreees). The size will\n% be selected interactiVELY. The bvalue in each\n% volume around a grid point containing ni earthquakes\n% will be calculated as well as the magnitude\n% of completness\n% Stefan Wiemer 1/95\n\n\ndisplay ('This is /src/bdepth_ratio_auto.m');\n\n\nglobal no1 bo1 inb1 inb2\n\nif sel == 'in'\n % get the grid parameter\n % initial values\n %\n dx = 0.1;\n dy = 0.1 ;\n ni = 1000;\n Nmin = 50;\n stan2 = nan;\n stan = nan;\n prf = nan;\n av = nan;\n mid_point = 5;\n top_zonet = 0;\n top_zoneb = 5;\n bot_zonet = 7;\n bot_zoneb = 15;\n topstan2 = nan;\n botstan2 = nan;\n topstan = nan;\n botstan = nan;\n topav = nan;\n botav = nan;\n\n\n % make the interface\n %\n figure_w_normalized_uicontrolunits(...\n 'Name','Depth Ratio Grid Input Parameter',...\n 'NumberTitle','off', ...\n 'MenuBar','none', ...\n 'NextPlot','new', ...\n 'units','points',...\n 'Visible','off', ...\n 'Position',[ wex+200 wey-200 650 300]);\n axis off\n labelList2=[' Automatic Mcomp (max curvature) | Fixed Mc (Mc = Mmin) | Automatic Mcomp (90% probability) | Automatic Mcomp (95% probability) | Best (?) combination (Mc95 - Mc90 - max curvature)'];\n\n labelPos = [0.2 0.60 0.6 0.08];\n hndl2=uicontrol(...\n 'Style','popup',...\n 'Position',labelPos,...\n 'Units','normalized',...\n 'String',labelList2,...\n 'Callback','inb2 =get(hndl2,''Value''); ');\n\n % set(hndl2,'value',5);\n\n\n % creates a dialog box to input grid parameters\n %\n %\n\n % mid_point_field=uicontrol('Style','edit',...\n % 'Position',[.47 .80 .12 .08],...\n % 'Units','normalized','String',num2str(mid_point),...\n % 'Callback','mid_point=str2double(get(mid_point_field,''String'')); set(mid_point_field,''String'',num2str(mid_point));');\n\n top_zonet_field=uicontrol('Style','edit',...\n 'Position',[.36 .80 .06 .06],...\n 'Units','normalized','String',num2str(top_zonet),...\n 'Callback','top_zonet=str2double(get(top_zonet_field,''String'')); set(top_zonet_field,''String'',num2str(top_zonet));');\n top_zoneb_field=uicontrol('Style','edit',...\n 'Position',[.36 .74 .06 .06],...\n 'Units','normalized','String',num2str(top_zoneb),...\n 'Callback','top_zoneb=str2double(get(top_zoneb_field,''String'')); set(top_zoneb_field,''String'',num2str(top_zoneb));');\n\n bot_zonet_field=uicontrol('Style','edit',...\n 'Position',[.78 .80 .06 .06],...\n 'Units','normalized','String',num2str(bot_zonet),...\n 'Callback','bot_zonet=str2double(get(bot_zonet_field,''String'')); set(bot_zonet_field,''String'',num2str(bot_zonet));');\n bot_zoneb_field=uicontrol('Style','edit',...\n 'Position',[.78 .74 .06 .06],...\n 'Units','normalized','String',num2str(bot_zoneb),...\n 'Callback','bot_zoneb=str2double(get(bot_zoneb_field,''String'')); set(bot_zoneb_field,''String'',num2str(bot_zoneb));');\n\n freq_field=uicontrol('Style','edit',...\n 'Position',[.30 .50 .12 .08],...\n 'Units','normalized','String',num2str(ni),...\n 'Callback','ni=str2double(get(freq_field,''String'')); set(freq_field,''String'',num2str(ni));set(tgl2,''value'',0); set(tgl1,''value'',1)');\n\n\n freq_field0=uicontrol('Style','edit',...\n 'Position',[.70 .50 .12 .08],...\n 'Units','normalized','String',num2str(ra),...\n 'Callback','ra=str2double(get(freq_field0,''String'')); set(freq_field0,''String'',num2str(ra)) ; set(tgl2,''value'',1); set(tgl1,''value'',0)');\n\n freq_field2=uicontrol('Style','edit',...\n 'Position',[.30 .40 .12 .08],...\n 'Units','normalized','String',num2str(dx),...\n 'Callback','dx=str2double(get(freq_field2,''String'')); set(freq_field2,''String'',num2str(dx));');\n\n freq_field3=uicontrol('Style','edit',...\n 'Position',[.30 .30 .12 .08],...\n 'Units','normalized','String',num2str(dy),...\n 'Callback','dy=str2double(get(freq_field3,''String'')); set(freq_field3,''String'',num2str(dy));');\n\n tgl1 = uicontrol('Style','checkbox',...\n 'string','Number of Events:',...\n 'Position',[.09 .50 .2 .08], 'Callback','set(tgl2,''value'',0)',...\n 'Units','normalized');\n\n set(tgl1,'value',1);\n\n tgl2 = uicontrol('Style','checkbox',...\n 'string','OR: Constant Radius',...\n 'Position',[.47 .50 .2 .08], 'Callback','set(tgl1,''value'',0)',...\n 'Units','normalized');\n\n\n freq_field4=uicontrol('Style','edit',...\n 'Position',[.30 .20 .12 .08],...\n 'Units','normalized','String',num2str(Nmin),...\n 'Callback','Nmin=str2double(get(freq_field4,''String'')); % set(freq_field4,''String'',num2str(Nmin));');\n\n\n close_button=uicontrol('Style','Pushbutton',...\n 'Position',[.60 .05 .15 .12 ],...\n 'Units','normalized','Callback','close;done','String','Cancel');\n\n go_button1=uicontrol('Style','Pushbutton',...\n 'Position',[.20 .05 .15 .12 ],...\n 'Units','normalized',...\n 'Callback',' inb1 =get(hndl2,''Value'');tgl1 =get(tgl1,''Value'');tgl2 =get(tgl2,''Value'');close,sel =''ca'', bdepth_ratio',...\n 'String','Go');\n Nmin;\n text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[0.20 .75 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String','Please choose an Mc estimation option ');\n\n mid_txt=text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[0.24 1.0 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String','Depth limits for depth ratio calculation ');\n\n top_txt=text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[-0.10 .85 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String','Top and bottom for TOP zone(km):');\n\n bot_txt=text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[0.40 .85 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String','Top and bottom for BOTTOM zone(km):');\n\n txt3 = text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[0.30 0.64 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String',' Grid Parameter');\n txt5 = text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[-0.06 0.40 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String','Spacing in x (dx) in deg:');\n\n txt6 = text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[-0.06 0.29 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String','Spacing in y (dy) in deg:');\n\n txt7 = text(...\n 'Color',[0 0 0 ],...\n 'EraseMode','normal',...\n 'Position',[-0.06 0.17 0 ],...\n 'Rotation',0 ,...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'FontWeight','bold',...\n 'String','Min. No. of events > Mc:');\n\n\n\n set(gcf,'visible','on');\n watchoff\n\nend % if nargin ==0\n\n% get the grid-size interactively and\n% calculate the b-value in the grid by sorting\n% thge seimicity and selectiong the ni neighbors\n% to each grid point\n\nif sel == 'ca'\n selgp\n itotal = length(newgri(:,1));\n if length(gx) < 4 || length(gy) < 4\n errordlg('Selection too small! (Dx and Dy are in degreees! ');\n return\n end\n\n\n zmap_message_center.set_info(' ','Running bdepth_ratio... ');think\n % make grid, calculate start- endtime etc. ...\n %\n t0b = min(a.Date) ;\n n = a.Count;\n teb = a(n,3) ;\n tdiff = round((teb - t0b)*365/par1);\n loc = zeros(3, length(gx)*length(gy));\n\n % loop over all points\n %\n i2 = 0.;\n i1 = 0.;\n bvg = [];\n allcount = 0.;\n nobv = 0;\n wai = waitbar(0,' Please Wait ... ');\n set(wai,'NumberTitle','off','Name','b-value grid - percent done');;\n drawnow\n\n\n % sort by depth\n\n % [s,is] = sort(a.Depth);\n % adepth = a(is(:,1),:);\n\n % find row index of ratio midpoint\n l = a.Depth >= top_zonet & a.Depth < top_zoneb;\n top_zone = a.subset(l);\n\n l = a.Depth >= bot_zonet & a.Depth < bot_zoneb;\n bot_zone = a.subset(l);\n\n\n\n %\n % overall b-value\n [bv magco stan av me mer me2, pr] = bvalca3(top_zone,inb1,inb2);\n tbo1 = bv; tno1 = length(top_zone(:,1));\n\n [bv magco stan av me mer me2, pr] = bvalca3(bot_zone,inb1,inb2);\n bbo1 = bv; bno1 = length(bot_zone(:,1));\n\n depth_ratio = tbo1/bbo1;\n\n disp(depth_ratio);\n\n % loop over all points\n for i= 1:length(newgri(:,1))\n x = newgri(i,1);y = newgri(i,2);\n allcount = allcount + 1.;\n i2 = i2+1;\n\n % calculate distance from center point and sort wrt distance\n l = sqrt(((a.Longitude-x)*cos(pi/180*y)*111).^2 + ((a.Latitude-y)*111).^2) ;\n [s,is] = sort(l);\n b = a(is(:,1),:) ; % re-orders matrix to agree row-wise\n\n if tgl1 == 0 % take point within r\n l3 = l <= ra;\n b = a.subset(l3); % new data per grid point (b) is sorted in distanc (from center point)\n rd = ra;\n else\n % take first ni points\n b = b(1:ni,:); % new data per grid point (b) is sorted in distance\n l2 = sort(l); rd = l2(ni);\n\n end\n\n\n %estimate the completeness and b-value\n newt2 = b;\n\n % sort by depth\n\n l = b(:,7) >= top_zonet & b(:,7) < top_zoneb;\n topb = b(l,:);\n\n l = b(:,7) >= bot_zonet & b(:,7) < bot_zoneb;\n botb = b(l,:);\n\n\n\n\n\n\n if length(topb) >= Nmin && length(botb) >= Nmin\n\n if inb1 == 3\n newt2 = topb;\n mcperc_ca3;\n l = topb(:,6) >= Mc90-0.05; magco = Mc90;\n n1 = length(topb(l,:));\n if length(topb(l,:)) >= Nmin\n [topbv magco stan av me mer me2, pr] = bvalca3(topb(l,:),2,2);\n [topav2 topbv2 topstan2 ] = bmemag(topb(l,:));\n else topbv = nan; topbv2 = nan, magco = nan; av = nan; topav2 = nan;\n nobv = nobv + 1;\n end\n newt2 = botb;\n mcperc_ca3;\n l = botb(:,6) >= Mc90-0.05; magco = Mc90;\n n2 = length(botb(l,:));\n if length(botb(l,:)) >= Nmin\n [botbv magco stan av me mer me2, pr] = bvalca3(botb(l,:),2,2);\n [botav2 botbv2 botstan2 ] = bmemag(botb(l,:));\n\n else botbv = nan; botbv2 = nan; magco = nan; av = nan; botav2 = nan;\n nobv = nobv + 1;\n end\n\n elseif inb1 == 4\n newt2 = topb;\n mcperc_ca3;\n l = topb(:,6) >= Mc95-0.05; magco = Mc95;\n n1 = length(topb(l,:));\n\n if length(topb(l,:)) >= Nmin\n [topbv magco topstan topav topme topmer topme2, toppr] = bvalca3(topb(l,:),2,2);\n [topav2 topbv2 topstan2 ] = bmemag(topb(l,:));\n else\n topbv = nan; topbv2 = nan, magco = nan; topav = nan; topav2 = nan;\n nobv = nobv + 1;\n end\n newt2 = botb;\n mcperc_ca3;\n l = botb(:,6) >= Mc90-0.05; magco = Mc95;\n n2 = length(botb(l,:));\n\n if length(botb(l,:)) >= Nmin\n [botbv magco botstan botav botme botmer botme2, botpr] = bvalca3(botb(l,:),2,2);\n [botav2 botbv2 botstan2 ] = bmemag(botb(l,:));\n else\n botbv = nan; botbv2 = nan, magco = nan; botav = nan; botav2 = nan;\n nobv = nobv + 1;\n end\n\n elseif inb1 == 5\n newt2 = topb;\n mcperc_ca3;\n if isnan(Mc95) == 0 \n magco = Mc95;\n elseif isnan(Mc90) == 0 \n magco = Mc90;\n else\n [bv magco stan av me mer me2, pr] = bvalca3(b,1,1);\n end\n\n l = topb(:,6) >= magco-0.05;\n n1 = length(topb(l,:));\n if length(topb(l,:)) >= Nmin\n [topbv magco topstan topav topme topmer topme2, toppr] = bvalca3(topb(l,:),2,2);\n [topav2 topbv2 topstan2 ] = bmemag(topb(l,:));\n else\n topbv = nan; topbv2 = nan, magco = nan; topav = nan; topav2 = nan;\n nobv = nobv + 1;\n end\n\n newt2 = botb;\n mcperc_ca3;\n l = botb(:,6) >= magco-0.05;\n n2 = length(botb(l,:));\n\n if length(botb(l,:)) >= Nmin\n [botbv magco botstan botav botme botmer botme2, botpr] = bvalca3(botb(l,:),2,2);\n [botav2 botbv2 botstan2 ] = bmemag(botb(l,:));\n else\n botbv = nan; botbv2 = nan, magco = nan; botav = nan; bottopav2 = nan;\n nobv = nobv + 1;\n end\n\n elseif inb1 == 1\n % newt2 = topb;\n % mcperc_ca3;\n [topbv magco topstan topav topme topmer topme2, toppr] = bvalca3(topb,1,1);\n l = topb(:,6) >= magco-0.05;\n if length(topb(l,:)) >= Nmin\n [topav2 topbv2 topstan2 ] = bmemag(topb(l,:));\n n1 = length(topb(l,:));\n else\n topbv = nan; topbv2 = nan; magco = nan; topav = nan; topav2 = nan;\n n1 = nan;\n\n\n nobv = nobv + 1;\n end\n % newt2 = botb;\n % mcperc_ca3;\n [botbv magco botstan botav botme botmer botme2, botpr] = bvalca3(botb,1,1);\n l = botb(:,6) >= magco-0.05;\n if length(botb(l,:)) >= Nmin\n [botav2 botbv2 botstan2 ] = bmemag(botb(l,:));\n n2 = length(botb(l,:));\n\n else\n botbv = nan; botbv2 = nan; magco = nan; botav = nan; botav2 = nan;\n n2 = nan;\n nobv = nobv + 1;\n end\n\n elseif inb1 == 2\n [topbv magco topstan topav topme topmer topme2, toppr] = bvalca3(topb,2,2);\n n1 = length(topb);\n [topav2 topbv2 topstan2 ] = bmemag(topb);\n\n [botbv magco botstan botav botme botmer botme2, botpr] = bvalca3(botb,2,2);\n\n n2 = length(botb);\n [botav2 botbv2 botstan2 ] = bmemag(botb);\n\n end\n\n else\n topbv = nan; topbv2 = nan; magco = nan; topav = nan; topav2 = nan;\n botbv = nan; botbv2 = nan; magco = nan; botav = nan; botav2 = nan;\n nobv = nobv + 1;\n\n end\n\n bv = topbv/botbv; bv2 = topbv2/botbv2; stan2 = topstan2/botstan2; av = topav/botav;\n stan = topstan/botstan;\n n = n1+n2; bo1 = topbv; b2 = botbv;\n da = -2*n*log(n) + 2*n1*log(n1+n2*bo1/b2) + 2*n2*log(n1*b2/bo1+n2) - 2;\n pr = (1 - exp(-da/2-2))*100;\n\n bvg = [bvg ; bv magco x y rd bv2 av pr topbv botbv];\n waitbar(allcount/itotal)\n\n end\n\n snobv = num2str(nobv);\n spnobv = num2str((nobv/allcount)*100.0);\n disp(['Not enough EQs to calculate b values for ', snobv, ' gridnodes. This is ',spnobv,'% of the total'])\n\n save tmpncal.mat\n quit\n\n % for newgr\n %save cnssgrid.mat\n %quit\n % save data\n %\n catSave3 =...\n [ 'zmap_message_center.set_info(''Save Grid'','' '');think;',...\n '[file1,path1] = uiputfile(fullfile(hodi, ''eq_data'', ''*.mat''), ''Grid Datafile Name?'') ;',...\n ' sapa2 = [''save '' path1 file1 '' bvg gx gy dx dy par1 tdiff t0b teb a main faults mainfault coastline yvect xvect tmpgri ll depth_ratio top_zonet top_zoneb bot_zoneb bot_zonet''];',...\n ' if length(file1) > 1, eval(sapa2),end , done']; eval(catSave3)\n\n close(wai)\n watchoff\n\n % plot the results\n % old and re3 (initially ) is the b-value matrix\n %\n normlap2=ones(length(tmpgri(:,1)),1)*nan;\n normlap2(ll)= bvg(:,1);\n re3=reshape(normlap2,length(yvect),length(xvect));\n\n normlap2(ll)= bvg(:,5);\n r=reshape(normlap2,length(yvect),length(xvect));\n\n normlap2(ll)= bvg(:,6);\n meg=reshape(normlap2,length(yvect),length(xvect));\n\n normlap2(ll)= bvg(:,2);\n old1=reshape(normlap2,length(yvect),length(xvect));\n\n % normlap2(ll)= bvg(:,7);\n % pro=reshape(normlap2,length(yvect),length(xvect));\n\n normlap2(ll)= bvg(:,7);\n avm=reshape(normlap2,length(yvect),length(xvect));\n\n % normlap2(ll)= bvg(:,9);\n % stanm=reshape(normlap2,length(yvect),length(xvect));\n\n normlap2(ll)= bvg(:,8);\n Prmap=reshape(normlap2,length(yvect),length(xvect));\n\n\n normlap2(ll)= bvg(:,9);\n top_b=reshape(normlap2,length(yvect),length(xvect));\n\n normlap2(ll)= bvg(:,10);\n bottom_b=reshape(normlap2,length(yvect),length(xvect));\n\n old = re3;\n\n % View the b-value map\n view_bdepth\n\nend % if sel = na\n\n% Load exist b-grid\nif sel == 'lo'\n [file1,path1] = uigetfile(['*.mat'],'b-value gridfile');\n if length(path1) > 1\n think\n load([path1 file1])\n normlap2=ones(length(tmpgri(:,1)),1)*nan;\n\n\n normlap2(ll)= bvg(:,1);\n re3=reshape(normlap2,length(yvect),length(xvect));\n\n normlap2(ll)= bvg(:,5);\n r=reshape(normlap2,length(yvect),length(xvect));\n\n normlap2(ll)= bvg(:,6);\n meg=reshape(normlap2,length(yvect),length(xvect));\n\n normlap2(ll)= bvg(:,2);\n old1=reshape(normlap2,length(yvect),length(xvect));\n\n % normlap2(ll)= bvg(:,7);\n % pro=reshape(normlap2,length(yvect),length(xvect));\n\n normlap2(ll)= bvg(:,7);\n avm=reshape(normlap2,length(yvect),length(xvect));\n\n % normlap2(ll)= bvg(:,9);\n % stanm=reshape(normlap2,length(yvect),length(xvect));\n\n normlap2(ll)= bvg(:,8);\n Prmap=reshape(normlap2,length(yvect),length(xvect));\n\n normlap2(ll)= bvg(:,9);\n top_b=reshape(normlap2,length(yvect),length(xvect));\n\n normlap2(ll)= bvg(:,10);\n bottom_b=reshape(normlap2,length(yvect),length(xvect));\n\n old = re3;\n\n view_bdepth\n else\n return\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/zmap_deprecated/orphaned/src/bdepth_ratio_auto.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3474975639539136}}
{"text": "function f = tan(f)\n%TAN Tangent of a CHEBFUN3T object.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Empty check: \nif ( isempty(f) )\n return\nend\n\nop = @(x,y,z) tan(feval(f, x, y, z)); % Resample\nf = chebfun3t(op, f.domain); % Call constructor.\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebfun3t/tan.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.34749755709560654}}
{"text": "% ------------------------------------------------------------------------ \n% Copyright (C)\n% Universitat Politecnica de Catalunya BarcelonaTech (UPC) - Spain\n% University of California Berkeley (UCB) - USA\n% \n% Jordi Pont-Tuset \n% Pablo Arbelaez \n% June 2014\n% ------------------------------------------------------------------------ \n% This file is part of the MCG package presented in:\n% Arbelaez P, Pont-Tuset J, Barron J, Marques F, Malik J,\n% \"Multiscale Combinatorial Grouping,\"\n% Computer Vision and Pattern Recognition (CVPR) 2014.\n% Please consider citing the paper if you use this code.\n% ------------------------------------------------------------------------\nfunction boxes = labels2boxes(superpixels, labels)\n\n% Get boxes of the superpixels\ntmp = regionprops(superpixels,'BoundingBox');\ntmp = cat(1,tmp.BoundingBox);\nsp_bboxes = [tmp(:,2)+0.5, tmp(:,1)+0.5, tmp(:,2)+tmp(:,4)-0.5, tmp(:,1)+tmp(:,3)-0.5];\n\n% Compute the boxes of the labels from those of the superpixels\nboxes = zeros(length(labels),4);\nfor ii=1:length(labels)\n curr_sp_bboxes = sp_bboxes(labels{ii},:);\n boxes(ii,1) = min(curr_sp_bboxes(:,1));\n boxes(ii,2) = min(curr_sp_bboxes(:,2));\n boxes(ii,3) = max(curr_sp_bboxes(:,3));\n boxes(ii,4) = max(curr_sp_bboxes(:,4));\nend\n\n", "meta": {"author": "jponttuset", "repo": "mcg", "sha": "e72031d793abf8921e39a8ef3c20de2198c8b26f", "save_path": "github-repos/MATLAB/jponttuset-mcg", "path": "github-repos/MATLAB/jponttuset-mcg/mcg-e72031d793abf8921e39a8ef3c20de2198c8b26f/pre-trained/src/bboxes/labels2boxes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.34749755709560654}}
{"text": "function [H, inls] = at_prosac_p3p(x1, x2, udists, TN, TLmax, tol, doLO, conf)\n\nnum_points = 3;\nif nargin < 7\n conf = .95; % in case, conf is not specified.\nend;\nlen = size(x1,2); % the maxinum number of points, i.e. \"N\" in PROSAC paper.\nmax_i = 3; % the number of inliers.\nk_star = TN; % the maximum number for terminating iteration. \"n*\" in PROSAC paper.\n\nt = 0;\nn_sub = num_points; % the number of subset points corresponds to \"n\" in PROSAC paper.\nTn = prosac_avsamplen(num_points,len,TN); % compute the average sampling number Tn'.\nn_star = len; % the number of sampling=iteration corresponds to \"n*\" in PROSAC paper.\n\nif ~exist('prosac_ImnP3P.mat','file') %|| len > 20000\n Imn = zeros(1,len);\n %%%%adhoc = round(len*(1-conf));\n adhoc = 0;\n for ii = 1:num_points+adhoc\n Imn(ii) = len;\n end\n for ii = num_points+1+adhoc:len\n Imn(ii) = prosac_nonrandom(num_points,ii,conf,0.1,len);\n fprintf('%d\\n',ii)\n end\nelse\n r = load('prosac_ImnP3P.mat');\n Imn = r.Imn; clear r;\nend;\n\nH = [];\ninls = [];\n\n[~, sindx] = sort(udists);\ntmax = TLmax;\n\nx1h = x1;\nx2h = x2;\n\nx1h(end+1,:) = 1 ;\nx2h(end+1,:) = 1 ;\n \n\n\n\n\n\nwhile (t < k_star && t < tmax)\n t = t+1; %msg(1,'%d\\n',t);\n if (t == Tn(n_sub) && n_sub < n_star)\n n_sub = n_sub + 1;\n end\n \n p_sample = sindx(prosac_rsample(num_points,Tn,t,n_sub));\n \n x1in = x1h(:,p_sample);\n x2in = x2h(:,p_sample);\n \n y = [x1in; x2in];\n \n \n pf = P3PSolver(y);\n \n e = PerspRepErr(P,X,K)\n \n% y = xf(:,i); % get a sample\n% pf = fitF(y); % fit a model\n r = resF(pf,xr,cnstr); % eval residuals & constraints\n il = abs(r)<=maxres; % inliers\n if size(il,1)>1 % there are more alternative models returned by fitF\n in = sum(il,2); % inlier #\n [in,ix] = max(in);\n il = il(ix,:); % select the best inliers\n r = r(ix,:); % select the residuals\n pf = pf{ix}; % select the best model\n else\n in = sum(il); % inlier #\n if ~isempty(pf)\n if iscell(pf)\n pf = pf{1};\n end\n end\n end\n \n \n S1 = centering(x1in) ;\n S2 = centering(x2in) ;\n x1c = S1 * x1in ;\n x2c = S2 * x2in ; \n M = [x1c, zeros(size(x1c)) ;\n zeros(size(x1c)), x1c ;\n bsxfun(@times, x1c, -x2c(1,:)), bsxfun(@times, x1c, -x2c(2,:))] ;\n if any(isnan(M(:))), continue; end;\n if any(isinf(M(:))), continue; end; \n [H21,D] = svd(M,'econ') ;\n H21 = reshape(H21(:,end),3,3)' ;\n H21 = S2 \\ H21 * S1 ;\n H21 = H21 ./ H21(end) ;\n \n% H21 = u2H([x2h(:,p_sample); x1h(:,p_sample)]);\n% if isempty(H21), continue; end;\n% H21 = H21 ./ H21(end);\n \n x1p = H21 * x1h;\n x1p = [x1p(1,:) ./ x1p(3,:) ; x1p(2,:) ./ x1p(3,:)] ;\n \n% tol = th * sqrt(det(H21(1:2,1:2)));\n dist2 = sum((x2 - x1p).^2,1) ;\n v = dist2 < tol^2;\n no_i = sum(v);\n \n if( max_i < no_i)\n if doLO && no_i > 4\n bH = u2H([x2h(:,v); x1h(:,v)]); \n bH = bH ./ bH(end);\n \n x1p = bH * x1h;\n x1p = [x1p(1,:) ./ x1p(3,:) ; x1p(2,:) ./ x1p(3,:)] ;\n% tol = th * sqrt(det(bH(1:2,1:2)));\n bdist2 = sum((x2 - x1p).^2,1) ;\n bv = bdist2 < tol^2;\n no_ib = sum(bv);\n if no_ib > no_i\n no_i = no_ib;\n H21 = bH;\n v = bv;\n% fprintf(1,'LO succeeded\\n');\n end;\n end;\n max_i = no_i;\n H = H21;\n inls = find(v);\n \n %% STEP 6 maximality of iteration\n for cn = num_points:len\n Icn = sum(v(1:cn));\n kcn = nsamples(Icn, cn, num_points, conf);%msg(1,'kcn=%f\\n',kcn);\n % inlfrc = [inlfrc, Icn/cn];\n if cn < n_sub\n kcn = kcn - (t - Tn(cn));\n end;\n if Icn >= Imn(cn) && kcn < k_star\n n_star = cn;\n k_star = kcn;\n end;\n end;\n \n% k_star = nsamples(max_i, len, num_points, conf);\n% fprintf(1,'PROSAC(H) iter=%d, #inl=%d, k_star=%2.2f\\n',t,max_i,k_star);\n end;\nend;\n% fprintf(1,'PROSAC(H) iter=%d, #inl=%d, k_star=%2.2f\\n',t,max_i,k_star);\n\nfunction urs_indx = prosac_rsample(m,Tn,t,n)\n% prosac sampling\nif Tn(n) > t\n tmp = randperm(n-1);\n urs_indx = [tmp(1:m-1),n];\nelse\n tmp = randperm(n-1);\n urs_indx = tmp(1:m);\n %msg(1,'why?\\n');\nend\n\nfunction [SampleCnt, q] = nsamples(ni, ptNum, pf, conf)\n%SampleCnt calculates number of samples needed to be done\n\nq = prod (((ni-pf+1) : ni) ./ ((ptNum-pf+1) : ptNum));\nif q < eps\n SampleCnt = Inf;\nelse\n % SampleCnt = log(1 - conf) / log(1 - q);\n if q > conf\n SampleCnt = 1;\n else\n SampleCnt = log(1 - conf) / log(1 - q);\n end;\nend;\n\n\nfunction Imin = prosac_nonrandom(m,n,conf,beta,len)\n% compute the Imin whch express the non-randomness.\n\nphi = 1-conf;\nii = (m:n);\nRn(ii) = binopdf(ii-m,n-m,beta); % see Eq. (7) in PROSAC paper.\nfor j = m:n\n if sum(Rn(j:n)) < phi\n Imin = j; break; % see Eq. (8) in PROSAC paper.\n else\n Imin = len;\n end\nend\n", "meta": {"author": "HajimeTaira", "repo": "InLoc_demo", "sha": "b4c42de09d288f35e65ec0156608c704d6176b4f", "save_path": "github-repos/MATLAB/HajimeTaira-InLoc_demo", "path": "github-repos/MATLAB/HajimeTaira-InLoc_demo/InLoc_demo-b4c42de09d288f35e65ec0156608c704d6176b4f/functions/ht_pnp_function/at_prosac_p3p.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.34749755709560654}}
{"text": "function res = bf_inverse_nutmeg(BF, S)\n% Interface to NUTMEG inverse methods \n% http://www.nitrc.org/plugins/mwiki/index.php/nutmeg:MainPage\n% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging\n\n\n% $Id: bf_inverse_nutmeg.m 7703 2019-11-22 12:06:29Z guillaume $\n\n%--------------------------------------------------------------------------\nif nargin == 0\n method = cfg_menu;\n method.tag = 'method';\n method.name = 'Method';\n method.labels = {\n 'sLORETA'\n 'swLORETA'\n 'dSPM'}; \n method.values = method.labels;\n method.help = {'Select one of NUTMEG methods'};\n \n snr = cfg_entry;\n snr.tag = 'snr';\n snr.name = 'SNR';\n snr.strtype = 'e';\n snr.num = [0 0];\n snr.val = {[]};\n snr.help = {'The assumed ratio of variances of signal and noise,',...\n 'used for setting the regularisation parameter.'};\n \n regularisation = cfg_entry;\n regularisation.tag = 'regularisation';\n regularisation.name = 'Regularisation parameter';\n regularisation.strtype = 'e';\n regularisation.num = [0 0];\n regularisation.val = {[]};\n regularisation.help = {'Optional regularization parameter.'};\n \n \n nutmeg = cfg_branch;\n nutmeg.tag = 'nutmeg';\n nutmeg.name = 'NUTMEG methods';\n nutmeg.val = {method, snr, regularisation};\n nutmeg.help = {'Methods ported from NUTMEG toolbox',...\n 'See http://www.nitrc.org/plugins/mwiki/index.php/nutmeg:MainPage'};\n \n res = nutmeg;\n \n return\nelseif nargin < 2\n error('Two input arguments are required');\nend\n\n\nC = BF.features.(S.modality).C;\nU = BF.features.(S.modality).U;\n\nL = S.L;\nW = cell(size(L));\nnvert = numel(W);\n\ndata.Ryy = C;\nflags = [];\nif ~isempty(S.snr)\n flags.snr = S.snr;\nend\nif ~isempty(S.regularisation)\n flags.gamma = S.regularisation;\nend\n\nLL = [];\nspm('Pointer', 'Watch');drawnow;\nspm_progress_bar('Init', nvert, ['Preparing ' S.modality ' leadfields']); drawnow;\nif nvert > 100, Ibar = floor(linspace(1, nvert,100));\nelse Ibar = 1:nvert; end\n\nfor i = 1:nvert\n lf = U'*L{i}; \n \n LL = cat(3, LL, lf);\n \n if ismember(i, Ibar)\n spm_progress_bar('Set', i); drawnow;\n end\nend\n\n\nswitch S.method\n case 'sLORETA'\n w = nut_sLORETA(LL,data,flags);\n case 'swLORETA'\n w = nut_swLORETA(LL,data,flags);\n case 'dSPM'\n w = nut_dSPM(LL,data,flags);\nend\n\n\nspm_progress_bar('Init', nvert, ['Preparing ' S.modality ' filters']); drawnow;\nif nvert > 100, Ibar = floor(linspace(1, nvert,100));\nelse Ibar = 1:nvert; end\n\nfor i = 1:nvert\n W{i} = spm_squeeze(w(:, :, i), 3)';\n \n if ismember(i, Ibar)\n spm_progress_bar('Set', i); drawnow;\n end\nend\n\n\nspm_progress_bar('Clear');\n\nres.W = W;", "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_inverse_nutmeg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.705785040214066, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.34737902316258784}}
{"text": "function result=cosmo_dim_generalization_measure(ds,varargin)\n% measure generalization across pairwise combinations over time (or any other dimension)\n%\n% result=cosmo_dim_generalization_measure(ds,varargin)\n%\n% Inputs:\n% ds dataset struct with d being a sample dimension, and\n% with ds.sa.chunks==1 for samples to use for\n% training and ds.sa.chunks==2 for those to use for\n% testing. Other values for chunks are not allowed.\n% 'measure',m function handle to apply to combinations of samples\n% in the input dataset ds, such as\n% - @cosmo_correlation_measure\n% - @cosmo_crossvalidation_measure\n% - @cosmo_target_dsm_corr_measure\n% 'dimension',d dimension along which to generalize. Typically this\n% will be 'time' for MEEG data\n% 'radius',r radius used for the d dimension. For example, when\n% set to r=4 with d='time', then 4*2+1 time points\n% are used to asses generalization, (except on the\n% edges). Note that when using a radius>0, it is\n% assumed that splits of the dataset by dimension d\n% have corresponding elements in the same order\n% (such as provided by cosmo_dim_transpose).\n% 'nproc', np Use np parallel threads. (Multiple threads may\n% speed up computations). If parallel processing is\n% not available, or if this option is not provided,\n% then a single thread is used.\n% K,V any other key-value pairs necessary for the measure\n% m, for example 'classifier' if\n% m=@cosmo_crossvalidation_measure.\n%\n% Output:\n% result dataset with ['train_' d] and ['test_' d] as sample\n% dimensions, i.e. these are in ds.a.sdim.labels\n% result.samples is Nx1, where N=K*J is the number of\n% combinations of (1) the K points in ds with\n% chunks==1 and different values in dimension d, and\n% (2) the J points in ds with chunks==2 and different\n% values in dimension d.\n%\n% Examples:\n% % Generalization over time\n% sz='big';\n% train_ds=cosmo_synthetic_dataset('type','timelock','size',sz,...\n% 'nchunks',2,'seed',1);\n% test_ds=cosmo_synthetic_dataset('type','timelock','size',sz,...\n% 'nchunks',3,'seed',2);\n% % set chunks\n% train_ds.sa.chunks(:)=1;\n% test_ds.sa.chunks(:)=2;\n% %\n% % construct the dataset\n% ds=cosmo_stack({train_ds, test_ds});\n% %\n% % make time a sample dimension\n% dim_label='time';\n% ds_time=cosmo_dim_transpose(ds,dim_label,1);\n% %\n% % set measure and its arguments\n% measure_args=struct();\n% %\n% % use correlation measure\n% measure_args.measure=@cosmo_correlation_measure;\n% % dimension of interest is 'time'\n% measure_args.dimension=dim_label;\n% %\n% % run time-by-time generalization analysis\n% dgm_ds=cosmo_dim_generalization_measure(ds_time,measure_args,...\n% 'progress',false);\n% %\n% % the output has train_time and test_time as sample dimensions\n% cosmo_disp(dgm_ds.a)\n% %|| .sdim\n% %|| .labels\n% %|| { 'train_time' 'test_time' }\n% %|| .values\n% %|| { [ -0.2 [ -0.2\n% %|| -0.15 -0.15\n% %|| -0.1 -0.1\n% %|| : :\n% %|| 0 0\n% %|| 0.05 0.05\n% %|| 0.1 ]@7x1 0.1 ]@7x1 }\n%\n%\n% % Searchlight example\n% % (This example requires FieldTrip)\n% cosmo_skip_test_if_no_external('fieldtrip');\n% %\n% sz='big';\n% train_ds=cosmo_synthetic_dataset('type','timelock','size',sz,...\n% 'nchunks',2,'seed',1);\n% test_ds=cosmo_synthetic_dataset('type','timelock','size',sz,...\n% 'nchunks',3,'seed',2);\n% % set chunks\n% train_ds.sa.chunks(:)=1;\n% test_ds.sa.chunks(:)=2;\n% %\n% % construct the dataset\n% ds=cosmo_stack({train_ds, test_ds});\n% %\n% % make time a sample dimension\n% dim_label='time';\n% ds_time=cosmo_dim_transpose(ds,dim_label,1);\n% %\n% % set measure and its arguments\n% measure_args=struct();\n% %\n% % use correlation measure\n% measure_args.measure=@cosmo_correlation_measure;\n% % dimension of interest is 'time'\n% measure_args.dimension=dim_label;\n% %\n% % only to make this example run fast, most channels are eliminated\n% % (there is no other reason to do this step)\n% ds_time=cosmo_slice(ds_time,ds_time.fa.chan<=20,2);\n% ds_time=cosmo_dim_prune(ds_time);\n% %\n% % define neighborhood for channels\n% nbrhood=cosmo_meeg_chan_neighborhood(ds_time,...\n% 'chantype','meg_combined_from_planar',...\n% 'count',5,'label','dataset');\n% %\n% % run searchlight with generalization measure\n% measure=@cosmo_dim_generalization_measure;\n% dgm_sl_ds=cosmo_searchlight(ds_time,nbrhood,measure,measure_args,...\n% 'progress',false);\n% %\n% % the output has train_time and test_time as sample dimensions,\n% % and chan as feature dimension\n% cosmo_disp(dgm_sl_ds.a,'edgeitems',1)\n% %|| .fdim\n% %|| .labels\n% %|| { 'chan' }\n% %|| .values\n% %|| { { 'MEG0112+0113' ... 'MEG0712+0713' }@1x7 }\n% %|| .meeg\n% %|| .samples_type\n% %|| 'timelock'\n% %|| .samples_field\n% %|| 'trial'\n% %|| .samples_label\n% %|| 'rpt'\n% %|| .sdim\n% %|| .labels\n% %|| { 'train_time' 'test_time' }\n% %|| .values\n% %|| { [ -0.2 [ -0.2\n% %|| : :\n% %|| 0.1 ]@7x1 0.1 ]@7x1 }\n%\n%\n% Notes:\n% - this function can be used together with searchlight\n% - to make a dimension d a sample dimension from a feature dimension\n% (usually necessary before running this function), or the other way\n% around (usually necessary after running this function), use\n% cosmo_dim_transpose.\n% - a 'partition' argument should not be provided, because this function\n% generates them itself. The partitions are generated so that there\n% is a single fold; samples with chunks==1 are always used for training\n% and those with chunks==2 are used for testing (e.g. when using\n% m=@cosmo_crossvalidation_measure). In the case of using\n% m=@cosmo_correlation_measure, this amounts to split-half\n% correlations.\n%\n% See also: cosmo_correlation_measure, cosmo_crossvalidation_measure\n% cosmo_target_dsm_corr_measure, cosmo_searchlight,\n% cosmo_dim_transpose\n%\n% # For CoSMoMVPA's copyright information and license terms, #\n% # see the COPYING file distributed with CoSMoMVPA. #\n\n defaults=struct();\n defaults.radius=0;\n defaults.progress=1;\n defaults.check_partitions=false;\n defaults.nproc=1;\n opt=cosmo_structjoin(defaults,varargin);\n\n cosmo_check_dataset(ds);\n check_input(ds,opt);\n\n % get training and test set\n halves=split_dataset_in_train_and_test(ds);\n\n % split the data in two halves\n [train_values,train_splits]=split_half_by_dimension(halves{1},opt);\n [test_values,test_splits]=split_half_by_dimension(halves{2},opt);\n\n halves=[]; % let GC do its work\n\n % get number of processes available\n nproc_available=cosmo_parallel_get_nproc_available(opt);\n\n % Matlab needs newline character at progress message to show it in\n % parallel mode; Octave should not have newline character\n environment=cosmo_wtf('environment');\n progress_suffix=get_progress_suffix(environment);\n\n % split training data in multiple parts, so that each thread can do a\n % subset of all the work\n % set options for each worker process\n worker_opt_cell=cell(1,nproc_available);\n block_size=ceil(length(train_values)/nproc_available);\n first=1;\n for p=1:nproc_available\n last=min(first+block_size-1,length(train_values));\n block_idxs=first:last;\n\n worker_opt=struct();\n worker_opt.train_splits=train_splits(block_idxs);\n worker_opt.train_values=train_values(block_idxs);\n worker_opt.train_values_ori=train_values;\n worker_opt.train_values_idx=block_idxs;\n worker_opt.test_splits=test_splits;\n worker_opt.test_values=test_values;\n worker_opt.opt=opt;\n worker_opt.worker_id=p;\n worker_opt.nworkers=nproc_available;\n worker_opt.progress=opt.progress;\n worker_opt.progress_suffix=progress_suffix;\n worker_opt_cell{p}=worker_opt;\n first=last+1;\n end\n\n % Run process for each worker in parallel\n % Note that when using nproc=1, cosmo_parcellfun does actually not\n % use any parallellization; the result is a cell with a single element.\n result_map_cell=cosmo_parcellfun(opt.nproc,...\n @run_with_worker,...\n worker_opt_cell,...\n 'UniformOutput',false);\n\n result=cosmo_stack(result_map_cell,1);\n cosmo_check_dataset(result);\n\n\nfunction result=run_with_worker(worker_opt)\n% run dimgen using the options in worker_opt\n\n train_splits = worker_opt.train_splits;\n train_values = worker_opt.train_values;\n train_values_ori = worker_opt.train_values_ori;\n train_values_idx = worker_opt.train_values_idx;\n test_splits = worker_opt.test_splits;\n test_values = worker_opt.test_values;\n opt = worker_opt.opt;\n worker_id=worker_opt.worker_id;\n nworkers=worker_opt.nworkers;\n progress=worker_opt.progress;\n progress_suffix=worker_opt.progress_suffix;\n\n % set partitions in case a crossvalidation or correlation measure is\n % used\n ntrain_elem=cellfun(@(x)size(x.samples,1),train_splits);\n ntest_elem=cellfun(@(x)size(x.samples,1),test_splits);\n opt.partitions=struct();\n opt.partitions.train_indices=cell(1);\n opt.partitions.test_indices=cell(1);\n\n % remove the dimension and measure arguments from the input\n dimension=opt.dimension;\n measure=opt.measure;\n\n opt=rmfield(opt,'dimension');\n opt=rmfield(opt,'measure');\n\n train_label=['train_' dimension];\n test_label=['test_' dimension];\n\n % see if progress has to be shown\n show_progress=~isempty(progress) && ...\n progress && ...\n worker_id==1;\n if show_progress\n prev_progress_msg='';\n clock_start=clock();\n end\n\n % allocate space for output\n ntrain=numel(train_values);\n ntest=numel(test_values);\n\n result_cell=cell(ntrain*ntest,1);\n\n % last non-empty row in result_cell\n pos=0;\n\n for k=1:ntrain\n % update partitions train set\n opt.partitions.train_indices{1}=1:ntrain_elem(k);\n for j=1:ntest\n % update partitions test set\n opt.partitions.test_indices{1}=ntrain_elem(k)+...\n (1:ntest_elem(j));\n % merge training and test dataset\n ds_merged=cosmo_stack({train_splits{k},test_splits{j}},...\n 1,1,false);\n\n opt.partitions=cosmo_balance_partitions(opt.partitions,...\n ds_merged,opt);\n\n % apply measure\n ds_result=measure(ds_merged,opt);\n\n % set dimension attributes\n nsamples=size(ds_result.samples,1);\n ds_result.sa.(train_label)=repmat(train_values_idx(k),...\n nsamples,1);\n ds_result.sa.(test_label)=repmat(j,nsamples,1);\n\n % store result\n pos=pos+1;\n result_cell{pos}=ds_result;\n end\n\n if show_progress\n if nworkers>1\n if k==ntrain\n % other workers may be slower than first worker\n msg=sprintf(['worker %d has completed; waiting for '...\n 'other workers to finish...%s'],...\n worker_id, progress_suffix);\n else\n % can only show progress from a single worker;\n % therefore show progress of first worker\n msg=sprintf('for worker %d / %d%s', worker_id, ...\n nworkers, progress_suffix);\n end\n else\n % no specific message\n msg='';\n end\n prev_progress_msg=cosmo_show_progress(clock_start, ...\n k/ntrain, msg, prev_progress_msg);\n end\n\n end\n\n % merge results into a dataset\n result=cosmo_stack(result_cell,1,'drop_nonunique');\n if isfield(result,'sa') && isfield(result.sa,dimension)\n result.sa=rmfield(result.sa,dimension);\n end\n\n % set dimension attributes in the sample dimension\n result=add_sample_attr(result, {train_label;test_label},...\n {train_values_ori;test_values});\n\n\n\nfunction check_input(ds,opt)\n % ensure input is kosher\n cosmo_isfield(opt,{'dimension','measure'},true);\n\n dimension=opt.dimension;\n dim_pos=cosmo_dim_find(ds,dimension,true);\n if dim_pos~=1\n error(['''%s'' must be a sample dimension (not a feature) '...\n 'dimension. To make ''%s'' a sample dimension in '...\n 'a dataset struct ds, use\\n\\n'...\n ' cosmo_dim_transpose(ds,''%s'',1);'],...\n dimension,dimension,dimension);\n end\n\n measure=opt.measure;\n if ~isa(measure,'function_handle')\n error('the ''measure'' argument must be a function handle');\n end\n\n if isfield(opt,'partitions')\n error(['the partitions argument is not allowed for this '...\n 'function, because it generates partitions itself.'...\n 'The dataset should have two chunks, with '...\n 'chunks set to 1 for the training set and '...\n 'set to 2 for the testing set']);\n end\n\nfunction halves=split_dataset_in_train_and_test(ds)\n % return cell with {train_ds,test_ds}\n halves=cosmo_split(ds,'chunks',1);\n if numel(halves)~=2 || ...\n halves{1}.sa.chunks(1)~=1 || ...\n halves{2}.sa.chunks(1)~=2\n error(['chunks must be 1 (for the training set) or 2'...\n '(for the testing set)' ]);\n end\n\nfunction [values,splits]=split_half_by_dimension(ds,opt)\n % split dataset by ds.a.(opt.dimension)\n dimension=opt.dimension;\n ds_pruned=cosmo_dim_prune(ds,'labels',{dimension},'dim',1);\n ds_tr=cosmo_dim_transpose(ds_pruned,dimension,2);\n\n nbrhood=cosmo_interval_neighborhood(ds_tr,dimension,opt);\n assert(isequal(nbrhood.a.fdim.labels,{dimension}));\n\n counts=cellfun(@numel,nbrhood.neighbors);\n\n keep_nbrs=find(counts==max(counts));\n\n % remove dimension information\n ds_tr=remove_fa_field(ds_tr,dimension);\n\n values=nbrhood.a.fdim.values{1}(keep_nbrs);\n sz=size(values);\n if sz(1)==1\n values=values';\n elseif sz(2)~=1\n error('dimension %s must be a row vector', dimension);\n end\n\n n=numel(keep_nbrs);\n splits=cell(n,1);\n\n for k=1:n\n idx=nbrhood.neighbors{keep_nbrs(k)};\n splits{k}=cosmo_slice(ds_tr,idx,2,false);\n end\n\n\nfunction ds=add_sample_attr(ds, dim_labels, dim_values)\n if ~isfield(ds,'a') || ~isfield(ds.a,'sdim')\n ds.a.sdim=struct();\n ds.a.sdim.labels=cell(1,0);\n ds.a.sdim.values=cell(1,0);\n end\n\n\n ds.a.sdim.values=[ds.a.sdim.values(:); dim_values]';\n ds.a.sdim.labels=[ds.a.sdim.labels(:); dim_labels]';\n\n\nfunction ds=remove_fa_field(ds,label)\n if isfield(ds.fa,label);\n ds.fa=rmfield(ds.fa,label);\n end\n\n [dim, index, attr_name, dim_name]=cosmo_dim_find(ds,...\n label,false);\n if ~isempty(dim)\n sfdim=ds.a.(dim_name);\n m=~cosmo_match(sfdim.labels,label);\n sfdim.values=sfdim.values(m);\n sfdim.labels=sfdim.labels(m);\n ds.a.(dim_name)=sfdim;\n end\n\nfunction suffix=get_progress_suffix(environment)\n % Matlab needs newline character at progress message to show it in\n % parallel mode; Octave should not have newline character\n\n switch environment\n case 'matlab'\n suffix=sprintf('\\n');\n case 'octave'\n suffix='';\n end\n", "meta": {"author": "CoSMoMVPA", "repo": "CoSMoMVPA", "sha": "5de75a1b4bef89b082d39d69e2b99d7f894ad717", "save_path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA", "path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA/CoSMoMVPA-5de75a1b4bef89b082d39d69e2b99d7f894ad717/mvpa/cosmo_dim_generalization_measure.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.3473790170707484}}
{"text": "% mtimesx_sparse does sparse matrix multiply of two inputs\n%******************************************************************************\n% \n% MATLAB (R) is a trademark of The Mathworks (R) Corporation\n% \n% Function: mtimesx_sparse\n% Filename: mtimesx_sparse.m\n% Programmer: James Tursa\n% Version: 1.00\n% Date: September 27, 2009\n% Copyright: (c) 2009 by James Tursa, All Rights Reserved\n%\n% This code uses the BSD License:\n%\n% Redistribution and use in source and binary forms, with or without \n% modification, are permitted provided that the following conditions are \n% met:\n%\n% * Redistributions of source code must retain the above copyright \n% notice, this list of conditions and the following disclaimer.\n% * Redistributions in binary form must reproduce the above copyright \n% notice, this list of conditions and the following disclaimer in \n% the documentation and/or other materials provided with the distribution\n% \n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE \n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE \n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS \n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN \n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE \n% POSSIBILITY OF SUCH DAMAGE.\n%\n%--\n%\n% mtimesx_sparse is a helper function for mtimesx and is not intended to be called\n% directly by the user.\n% \n% ---------------------------------------------------------------------------------------------------------------------------------\n\nfunction result = mtimesx_sparse(a,transa,b,transb)\nif( transa == 'N' )\n if( transb == 'N' )\n result = a * b;\n elseif( transb == 'G' )\n result = a * conj(b);\n elseif( transb == 'T' )\n result = a * b.';\n else\n result = a * b';\n end\nelseif( transa == 'G' )\n if( transb == 'N' )\n result = conj(a) * b;\n elseif( transb == 'G' )\n result = conj(a) * conj(b);\n elseif( transb == 'T' )\n result = conj(a) * b.';\n else\n result = conj(a) * b';\n end\nelseif( transa == 'T' )\n if( transb == 'N' )\n result = a.' * b;\n elseif( transb == 'G' )\n result = a.' * conj(b);\n elseif( transb == 'T' )\n result = a.' * b.';\n else\n result = a.' * b';\n end\nelse\n if( transb == 'N' )\n result = a' * b;\n elseif( transb == 'G' )\n result = a' * conj(b);\n elseif( transb == 'T' )\n result = a' * b.';\n else\n result = a' * b';\n end\nend\nend\n", "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/external_libs/mtimesx/mtimesx_sparse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.34734534724611094}}
{"text": "filename = 'CantileverSquareSym';%'CantileverSquareNewFine';%'LshapeTriFine';%'CantileverSquareNew';'ArchTriFine';%'CantileverSquare';%'ArchTriFine';%'CantileverSquare';%'Lshape';%'LshapeTriFine';%'CantileverSquareSmall';%'';%'Lshape';'CantileverSquare';'Lshape';%'CantileverSquare';%'LshapeFine';%'Bridge_quad_coarse';%'Arch_quad_coarse';%'BridgeCool_Quadrilateral_Bilinear_Structured_Coarse';%'Bridge';%'CantileverSquareSmall';\nptype = 'MACRO';\ninitial_case = 'given';\n% m1 = 0.0101;\n% m2 = 0.0101;\nm1 = 0.8;\nm2 = 0.8;\n%cost = {'compliance'};\ncost = {'stressNorm'};\n%cost = {'stressNorm','compliance'};\n%weights = [0.55,0.45];\nweights = 1;\nconstraint = {'volumeConstraint'};\nfilterType = 'P1';\nconstraint_case = 'EQUALITY';\n\nVfrac_initial = 0.3;\noptimality_initial = 1e-5;\nconstr_initial = 1e-5;\n\nVfrac_final = 0.3;\noptimality_final = 1e-5;\nconstr_final = 1e-5;\n\nstressNormExponent_initial = 2;\nstressNormExponent_final = 32;\n\noptimizer = 'DualNestedInPrimal';\noptimizerUnconstrained = 'PROJECTED GRADIENT';\n\ndesignVariable = 'MicroParams';\nub = 0.989;\nlb = 0.011;\nhomegenizedVariablesComputer = 'ByVademecum';\n% \nvademecumFileName = 'SuperEllipseQMax';\n%vademecumFileName = 'SuperEllipseQ2';\n%vademecumFileName = 'SuperEllipseQOptAnalytic';\n% \n% designVariable = 'Density';\n% homegenizedVariablesComputer = 'ByInterpolation';\n% method = 'SIMPALL';\n% materialType = 'ISOTROPIC';\n\nkfrac = 2;\nnsteps = 50;\n\nplotting = false;\nprinting = true;\nmonitoring = true;\nmonitoring_interval = 1;\nmaxiter = 500;\n\nline_search_initiator = 'INCREASING LAST STEP';\nincrementFactor = 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/LatticeExperiments/LatticeExperimentInputCantileverSymRectangleDoubleLineSearch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.34734534724611094}}
{"text": "% Check the configuration section to make the necessary adjustments to\n% run this script.\n\n% @\n% Copyright (C) 2017 Jonas Ruesch\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% Configuration\n% ===================================================================================\ntornadoDirectory = 'F:\\svn\\dev\\matlab\\tornado\\T135_export'; % where is Tornado installed?\nnameTornadoAircraftGeometry = 'ExperimentalCarrier'; % which Tornado model to use?\nestimatedVelocity = 12; % 12; % the velocity at which aerodynamic coefficients are computed.\nvelocityDeviationTol = 0.5; % how much the found trimmed velocity can differ from the estimated velocity to accept the solution.\nairDensity = 1.225;\nelevatorFlapIndex = 1; % which is the elevator flap in the Tornado model?\nrudderFlapIndex = 2; % which is the rudder flap in the Tornado model?\ncenterOfGravity = 0.092; % in meters from zero of Tornado aircraft model reference frame. Tornado x-axis extends aft (!) -> positive.\nmass = 1.56; % aircraft mass in kg (overwrites the value set in the Tornado model).\nInertiaTensor = [1 0 0; 0 1 0; 0 0 1]; % inertia tensor (TODO: compute a realistic one :)\n% The alpha-sweep configuration\nalphaStart = 4; %2;\nalphaEnd = 6; % 6;\nnumAlphas = 5;\n% The beta-sweep configuration\nbetaStart = -1;\nbetaEnd = 1;\nnumBetas = 5;\ncomputeStaticMargin = 0; % [0/1]\n% ===================================================================================\n\nnameLongitudinalModel = 'ExperimentalCarrier_longitudinal';\nnameLateralModel = 'ExperimentalCarrier_lateral';\n\ndisp(' ');\n\n% Compute longitudinal and lateral LTIs for trimmed gliding. \n[ltiLongitudinal, trimmedStateVariablesLongitudinal, ltiLateral, trimmedStateVariablesLateral, Cm_longitudinal, Cn_lateral] = computeLTIs(...\n tornadoDirectory, ... % absolute path to the Tornado root directory\n nameTornadoAircraftGeometry, ... % the name of the Tornado geometry file\n nameLongitudinalModel, ... % the name of the Simulink long. model.\n nameLateralModel,... % the name of the Simulink lateral model. \n alphaStart, alphaEnd, ... % range in degrees over which coefficients are computed for the longitudinal model\n numAlphas, ... % the number of alphas to sample\n betaStart, betaEnd, ... range in degrees over which coefficients are computed for the lateral model\n numBetas, ... the number of betas to sample \n estimatedVelocity, ... % velocity in m/s for which aerodyn. coeffs. are computed\n velocityDeviationTol, ... % factor [0 ... 1].\n airDensity, ... % kg/m^3 -> 1.225 at sea level\n elevatorFlapIndex, ...\n rudderFlapIndex, ...\n mass, ...\n centerOfGravity, ...\n InertiaTensor); % inertia tensor\ntrimmedAlphaRad = atan(trimmedStateVariablesLongitudinal(2)/trimmedStateVariablesLongitudinal(1)); % atan(w/u);\ntrimmedBetaRad = atan(trimmedStateVariablesLateral(1)/trimmedStateVariablesLongitudinal(1)); % atan(w/v);\n\n% Compute static margin of the aircraft.\nif(computeStaticMargin)\n disp('Computing static margin of longitudinal dynamics...');\n [ac, staticMarginMAC, staticMarginInMeters] = computeStaticMargin(nameTornadoAircraftGeometry, ...\n estimatedVelocity, airDensity, tornadoDirectory, centerOfGravity);\n disp(['Static margin as MAC factor : ' num2str(staticMarginMAC)]);\n disp(['Static margin (sm) (m) : ' num2str(staticMarginInMeters)]);\n disp(['Aerodynamic center (ac) (m) : ' num2str(ac)]);\n disp(['ac - sm = center of gravity : ' num2str(ac - staticMarginInMeters)]);\nend\n\n% Longitudinal\n% ========================================================================\n% disp('The longitudinal LTI:');\n% ltiLongitudinal\n\n% sort complex numbers\npolesLongitudinal = cplxpair(pole(ltiLongitudinal)); % sort first complex pairs (each with negative imag. part first, then pure real (ascending?)).\n\n% Poles Map\nfigure();\nh = subplot(2,2,1);\nhold on;\nplot(h, real(polesLongitudinal(1)), imag(polesLongitudinal(1)), 'rx');\nplot(h, real(polesLongitudinal(2)), imag(polesLongitudinal(2)), 'bx');\nplot(h, real(polesLongitudinal(3)), imag(polesLongitudinal(3)), 'ro');\nplot(h, real(polesLongitudinal(4)), imag(polesLongitudinal(4)), 'bo');\nhold off;\nlegend('phugoid mode 1', 'phugoid mode 2', 'short period mode 1', 'short period mode 2');\ntitle('Longitudinal Poles Map');\nxlabel('re');\nylabel('im');\n\n% Step response\n% Remember: for a trimmed glide, LTI state variables are all 0. Thus, the plot \n% shows the resulting deviation of state variables from the trimmed state.\n% Also note: with the current model (very little air resistance -> very\n% good gliding ratio, the non-linear matlab model shows that it is sensible\n% that w (the velocity in body-z) is becoming negative (moving 'upwards' in\n% body-z).\nh = subplot(2,2,2);\nelevatorDeflectionStep = 2*pi/180;\nstepOpt = stepDataOptions('StepAmplitude', elevatorDeflectionStep); % step response for elevatorDeflectionStep radian elevator deflection\nstepplot(h, ltiLongitudinal, stepOpt);\ntitle('Longitudinal Step Response');\nhAllAxes = findobj(gcf,'type','axes');\nhLeg = findobj(hAllAxes,'tag','legend');\nhAxes = setdiff(hAllAxes,hLeg); % All axes which are not\nfor k=1:length(hAxes)\n if ~isempty(strfind(hAxes(k).YLabel.String, '(1)'))\n hAxes(k).Title.String = ['State change for an elevator step of ' num2str(elevatorDeflectionStep*180/pi) ' degrees'];\n hAxes(k).YLabel.String = 'u (m/s)'; % velocity in body x-axis\n elseif ~isempty(strfind(hAxes(k).YLabel.String, '(2)'))\n hAxes(k).YLabel.String = 'w (m/s)'; % velocity in body z-axis\n elseif ~isempty(strfind(hAxes(k).YLabel.String, '(3)'))\n hAxes(k).YLabel.String = 'q (rad/s)'; % rotation velocity around y-axis\n elseif ~isempty(strfind(hAxes(k).YLabel.String, '(4)'))\n hAxes(k).YLabel.String = 'theta (rad)'; % angle body-x vs earth-x\n end\nend\n\n% Impulse response\nh = subplot(2,2,3);\nimpulseplot(h, ltiLongitudinal);\ntitle('Longitudinal Impulse Response');\nhAllAxes = findobj(gcf,'type','axes');\nhLeg = findobj(hAllAxes,'tag','legend');\nhAxes = setdiff(hAllAxes,hLeg); % All axes which are not\nfor k=1:length(hAxes)\n if ~isempty(strfind(hAxes(k).YLabel.String, '(1)'))\n hAxes(k).Title.String = 'State change for an elevator dirac impulse';\n hAxes(k).YLabel.String = 'u (m/s)'; % velocity in body x-axis\n elseif ~isempty(strfind(hAxes(k).YLabel.String, '(2)'))\n hAxes(k).YLabel.String = 'w (m/s)'; % velocity in body z-axis\n elseif ~isempty(strfind(hAxes(k).YLabel.String, '(3)'))\n hAxes(k).YLabel.String = 'q (rad/s)'; % rotation velocity around y-axis\n elseif ~isempty(strfind(hAxes(k).YLabel.String, '(4)'))\n hAxes(k).YLabel.String = 'theta (rad)'; % angle body-x vs earth-x\n end\nend\n\n% Plot pitch moment curve\nh = subplot(2,2,4);\nhold on;\nplot(h, [alphaStart:(alphaEnd-alphaStart)/(numAlphas-1):alphaEnd], Cm_longitudinal, 'r-');\nplot(h, trimmedAlphaRad*180/pi, 0, 'bx');\nhold off;\nlegend('Cm', ['trimmed alpha = ' num2str(trimmedAlphaRad*180/pi) ' (deg)']);\ntitle('Pitch moment');\nxlabel('alpha');\nylabel('Cm');\n\n% Compute damping, frequency, period from poles. See also p83 in Caughey.\n\n% Short period poles\npolesShortPeriod = polesLongitudinal(3:4); % choose last ones from sorted complex numbers\npolesShortPeriodReal = real(polesShortPeriod);\npolesShortPeriodImag = imag(polesShortPeriod);\n\nDamping_sp = sqrt(1./(1+(polesShortPeriodImag./polesShortPeriodReal).^2)); % Damping ratio\nFrequency_sp = -polesShortPeriodReal./Damping_sp; % Undampted, natural frequency per second\nPeriod_sp = 2*pi./(Frequency_sp.*sqrt(1-Damping_sp.^2)); % seconds\nCycles_half_sp = ((log(2))/(2*pi))*sqrt(1-Damping_sp.^2)./Damping_sp; % Number of cycles to damp to half the amplitude\n\n% Output result for longitudinal trimmed state\ndisp('Short Period Mode Properties (longitudinal): ');\ndisp(' Pole 1 Pole 2');\ndisp('==============================================================================');\ndisp(sprintf(['Damping ratio : ' num2str(Damping_sp(:)')]));\ndisp(sprintf(['Undampted, natural frequency (1/s): ' num2str(Frequency_sp(:)')]));\ndisp(sprintf(['Period (s): ' num2str(Period_sp(:)')]));\ndisp(sprintf(['Num. cycles to damp to half the amplitude : ' num2str(Cycles_half_sp(:)')]));\ndisp(' ');\n\n% Phugoid poles\npolesPhugoid = polesLongitudinal(1:2); % choose first ones from sorted complex numbers\npolesPhugoidReal = real(polesPhugoid);\npolesPhugoidImag = imag(polesPhugoid);\n\nDamping_ph = sqrt(1./(1+(polesPhugoidImag./polesPhugoidReal).^2)); % Damping ratio\nFrequency_ph = -polesPhugoidReal./Damping_ph; % Undampted, natural frequency per second\nPeriod_ph = 2*pi./(Frequency_ph.*sqrt(1-Damping_ph.^2)); % seconds\nCycles_half_ph = ((log(2))/(2*pi))*sqrt(1-Damping_ph.^2)./Damping_ph; % Number of cycles to damp to half the amplitude\n\n% Output result for longitudinal trimmed state\ndisp('Phugoid Mode Properties (longitudinal): ');\ndisp(' Pole 1 Pole 2');\ndisp('==============================================================================');\ndisp(sprintf(['Damping ratio : ' num2str(Damping_ph(:)')]));\ndisp(sprintf(['Undampted, natural frequency (1/s): ' num2str(Frequency_ph(:)')]));\ndisp(sprintf(['Period (s): ' num2str(Period_ph(:)')]));\ndisp(sprintf(['Num. cycles to damp to half the amplitude : ' num2str(Cycles_half_ph(:)')]));\ndisp(' ');\n\n% Lateral\n% ========================================================================\n\n%disp('The lateral LTI:');\n%ltiLateral\n\n% sort complex numbers\npolesLateral = cplxpair(pole(ltiLateral)); % sort first complex pairs (each with negative imag. part first, then pure real (ascending?)).\n\n% Poles Map\nfigure();\nh = subplot(2,2,1);\nhold on;\nplot(h, real(polesLateral(1)), imag(polesLateral(1)), 'rx');\nplot(h, real(polesLateral(2)), imag(polesLateral(2)), 'bx');\nplot(h, real(polesLateral(3)), imag(polesLateral(3)), 'ro');\nplot(h, real(polesLateral(4)), imag(polesLateral(4)), 'bo');\nhold off;\nlegend('dutch roll mode 1', 'dutch roll mode 2', 'rolling mode', 'spiral mode');\ntitle('Lateral Poles Map');\nxlabel('re');\nylabel('im');\n\n% Step response\n% Remember: for a trimmed glide, LTI state variables are all 0. Thus, the plot \n% shows the resulting deviation of state variables from the trimmed state.\nh = subplot(2,2,2);\nrudderDeflectionStep = 2*pi/180;\nstepOpt = stepDataOptions('StepAmplitude', rudderDeflectionStep); % step response for elevatorDeflectionStep radian elevator deflection\nstepplot(h, ltiLateral, stepOpt);\ntitle('Lateral Step Response');\nhAllAxes = findobj(gcf,'type','axes');\nhLeg = findobj(hAllAxes,'tag','legend');\nhAxes = setdiff(hAllAxes,hLeg); % All axes which are not\nfor k=1:length(hAxes)\n if ~isempty(strfind(hAxes(k).YLabel.String, '(1)'))\n hAxes(k).Title.String = ['State change for a rudder step of ' num2str(rudderDeflectionStep*180/pi) ' degrees'];\n hAxes(k).YLabel.String = 'v (m/s)'; % velocity in body y-axis\n elseif ~isempty(strfind(hAxes(k).YLabel.String, '(2)'))\n hAxes(k).YLabel.String = 'p (rad/s)'; % rotation velocity around x-axis\n elseif ~isempty(strfind(hAxes(k).YLabel.String, '(3)'))\n hAxes(k).YLabel.String = 'phi (rad)'; % roll angle (euler phi)\n elseif ~isempty(strfind(hAxes(k).YLabel.String, '(4)'))\n hAxes(k).YLabel.String = 'r (rad/s)'; % rotation velocity around z-axis\n end\nend\n\n% Impulse response\nh = subplot(2,2,3);\nimpulseplot(h, ltiLateral);\ntitle('Lateral Impulse Response');\nhAllAxes = findobj(gcf,'type','axes');\nhLeg = findobj(hAllAxes,'tag','legend');\nhAxes = setdiff(hAllAxes,hLeg); % All axes which are not\nfor k=1:length(hAxes)\n if ~isempty(strfind(hAxes(k).YLabel.String, '(1)'))\n hAxes(k).Title.String = 'State change for a rudder dirac impulse';\n hAxes(k).YLabel.String = 'v (m/s)'; % velocity in body y-axis\n elseif ~isempty(strfind(hAxes(k).YLabel.String, '(2)'))\n hAxes(k).YLabel.String = 'p (rad/s)'; % rotation velocity around x-axis\n elseif ~isempty(strfind(hAxes(k).YLabel.String, '(3)'))\n hAxes(k).YLabel.String = 'phi (rad)'; % roll angle (euler phi)\n elseif ~isempty(strfind(hAxes(k).YLabel.String, '(4)'))\n hAxes(k).YLabel.String = 'r (rad/s)'; % rotation velocity around z-axis\n end\nend\n\n% Plot yaw moment curve\nh = subplot(2,2,4);\nhold on;\nplot(h, [betaStart:(betaEnd-betaStart)/(numBetas-1):betaEnd], Cn_lateral, 'r-');\nplot(h, trimmedBetaRad*180/pi, 0, 'bx');\nhold off;\nlegend('Cn', ['trimmed beta = ' num2str(trimmedBetaRad*180/pi) ' (deg)']);\ntitle('Yaw moment');\nxlabel('beta');\nylabel('Cn');\n\n% Compute damping, frequency, period from poles. See also p83 in Caughey.\n\n% Roll pole\npoleRoll = polesLateral(3);\npoleRollReal = real(poleRoll);\npoleRollImag = imag(poleRoll);\n\nDamping_roll = sqrt(1./(1+(poleRollImag./poleRollReal).^2)); % Damping ratio\nFrequency_roll = -poleRollReal./Damping_roll; % Undampted, natural frequency per second\nPeriod_roll = 2*pi./(Frequency_roll.*sqrt(1-Damping_roll.^2)); % seconds\nCycles_half_roll = ((log(2))/(2*pi))*sqrt(1-Damping_roll.^2)./Damping_roll; % Number of cycles to damp to half the amplitude\n\ndisp('Roll Mode Properties (lateral): ');\ndisp(' Pole 1');\ndisp('==============================================================================');\ndisp(sprintf(['Damping ratio : ' num2str(Damping_roll(:)')]));\ndisp(sprintf(['Undampted, natural frequency (1/s): ' num2str(Frequency_roll(:)')]));\ndisp(sprintf(['Period (s): ' num2str(Period_roll(:)')]));\ndisp(sprintf(['Num. cycles to damp to half the amplitude : ' num2str(Cycles_half_roll(:)')]));\ndisp(' ');\n\n% Spiral pole\npoleSpiral = polesLateral(4);\npoleSpiralReal = real(poleSpiral);\npoleSpiralImag = imag(poleSpiral);\n\nDamping_spiral = sqrt(1./(1+(poleSpiralImag./poleSpiralReal).^2)); % Damping ratio\nFrequency_spiral = -poleSpiralReal./Damping_spiral; % Undampted, natural frequency per second\nPeriod_spiral = 2*pi./(Frequency_spiral.*sqrt(1-Damping_spiral.^2)); % seconds\nCycles_half_spiral = ((log(2))/(2*pi))*sqrt(1-Damping_spiral.^2)./Damping_spiral; % Number of cycles to damp to half the amplitude\n\ndisp('Spiral Mode Properties (lateral): ');\ndisp(' Pole 1');\ndisp('==============================================================================');\ndisp(sprintf(['Damping ratio : ' num2str(Damping_spiral(:)')]));\ndisp(sprintf(['Undampted, natural frequency (1/s): ' num2str(Frequency_spiral(:)')]));\ndisp(sprintf(['Period (s): ' num2str(Period_spiral(:)')]));\ndisp(sprintf(['Num. cycles to damp to half the amplitude : ' num2str(Cycles_half_spiral(:)')]));\ndisp(' ');\n\n% Dutch Roll poles\npolesDutchRoll = polesLateral(1:2); % choose first ones from sorted complex numbers\npolesDutchRollReal = real(polesDutchRoll);\npolesDutchRollImag = imag(polesDutchRoll);\n\nDamping_dutch = sqrt(1./(1+(polesDutchRollImag./polesDutchRollReal).^2)); % Damping ratio\nFrequency_dutch = -polesDutchRollReal./Damping_dutch; % Undampted, natural frequency per second\nPeriod_dutch = 2*pi./(Frequency_dutch.*sqrt(1-Damping_dutch.^2)); % seconds\nCycles_half_dutch = ((log(2))/(2*pi))*sqrt(1-Damping_dutch.^2)./Damping_dutch; % Number of cycles to damp to half the amplitude\n\n% Output result for longitudinal trimmed state\ndisp('Dutch Roll Mode Properties (lateral): ');\ndisp(' Pole 1 Pole 2');\ndisp('==============================================================================');\ndisp(sprintf(['Damping ratio : ' num2str(Damping_dutch(:)')]));\ndisp(sprintf(['Undampted, natural frequency (1/s): ' num2str(Frequency_dutch(:)')]));\ndisp(sprintf(['Period (s): ' num2str(Period_dutch(:)')]));\ndisp(sprintf(['Num. cycles to damp to half the amplitude : ' num2str(Cycles_half_dutch(:)')]));\ndisp(' ');\n\n% =========================================================================\n\n% Observability\ndisp(['Number of unobservable states (longitudinal) : ' num2str(length(ltiLongitudinal.a) - rank(obsv(ltiLongitudinal)))]);\ndisp(['Number of unobservable states (lateral) : ' num2str(length(ltiLateral.a) - rank(obsv(ltiLateral)))]);\ndisp(' ');\n\n% Controllability\ndisp(['Number of uncontrollable states (longitudinal): ' num2str(length(ltiLongitudinal.a) - rank(ctrb(ltiLongitudinal)))]);\ndisp(['Number of uncontrollable states (lateral) : ' num2str(length(ltiLateral.a) - rank(ctrb(ltiLateral)))]);\ndisp(' ');\n\n% TODO\n% ========================================================================\n\n% 1) Run this whole thing for different center of gravity settings and plot\n% Cm curve and poles.\n\n", "meta": {"author": "jrgenerative", "repo": "fixed-wing-sim", "sha": "53fd5b616a2bd296f37f1f105617c606c2f63066", "save_path": "github-repos/MATLAB/jrgenerative-fixed-wing-sim", "path": "github-repos/MATLAB/jrgenerative-fixed-wing-sim/fixed-wing-sim-53fd5b616a2bd296f37f1f105617c606c2f63066/ExperimentalCarrierSimulink/code/mainComputeLTIs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.45326184801538605, "lm_q1q2_score": 0.3473316727875848}}
{"text": "function [xsol,objp,info,msg,times,x,y,z,s,w] = lipsol(A,b,c,lb,ub,opts)\n% LIPSOL - Main program for LIPSOL\n\n% Yin Zhang, January, 1995\n% Department of Mathematics and Statistics\n% University of Maryland Baltimore County\n% Modified J.Currie AUT May 2013\n\nglobal probData\n\nif(nargin < 6)\n opts = lipsolset; \n opts.maxiter = 100;\n opts.maxtime = 1000;\n opts.tol = 1e-5;\nend\nif(nargin < 5), ub = []; end\nif(nargin < 4), lb = []; end\nif(nargin < 3), error('You must supply at least 3 arguments to lipsol(A,b,c)'); end\n\ntimes = zeros(5,1);\nt0 = tic;\n\n%Problem Data Structure to avoid so many Global Variables\nprobData = struct('NNZA',0,'NNZL',0,'XLNZ',[],'PERM',[],'INVP',[],'LNZ',[],'LOOP_LEVEL',[],...\n 'XSUPER',[],'XLINDX',[],'LINDX',[],'SNODE',[],'SPLIT',[],'TMPSIZ',[],...\n 'LNZ0',[],'b_orig',b,'c_orig',c,'data_changed',0,'isFeasible',1,...\n 'Lbounds_non0',[],'Ubounds_exist',0,'nub',0,'Fixed_exist',0,...\n 'ifix',[],'infx',[],'xfix',[],'Zrcols_exist',0,'izrcol',[],...\n 'inzcol',[],'xzrcol',[],'Sgtons_exist',0,'isolved',[],...\n 'insolved',[],'xsolved',[],'nt',0,'message',[],...\n 'col_scaled',0,'colscl',[],'Dense_cols_exist',0,'Mdense',[],...\n 'idense',[],'ispars',[],'Hist',[],'Sherman_OK',[],'backed',[]);\n%Initial Time \nopts.t0 = tic;\n\n%Save loop_level into problem structure\nprobData.LOOP_LEVEL = opts.loop_level;\n \n%Pretty Printing\nif(opts.verb), fprintf('----------------------------------------------\\n'); end\n \n%Preprocess the Input Data\n[A,b,c,lb,ub] = ls_preprocess(A,b,c,lb,ub,opts); \ntimes(1) = toc(t0);\n\n%Check if preproccesor indicates infeasible\nif(~probData.isFeasible)\n xsol = []; objp = []; info = [-1 0 0]; msg = 'Presolve Indicated Infeasible'; times = [];\n x = []; y = []; z = []; s = []; w = [];\n return;\nend\n\n%Scale the Input Data if Required\n[A,b,c,ub] = scaling(A,b,c,ub,opts);\n%Determine density of the problem\ncheckDense(A,opts);\ntimes(2) = toc(t0) - times(1);\n\n%Solve the Problem\n[x,y,z,s,w,info] = ls_miip(A,b,c,ub,opts); \ntimes(3) = toc(t0) - times(2);\n\n%Display Solve Status\nif(opts.verb && ~isempty(probData.message)), fprintf('\\n Status: %s\\n',probData.message); end\n\n%Post Process the Solution\n[xsol, objp, times ] = ls_postprocess(x,y,lb,opts.verb,times,t0);\nmsg = probData.message;\n\n%Pretty Printing\nif(opts.verb), fprintf('----------------------------------------------\\n'); end\n\n\nfunction [A,b,c,ub] = scaling(A,b,c,ub,opts)\n% SCALING - Scale matrix A. Usage: [A,b,c,ubounds] = scaling(A,b,c,ubounds)\n% Yin Zhang, January, 1995\n% Department of Mathematics and Statistics\n% University of Maryland Baltimore County\n\nglobal probData\n\n[m, n] = size(A);\nbadscl = 1.e-4;\n\nabsnzs = abs(nonzeros(A));\nthescl = min(absnzs)/max(absnzs);\nclear absnzs\n\nif (thescl < badscl)\n if(opts.verb), fprintf('Scaling ...\\n'); end\n\n % ----- scaling vectors ------\n AA = abs(A);\n colscl = full(sqrt(max(AA)'));\n rowscl = full(sqrt(max(AA,[],2)));\n clear AA;\n\n % ----- column scaling -----\n if (probData.Ubounds_exist), ub = ub.*colscl; end\n colscl = reciprocal(colscl);\n A = A*sparse(1:n,1:n,colscl);\n c = c.*colscl;\n probData.col_scaled = 1;\n\n % ----- row scaling -----\n rowscl = reciprocal(rowscl);\n A = sparse(1:m,1:m,rowscl)*A;\n b = b.*rowscl;\n bnrm = norm(b);\n if (bnrm > 0) \n q = median([1 norm(c)/bnrm 1.e+8]);\n if (q > 10), A = q*A; b = q*b; end\n end\n probData.data_changed = 1;\n probData.colscl = colscl;\nend\n\n\nfunction checkDense(A,opts) %#ok\n% CHECKDENSE - Determine and locate dense columns of matrix A.\n% Yin Zhang, January, 1995\n% Department of Mathematics and Statistics\n% University of Maryland Baltimore County\n\n%PROBLEM IN PCG - SKIPPING DENSE COLUMN MANAGEMENT [J.C. 19/5/13]\n\n% global probData\n% \n% [m, n] = size(A);\n% probData.ispars = 1:n; \n% nzratio = 1;\n% if (m > 500), nzratio = 0.20; end;\n% if (m > 1000), nzratio = 0.10; end;\n% if (m > 5000), nzratio = 0.05; end;\n% \n% if (nzratio < 1)\n% checking = sum(spones(A))/m <= nzratio;\n% if any(checking == 0)\n% probData.Dense_cols_exist = 1;\n% probData.idense = find(sparse(1-checking)); % Dense column indices\n% probData.ispars = find(checking); % Sparse column indices\n% if(opts.verb), fprintf('Dense columns (nnz/m > %g): %i\\n',nzratio,length(probData.idense)); end\n% else\n% if(opts.verb), fprintf('No Significant Dense Columns\\n'); end\n% end\n% clear checking\n% else\n% if(opts.verb), fprintf('Problem is Small Enough to Ignore Dense Columns\\n'); end\n% end\n\n\nfunction Y = reciprocal(X)\n% RECIPROCAL - Invert the nonzero entries of a matrix elementwise.\n% Y = RECIPROCAL(X) has the same sparsity pattern as X\n%\t (except possibly for underflow).\n\n% Yin Zhang, January, 1995\n% Department of Mathematics and Statistics\n% University of Maryland Baltimore County\n\nif issparse(X)\n [m, n] = size(X);\n [i,j,Y] = find(X);\n Y = sparse(i,j,1./Y,m,n);\nelse\n Y = 1./X;\nend\nceiling = 1.e+16; Y = min(ceiling,Y);", "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/lipsol/lipsol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.34722653010511845}}
{"text": "% Codes for CVPR-15 work `Face Alignment by Coarse-to-Fine Shape Searching'\n% Any question please contact Shizhan Zhu: zhshzhutah2@gmail.com\n% Released on July 25, 2015\n\nfunction reg_model = trainLR_averagedHalfBagging(X,y,iter,regressorInfo)\n\n% train regressor using all the samples only once\n\nassert(size(X,1) == size(y,1));\nm = size(X,1);\nREG = zeros(size(X,2)+1,size(y,2));\n\nfor i = 1:regressorInfo.times\n train_ind = randperm(m,ceil(m/2));\n REG = REG + (1/regressorInfo.times) * ...\n regressorInfo.trainMethod(X(train_ind,:),y(train_ind,:),regressorInfo.lambda(iter));\nend;\nreg_model = REG;\n\nend\n", "meta": {"author": "zhusz", "repo": "CVPR15-CFSS", "sha": "11b8d0b28a4a3e954741a4dae2f114df7b644d4e", "save_path": "github-repos/MATLAB/zhusz-CVPR15-CFSS", "path": "github-repos/MATLAB/zhusz-CVPR15-CFSS/CVPR15-CFSS-11b8d0b28a4a3e954741a4dae2f114df7b644d4e/codes_release/ml/ridge/trainLR_averagedHalfBagging.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.34722651537866095}}
{"text": "function [funOut, indexStart, problemDom, coeffs, totalDiffOrders] = ...\n toFirstOrder(funIn, rhs, domain, numArgs, cellArg)\n%TOFIRSTORDER Convert higher order anonymous functions to first order systems.\n% Calling sequence:\n% [FUNOUT, INDEXSTART, PROBLEMDOM, COEFFS, TOTALDIFFORDERS] = ...\n% TOFIRSTORDER(FUNIN, RHS, DOMAIN)\n% where the inputs are:\n% FUNIN: An anonymous function which describes an ODE, usually including\n% higher order derivatives, e.g. @(x,u) diff(u, 2) + sin(u).\n% Usually, the anonymous function comes from the OP field of a\n% CHEBOP.\n% RHS: The right hand side of the differential equation being solved\n% with a CHEBOP, that is, the right argument of a CHEBOP\n% backslash.\n% DOMAIN: The domain of the problem we're trying to solve.\n% and the outputs are:\n% FUNOUT: An anonymous function that is the first order reformulation\n% of FUNIN, which can be passed to the MATLAB solvers.\n% INDEXSTART: A vector that denotes at which index we should start\n% indexing each variable from so that they're in the correct\n% order for the MATLAB ODE solvers.\n% PROBLEMDOM: The domain on which the problem can be specified, which may\n% include breakpoints originally not included in DOMAIN.\n% COEFFS: A cell array of the coefficients the multiply the highest\n% order derivatives in problem. For example, for the problem\n% @(x,u) 5*diff(u, 2) + u, we will have COEFFS{1} = 5.\n% TOTALDIFFORDERS:\n% A vector that contains the maximum diffOrder applying to\n% each variable in the problem.\n%\n% In addition, one can pass the following arguments to the function, which are\n% only required if working in CHEBMATRIX syntax, for example, \n% @(x,u)[diff(u{1}) + u{2};...]:\n% NVARS: The number of unknown variables in the ODE.\n% CELLARG: Specify as TRUE if FUNIN is specified in CHEBMATRIX syntax.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Independent variable on the domain\nt = chebfun(@(t) t, domain);\n\n% See if we need to determine the number of variables involved, or if it was\n% passed as an argument.\nif ( nargin < 4)\n % We always have at least one argument to FUNIN, even in the scalar case. In\n % the system case, the first argument to funIn must be the independent time\n % variable. So the number of treeVar arguments needed is one less:\n numArgs = max(1, nargin(funIn) - 1);\n % If working in CHEBMATRIX syntax, we need all possible input variables to\n % be passed in as arguments:\n cellArg = false;\nend\nargs = cell(numArgs, 1);\nargsVec = zeros(1, numArgs);\n\n% Populate the args cell\nfor argCount = 1:numArgs\n argsVec(argCount) = 1;\n args{argCount} = treeVar(argsVec, domain);\n % Reset the index vector\n argsVec = 0*argsVec;\nend\n\n% Evaluate FUNIN with the TREEVAR arguments. Need different calling sequences\n% depending on whether we're working with CHEBMATRIX syntax and cells or not:\nif ( cellArg )\n fevalResult = funIn(t, args);\nelse\n % If FUNIN only takes one argument, we just give it the TREEVAR argument. \n % Otherwise, the first input will be the independent variable on the domain:\n if ( nargin(funIn) == 1 )\n fevalResult = funIn(args{:});\n else\n fevalResult = funIn(t, args{:});\n end\nend\n\n% If we got passed the problem as N\\0, i.e. a RHS that did not match the\n% dimensions, we need to repmat it so that the RHS variable has the correct\n% dimensions below:\nif ( isnumeric(rhs) && length(rhs) == 1 )\n rhs = repmat(rhs, size(fevalResult));\nend\n\n% Ensure RHS is a CHEBMATRIX\nif ( ~isa(rhs, 'chebmatrix') )\n rhs = chebmatrix(rhs, domain);\nend\n\n\n% Initialize cells to store the infix forms of the expressions, the coefficients\n% multiplying the highest order derivatives and any variables that appear in the\n% anonymous functions:\nsystemInfix = cell(length(fevalResult), 1);\ncoeffs = systemInfix;\nvarArrays = systemInfix;\n\n% We want to return all potential breakpoints caused by piecewise coefficients\n% in the problem. So loop through fevalResult, and take the union of the\n% breakpoints:\nproblemDom = fevalResult(1).domain;\nfor resCounter = 2:length(fevalResult)\n problemDom = union(problemDom, fevalResult(resCounter).domain);\nend\n\n% Ensure we also include potential breakpoints from the RHS:\nproblemDom = union(problemDom, rhs.domain);\n\n% First look at all diffOrders to ensure we start with the correct indices.\n% INDEXSTART denotes at which index we should start indexing each variable from.\n% E.g., in the coupled system\n% [v'' + w; v + w'']\n% we will have v = u(1), v' = u(2), w = u(3), w' = u(4), so INDEXSTART = [1, 3],\n% since v and its derivatives starts getting counted at 1, and w and its\n% derivatives start getting counted at 3.\n%\n% The vector INDEXSTARTDER is similar, but here, we also assign the highest\n% order derivative of each variable it's own index. This is so that later on, we\n% can correctly evaluate the coefficient multiplying the highest order\n% derivative in problem. Thus, in the example above, we'd have\n% v = u(1), v' = u(2), v'' = u(3), w = u(4), w' = u(5), w'' = u(6)\n% Here, INDEXSTARTDER = [1 4].\n\n% First, we need to find out the maximum diffOrder of each variable appearing in\n% the problem. We loop through the each component of the evaluation tree:\ntotalDiffOrders = zeros(1, numArgs);\nfor wCounter = 1:length(fevalResult)\n totalDiffOrders = max(totalDiffOrders, ...\n fevalResult(wCounter).tree.diffOrder);\nend\n\n% We always start indexing the first variable and its derivative(s) at 1. The\n% index of the other variables depend on the cumulative diffOrders of the\n% variables with lower indices.\nindexStart = [ 1, cumsum(totalDiffOrders(1:end-1)) + 1 ];\n% To get the indices of the derivatives as well, we shift all the previous\n% indices right by 1, in cumulative fashion:\nindexStartDer = indexStart + (0:numArgs-1);\n\n% COEFFARG will be used to evaluate the functions that gives us information\n% about the coefficients multiplying the highest order derivative in each\n% equation. The vector has to be equally long to the total number of derivatives\n% appearing in the problem; we'll then change one of the entries to 1 at a time\n% to get the coefficient information.\ncoeffArg = zeros(1, indexStartDer(end) + totalDiffOrders(end));\n\n% Go through each componenent from the result of evaluating FUNIN,\n% and change it to infix format.\nfor wCounter = 1:length(fevalResult)\n \n % The current result we're looking at.\n res = fevalResult(wCounter);\n \n % Current diffOrders\n diffOrders = res.tree.diffOrder;\n \n % Ensure that we never have the highest derivatives of more than one\n % variable appearing in a single equation:\n if ( sum(totalDiffOrders == diffOrders) > 1 )\n error('CHEBFUN:TREEVAR:toFirstOrder:diffOrders', ...\n ['The highest order derivative of more than one variable ' ...\n 'appears to be\\npresent in the same equation. ' ...\n 'Unable to convert to first order format.'])\n end\n \n % Expand the tree, so that PLUS rather than TIMES is sitting at the top of\n % it.\n expTree = treeVar.expandTree(res.tree, totalDiffOrders);\n \n % Split the tree into derivative part and non-derivative part.\n [newTree, derTree] = treeVar.splitTree(expTree, totalDiffOrders);\n \n % If newTree is empty, we only have a derivative part in the expression,\n % e.g. diff(u) = 0. We must replace it with a 0, as otherwise, we can't\n % evaluate the resulting odeFun in the ODE solvers.\n if ( isempty(newTree) )\n newTree = 0;\n end\n \n % Find what argument corresponds to the highest derivative one in the\n % current expression we're looking at. This will also be the order in which\n % we store the outputs from converting individual expressions to first order\n % form -- if the input is of the form @(x,u,v) [diff(v) - u; diff(u) - v],\n % the equations have to be sorted so that they'll be correctly converted.\n maxDerLoc = find(expTree.diffOrder == totalDiffOrders);\n \n % Convert the derivative part to infix form.\n % Indicate that we are converting a coeffFun\n isCoeffFun = true;\n [infixDer, varArrayDer] = ...\n treeVar.tree2infix(derTree, maxDerLoc, indexStartDer, isCoeffFun);\n \n % Convert the infix form of the expression that gives us the coefficient\n % multiplying the highest order derivative appearing in the expression to an\n % anonymous function we can evaluate:\n coeffFun = treeVar.toAnon(infixDer, varArrayDer);\n \n % Reset coeffArg for next evaluation:\n coeffArg = 0*coeffArg;\n \n % Replace one of the 0s in coeffFun with 1 so that we can evaluate COEFFFUN:\n if ( maxDerLoc == numArgs )\n % The last variable in the system currently appears in the highest order\n % derivate.\n coeffArg(end) = 1;\n else\n % The variable with index maxDerLoc+1 is the next variable we need to\n % start numbering at. So subtract 1 for the index of the highest\n % derivative we're currently interested in.\n coeffArg(indexStartDer(maxDerLoc+1) - 1) = 1;\n end\n \n % Evaluate the COEFFFUN to the coefficient!\n coeffs{maxDerLoc} = coeffFun(t, coeffArg);\n \n % Now work with the remaining syntax tree of the current expression of\n % interest. We need to negate the syntax tree as we're moving it to the\n % right-hand side. But if it already starts with a unary minus, we can\n % simply remove it rather than doing a double negation:\n % [TODO: Remove double UMINUS]\n newTree = struct('method', 'minus', 'numArgs', 2, ...\n 'left', rhs{wCounter}, 'right', newTree);\n % Convert current expression to infix form:\n isCoeffFun = false;\n [infix, varArray] = ...\n treeVar.tree2infix(newTree, maxDerLoc, indexStart, isCoeffFun);\n % Store the infix form and the variables that appeared in the anonymous\n % function.\n systemInfix{maxDerLoc} = infix;\n varArrays{maxDerLoc} = varArray;\nend\n\n% Convert all the infix expressions, coefficients and variables stored to an\n% anonymous function we can evaluate and use as the RHS of our ODE system:\nfunOut = treeVar.toRHS(systemInfix, varArrays, coeffs, ...\n indexStart, totalDiffOrders);\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/@treeVar/toFirstOrder.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.34722651537866095}}
{"text": "%BASE64ENCODE encodes a vector of uint8s as a base64 string\n% BASE64ENCODE(BYTES)\n% Encodes every tree BYTES in four printable ASCII characters.\n% If LENGTH(BYTES) is not a multiple of three, it is padded with\n% zeros and unused characters are replaced with '='.\n\n% (c) 2014 Bastian Bechtold\n% This code is licensed under the BSD 3-clause license\n\nfunction base64 = base64encode(bytes)\n % pad the base64 string to a multiple of 3\n if mod(length(bytes), 3) ~= 0\n padding = 3-mod(length(bytes), 3);\n bytes = [bytes; zeros(3-mod(length(bytes), 3), 1, 'uint8')];\n else\n padding = 0;\n end\n\n % convert every three uint8 bytes into four base64 bytes\n base64 = zeros(length(bytes)/3*4, 1, 'uint8');\n base64(1:4:end) = bitshift(bytes(1:3:end), -2);\n base64(2:4:end) = bitor(bitshift(bitand(bytes(1:3:end), 3), 4), ... % two LSB\n bitshift(bytes(2:3:end), -4));\n base64(3:4:end) = bitor(bitshift(bitand(bytes(2:3:end), 15), 2), ... % four LSB\n bitshift(bytes(3:3:end), -6));\n base64(4:4:end) = bitand(bytes(3:3:end), 63); % six LSB\n\n % convert from base64 bytes to string representation\n table = ['A':'Z' 'a':'z' '0':'9' '+' '/'];\n base64 = table(base64+1);\n base64(end-padding+1:end) = '=';\nend\n", "meta": {"author": "bastibe", "repo": "transplant", "sha": "b6215fadd66514e9ddff24a30bebac966ba80c57", "save_path": "github-repos/MATLAB/bastibe-transplant", "path": "github-repos/MATLAB/bastibe-transplant/transplant-b6215fadd66514e9ddff24a30bebac966ba80c57/transplant/base64encode.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175139669998, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3471944343972959}}
{"text": "function [v2gMap, sqDist] = mrmMapVerticesToGray(vertexCoords, grayNodes, mmPerVox, grayEdges,distThresh)\n%\n% [v2gMap sqDist] = mrmMapVerticesToGray(vertices, grayNodes, mmPerVox, [grayEdges]);\n%\n% Finds a map between the mesh vertices and gray nodes.\n% To see the coordinates of the gray matter node (or nodes) nearest to \n% mesh vertex I, we can use:\n% \n% nearestNodeCoords = grayNodes(1:3, v2gMap(:,I))\n%\n%\n% If the grayEdges are also passed in, then we'll compute the mapping for\n% all gray layers. Layer 1 mapping will be in the first row, and layers\n% >1 in subsequent columns. As always, vertices with no mapping will be set\n% to 0.\n%\n% The vertexGrayMap now has multiple rows to represent mappings from\n% each vertex (the columns) to all gray layers. This mapping is computed in\n% two steps:\n%\n% 1. For each vertex, find the nearest layer 1 gray node, where 'nearest'\n% is simply the smallest 3d Euclidian distance, with a threshold to leave\n% vertices that are too far from any layer 1 nodes unmapped (zero entry in\n% vertexGrayMap). This threshold is currently set to 4mm- edit\n% mrmMapVerticesToGray if you want to change this. This layer-1 mapping\n% forms the first column of the vertexGrayMap. \n%\n% 2. For each vertex (row), find all the nodes from layers >1 that should\n% map to this vertex. This is a somewhat ill-posed problem, so we had to\n% make a choice about which solution we wanted. We decided to use the gray\n% layer connections to find all the layer >1 nodes that form a direct\n% connection to the nearest layer 1 node that we mapped in step 1. As you\n% discovered, this gives us a very redundant sampling of the gray nodes.\n% The number of nodes >1 that are most directly connected to a given layer\n% 1 node can be very high, especially in regions of high convexity. The\n% algorithm for doing this essentially starts at the highest layers and\n% maps them down to the most direct (ie. shortest path) layer 1 node. In a\n% region of GM at the end of a thick finger of WM, this can map many nodes\n% to one layer 1 node (apparently 84 in one case). The vertexGrayMap is an\n% array, so the number of columns represents the most densely connected\n% case. If you look at it, there are probably only a few vertices with as\n% many as 84 connections. Most vertices probably have lots of zeros in\n% those higher columns. In fact, in regions of high concavity, you should\n% see some with no layers >1 (ie. a row with all zeros except for the first\n% column).\n%\n% We realize that this choice of implementation might not be what everyone\n% wants. But it works pretty well for our purposes. Of course, one downside\n% to the highly redundant mapping is an effective 'smoothing' of the data,\n% especially when you choose to average all layers (in your 3d window\n% preferences settings). What we do is look at our data collapsed across\n% layers as well as combining all layers, just to make sure we aren't\n% missing something. \n\n%\n% HISTORY:\n% 2003.09.16 RFD (bob@white.stanford.edu)\n% 2004.05.21 RFD: now uses Dan Merget's nearpoints to find a proper\n% mapping. No more hacks! Aside from being a bit faster, the result should\n% be substantially more accurate.\n% 2005.07.26 RFD: We now return a mapping for all gray layers, if\n% grayEdges is passed in.\n% 2005.08.05 RFD: all gray layer mapping is turned off by default, until\n% we figure out how to make it go faster.\n% 2005.10.26 GB: Tentative speed improvement in the main loop\n% 2006.06.01 RFD: added comments above. These were prompted by an email\n% exchange with David Ress.\n% 2007.05.23 ARW : Gray layer mapping seems to be available. Which is\n% nice. Added some minor mods to return sqDist and detect dist thresholds.\nverbose = prefsVerboseCheck;\n\nif notDefined('mmPerVox'), error('Voxel size (mm per vox) is required.'); end;\nif (notDefined('distThresh'))\n if (ispref('VISTA','defaultSurfaceWMMapDist'))\n\t\tif verbose,\t\n\t disp('Setting distThresh to the one in VISTA preferences');\n\t\tend\n distThresh = getpref('VISTA','defaultSurfaceWMMapDist');\n else\n if verbose, disp('Setting distThresh to 2'); end\n distThresh = 3;\n end\nend\n\nvertexCoords = double(vertexCoords);\ngrayNodes = double(grayNodes);\n\nif notDefined('grayEdges')\n grayEdges=[];\nend\n\ngrayEdges = double(grayEdges);\n\nprefs = mrmPreferences;\nif(strcmp(prefs.layerMapMode,'all'))\n mapToAllLayers = true;\nelse\n mapToAllLayers = false;\nend\n\n% This is now a real distance threshold, in mm. For each mesh vertex, the\n% algorithm will find the nearest gray coord. If the nearest coord is >\n% distThresh from the vertex, then that vertex gets no mapping ('0'). \n\n% The gray coordinates are in voxels in the vAnatomy file. This scales\n% them into real physical (mm) coordinates. And transposes them.\ngrayCoords = grayNodes([1,2,3], :);\ngrayCoords = [grayCoords(1,:).*mmPerVox(1); ...\n grayCoords(2,:).*mmPerVox(2); ...\n grayCoords(3,:).*mmPerVox(3) ]';\n\n% Transposes these mesh coordinates, which were already built in real\n% physical coordinates. \n% Major comments needed here.\nvertexCoords = vertexCoords' + 1;\n\n% Mask out non-layer 1 nodes so that they are not found\nif (~strcmp(prefs.layerMapMode,'any'))\n\tif verbose, disp('Masking out layers > 1'); end\n grayCoords(grayNodes(6,:)~=1,:) = -9999;\nend\n\n[v2gMap, sqDist] = nearpoints(double(vertexCoords'), double(grayCoords'));\n\nif verbose, \n\tfprintf('Excluding mesh nodes further than %d away from the boundary \\n', ...\n\t\t\tdistThresh);\nend\n\nv2gMap(sqDist > (distThresh^2)) = 0;\n\nv2gMap = int32(v2gMap);\n\nif(mapToAllLayers && exist('grayEdges','var') && ~isempty(grayEdges))\n layer1Nodes = v2gMap;\n curValid = double(layer1Nodes) > 0;\n numLayers = max(grayNodes(6,:));\n n = length(curValid);\n curLayerNum = 2;\n\n % GB 2005.10.26\n % We map from higher layers to lower layers,\n % selecting the closest connected node in the lower layer. This way we\n % will avoid multiply-connected \n\n noNeighborsDown = 0;\n noNeighbor = 0;\n noNeighbor2 = 0;\n \n v2gMapTemp = zeros(numLayers,size(grayNodes,2));\n \n h = mrvWaitbar(0, 'Computing between layers connections...');\n progress = 0;\n for iLayer = numLayers:-1:curLayerNum\n midprogress = 0;\n \n curNodes = find(grayNodes(6,:) == iLayer);\n for iNode = curNodes\n % disp(iNode) % debugging\n offset = grayNodes(5,iNode);\n numConnected = grayNodes(4,iNode);\n if numConnected == 0\n noNeighbor = noNeighbor + 1;\n continue %mrmMapVerticesToGray\n end\n neighbors = grayEdges(offset:offset + numConnected - 1);\n neighbors(grayNodes(6,neighbors) ~= (iLayer - 1)) = [];\n distance = sum(grayNodes(1:3,neighbors).^2,1);\n [value,nearest] = min(distance);\n if ~isempty(nearest)\n v2gMapTemp(iLayer,iNode) = neighbors(nearest);\n elseif length(nearest) > 1\n neighbors = neighbors(nearest);\n distanceIndex = abs(neighbors - iNode);\n [value,nearest] = min(distanceIndex);\n v2gMapTemp(iLayer,iNode) = neighbors(nearest);\n else\n neighbors = grayEdges(offset:offset + numConnected - 1);\n neighbors(grayNodes(6,neighbors) < iLayer - 1) = [];\n nextNeighbors = [];\n neighborsDown = [];\n iter = 0; % debugging\n while isempty(neighborsDown) && ~isequal(neighbors,nextNeighbors)\n iter = iter+1; %debugging\n if iter> 1000,\n disp foo\n break\n end\n neighbors = union(nextNeighbors,neighbors);\n nextNeighbors = [];\n for iNeighbor = 1:length(neighbors)\n offset = grayNodes(5,neighbors(iNeighbor));\n numConnected = grayNodes(4,neighbors(iNeighbor));\n nextNeighbors = [nextNeighbors grayEdges(offset:offset+numConnected-1)];\n end\n nextNeighbors = unique(nextNeighbors);\n neighborsDown = nextNeighbors(grayNodes(6,nextNeighbors) == (iLayer - 1));\n end\n \n if isempty(neighborsDown)\n noNeighbor2 = noNeighbor2 + 1;\n else\n distance = sum(grayNodes(1:3,neighborsDown).^2,1);\n [value,nearest] = min(distance);\n if length(nearest) == 1\n v2gMapTemp(iLayer,iNode) = neighborsDown(nearest(1));\n else\n neighborsDown = neighborsDown(nearest);\n distanceIndex = abs(neighborsDown - iNode);\n [value,nearest] = min(distanceIndex);\n v2gMapTemp(iLayer,iNode) = neighborsDown(nearest);\n end\n end\n noNeighborsDown = noNeighborsDown + 1;\n end\n end\n progress = progress + 1/(numLayers - curLayerNum + 1);\n mrvWaitbar(progress/2,h);\n end\n \n indices = 2*ones(1,size(v2gMap,2));\n indexNodes = cell(1,size(grayNodes,2));\n for curNode = find(curValid)\n indexNodes{v2gMap(1,curNode)} = [indexNodes{v2gMap(1,curNode)} curNode];\n end\n \n h = mrvWaitbar(1/2, h, 'Creating connections table...');\n progress = 0;\n for iNode = 1:size(grayNodes,2)\n if iNode > (progress + 1/10)*size(grayNodes,2)\n progress = progress + 1/10;\n mrvWaitbar(0.5 + progress/2);\n end\n \n curLayer = grayNodes(6,iNode);\n curNode = iNode;\n for iLayer = curLayer:-1:2\n if curNode == 0\n break\n end\n curNode = v2gMapTemp(iLayer,curNode);\n end\n if (curNode == 0) || (curNode == iNode)\n continue\n end\n\n indexNode = indexNodes{curNode};\n if isempty(indexNode)\n continue\n end\n \n v2gMap(indices(indexNode),indexNode) = iNode;\n indices(indexNode) = indices(indexNode) + 1;\n \n end\n close(h);\n \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/mrMesh/mrm/mrmMapVerticesToGray.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.34719443439729586}}
{"text": "function y = vl_nnrelu(x,dzdy)\n% VL_NNRELU CNN rectified linear unit\n% Y = VL_NNRELU(X) applies the rectified linear unit to the data\n% X. X can have arbitrary size.\n%\n% DZDX = VL_NNRELU(X, DZDY) computes the network derivative DZDX\n% with respect to the input X given the derivative DZDY with respect\n% to the output Y. DZDX has the same dimension as X.\n\n% Copyright (C) 2014 Andrea Vedaldi.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nif nargin <= 1 || isempty(dzdy)\n y = max(x, single(0)) ;\nelse\n y = dzdy .* (x > single(0)) ;\nend\n", "meta": {"author": "ybsong00", "repo": "Vital_release", "sha": "50de529396e2f452626aef41084972149cf4a7c7", "save_path": "github-repos/MATLAB/ybsong00-Vital_release", "path": "github-repos/MATLAB/ybsong00-Vital_release/Vital_release-50de529396e2f452626aef41084972149cf4a7c7/matconvnet/matlab/vl_nnrelu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3471944273284509}}
{"text": "function cvx_optpnt = nonnegative( sx ) %#ok\n\n%NONNEGATIVE The nonnegative orthant.\n% NONNEGATIVE(SX), where SX is a valid size vector, creates an array\n% of size SX and constrains each element to be nonnegative. Therefore,\n% given the declaration\n% variable x(sx)\n% the constraint\n% x == nonnegative(sx);\n% is equivalent to\n% x >= 0;\n% Obviously, the inequality form is simpler and is preferred in most\n% circumstances.\n%\n% Disciplined convex programming information:\n% NONNEGATIVE is a cvx set specification. See the user guide for\n% details on how to use sets.\n\nnarginchk(1,1);\n\n[ temp, sx ] = cvx_check_dimlist( sx, true );\nif ~temp,\n error( 'Argument must be a non-empty dimension vector.' );\nend\n \ncvx_begin set\n variables x( sx )\n if all( sx ~= 0 ),\n [ tx, dummy ] = find( cvx_basis( x ) ); %#ok\n newnonl( cvx_problem, 'nonnegative', tx(:) );\n end\ncvx_end\n\n% Copyright 2005-2016 CVX Research, Inc. \n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/sets/nonnegative.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6584175005616829, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.34719442732845085}}
{"text": "function F = complements(C1,C2)\n%COMPLEMENTS Defines complementary constraints\n% \n% F = COMPLEMENTS(C1,C2) \n\nF = complements(lmi(C1),lmi(C2));\n\t", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/extras/@constraint/complements.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.5544704649604274, "lm_q1q2_score": 0.34716737140727527}}
{"text": "function boolean = CalculateTimeForTakingOutBillet(T_new,reference_Temperature,x_intervals,y_intervals)\nboolean = 0;\ncount = 0;\n\nfor x_index = 2:1:(x_intervals-1)\n for y_index = 2:1:(y_intervals-1)\n if(abs(T_new(x_index,y_index))-reference_Temperature < 01 ) \n count = 1;\n end\n end\n if(count >= ((x_intervals*y_intervals)/2))\n boolean = 1;\n break;\n end\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/41696-2d-transient-heat-conduction/CalculateTimeForTakingOutBillet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.34716736367074236}}
{"text": "function [stlStruct] = import_STL_bin(fileName)\n\n% function [stlStruct] = import_STL_bin(fileName)\n% ------------------------------------------------------------------------\n%\n% This function reads an STL file in binary format into stlStruct\n%\n%\n% Based on code originally written by: Doron Harlev, Eric C. Johnson\n% (11-Dec-2008), and Francis Esmonde-White (May 2010).\n%\n%\n% Kevin Mattheus Moerman\n% gibbon.toolbox@gmail.com\n%\n% 2016/02/24 Added to GIBBON and altered syntax and behaviour\n%------------------------------------------------------------------------\n\n%% Access file\n\nfid=fopen(fileName, 'r'); %Open the file, assumes STL Binary format.\nif fid == -1\n error('File could not be opened, check name or path.')\nend\n\n%% Read title\nsolidNameBin=fread(fid,80,'uchar=>schar'); % Read file title\nsolidName = char(solidNameBin');\n\n%% Get number of faces\nnumFaces=fread(fid,1,'int32'); % Read number of Faces\n\n%% Read remainder\n\nT = fread(fid,inf,'uint8=>uint8'); % read the remaining values\nfclose(fid); %Close file\n\n%% Process import\n\n% Each facet is 50 bytes\n% - Three single precision values specifying the face normal vector\n% - Three single precision values specifying the first vertex (XYZ)\n% - Three single precision values specifying the second vertex (XYZ)\n% - Three single precision values specifying the third vertex (XYZ)\n% - Two color bytes (possibly zeroed)\n\n% 3 dimensions x 4 bytes x 4 vertices = 48 bytes for triangle vertices\n% 2 bytes = color (if color is specified)\n\ntrilist = 1:48;\n\nind = reshape(repmat(50*(0:(numFaces-1)),[48,1]),[1,48*numFaces])+repmat(trilist,[1,numFaces]);\ncoordNormData = reshape(typecast(T(ind),'single'),[3,4,numFaces]);\n\nN=squeeze(coordNormData(:,1,:))';\nN=double(N);\n\nV=coordNormData(:,2:4,:);\nV=reshape(V,[3,3*numFaces]);\nV=double(V)';\n\nF=reshape(1:3*numFaces,[3,numFaces])';\n\nc0 = typecast(T(49:50),'uint16');\nif (bitget(c0(1),16)==1)\n trilist = 49:50;\n ind = reshape(repmat(50*(0:(numFaces-1)),[2,1]),[1,2*numFaces])+repmat(trilist,[1,numFaces]);\n c0 = reshape(typecast(T(ind),'uint16'),[1,numFaces]);\n \n r=bitshift(bitand(2^16-1, c0),-10);\n g=bitshift(bitand(2^11-1, c0),-5);\n b=bitand(2^6-1, c0);\n C=[r; g; b]';\nelse\n C = zeros(numFaces,3);\nend\n\n\n%% Arrange output in structure array\nstlStruct.solidNames{1}=solidName;\nstlStruct.solidVertices{1}=V;\nstlStruct.solidFaces{1}=F;\nstlStruct.solidNormals{1}=N;\nstlStruct.solidColors{1}=C;\n\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/import_STL_bin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.34716736367074236}}
{"text": "function header = dtiReadPDBHeader (fid)\n\nif (~exist('fid','var'))\n header = struct();\n header.xformToAcPc = repmat (0, 4);\n header.numPaths = 0;\nelse\n offset = fread (fid, 1, 'uint');\n mx = fread (fid, 16, 'double');\n header.xformToAcPc = reshape (mx, 4,4);\n fseek (fid, offset-4, -1);\n header.numPaths = fread (fid, 1, 'uint');\nend\n \n% xxx should contain information about statistics too!", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/fileFilters/cinch/utils/dtiReadPDBHeader.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6261241632752916, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.34716735593420944}}
{"text": "function [edgeS, maskDown3D] = getSurface(structNumV, marginV, xyDownsampleIndex, planC)\n%\"getSurface\"\n% Get all the surface points of a a composite structure defined by the \n% structures given in structNumV, with margins epanded in 3D according to\n% marginV. The iV, jV, kV index vectors give all the surface points with\n% respect to the uniformized CT scan.\n%\n%JOD, 14 Nov 03.\n%JRA, 27 Mar 05.\n%\n%Usage:\n% [iEdgeV,jEdgeV,kEdgeV] = getSurface(structNumV,marginV, xyDownsampleIndex)\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\nif ~exist('planC') \n global planC\nend\nindexS = planC{end};\n\nglobal stateS\n\nif any(marginV ~= marginV(1))\n error('Currently only supports the same PB margin around each target.')\nend\nmargin = marginV(1);\n\nscanNum = getStructureAssociatedScan(structNumV(1));\nCTUniformInfoS = planC{indexS.scan}(scanNum).uniformScanInfo;\n\nxOffset = CTUniformInfoS.xOffset;\nyOffset = CTUniformInfoS.yOffset;\n\nsliceThickness = CTUniformInfoS.sliceThickness;\n\ndelta_xy = CTUniformInfoS.grid1Units;\n\n%-----------build composite target volume---------------------%\n\nmask3D = getUniformStr(structNumV(1));\n\nSZ=size(mask3D);\n\nmaskDown3D = logical(getDownsample3(mask3D, xyDownsampleIndex, 1));\n\nclear mask3D\n\nS = size(maskDown3D);\n\nlen = length(structNumV);\n\nfor i = 2 : len\n\n maskSingle = getUniformStr(structNumV(i));\n\n mask3D = maskSingle; clear maskSingle;\n\n tmp3D = logical(getDownsample3(mask3D, xyDownsampleIndex, 1));\n\n clear mask3D\n\n maskDown3D = tmp3D | maskDown3D;\n\nend\n\n% II. Get surface points from target volume\n\nedge = [0 0 0; 0 1 0; 0 0 0];\nedge(:,:,2) = [0 1 0; 1 1 1; 0 1 0];\nedge(:,:,3) = [0 0 0; 0 1 0; 0 0 0];\nedge = edge/7;\n\nsurfPoints = getSurfacePoints(maskDown3D);\nedge3D = repmat(logical(0), size(maskDown3D));\nfor i=1:size(surfPoints,1)\n edge3D(surfPoints(i,1),surfPoints(i,2), surfPoints(i,3)) = 1;\nend\n \n%Expand margin using convolution\n%Create margin ball:\n\nc1 = ceil(margin/delta_xy);\nc2 = ceil(margin/delta_xy);\nc3 = ceil(margin/sliceThickness);\n\n[uM,vM,wM] = meshgrid(- c1 : c1, -c2 : c2, - c3 : c3);\n\nxM = uM * delta_xy;\nyM = vM * delta_xy;\nzM = wM * sliceThickness;\n\nrM = (xM.^2 + yM.^2 + zM.^2).^0.5;\n\nball = [rM <= margin];\n\n[iBallV,jBallV,kBallV] = find3d(ball);\n\nsR = size(rM);\n\ndeltaV = (sR - 1)/2 +1;\n\nonesV = repmat(logical(1), [1,length(iBallV)]);\n\n[iV,jV,kV] = find3d(edge3D);\n\nsV = size(maskDown3D);\n\nind_surfV = sub2ind(sV,iV,jV,kV);\n\nball_offsetV = (iBallV - deltaV(1)) + sV(1) * (jBallV - deltaV(2)) + sV(1) * sV(2) * (kBallV - deltaV(3));\n\nfor i = 1 : length(ind_surfV) %put ones in\n\n total_indV = ind_surfV(i) + ball_offsetV;\n\n total_indV = clip(total_indV,1,prod(sV),'limits');\n\n maskDown3D(total_indV) = onesV;\n\nend\n\n%Find new edge\nsurfPoints = getSurfacePoints(maskDown3D);\n\nedgeS.rows = surfPoints(:,1);%iV;\nedgeS.cols = surfPoints(:,2);%jV;\nedgeS.slices = surfPoints(:,3);%kV;", "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/getSurface.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3470061702301259}}
{"text": "function [x,M] = spm_x_nmm(P)\n% initialises a state structure for a mean field model\n% FORMAT [x,M] = spm_x_nmm(P)\n%\n% P - parameter structure\n% M - model structure\n%\n% x - array of states\n% x(i,j,k) - k-th state of j-th population on i-th source\n%\n% population: 1 - excitatory spiny stellate cells (input cells)\n% 2 - inhibitory interneurons\n% 3 - excitatory pyramidal cells (output cells)\n%\n% state: 1 V - voltage\n% 2 gE - conductance (excitatory)\n% 3 gI - conductance (inhibitory)\n%\n% M - model structure\n%\n% see also: spm_x_mfm\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: spm_x_nmm.m 2393 2008-10-23 14:58:50Z karl $\n \n\n% get initialisation from full mean-field model\n%==========================================================================\n[x M] = spm_x_mfm(P);\n \n% remove dispersion and fix the covariance of the states (Cx)\n%--------------------------------------------------------------------------\nM.x = x{1};\nM.Cx = x{2}(:,:,1,1);\nx = x{1};\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_x_nmm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.34700616473087226}}
{"text": "%%*****************************************************************\n%% linsysolve: solve linear system to get dy, and direction\n%% corresponding to unrestricted variables. \n%%\n%% [xx,coeff,L,resnrm] = linsysolve(schur,UU,EE,Bmat,rhs); \n%%\n%% child functions: mybicgstable.m\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 [xx,coeff,L,resnrm] = HSDlinsysolve(par,schur,UU,EE,Bmat,rhs); \n \n global solve_ok msg\n global nnzmat nnzmatold matfct_options matfct_options_old use_LU\n\n spdensity = par.spdensity;\n printlevel = par.printlevel;\n iter = par.iter; \n\n m = length(schur); \n if (iter==1); use_LU = 0; matfct_options_old = ''; end\n if isempty(nnzmatold); nnzmatold = 0; end\n%%\n%% diagonal perturbation\n%% old: pertdiag = 1e-15*max(1,diagschur);\n%% \n diagschur = abs(full(diag(schur)));\n const = 1e-2/max(1,norm(par.dy2)); \n alpha = max(1e-14,min(1e-10,const*norm(par.rp))/(1+norm(diagschur.*par.dy2)));\n pertdiag = alpha*max(1e-8,diagschur); %% Note: alpha is close to 1e-15.\n mexschurfun(schur,pertdiag); \n %%if (printlevel); fprintf(' %3.1e ',alpha); end\n if (par.depconstr) | (min(diagschur) < min([1e-20*max(diagschur), 1e-4])) \n lambda = 0.1*min(1e-14,const*norm(par.rp)/(1+norm(par.diagAAt.*par.dy2)));\n mexschurfun(schur,lambda*par.diagAAt); \n %%if (printlevel); fprintf('*'); end\n end\n if (max(diagschur)/min(diagschur) > 1e14) & (par.blkdim(2) == 0) ...\n & (iter > 10)\n tol = 1e-6; \n idx = find(diagschur < tol); len = length(idx);\n pertdiagschur = zeros(m,1); \n if (len > 0 & len < 5) & (norm(rhs(idx)) < tol) \n pertdiagschur(idx) = 1*ones(length(idx),1); \n mexschurfun(schur,pertdiagschur); \n if (printlevel); fprintf('#'); end\n end\n end\n%%\n%%\n%%\n UU = [UU, Bmat]; \n if ~isempty(EE)\n len = max(max(EE(:,1)),max(EE(:,2))); \n else\n len = 0;\n end\n tmp = [len+1,len+3,-1; len+2,len+4,1; len+3,len+1,1; len+4,len+2,-1; \n len+2,len+2,par.addschur]; %% this is the -inverse\n EE = [EE; tmp]; \n ncolU = size(UU,2);\n%%\n%% assemble coefficient matrix\n%% \n if isempty(EE)\n coeff.mat22 = []; \n else\n coeff.mat22 = spconvert(EE);\n end\n coeff.mat12 = UU; \n coeff.mat11 = schur; %% important to use perturbed schur matrix\n%%\n%% pad rhs with zero vector\n%% decide which solution methods to use\n%%\n rhs = [rhs; zeros(m+ncolU-length(rhs),1)]; \n if (ncolU > 300); use_LU = 1; end\n%%\n%% Cholesky factorization\n%%\n L = []; resnrm = []; xx = inf*ones(m,1);\n if (~use_LU)\n nnzmat = mexnnz(coeff.mat11);\n nnzmatdiff = (nnzmat ~= nnzmatold); \n solve_ok = 1; solvesys = 1; \n if (nnzmat > spdensity*m^2) | (m < 500) \n matfct_options = 'chol';\n else\n matfct_options = 'spchol'; \n end\n if (printlevel > 2); fprintf(' %s',matfct_options); end \n L.matdim = length(schur); \n if strcmp(matfct_options,'chol')\n if issparse(schur); schur = full(schur); end;\n if (iter<=5); %%--- to fix strange anonmaly in Matlab\n mexschurfun(schur,1e-20,2); \n end \n L.matfct_options = 'chol'; \n [L.R,indef] = chol(schur); \n L.perm = [1:m];\n elseif strcmp(matfct_options,'spchol')\n if ~issparse(schur); schur = sparse(schur); end;\n L.matfct_options = 'spchol'; \n [L.R,indef,L.perm] = chol(schur,'vector'); \n L.Rt = L.R'; \n end \n if (indef)\n solve_ok = -2; solvesys = 0; \n msg = 'HSDlinsysolve: Schur complement matrix not positive definite'; \n if (printlevel); fprintf('\\n %s',msg); end\n end\n if (solvesys)\n if (ncolU)\n tmp = coeff.mat12'*linsysolvefun(L,coeff.mat12)-coeff.mat22;\n\t if issparse(tmp); tmp = full(tmp); end\n [L.Ml,L.Mu,L.Mp] = lu(tmp);\n tol = 1e-16;\n condest = max(abs(diag(L.Mu)))/min(abs(diag(L.Mu))); \n idx = find(abs(diag(L.Mu)) < tol);\n if ~isempty(idx) | (condest > 1e50*sqrt(norm(par.diagAAt))); %% old: 1e30 \n solvesys = 0; solve_ok = -4; \n use_LU = 1; \n msg = 'SMW too ill-conditioned, switch to LU factor'; \n if (printlevel); fprintf('\\n %s, %2.1e.',msg,condest); end\n end \n end\n if (solvesys)\n [xx,resnrm,solve_ok] = HSDbicgstab(coeff,rhs,L,[],[],printlevel);\n if (solve_ok<=0) & (printlevel)\n fprintf('\\n warning: HSDbicgstab fails: %3.1f.',solve_ok); \n end\n end\n end\n if (solve_ok < 0) \n if (m < 6000 & strcmp(matfct_options,'chol')) | ...\n (m < 1e5 & strcmp(matfct_options,'spchol')) \n use_LU = 1;\n if (printlevel); fprintf('\\n switch to LU factor'); end\n end\n end\n end\n%%\n%% LU factorization\n%%\n if (use_LU)\n nnzmat = mexnnz(coeff.mat11)+mexnnz(coeff.mat12); \n nnzmatdiff = (nnzmat ~= nnzmatold); \n solve_ok = 1; \n if ~isempty(coeff.mat22)\n raugmat = [coeff.mat11, coeff.mat12; coeff.mat12', coeff.mat22]; \n else\n raugmat = coeff.mat11; \n end\n if (nnzmat > spdensity*m^2) | (m+ncolU < 500) \n matfct_options = 'lu'; \n else\n matfct_options = 'splu'; \n end \n if (printlevel > 2); fprintf(' %s ',matfct_options); end \n L.matdim = length(raugmat); \n if strcmp(matfct_options,'lu') \n if issparse(raugmat); raugmat = full(raugmat); end\n L.matfct_options = 'lu'; \n [L.L,L.U,L.p] = lu(raugmat,'vector'); \n elseif strcmp(matfct_options,'splu') \n if ~issparse(raugmat); raugmat = sparse(raugmat); end \n L.matfct_options = 'splu'; \n [L.L,L.U,L.p,L.q,L.s] = lu(raugmat,'vector'); \n L.s = full(diag(L.s)); \n elseif strcmp(matfct_options,'ldl') \n if issparse(raugmat); raugmat = full(raugmat); end\n L.matfct_options = 'ldl'; \n [L.L,L.D,L.p] = ldl(raugmat,'vector'); \n L.D = sparse(L.D);\n elseif strcmp(matfct_options,'spldl') \n if ~issparse(raugmat); raugmat = sparse(raugmat); end \n L.matfct_options = 'spldl'; \n [L.L,L.D,L.p,L.s] = ldl(raugmat,'vector');\n L.s = full(diag(L.s)); \n L.Lt = L.L'; \n end\n [xx,resnrm,solve_ok] = HSDbicgstab(coeff,rhs,L,[],[],printlevel);\n if (solve_ok<=0) & (printlevel)\n fprintf('\\n warning: HSDbicgstab fails: %3.1f,',solve_ok); \n end\n end\n if (printlevel>=3); fprintf('%2.0f ',length(resnrm)-1); end\n%%\n nnzmatold = nnzmat; matfct_options_old = matfct_options; \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/HSDSolver/HSDlinsysolve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7401743735019594, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.3469868083666709}}
{"text": "% LIONSIMBA example script\n% Different heat exchange coefficients: this script provides the example simulation shown in the\n% paper.\n\n% This file is part of the LIONSIMBA Toolbox\n%\n%\tOfficial web-site: \thttp://sisdin.unipv.it/labsisdin/lionsimba.php\n% \tOfficial GitHUB: \thttps://github.com/lionsimbatoolbox/LIONSIMBA\n%\n% LIONSIMBA: A Matlab framework based on a finite volume model suitable for Li-ion battery design, simulation, and control\n% Copyright (C) 2016-2018 :Marcello Torchio, Lalo Magni, Davide Raimondo,\n% University of Pavia, 27100, Pavia, Italy\n% Bhushan Gopaluni, Univ. of British Columbia, \n% Vancouver, BC V6T 1Z3, Canada\n% Richard D. Braatz, \n% Massachusetts Institute of Technology, \n% Cambridge, Massachusetts 02142, USA\n% \n% Main code contributors to LIONSIMBA 2.0:\n% Ian Campbell, Krishnakumar Gopalakrishnan,\n% Imperial college London, London, UK\n%\n% LIONSIMBA is a free Matlab-based software distributed with an MIT\n% license.\n\n% Clear the workspace\nclear\n\n% Define the integration times.\nt0 = 0;\ntf = 10^4;\n% Define the parameters structure. By default the hcell parameter is set to\n% 1 [W / (m^2 K)]\nparam{1} = Parameters_init;\n\n% Change the hcell parameter and set it to 0.01 [W / (m^2 K)]\nparam{1}.hcell = 0.01;\n\n% Start the simulation. Note that the final integration time is 10^4 and\n% LIONSIMBA will stop automatically when reached the Cutoff Voltage of\n% 2.5V. Note that no Jacobian among one simulation and the other. This is\n% due to the fact that the model structure changes for each of the\n% simulation (because hcell changes) and consequently also the Jacobian\n% matrix changes and cannot be used for all the scenarios.\n\nout1 = startSimulation(t0,tf,[],-30,param);\n\n% Change the hcell parameter and set it to 1 [W / (m^2 K)]\nparam{1}.hcell = 1;\n\n% Run the simulation\nout2 = startSimulation(t0,tf,[],-30,param);\n\n% Change the hcell parameter and set it to 100 [W / (m^2 K)]\nparam{1}.hcell = 100;\n\n% Run the simulation\nout3 = startSimulation(t0,tf,[],-30,param);\n\n%% Plot the results\n\nfigure(1)\nplot(out1.time{1},out1.Temperature{1}(:,end),'LineWidth',6)\nhold on\nplot(out2.time{1},out2.Temperature{1}(:,end),'--','LineWidth',6)\nplot(out3.time{1},out3.Temperature{1}(:,end),'-.','LineWidth',6)\nxlabel('Time [s]')\nylabel('Temperature [K]')\ngrid on\nbox on\n\nfigure(2)\nplot(out1.time{1},out1.Voltage{1},'LineWidth',6)\nhold on\nplot(out2.time{1},out2.Voltage{1},'--','LineWidth',6)\nplot(out3.time{1},out3.Voltage{1},'-.','LineWidth',6)\nxlabel('Time [s]')\nylabel('Voltage [V]')\ngrid on\nbox on\n\n", "meta": {"author": "lionsimbatoolbox", "repo": "LIONSIMBA", "sha": "d1cf29a4dcfa8e7824fc2416ac3e6ec760bb9b66", "save_path": "github-repos/MATLAB/lionsimbatoolbox-LIONSIMBA", "path": "github-repos/MATLAB/lionsimbatoolbox-LIONSIMBA/LIONSIMBA-d1cf29a4dcfa8e7824fc2416ac3e6ec760bb9b66/example_scripts/different_heat_exchange.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.3469382910477655}}
{"text": "function [Lmk,Obs] = reparametrizeLmk(Rob,Sen,Lmk,Obs,Opt)\n\n%REPARAMETRIZELMK Reparametrize landmark.\n% [LMK,OBS] = REPARAMETRIZELMK(ROB,SEN,LMK,OBS,OPT) return the\n% reparametrized landmark and Obs structure.\n% The landmark is reparametrized only in the case of an inverse depth \n% point. A linearity test of cartesian point given inverse depth \n% point is performed.\n\n% Copyright 2009 David Marquez @ LAAS-CNRS.\n\n\nglobal Map\n\nswitch Lmk.type\n \n case 'idpPnt' \n % we will convert from inverse-depth to euclidean.\n \n % Test for linearity:\n Ld = idpLinearTest(Rob,Sen,Lmk);\n \n if Ld < Opt.correct.linTestIdp\n \n % ranges\n ir = Lmk.state.r; % idp\n er = ir(1:3); % euclidean\n m = Map.used; % map\n \n % point coordinates\n idp = Map.x(ir); % idp\n [p,P_i] = idp2euc(idp); % euclidean\n \n % map updates\n Map.x(er) = p; % mean\n \n Map.P(er,m) = P_i * Map.P(ir,m); % co- and cross-variances\n Map.P(m,er) = Map.P(m,ir) * P_i';\n \n Map.used(Lmk.state.r(4:6)) = false; % used positions\n \n % Lmk and Obs updates\n Lmk.state.r = er; % new range\n Lmk.type = 'eucPnt'; % new type\n Obs.ltype = 'eucPnt'; % new type\n end\n \n case 'ahmPnt' \n % we will convert from anchored homogeneous to euclidean.\n \n % Test for linearity:\n Ld = ahmLinearTest(Rob,Sen,Lmk);\n \n if Ld < Opt.correct.linTestIdp\n \n % ranges\n ar = Lmk.state.r; % ahmPnt\n er = ar(1:3); % euclidean\n m = Map.used; % map\n \n % point coordinates\n ahm = Map.x(ar); % idp\n [p,P_a] = ahm2euc(ahm); % euclidean\n \n % map updates\n Map.x(er) = p; % mean\n \n Map.P(er,m) = P_a * Map.P(ar,m); % co- and cross-variances\n Map.P(m,er) = Map.P(m,ar) * P_a';\n \n Map.used(Lmk.state.r(4:7)) = false; % used positions\n \n % Lmk and Obs updates\n Lmk.state.r = er; % new range\n Lmk.type = 'eucPnt'; % new type\n Obs.ltype = 'eucPnt'; % new type\n end\n \n case {'eucPnt'}\n % do nothing\n \n case {'hmgPnt','ahmPnt','plkLin','aplLin','idpLin','ahmLin','hmgLin'}\n % do nothing, by now <- probably add here something to do\n % Points should go to euclidean\n % Lines should go to some minimal representation (polar? 'plrLin')\n \n % case 'myLmk' \n % edit this 'myLmk' name to put your own landmark type\n % do something\n \n otherwise\n error('??? Unknown landmark type ''%s''.',Lmk.type)\n\nend\n\n\n\n% ========== End of function - Start GPL license ==========\n\n\n% # START GPL LICENSE\n\n%---------------------------------------------------------------------\n%\n% This file is part of SLAMTB, a SLAM toolbox for Matlab.\n%\n% SLAMTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% SLAMTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with SLAMTB. If not, see .\n%\n%---------------------------------------------------------------------\n\n% SLAMTB is Copyright:\n% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,\n% Copyright (c) 2010-2013, Joan Sola,\n% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,\n% SLAMTB is Copyright 2009 \n% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol\n% @ LAAS-CNRS.\n% See on top of this file for its particular copyright.\n\n% # END GPL LICENSE\n\n", "meta": {"author": "joansola", "repo": "slamtb", "sha": "b4767f6bf38bceed205abb85f1aed12422c9a972", "save_path": "github-repos/MATLAB/joansola-slamtb", "path": "github-repos/MATLAB/joansola-slamtb/slamtb-b4767f6bf38bceed205abb85f1aed12422c9a972/InterfaceLevel/reparametrizeLmk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.34693828542253363}}
{"text": "%Script to ectract heterogenity metrics from MR images\n%\n%APA, 03/16/2010\n\nglobal planC\nindexS = planC{end};\nstructNum = 1;\ndisp('Heterogenity Metrics for MR')\n[energy_40base,contrast_40base,Entropy_40base,Homogeneity_40base,standard_dev_40base,Ph_40base,slope_base] = getHaralicParams(structNum);\n[jnk,jnk,raw] = xlsread('Cervix_MR_data.xls');\nrowIndex = size(raw,1)+1;\ndataM = [slope_base,energy_40base,contrast_40base,Entropy_40base,Homogeneity_40base,standard_dev_40base];\nPtName = planC{indexS.scan}(1).scanInfo(1).patientName;\n[SUCCESS,MESSAGE] = xlswrite('Cervix_MR_data.xls',{PtName},['A',num2str(rowIndex),':A',num2str(rowIndex)]);\nif ~SUCCESS\n errordlg(MESSAGE.message,'Error Writing to Excel','modal')\n return\nend\n[SUCCESS,MESSAGE] = xlswrite('Cervix_MR_data.xls',{datestr(now)},['B',num2str(rowIndex),':B',num2str(rowIndex)]);\nif ~SUCCESS\n errordlg(MESSAGE.message,'Error Writing to Excel','modal')\n return\nend\nacquisitionDate = datestr(datenum(num2str(planC{indexS.scan}(1).scanInfo(1).DICOMHeaders.AcquisitionDate),'yyyymmdd'));\n[SUCCESS,MESSAGE] = xlswrite('Cervix_MR_data.xls',{acquisitionDate},['D',num2str(rowIndex),':D',num2str(rowIndex)]);\nif ~SUCCESS\n errordlg(MESSAGE.message,'Error Writing to Excel','modal')\n return\nend\n[SUCCESS,MESSAGE] = xlswrite('Cervix_MR_data.xls',dataM,['E',num2str(rowIndex),':J',num2str(rowIndex)]);\nif ~SUCCESS\n errordlg(MESSAGE.message,'Error Writing to Excel','modal')\n return\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/PlanMetrics/heterogenity_metrics/helper_functions/extract_Cervix_MR_Data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3468958097359066}}
{"text": "% OCR (Optical Character Recognition).\n% PRINCIPAL PROGRAM\nwarning off %#ok\n% Clear all\nclc, close all, clear all\n% Read image\nimagen=imread('TEST_1.jpg');\n% Show image\nimshow(imagen);\ntitle('INPUT IMAGE WITH NOISE')\n% Convert to gray scale\nif size(imagen,3)==3 %RGB image\n imagen=rgb2gray(imagen);\nend\n% Convert to BW\nthreshold = graythresh(imagen);\nimagen =~im2bw(imagen,threshold);\n% Remove all object containing fewer than 30 pixels\nimagen = bwareaopen(imagen,30);\n%Storage matrix word from image\nword=[ ];\nre=imagen;\n%Opens text.txt as file for write\nfid = fopen('text.txt', 'wt');\n% Load templates\nload templates\nglobal templates\n% Compute the number of letters in template file\nnum_letras=size(templates,2);\nwhile 1\n %Fcn 'lines' separate lines in text\n [fl re]=lines(re);\n imgn=fl;\n %Uncomment line below to see lines one by one\n %imshow(fl);pause(0.5) \n %----------------------------------------------------------------- \n % Label and count connected components\n [L Ne] = bwlabel(imgn); \n for n=1:Ne\n [r,c] = find(L==n);\n % Extract letter\n n1=imgn(min(r):max(r),min(c):max(c)); \n % Resize letter (same size of template)\n img_r=imresize(n1,[42 24]);\n %Uncomment line below to see letters one by one\n %imshow(img_r);pause(0.5)\n %-------------------------------------------------------------------\n % Call fcn to convert image to text\n letter=read_letter(img_r,num_letras);\n % Letter concatenation\n word=[word letter];\n end\n %fprintf(fid,'%s\\n',lower(word));%Write 'word' in text file (lower)\n fprintf(fid,'%s\\n',word);%Write 'word' in text file (upper)\n % Clear 'word' variable\n word=[ ];\n %*When the sentences finish, breaks the loop\n if isempty(re) %See variable 're' in Fcn 'lines'\n break\n end \nend\nfclose(fid);\n%Open 'text.txt' file\nwinopen('text.txt')\nfprintf('For more information, visit: www.matpic.com \\n')\nclear all\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/matlab-OCR-master/OCR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.3468958035175102}}
{"text": "function [x,paramvec,paramindex,ons] = cond2reg(c,mspec,paramvec,paramindex)\n% given a condition structure, returns regressor\n%\n% x is reg or set of regs to add to model\n% paramvec is cell array of onsets (relative to...) for design reconstruction\n% paramindex is index of which cell in paramvec to use for reconstruction of which condition\n% ons is vector of trial onsets, for updating conditions, if necessary\n%\n% This function is not used in GA2: it's an extra function that mirrors a subfunction of\n% construct_model.m\n%\n% THIS IS OLD! DOES IT WORK?\n%\n% Tor Wager\n\n if isfield(c,'parts')\n if c.parts ~= 1\n % can't build regressor from trial type with parts - return\n x = [];\n return\n end\n end\n \n % determine onset times\n % -----------------------------------------------------------------------------------\n delta = zeros(mspec.numframes,1);\n if size(c.onsets,1) == 1\n % fixed onsets for condition, but sub-trial may be variable\n \n if isfield(c,'baseons') % for sub-parts of trials\n if size(c.onsets,2) == 2 % sub-trial, range is given; get random\n if length(paramvec) < paramindex,\n paramvec{paramindex} = round(randrange(c.onsets,length(c.baseons)));\n end\n c.onsets = paramvec{paramindex};\n paramindex = paramindex + 1;\n end\n ons = c.onsets + c.baseons;\n \n else \n ons = c.onsets;\n \n end\n ons = round(ons);\n delta(1 + (ons)) = 1;\n \n else\n % variable (random) onsets\n if length(paramvec) < paramindex\n % build new ones if they're not input\n paramvec{paramindex} = onsetbuilder(c.onsets,mspec.numframes);\n end\n \n if isfield(c,'baseons') % for sub-parts of trials\n ons = paramvec{paramindex} + c.baseons;\n else \n ons = paramvec{paramindex};\n end\n delta(1 + (paramvec{paramindex})) = 1; \n paramindex = paramindex + 1;\n end\n\n % convolve or shift\n % -----------------------------------------------------------------------------------\n \n if isfield(c,'parts')\n if c.parts == 1\n doconv = c.subcond(1).convolve;\n hrfest = c.subcond(1).hrfest;\n else\n error('This should never ever happen.')\n end\n else\n % this c IS a subpart\n doconv = c.convolve;\n hrfest = c.hrfest;\n end\n \n if doconv,\n x = conv(mspec.hrf,delta);\n elseif ~isempty(hrfest)\n sf{1} = delta;\n [x] = tor_make_deconv_mtx(sf,round(hrfest),1);\n else\n x = delta;\n end\n \n x = x(1:ceil(mspec.numframes),:);\n \nreturn\n \n\n\n\n% -----------------------------------------------------------------------------------\n% * fill the run with as many trials as possible, given range of random lengths and delays\n% -----------------------------------------------------------------------------------\n\nfunction [onsets] = onsetbuilder(range,numframes)\n% builds list of trials with random onset times\n% range is range of onset times in condition.onsets, a 2 x 2 matrix\n\nonsets = []; tend = 0; % 0 is first time point in run\ndlen = round(randrange(range(1,:),1));\ndnaindex = 2;\n\nwhile tend + dlen < numframes % while onset of next trial is < end of run\n \n tlen = round(randrange(range(2,:),1)); % trial length\n if tend + dlen + tlen > numframes, break,end % trial will not fit in run\n \n % add a trial\n onsets(end+1) = tend + dlen; % specify onset after start delay of dlen\n tend = onsets(end) + tlen; % specify ending point of trial\n dlen = round(randrange(range(1,:),1)); % re-randomize delay for next trial\n \nend\n\n\n\n\n \n% -----------------------------------------------------------------------------------\n% * get a random number or vector within a specified range\n% ----------------------------------------------------------------------------------- \nfunction rval = randrange(range,num)\n rval = rand(1,num) * (range(1,2) - range(1,1)) + range(1,1);\nreturn\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/GA2/cond2reg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.34688119032295395}}
{"text": "function confidences = test_boosted_dt_mc(classifier, features)\n% confidences = test_boosted_dt_mc(classifier, features)\n% returns a log likelihod ratio for each class in the classifier \n% confidences(ndata, nclasses)\n\ndt = classifier.wcs(1).dt;\nif size(features, 2)~=dt.npred\n error('Incorrect number of attributes')\nend\n\nwcs = classifier.wcs; \nnclasses = size(wcs, 2);\n\nntrees = size(wcs, 1);\n\nconfidences = zeros(size(features, 1), nclasses);\nfor c = 1:nclasses \n for t = 1:ntrees \n if ~isempty(wcs(t,c).dt) \n dt = wcs(t,c).dt;\n [var, cut, children, catsplit] = tree_getParameters(dt);\n nodes = treevalc(int32(var), cut, int32(children(:, 1)), ...\n int32(children(:, 2)), catsplit(:, 1), features'); \n %[class_indices, nodes2, classes] = treeval(wcs(t, c).dt, features); \n % if sum(nodes~=nodes2)>0\n % disp('error')\n % % disp(num2str([nodes nodes2])) \n % end\n confidences(:, c) = confidences(:, c) + wcs(t, c).confidences(nodes);\n end \n end\n confidences(:, c) = confidences(:, c) + classifier.h0(c);\nend\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/boosting/test_boosted_dt_mc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.3468811903229539}}
{"text": "%%***************************************************************************\n%% steplength: compute xstep such that X + xstep*dX >= 0.\n%%\n%% [xstep] = steplength(blk,X,dX,Xchol,invXchol);\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 [xstep,invXchol] = steplength(blk,X,dX,Xchol,invXchol);\n\n%%\n for p = 1:size(blk,1)\n pblk = blk(p,:); \n numblk = length(pblk{2}); \n pblksize = sum(pblk{2});\n if (any(isnan(dX{p})) | any(isinf(dX{p}))); xstep = 0; break; end; \n if strcmp(pblk{1},'s') \n if (max(pblk{2}) >= 200) \n use_lanczos = 1; \n else\n use_lanczos = 0; \n end \n if (use_lanczos)\n tol = 1e-3; \n maxit = max(min(pblksize,30),round(sqrt(pblksize))); \n [lam,delta,res] = lanczosfun(Xchol{p},-dX{p},maxit,tol);\n %%\n %% Note: lam <= actual largest eigenvalue <= lam + delta.\n %% \n\t d = lam+delta; \n else\n if isempty(invXchol{p}); \n invXchol{p} = inv(Xchol{p}); \n end\n\t tmp = Prod2(pblk,dX{p},invXchol{p},0); \n M = Prod2(pblk,invXchol{p}',tmp,1); \n if (exist('mexblkeig')==3)\n d = mexblkeig(pblk,-M); \n else\n d = blkeig(pblk,-M); \n end\n end\n tmp = max(d) + 1e-15*max(abs(d)); \n if (tmp > 0); \n xstep(p) = 1/max(tmp);\n else \n xstep(p) = 1e12; \n end\n elseif strcmp(pblk{1},'q')\n aa = qops(pblk,dX{p},dX{p},2); \n bb = qops(pblk,dX{p},X{p},2); \n cc = qops(pblk,X{p},X{p},2);\n dd = bb.*bb - aa.*cc; \n tmp = min(aa,bb); \n idx = find(dd > 0 & tmp < 0); \n steptmp = 1e12*ones(numblk,1); \n if ~isempty(idx)\n steptmp(idx) = -(bb(idx)+sqrt(dd(idx)))./aa(idx); \n end\n idx = find(abs(aa) < eps & bb < 0); \n if ~isempty(idx)\n steptmp(idx) = -cc(idx)./(2*bb(idx)); \n end\n %%\n %% also need first component to be non-negative\n %%\n ss = 1 + [0, cumsum(pblk{2})];\n ss = ss(1:length(pblk{2})); \n dX0 = dX{p}(ss); \n X0 = X{p}(ss); \n idx = find(dX0 < 0 & X0 > 0); \n if ~isempty(idx)\n steptmp(idx) = min(steptmp(idx),-X0(idx)./dX0(idx)); \n end\n xstep(p) = min(steptmp); \n elseif strcmp(pblk{1},'l')\n idx = find(dX{p} < 0); \n if ~isempty(idx)\n xstep(p) = min(-X{p}(idx)./dX{p}(idx)); \n else \n xstep(p) = 1e12;\n end\n elseif strcmp(pblk{1},'u')\n xstep(p) = 1e12; \n end\n end\n xstep = min(xstep); \n%%***************************************************************************\n%%***************************************************************************\n%% lanczos: find the largest eigenvalue of \n%% invXchol'*dX*invXchol via the lanczos iteration.\n%%\n%% [lam,delta] = lanczosfun(Xchol,dX,maxit,tol,v)\n%%\n%% lam: an estimate of the largest eigenvalue.\n%% lam2: an estimate of the second largest eigenvalue.\n%% res: residual norm of the largest eigen-pair.\n%% res2: residual norm of the second largest eigen-pair.\n%%***************************************************************************\n\n function [lam,delta,res] = lanczosfun(Xchol,dX,maxit,tol,v) \n \n if (norm(dX,'fro') < 1e-13) \n lam = 0; delta = 0; res = 0; \n return;\n end\n n = length(dX); \n if (nargin < 5); \n state = randn('state'); \n randn('state',0); \n v = randn(n,1); \n randn('state',state); \n end\n if (nargin < 4); tol = 1e-3; end\n if (nargin < 3); maxit = 30; end\n V = zeros(n,maxit+1); H = zeros(maxit+1,maxit); \n v = v/norm(v); \n V(:,1) = v; \n if issparse(Xchol); Xcholtransp = Xchol'; end\n%%\n%% lanczos iteration. \n%%\n for k = 1:maxit\n if issparse(Xchol)\n w = dX*mextriangsp(Xcholtransp,v,1); \n w = mextriangsp(Xchol,w,2); \n else \n w = dX*mextriang(Xchol,v,1); \n w = mextriang(Xchol,w,2); \n end \n wold = w;\n if (k > 1); \n w = w - H(k,k-1)*V(:,k-1); \n end;\n alp = w'*V(:,k); \n w = w - alp*V(:,k); \n H(k,k) = alp; \n %%\n %% one step of iterative refinement if necessary. \n %%\n if (norm(w) <= 0.8*norm(wold));\n s = (w'*V(:,1:k))'; \n w = w - V(:,1:k)*s;\n H(1:k,k) = H(1:k,k) + s;\n end; \n nrm = norm(w); \n v = w/nrm; \n V(:,k+1) = v; \n H(k+1,k) = nrm; H(k,k+1) = nrm; \n %%\n %% compute ritz pairs and test for convergence\n %%\n if (rem(k,5) == 0) | (k == maxit); \n Hk = H(1:k,1:k); Hk = 0.5*(Hk+Hk'); \n [Y,D] = eig(Hk); \n eigH = real(diag(D)); \n [dummy,idx] = sort(eigH);\n res_est = abs(H(k+1,k)*Y(k,idx(k)));\n if (res_est <= 0.1*tol) | (k == maxit);\n lam = eigH(idx(k)); \n lam2 = eigH(idx(k-1)); \n z = V(:,1:k)*Y(:,idx(k));\n z2 = V(:,1:k)*Y(:,idx(k-1));\n if issparse(Xchol) \n tmp = dX*mextriangsp(Xcholtransp,z,1); \n res = norm(mextriangsp(Xchol,tmp,2) -lam*z); \n tmp = dX*mextriangsp(Xcholtransp,z2,1); \n res2 = norm(mextriangsp(Xchol,tmp,2) -lam*z2); \n else\n tmp = dX*mextriang(Xchol,z,1); \n res = norm(mextriang(Xchol,tmp,2) -lam*z); \n tmp = dX*mextriang(Xchol,z2,1); \n res2 = norm(mextriang(Xchol,tmp,2) -lam*z2); \n end\n tmp = lam-lam2 -res2; \n if (tmp > 0); beta = tmp; else; beta = eps; end; \n delta = min(res,res^2/beta); \n if (delta <= tol); break; end;\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/steplength.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.3468811903229539}}
{"text": "% Copyright (C) Daphne Koller, Stanford Univerity, 2012\n%\n% Author: Huayan Wang\n\nfunction VisualizeModels(P, G)\nK = length(P.c);\n\nf = figure;\nwhile(1)\n for k=1:K\n subplot(1,K,k);\n if size(G,3) == 1 % same graph structure for all classes\n \n pose = SamplePose(P,G,k);\n \n else % different graph structure for each class\n \n pose = SamplePose(P,G(:,:,k),k);\n \n end\n \n img = ShowPose(pose);\n imshow(img);\n pause(0.3)\n if (~ishandle(f)) return; end; % quit loop when user closes the figure\n end\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/8.Learning Tree Structured Networks/VisualizeModels.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3467904083364927}}
{"text": "function model=rmInterpolate(view,model,params)\n% rmInterpolate - interpolate missing values across the Gray surface\n% that were not sampled with the coarse sampling\n%\n% model = rmInterpolate(view,model,params);\n%\n% 2007/03 SOD: wrote it.\n\nif notDefined('view'), error('Need view'); end;\nif notDefined('model'), error('Need model'); end;\nif notDefined('params'), error('Need params'); end;\n\nnumNeighbors = double(view.nodes(4,:));\nmyzeros = zeros(size(numNeighbors));\ngrayConMat = [];\n\nroiCoords = rmGet(params,'roiCoords');\nif ~isempty(roiCoords),\n % find the index' that cover the roi\n doROI = true;\n inROI = rmGet(params,'roiIndex');\n % coords with data within roi\n coarseIndex = rmCoarseSamples(roiCoords,params.analysis.coarseSample);\n withData = logical(myzeros);\n withData(inROI(coarseIndex)) = true;\n\n % coords without data within roi\n toInterp = logical(myzeros);\n toInterp(inROI(~coarseIndex)) = true;\nelse\n doROI = false;\n coarseIndex = rmCoarseSamples(viewGet(view,'coords'),params.analysis.coarseSample);\n % coords with data\n withData = coarseIndex;\n % coords without data\n toInterp = ~coarseIndex;\nend;\n\n% Sanity check: we only need interpolation if there are points to\n% interpolate, e.g. very small ROIs will not be coarsely sampled.\nif all(coarseIndex), % if all data points have estimates,\n return;\nend;\n\n\n% now we have to loop over models and parameters\n%rp = {'x','y','s','rss','rawrss','x02','y02','s2','rss2','rawrss2', 'exponent','sigmamajor','sigmaminor'};\nfor n=1:numel(model),\n if strcmp(model{n}.description,'radial oval 2D pRF fit (x,y,sigma_major,sigma_minor)')\n rp = {'x','y','rss','rawrss','x02','y02','rss2','rawrss2', 'exponent','sigmamajor','sigmaminor','theta'};\n else\n rp = {'x','y','s','rss','rawrss','x02','y02','s2','rss2','rawrss2', 'exponent'};\n end\n\n % reset for different models (should be the same i think)\n fulval = myzeros;\n for p=1:numel(rp),\n val = rmGet(model{n},rp{p});\n if ~isempty(val) && numel(val)==sum(coarseIndex),\n % put data in full datastructure and fill the rest with zeros\n if doROI,\n fulval(inROI(coarseIndex)) = double(val);\n else\n fulval(coarseIndex) = double(val);\n end;\n % now interpolate the data to some voxels without data\n %newval = myinterp(fulval,withData,toInterp,edges,numNeighbors,edgeOffsets);\n [newval grayConMat] = myinterp(fulval,withData,toInterp,view,grayConMat);\n % if roi we should store the roi voxels only otherwise store\n % the whole thing\n if doROI,\n model{n} = rmSet(model{n},rp{p},newval(inROI));\n else\n model{n} = rmSet(model{n},rp{p},newval);\n end;\n elseif ~isempty(val) && numel(val)==numel(fulval),\n model{n} = rmSet(model{n},rp{p},val);\n end; \n end;\n if isfield(model{n}, 'exponent') && ~isempty(model{n}.exponent) && ~strcmp(model{n}.description,'radial oval 2D pRF fit (x,y,sigma_major,sigma_minor)')\n model{n} = rmSet(model{n}, 's', model{n}.sigma.major .* sqrt(model{n}.exponent));\n end\nend;\n\n% separate loop for the betas, because they are saved in a different way\nfor n=1:numel(model),\n % reset for different models (should be the same i think)\n fulval = myzeros;\n val = double(rmGet(model{n},'b'));\n nBetas = size(val,3);\n newBeta = zeros(size(val,1),numel(coarseIndex),nBetas);\n\n for ii=1:nBetas,\n if doROI,\n fulval(inROI(coarseIndex)) = double(val(:,:,ii));\n else\n fulval(coarseIndex) = double(val(:,:,ii));\n end\n newval = myinterp(fulval,withData,toInterp,view,grayConMat);\n % if roi we should store the roi voxels only otherwise store\n % the whole thing\n if doROI,\n newBeta(:,:,ii) = newval(inROI);\n else\n newBeta(:,:,ii) = newval;\n end;\n end; \n model{n} = rmSet(model{n},'b',newBeta);\nend;\n\nreturn;\n%---------------------------------------\n\n\n%---------------------------------------\nfunction [val grayConMat] = myinterp(val,withData,toInterp,view,grayConMat)\n% actual interpolation function\n\nlzeros = false(size(withData));\ndoTouch = toInterp; % keep refining these estimates\noldtoInterp = toInterp; \nwhile (1),\n % 'smooth' data. Points without data are zero and do contribute to this\n % initial estimate:\n [tmp grayConMat] = dhkGraySmooth(view,val,[1 1],grayConMat);\n \n % Now check which surrounding points had data, 0=no data in\n % neighborhood, 1=all neighbors have data, intermediate is the weight\n % that should have been used to create the new estimate and will be\n % used to remove the contributions of no-data neighbors (0).\n c2 = dhkGraySmooth(view,double(withData),[1 1],grayConMat);\n \n % All point that we want to interpolate (doTouch) that have neighbors\n % with data and that thus will have a new estimate.\n toInterp = lzeros;\n toInterp(doTouch) = c2(doTouch)>0.001;\n\n % Compute new final values taking into account the number of points\n % that had data (c2)\n val(toInterp) = tmp(toInterp)./c2(toInterp);\n \n % update toInterp: find voxels that still need interpolating\n toInterp = (oldtoInterp-toInterp)>0;\n\n % sanity check: if no changes in toInterp than quit. Ideally\n % toInterp should go to zero but this does not have to be the\n % case if some voxels are not connected to voxels with data.\n if any(oldtoInterp-toInterp) || sum(toInterp)==0,\n break;\n else\n % 'grow' logical matrix that keeps track of which voxels have data\n withData = toInterp | withData;\n % update\n oldtoInterp = toInterp;\n end;\nend;\n\nreturn;\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/mrBOLD/Analysis/retinotopyModel/rmInterpolate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7217431943271998, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.34678221590040664}}
{"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 izakt\n%IZAKT\tUnit test for the function izak.\n\n%\tO. Lemoine - February 1996.\n\nN=256;\n\n% Perfect reconstruction\nsig=noisecg(N);\nDZT=zak(sig);\nsigr=izak(DZT);\nerrors=find(any(abs(sig-sigr)>sqrt(eps)));\nif length(errors)~=0,\n error('izak test 1 failed');\nend\n\nsig=noisecg(N);\nDZT=zak(sig,8,32);\nsigr=izak(DZT);\nerrors=find(any(abs(sig-sigr)>sqrt(eps)));\nif length(errors)~=0,\n error('izak test 2 failed');\nend\n\nsig=noisecg(N);\nDZT=zak(sig,128,2);\nsigr=izak(DZT);\nerrors=find(any(abs(sig-sigr)>sqrt(eps)));\nif length(errors)~=0,\n error('izak test 3 failed');\nend\n\n\nN=315;\n\n% Perfect reconstruction\nsig=noisecg(N);\nDZT=zak(sig);\nsigr=izak(DZT);\nerrors=find(any(abs(sig-sigr)>sqrt(eps)));\nif length(errors)~=0,\n error('izak test 4 failed');\nend\n\nsig=noisecg(N);\nDZT=zak(sig,9,35);\nsigr=izak(DZT);\nerrors=find(any(abs(sig-sigr)>sqrt(eps)));\nif length(errors)~=0,\n error('izak test 5 failed');\nend\n\nsig=noisecg(N);\nDZT=zak(sig,3,105);\nsigr=izak(DZT);\nerrors=find(any(abs(sig-sigr)>sqrt(eps)));\nif length(errors)~=0,\n error('izak test 6 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/izakt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3467699116908309}}
{"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% integrate_poisspdf.m\n% integrates a poisson pdf with respect to lambda from a to b\n%\n% 022300 tdr created\n% 030400 tdr replaced global variable approach to getting x and n to binopdf.\n% 030600 tdr added adjustments to a and b to help quad8 converge quickly.\n% \t\t\tquad8 has trouble with long stretches of near-zero values\n% \t\t\tso we try to bound the interval to avoid these regions\n% 031600 tdr created integrate_poisspdf.m from integrate_binopdf.m\n% 012901 tdr changed quad8 to quadl per MatLab 6 recommendation. Turned off warnings\n% for quadl call because it thinks intervals starting at zero or ending at one \n% involve singularities and generates a warning, although accuracy is okay.\n% 031501 tdr changed thres2 from 0.001 to 1.\n\nfunction y = integrate_poisspdf(x,a,b)\n\nif nargin ~= 3, \n error('Requires three input arguments (x,a,b)');\nend\n\nTRACE = 0;\nlambda_hat = x;\nthres = 1e-6*poisspdf_0ok(x,x); % pdf values less than this are assumed to be negligible.\nthres2 = 1; % resolution of adjustments to a and b.\ntiny_a = (poisspdf_0ok(x,a) < thres);\ntiny_b = (poisspdf_0ok(x,b) < thres);\n\nif tiny_a & tiny_b & (a > lambda_hat | b < lambda_hat),\n\t%both a and b give results near zero, with no non-zero values between them\n y = 0;\n return\nend;\n\n% defaults\nnew_a = a;\nnew_b = b;\n\nif tiny_a,\n\t% a needs to be increased, but not past b or lambda_hat\n\tll = a; ul = min(b, lambda_hat);\n while (abs(ll - ul) > thres2),\n \ttest = (ll + ul)/2;\n if poisspdf_0ok(x,test) < thres,\n \tll = test;\n else\n \tul = test;\n end;\n end;\n\tnew_a = ll; \nend;\n\nif tiny_b,\n\t% b needs to be decreased, but not past a or lambda_hat\n\tll = max(a, lambda_hat); ul = b;\n while (abs(ll - ul) > thres2),\n \ttest = (ll + ul)/2;\n if poisspdf_0ok(x,test) < thres,\n \tul = test;\n else\n \tll = test;\n end;\n end;\n\tnew_b = ul; \nend;\n\n% call quad with increased a\n% quadl thinks interval starting at zero or ending at one might involve \n% a singularity and produces a warning, despite being accurate.\nwarning off; \ny=quadl('poisspdf_of_lambda',new_a,new_b,[],TRACE,x);\nwarning on;\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/integrate_poisspdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3467699116908309}}
{"text": "function view=mrv_dilateCurrentROI(view,iterations)\n% function d=mrv_dilateCurrentROI(view)\n% PURPOSE: Dilates the current ROI in the Gray view.\n% HISTORY: 100704: ARW: Wrote it.\n% Note: Large numbers of iterations can result in long processing times.\nif (~exist('iterations','var'))\n iterations=1; \nend\nif ~(strcmp(view.viewType,'Gray') | strcmp(view.viewType,'Volume'))\n error('This routine requires you to be in the Gray view');\nend\n\nthisROI=view.ROIs(view.selectedROI);\nif(~isfield(view,'grayConMat') | isempty(view.grayConMat));\n disp('Computing connection matrix...');\n view.grayConMat = makeGrayConMat(view.nodes,view.edges,0);\nend\nthisROI.coords=mrv_dilateGrayROI(view,thisROI.coords,iterations);\nthisROI.name=[thisROI.name,'_dilated'];\nview=addROI(view,thisROI);\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/ROI/mrv_dilateCurrentROI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.34676990327161716}}
{"text": "function calcRigor( config )\n%RIGOR Summary of this function goes here\n% Detailed explanation goes here\n\nrigorconfig = config.rigor;\nparam = rigorconfig.params.param_set;\n\n%Check if image location exists or not.\n\nif(~exist(config.imageLocation, 'dir'))\n\tfprintf('Image Location does not exist. Please check path once again \\n');\n\treturn;\nend\n\nif(~exist(config.outputLocation, 'dir'))\n\tfprintf('Image Location does not exist. Please check path once again \\n');\n\treturn;\nend\n\n%Load All images in a particular folder\nimages = dir(config.imageLocation);\nimages = regexpi({images.name}, '.*jpg|.*jpeg|.*png|.*bmp', 'match');\nimages = [images{:}];\n\nfor i=1:length(images)\n imname = char(images(i));\n impath = fullfile(config.imageLocation, imname);\n whos impath\n im=imread(impath);\n fprintf('Calculating RIGOR for %s\\n', imname);\n proposals =calcrigorForIm(impath,rigorconfig); \n saveFile=[imname '.mat'];\n save([config.outputLocation saveFile], 'proposals');\nend\nend\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/rigor/API/calcrigor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.34676990327161716}}
{"text": "function tests = test_spm_get_lm\n% Unit Tests for spm_get_lm\n%__________________________________________________________________________\n% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging\n\n% $Id: test_spm_get_lm.m 6534 2015-08-24 16:02:56Z guillaume $\n\ntests = functiontests(localfunctions);\n\n\nfunction test_spm_get_lm_2D(testCase)\ndim = [5 5];\nvol = rand(dim(1),dim(2));\nsubvol = vol(2:4,2:4);\nvol(3,3) = max(subvol(:)) + 0.1;\n[X,Y] = ndgrid(1:dim(1),1:dim(2));\ngm = sub2ind(size(vol),3,3);\nidx = spm_get_lm(vol,[X(:)';Y(:)']);\ntestCase.verifyTrue(any(idx == gm));\n\n\nfunction test_spm_get_lm_3D(testCase)\ndim = [5 5 5];\nvol = rand(dim(1),dim(2),dim(3));\nsubvol = vol(2:4,2:4,2:4);\nvol(3,3,3) = max(subvol(:)) + 0.1;\n[X,Y,Z] = ndgrid(1:dim(1),1:dim(2),1:dim(3));\ngm = sub2ind(size(vol),3,3,3);\nidx = spm_get_lm(vol,[X(:)';Y(:)';Z(:)']);\ntestCase.verifyTrue(any(idx == gm));\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/tests/test_spm_get_lm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3467585374639343}}
{"text": "function VoigtSpectrGUI\n%this is a GUI program i wrote about simulating absorption lineshape and \n%spectrum from HITRAN output data \n% this program simulate the spectrum using the HITRAN data and \n% Calculating the Voigt porfile According to the paper: \n% Applied spectro. V58, 468(2004);\n% Phi= A*K(x,y) \n% The lineshape depends on Guassian (vD) width and Lorentzian width(vL). \n% Absorption depends on number density and absorption length, I/I0 = Exp(-aNL);\n% Notice the Half Width at Half Maxium for the vD and vL inputs;\n\n fh = figure('Visible','off','Name','Spectrum Simulation',...\n 'position',[50,50, 850, 600]);\n \n hax = axes('Units','pixels','Position',[60,60,500,500]);\n \n %construct the components\n hp = uipanel('Units','pixels','ShadowColor',[0.1,1,0.01],...\n 'Position',[628 160 200 430]);\n \n \n hpb1 = uicontrol('Style','pushbutton','String','Open HITRFile',...\n 'Foregroundcolor',[1 0.1 0.2],'FontWeight','bold',...\n 'Position',[650 540, 110, 30],'Callback',{@fileopen_Callback});\n \n het1 = uicontrol('Style','edit','String','file name',...\n 'Foregroundcolor',[0.2 0.4 0.1],'FontWeight','bold',...\n 'Position',[650,510,110,30],'Callback',{@edittext_Callback});\n \n hst1 = uicontrol('Style','text', 'String','HWHM[vD vL]/cm-1',...\n 'Foregroundcolor',[0.2 0.3 0.3],'FontWeight','bold',...\n 'Backgroundcolor',[0.7 0.98 0.98],...\n 'Position', [650 470 160 15]);\n \n het2 = uicontrol('Style','edit', 'String','0.003',...\n 'Foregroundcolor',[0.30 0.1 1],'FontWeight','bold',...\n 'Backgroundcolor',[0.97842 0.98 1],...\n 'Position', [650 445 75 20]); \n \n het3 = uicontrol('Style','edit', 'String','0.006',...\n 'Foregroundcolor',[0.30 0.1 1],'FontWeight','bold',...\n 'Backgroundcolor',[1 0.99 1],...\n 'Position', [735 445 75 20]); \n\n \n hst2 = uicontrol('Style','text', 'String','NumDensity/Lightpath/cm',...\n 'Foregroundcolor',[0.2 0.3 0.3],'FontWeight','bold',...\n 'Backgroundcolor',[0.7 0.98 1],...\n 'Position', [650 410 160 15]);\n \n het4 = uicontrol('Style','edit', 'String','1E+10',...\n 'Foregroundcolor',[0.30 0.1 1],'FontWeight','bold',...\n 'Backgroundcolor',[0.97842 0.98 1],...\n 'Position', [650 385 75 20]); \n \n het5 = uicontrol('Style','edit', 'String','1E+5',...\n 'Foregroundcolor',[0.30 0.1 1],'FontWeight','bold',...\n 'Backgroundcolor',[1 0.99 1],...\n 'Position', [735 385 75 20]); \n \n hpb2 = uicontrol('Style','pushbutton','String','Simu-LineShape',... \n 'Foregroundcolor',[1 0.1 0.2],'FontWeight','bold',...\n 'Position',[650 340, 110, 30],'Callback',{@SimuLS_Callback}); \n \n het6 = uicontrol('Style','edit', 'String','VoigtWidth',...\n 'Foregroundcolor',[0.30 0.1 1],'FontWeight','bold',...\n 'Backgroundcolor',[0.4 0.9 0.7],...\n 'Position', [735 315 75 20]); \n \n hpb3 = uicontrol('Style','pushbutton','String','Simu-Absorption',... \n 'Foregroundcolor',[1 0.1 0.2],'FontWeight','bold',...\n 'Position',[650 280, 110, 30],'Callback',{@SimuAp_Callback}); \n \n hpb4 = uicontrol('Style','pushbutton','String','Open ExpSpec',... \n 'Foregroundcolor',[1 0.1 0.2],'FontWeight','bold',...\n 'Position',[650 240, 110, 30],'Callback',{@ExpSpectr_Callback});\n \n \n hst4 = uicontrol('Style','text', 'String','Display Options',... \n 'Backgroundcolor',[0.678402 0.98 1],...\n 'Foregroundcolor',[0.2 0.3 0.3],'FontWeight','bold',...\n 'Position',[650 210 130 15]); \n\n\n hpm = uicontrol('Style','popupmenu',...\n 'String',{'LineShape','Absorption','CombinedPlot'},...\n 'Foregroundcolor',[0.99 0.01 0.01],'FontWeight','bold',...\n 'Value',1,'Position',[690 170 110 30],'Callback',{@popup_Callback}); \n \n \n hp2 = uipanel('Units','pixels','ShadowColor',[0.1 0.1 1],...\n 'Position',[628 40 200 100]); \n \n \n het7 = uicontrol('Style','edit','String','FileName.dat',...\n 'Foregroundcolor',[0.2 0.4 0.1],'FontWeight','bold',...\n 'Position',[640,105,90,25]); \n \n hcb1 = uicontrol('Style','checkbox','String','Line Shape',...\n 'Position',[655 75 85 25],'Foregroundcolor',[0.2 0.3 0.9]);\n hcb2 = uicontrol('Style','checkbox','String','Absorption',...\n 'Position',[655 50 85 25],'Foregroundcolor',[0.2 0.3 0.9]);\n \n hpb5 = uicontrol('Style','pushbutton','String','Save',... \n 'Foregroundcolor',[0.6 0.2 0.3],'FontWeight','bold',...\n 'Position',[750 66, 60, 50],'Callback',{@save_Callback});\n \n % to align the controls\n align([hp,het1,het6,hpb1,hpb2,hpb3,hpb4,hst1,hst2,hst4,hpm,hp2],'Center','None');\n\n % Initialize the GUI.\n % Change units to normalized so components resize automatically.\n set([hp,het1,het2,het3,het4,het5,het6,het7,hpb1,hpb2,hax,hst1,hst2,...\n hst4,hpm,hpb3,hpb4,hp2,hcb1,hcb2,hpb5],'Units','normalized');\n \n %make figure visible.\n set(fh, 'Visible','on');\n set(fh, 'NumberTitle','off')%% supress the NumverTitle\n \n % define some variables\n format long e ; %% define numerical format\n stp=0.0002; %% calculation(convolution) stepsize \n Dd = 0.5; %% define the edge extended beyond the spectrum region\n Nd = 1E+10; %% Number density\n L = 1E+5; %% Optical path length cm\n \n gL = 0.001; %% in cm -1, pressure broadening cofffient at 50 torr.\n gD = 0.003; %% 0.0032 doppler broadening in cm-1\n SgmvTot= zeros(1,10); %% initiate the arrays\n expx = zeros(1,10); \n expy = zeros(1,10);\n A = zeros(1,10);\n dtfl = zeros(1,10);\n grd = zeros(1,10); %% default grid\n \n %%file open callback\n function fileopen_Callback(source,eventdata)\n % **********uiputfile for open the save file dialog*********\n \n [flnm, flpth] = uigetfile({'*.out','All Files' },...\n 'Select HITRAN outputfile','fl.out');\n %specify application data, so it can be used by other objects;\n % setappdata(h,'name',value) \n setappdata(hpb1,'fname',flnm);\n \n set(het1, 'String',flnm);\n % set the edit text box value.\n \n end\n \n % read in the HITRAN data and simulate Line Shape spectrum\n function SimuLS_Callback(source, eventdata)%callback is just a regular func\n \n format long e ;\n % get the value of specified data\n % value = getappdata(h,name)\n % values = getappdata(h)\n flnm = getappdata(hpb1,'fname');\n \n fid = fopen(flnm);\n C = textscan(fid,...\n '%d%f%f%u%f%f%f%f %d%d%d%d%d %d%d%d%d %d%d%d%d %d%d%d%d%d%d%d%d%d%d%d%d%d ');\n fclose(fid); %% returned C is a cell \n \n N = length(C{2}); %% Number of lines/ Cell length\n %% define a grid\n rangeL= -Dd + min(C{2}); %% spectrum region: First line minus 1 cm-1\n rangeH = Dd + max(C{2}); %% Last line position + 1 cm-1\n grd=[rangeL:stp:rangeH]; %% define the grid\n \n v = grd;\n gD = str2num(get(het2, 'string'));\n gL = str2num(get(het3, 'string'));\n gV = 0.5346*gL + sqrt(0.2166*gL^2 + gD^2); %% Voigt profile half width\n x = gL/gV;\n SgmvTot = 0;\n \n for i=1:N %% calculate the line shape for each peak\n \n v0(i) = C{2}(i);\n S(i) = C{3}(i);\n y = abs(v-v0(i))/gV;\n Sgmv0(i) = S(i)/(2*gV*(1.065 + 0.447*x + 0.058*x^2));\n Sgmv = Sgmv0(i)*((1-x)*exp(-0.693.*y.^2) + (x./(1+y.^2)) + ...\n 0.016*(1-x)*x*(exp(-0.0841.*y.^2.25)-1./(1 + 0.021.*y.^2.25)));\n \n SgmvTot = SgmvTot + Sgmv; \n \n end\n\n plot(grd,SgmvTot,'-b.');\n xlabel('WaveLength in cm-1');\n ylabel('Effective absorption Cross Section in cm2');\n \n set(hpm, 'Value',1)% change the popup menu settings;\n \n %% display the Voigt width;\n strg = sprintf('gV= %1.4f',gV);\n set(het6,'string',strg);\n set(het6,'Backgroundcolor',[0.9 0.9 0.9])\n\n %%figure, plot(v,A);\n %%ylabel('Absorption')\n end\n \n\n function SimuAp_Callback(source, eventdata) \n %% calculate absorption\n \n Nd = str2num(get(het4, 'string')); %% Number density in molecule/cm3\n L = str2num(get(het5, 'string')); %% effective length path in cm\n A = 1 - exp(-SgmvTot.*Nd*L); %% I/I0 = Exp(-aNL);\n \n plot(grd,A,'-m');\n xlabel('WaveLength in cm-1'); \n set(hpm, 'Value',2)% change the popup menu settings;\n \n end\n\n\n %slice X callback\n function ExpSpectr_Callback(source, eventdata)\n \n format long e ;\n [flnm, flpth] = uigetfile({'*.dat','All Files' },'Select Exp. file','ExpSpectr.dat');\n fid = fopen(flnm, 'r');\n a = fscanf(fid, '%f %f', [2 inf]); % It has two rows now.\n a = a';\n fclose(fid)\n expx = a(:,1);\n expy = a(:,2);\n hold on;\n plot3 = plot(expx,expy,'-.b');\n ylabel('Absorption')\n \n hold off;\n \n end\n\n\n %popup menu callback\n function popup_Callback(source,eventdata)\n str = get(source, 'String');\n val = get(hpm, 'Value'); %use either function handle 'hpm' or 'source';\n % the string of popup menu is a cell array {}, cell{num} returns num th\n % element of the cell.\n switch val\n case 1 %'showImage' \n %disp(str{val});\n hold off;\n plot(grd,SgmvTot,'-b.');\n xlabel('WaveLength in cm-1')\n ylabel('Effective absorption Cross Section in cm2')\n \n case 2 \n hold off;\n plot(grd,A,'-m');\n \n case 3 %combined plot\n hold on;\n plot(expx,expy,'-.b');\n ylabel('Absorption')\n \n hold off;\n \n end\n end\n \n\n function save_Callback(source, eventdata)\n \n if get(hcb1,'Value')> 0.9 % it should be 1.0 \n dtfl = [grd;SgmvTot]; %% create a data matrix for data saving\n fid = fopen(get(het7, 'string'), 'wt');\n fprintf(fid, '%6.4f %e\\n', dtfl); %% set the data format\n fclose(fid);\n \n end\n \n if get(hcb2,'Value')> 0.9 % it should be 1.0 \n \n dtfl = [grd;A]; %% create a data matrix for data saving\n fid = fopen(get(het7, 'string'), 'wt');\n fprintf(fid, '%6.4f %5.6f\\n', dtfl); %% set the data format\n fclose(fid); \n end \n \n if get(hcb1,'Value')> 0.9 && get(hcb2,'Value')> 0.9 % it should be 1.0 \n \n dtfl = [grd;SgmvTot;A]; %% create a data matrix for data saving\n \n fid = fopen(get(het7, 'string'), 'wt');\n fprintf(fid, '%6.4f %e %5.6f\\n', dtfl); %% set the data format\n fclose(fid);\n \n end\n end\n\n%%% read in the HITRAN file to obtain line positions and intensities.\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/26707-voigt-lineshape-spectrum-simulation-gui/VoigtSpectrGUI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.5506073655352403, "lm_q1q2_score": 0.3467585298119605}}
{"text": "function x = cs_reach(L,b) %#ok\n%CS_REACH non-recursive reach (interface to CSparse cs_reach)\n% find nonzero pattern of x=L\\sparse(b). L must be sparse, real, and lower\n% triangular. b must be a real sparse vector.\n%\n% Example:\n% x = cs_reach(L,b)\n% See also: cs_demo\n\n% Copyright 2006-2007, Timothy A. Davis.\n% http://www.cise.ufl.edu/research/sparse\n\nerror ('cs_reach mexFunction not found') ;\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/CXSparse/MATLAB/Test/cs_reach.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.3467084399388914}}
{"text": "function h = cbarDraw(cbar, parent);\n%\n% h = cbarDraw(cbar, [parent=gca]);\n%\n% Render a color bar, according to the settings specified in the cbar\n% struct.\n%\n% These color bars differ from the built-in matlab color bar tools in a few\n% basic respects:\n%\n% * They draw colorbars based on any colormap the user inputs, rather\n% than the color map assigned to the current figure. This is useful for\n% illustrating color codes on true color images, or images with overlaid \n% responses (like fMRI activation maps)\n%\n% * In addition to being able to render vertical and horizontal color bars, \n% these tools may also render 'color wheel' colorbars, showing e.g. polar\n% angle. Other possible renderings (like rings) may be added down the\n% line.\n%\n% cbar is a struct with the following fields:\n%\n% cmap: color map (nColors x 3) for the color bar. (Columns ar [R G B],\n% from 0-255).\n%\n% nColors: # of colors to use in the cmap. \n%\n% clim: color limits (aka 'clip mode'), which determines primarily\n% the labeling of the color bar. Can be set to 'auto', in which case\n% the labeling will be from 1:nColors. Otherwise, will label according to\n% the clim values (format is [min max]).\n%\n% colorWheel: use a color wheel instead of a bar (e.g., to show polar\n% angle for a polar angle map). \n%\n% colorWheelStart: degrees clockwise from 12-o-clock which map to beginning of\n% color map.\n%\n% colorWheelDirection: direction of the color wheel. Can be: \n% 1 or 'clockwise' (equivalent); or, 2 or 'counterclockwise' (equiv.)\n%\n% colorWheelExtent: degrees (1 - 360) subtended by the color map, for polar\n% angle maps.\n%\n% ras, 08/2006\nif ~exist('cbar', 'var') | isempty(cbar), cbar = cbarDefault; end\nif ~exist('parent', 'var') | isempty(parent), parent = gca; end\n\nif cbar.colorWheel==1\n % draw a color wheel\n if isequal(lower(cbar.colorWheelDirection), 'clockwise')\n direction = 0;\n else \n direction = 1; \n end\n startAngle = cbar.colorWheelStart;\n\tcmap = cbar.cmap;\t\n\tp.doPlot = 0; p.trueColor = 1; p.background = get(gcf, 'Color');\n\tp.visualField = 'b'; % 'both' fields in cmapWedge \n\th = image(cmapWedge(cmap, startAngle, direction, p), 'Parent', parent);\n axis(parent, 'image'); axis(parent, 'off');\n \n% AX = axis;\n% xText = AX(2) + .1*(AX(2)-AX(1));\n% yText = AX(3) + .5*(AX(4)-AX(3));\n% text(xText, yText, cbar.label, 'Parent', parent);\n \n% % correct funky aspect ratios (gum):\n% pos = get(parent, 'Position');\n% aspectRatio = pos(3) / pos(4);\n% if aspectRatio > 4 | aspectRatio < 1/4\n% set(parent, 'Position', [pos(1) 0 pos(3) 1]);\n% end\n\n \nelseif isequal(cbar.direction, 'horiz');\n % draw a horizontal bar\n if isequal(cbar.clim, 'auto') | isempty(cbar.clim)\n clim = [1 cbar.nColors];\n else\n clim = cbar.clim;\n end\n img = ind2rgb(1:cbar.nColors, cbar.cmap);\n\t\n\t% show the image\n\t% (The Y values maintain an aspect ratio of 35:1)\n\taspRatio = 1/15;\n h = image(clim, clim ./ aspRatio, img, 'Parent', parent);\n\t\n% \taxis(parent, 'image'); \n% \taxis(parent, [clim clim .* aspRatio]);\n set(parent, 'YTick', []);\n cbar.label(cbar.label=='_') = '-';\n xlabel(parent, cbar.label, 'FontSize', cbar.fontsz, ...\n\t\t 'FontName', cbar.font, 'Interpreter', 'none');\n \nelse\n % draw a vertical bar\n if isequal(cbar.clim, 'auto')\n clim = [1 cbar.nColors];\n else\n clim = cbar.clim;\n\tend\n img = ind2rgb([cbar.nColors:-1:1]', cbar.cmap);\n\n\t% show the image\n\t% (The X values maintain an aspect ratio of 15:1)\n\taspRatio = 1/15;\n\th = image(clim ./ 20, fliplr(clim), img, 'Parent', parent);\n\t\n% \taxis(parent, 'image'); \n\taxis(parent, [clim .* aspRatio, clim]);\n set(parent, 'XTick', [], 'Ydir', 'normal');\n\tif checkfields(cbar, 'labelSide') & cbar.labelSide==1\n\t\tset(parent, 'YAxisLocation', 'right');\n\tend\n cbar.label(cbar.label=='_') = '-';\n ylabel(parent, cbar.label, 'FontSize', cbar.fontsz, ...\n\t\t\t'FontName', cbar.font, 'Interpreter', 'none');\n \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/mrBOLD/Colormap/cbarDraw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.34670843128633866}}
{"text": "% mlf2pdf_ex is an example for how to use mlf2pdf.\n% It creates two buttons (Exit and PDF), which you may use either to exit the\n% script or to create the pdf file from the current figure. So you can edit\n% the plot \"online\" and create the pdf from the figure the way it is. \n\nfunction mlf2pdf_ex\n\nfpl=figure('units','centimeters',...%plotfigure\n 'Position',[10 10 10 5]); % position: [llx lly width height]\nf=figure('units','centimeters','Position',[5 10 2 2]); %Buttons\nuicontrol(f,'Style','pushbutton','String','-> PDF',...\n 'Units','normalized','Pos',[0 0 1 .5],'Callback',@callback_mlf2pdf);\nuicontrol(f,'Style','pushbutton','String','Exit',...\n 'Units','normalized','Pos',[0 0.5 1 .5],'Callback','close all');\nfigure(fpl); %activate plot figure\n\n\nfilename='yourfilename'; %enter your filename here\nyourplot; %place your plot commands here\n\n\n function callback_mlf2pdf(dummy1,dummy2)\n mlf2pdf(fpl,filename,'SIUnits');\n end\n\n function yourplot\n X=0:pi/10:2*pi;\n Y=sin(X);\n plot(X,Y);\n axis([0,2*pi,-1.5,1.5]);\n grid on;\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/28545-matlabfrag-to-pdf/mlf2pdf_ex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.3467084226337856}}
{"text": "function cS = magnetite\n\n%\ncs_Mag = crystalSymmetry('m3m');\nN = Miller({1,0,0},{1,1,1},cs_Mag);\ndist = [0.95, 1];\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/magnetite.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7520125737597971, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.3466904147571071}}
{"text": "function errMsg = validateNumber(x, numberName, lb, ub, isInt, prevErrMsgs, enteredStr)\n%validateNumber Summary of this function goes here\n% Detailed explanation goes here\n \n errMsg=prevErrMsgs;\n if(not(isnumeric(x)) || isnan(x))\n enteredStr = ['(Entered: ', enteredStr, ')'];\n errMsg{end+1} = [numberName, ' must be numeric. ', enteredStr];\n return;\n end\n \n enteredStr = ['(Entered: ', num2str(x), ')'];\n\n if(isInt==true)\n if(not(ceil(x) == floor(x)))\n errMsg{end+1} = [numberName, ' must be an integer. ', enteredStr];\n end\n end\n \n if(xub)\n rngStr = ['[',num2str(lb), ', ', num2str(ub) ,']'];\n errMsg{end+1} = [numberName, ' must be within the range ', rngStr, '. ', enteredStr];\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/validation/validateNumber.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.3466676140687354}}
{"text": "function out = mtimes(a,b,varargin)\n% outer quaternion multiplication\n%\n% Syntax\n% out = a * b\n% out = a * v\n%\n% Input\n% a - @SO3Grid\n% b - @quaternion \n% v - @vector3d\n%\n% Output\n% out - @SO3Grid / @vector3d\n\nif isa(a,'SO3Grid') % right multiplication\n \n if isa(b,'SO3Grid'), b = orientation(b); end\n \n out = orientation(a) * b;\n \nelseif isa(a,'quaternion') \n \n if length(a) == 1 % rotate center only\n \n r = mtimes@orientation(a,b);\n out = b;\n out.a = r.a;\n out.b = r.b;\n out.c = r.c;\n out.d = r.d;\n out.i = r.i;\n if isempty(b.center)\n out.center = a;\n else\n out.center = a * out.center;\n end\n \n else\n \n out = a * orientation(b);\n \n end\n \nelse\n error('type mismatch!')\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/@SO3Grid/mtimes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.8354835534888481, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.346641162024706}}
{"text": "function test_suite = test_isLeftOriented\n% One-line description here, please.\n% output = test_isLeftOriented(input)\n%\n% Example\n% test_isLeftOriented\n%\n% See also\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2009-04-22, using Matlab 7.7.0.471 (R2008b)\n% Copyright 2009 INRA - Cepia Software Platform.\n\ntest_suite = functiontests(localfunctions); \n\nfunction test_HorizLeft(testCase) %#ok<*DEFNU>\n\nline = [10 20 3 0];\np1 = [15 25];\n\ntestCase.assertTrue(isLeftOriented(p1, line));\n\n\nfunction test_HorizRight(testCase) %#ok<*DEFNU>\n\nline = [10 20 3 0];\np1 = [15 5];\n\ntestCase.assertFalse(isLeftOriented(p1, line));\n\n\nfunction test_PointArray(testCase) %#ok<*DEFNU>\n\n% one line, three points\nline = [10 20 3 0];\npts = [15 25; 15 15; 15 05];\n\n% expect 3-by-1 array\nexp = [true; false; false];\ntestCase.assertEqual(exp, isLeftOriented(pts, line));\n\n\nfunction test_LineArray(testCase)\n\n% four lines, one point\nlines = [....\n 10 10 3 0; ... % left\n 10 10 0 3; ... % right\n 10 10 1.5 1.5; ... % left\n 10 10 1.5 -1.5; ... % left\n]; \npt = [21.1 32.2];\n\n% expect 1-by-4 array\nexp = [true false true true];\n\ntestCase.assertEqual(exp, isLeftOriented(pt, lines));\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_isLeftOriented.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.3466190438589708}}
{"text": "function [i] = plotgp(i, t, sys, y, std)\n% Function plots results of simulation or one-step-ahead\n% prediction. \n%\n%% Syntax\n% [i] = plotgp(i, t, sys, y, std);\n%\n%% Description\n% In the upper 2/3 of the figure the output together with 95%\n% confidence band and target is plotted, in the lower third of the figure\n% the error with corresponding 95% confidence band is plotted. Can be used\n% to plot in new or currently active figure. \n%\n% Input: \n% * i ... the figure handle, if i==0 function plots in current figure \n% * t ... the time vector (x-axis) \n% * sys ... the target output \n% * y ... the predicted output \n% * std ... the predicted standard deviation \n% \n% Output: \n% * i ... the figure handle \n%\n% See Also:\n% plotgpy, plotgpe\n%\n% Examples:\n% demo_example_gp_simulation.m\n%\n%%\n% * Written by Dejan Petelin\n\n% check sizes of vectors \nsz = size(t);\nif((size(t,1)~=sz(1) | size(sys,1)~=sz(1) |size(y,1)~=sz(1) | size(std,1)~=sz(1))...\n | (size(t,2)~=sz(2) | size(sys,2)~=sz(2) |size(y,2)~=sz(2) | size(std,2)~=sz(2)))\n warning(['figure ', num2str(i), ': vectors: t, tt, y, std must be same size']);\n disp(strcat(['t: ', num2str(size(t))])); \n disp(strcat(['sys: ', num2str(size(sys))])); \n disp(strcat(['y: ', num2str(size(y))])); \n disp(strcat(['std: ', num2str(size(std))])); \n out = -1; \n return; \nend\n\nix_plot = 1:length(t); \n% reduce vector if borders are wanted in figure, \n% e.g. ixplot = 2:length(t)-1;\n\nxfill = [t(ix_plot); flipdim(t(ix_plot),1)]; \nyfill = [y(ix_plot)+2*std(ix_plot);flipdim(y(ix_plot)-2*std(ix_plot),1)]; \n\n\n% if i==0 use current axis (figure) \nif (i~=0)\nfigure(i);\nend \n\n% upper part of figure: y \nsubplot(3,1,1:2)\nfill(xfill, yfill, [7 7 7]/8, 'EdgeColor', [0 0 0]/8);\nhold on \nplot(t,y, 'k-', 'LineWidth',1); \nplot(t,sys, 'k--', 'LineWidth',2); \n\nhold off \ngrid on \nxlabel('t'); \nylabel('y'); \ntitle('GP model simulation')\nlegend('\\mu \\pm 2\\sigma', '\\mu', 'system','Location','NorthEast'); \nAX=axis; \nAX(1:2)=[t(1) t(end)]; \naxis(AX); \n\n% lower part of figure: e \nsubplot(3,1,3)\nxfill = [t(ix_plot); flipdim(t(ix_plot),1)]; \nyfill = [2*std(ix_plot);zeros(size(std(ix_plot)))]; \nfill(xfill, yfill, [7 7 7]/8, 'EdgeColor', [0 0 0]/8);\n\nhold on \nplot(t,abs(y-sys), 'k-', 'LineWidth',1); \nhold off \nlegend('2\\sigma', '|e|', 'Location','NorthEast'); \ngrid \nxlabel('t'); \nylabel('e'); \nAX=axis; \nAX(1:2)=[t(1) t(end)]; \naxis(AX); \n\n\n\nreturn \n\n\n\n\n\n\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-utilities/plotgp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953797290152, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3466060044399067}}
{"text": "function jac = autoJac(fun,x0,varargin)\n%AUTOJAC Returns a Automatically Differentiated (AD) Jacobian\n% \n% jac = autoJac(fun,x0) uses the user supplied Matlab function to\n% generate the Jacobian using automatic differentiation. The user\n% function must be a Matlab function and must not call external code or\n% class / toolbox functions. If your function breaks any of these\n% conditions consider using mklJac instead.\n%\n% The underlying AD algorithm is adiff by William McIlhagga and its\n% documentation pdf is provided in the Differentiation folder. See the\n% BSD license below the code.\n\n% Copyright (C) 2011 Jonathan Currie (I2C2)\n\nif(~isa(fun,'function_handle'))\n error('Fun should be a function handle!');\nend\n\n[~,jac] = adiffget(fun(adiff(x0),varargin{:}));\n\nend\n\n% Copyright (c) 2010, William McIlhagga\n% All rights reserved.\n% \n% Redistribution and use in source and binary forms, with or without \n% modification, are permitted provided that the following conditions are \n% met:\n% \n% * Redistributions of source code must retain the above copyright \n% notice, this list of conditions and the following disclaimer.\n% * Redistributions in binary form must reproduce the above copyright \n% notice, this list of conditions and the following disclaimer in \n% the documentation and/or other materials provided with the distribution\n% \n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE \n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE \n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS \n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN \n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE \n% POSSIBILITY OF SUCH DAMAGE.\n", "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/autoJac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.34660600397108476}}
{"text": "report_this_filefun(mfilename('fullpath'));\n\nfigure\n\n[xx,yy]=meshgrid(vlon,vlat);\nsurfl(yy,xx,tmap/1000),shading interp;\n\nli = light('Position',[ 0 0 100],'Style','infinite');\nmaterial shiny\nlighting gouraud\n% axis([ min(vlat) max(vlat) min(vlon) max(vlon) ]);\n\nset(gca,'FontSize',12,'FontWeight','bold',...\n 'LineWidth',1.5,...\n 'Box','on','SortMethod','childorder','TickDir','out')\naxis ij\nview([ -90 90])\ncolormap(gray)\n\nset(gca,'Ylim',[min(vlon) max(vlon)]);\nset(gca,'Xlim',[min(vlat) max(vlat)]);\n\nhold on\n\n%pl = plot3(a.Latitude,a.Longitude,a.Longitude*0+6000,'or');\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/nicetomap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3466059957112453}}
{"text": "classdef NodalFieldPlotter < handle\n \n properties (Access = private)\n mesh\n field\n end\n \n methods (Access = public)\n \n function obj = NodalFieldPlotter(cParams)\n obj.init(cParams)\n end\n \n function plot(obj)\n x = obj.mesh.coord(:,1);\n y = obj.mesh.coord(:,2);\n z = obj.field;\n %figure()\n trisurf(obj.mesh.connec,x,y,z)\n view(0,90)\n colorbar\n end\n \n end\n \n methods (Access = private)\n \n function init(obj,cParams)\n obj.mesh = cParams.mesh;\n obj.field = cParams.field;\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/NodalFieldPlotter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.34660599571124523}}
{"text": "function out = ConvertToCursor(i)\n\n% Converts an RGB image to a matlab compatiable cursor CData.\n%\n% White Pixels and black pixels will be kept. All other values\n% will be converted to NaN (transparent)\n%\n% Author: Richard Medlock. (2003)\n\nnRows = size(i,1);\nnCols = size(i,2);\n\nfor r = 1:nRows\n \n for c = 1:nCols\n \n if i(r,c,1) == 255 & i(r,c,2) == 255 & i(r,c,3) == 255 % White\n \n out(r,c) = 2;\n \n elseif i(r,c,1) == 0 & i(r,c,2) == 0 & i(r,c,3) == 0 % Black\n \n out(r,c) = 1;\n \n else % Any other colour\n \n out(r,c) = NaN; \n \n end\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/3328-convert-to-cursor/ConvertToCursor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6001883592602049, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.3466059957112451}}
{"text": "%% dbDivision.m\n% This script randomly divides database into 3 parts - training (TRN),\n% validating (VAL) and testing (TST).\n% \n% 16-07-10 Michal Uricar\n% 21-03-12 Michal Uricar, LFW annotation in one file\n\nclearvars; close all;\n\n%% Timestamp\n\nfprintf(1,'Started on %s\\n\\n', datestr(now));\n\n%% Load pruned database\n\naddpath('./Functions');\n\n% load('./MAT/eyefd_on_lfw_pruned.mat');\nload('./MAT/db_good.mat');\n\ntmp_as = annotation_struct;\n\nN = annotation_struct.N;\n\nper60 = round(60/100*N);\nper20 = round(20/100*N);\n\ntic\nindices_perm = randperm(N);\ntoc\n\n% 60% of images will form training set\ntraining = indices_perm(1:per60); indices = training;\nindices_perm(1:per60) = []; \n% save training set\n%image = tmp_image(training);\nannotation_struct.bbox = tmp_as.bbox(training, :);\nannotation_struct.names = tmp_as.names(training);\nannotation_struct.eye_r = tmp_as.eye_r(training, :);\nannotation_struct.eye_l = tmp_as.eye_l(training, :);\nannotation_struct.canthus_rr = tmp_as.canthus_rr(training, :);\nannotation_struct.canthus_rl = tmp_as.canthus_rl(training, :);\nannotation_struct.canthus_lr = tmp_as.canthus_lr(training, :);\nannotation_struct.canthus_ll = tmp_as.canthus_ll(training, :);\nannotation_struct.mouth = tmp_as.mouth(training, :);\nannotation_struct.mouth_corner_r = tmp_as.mouth_corner_r(training, :);\nannotation_struct.mouth_corner_l = tmp_as.mouth_corner_l(training, :);\nannotation_struct.nose = tmp_as.nose(training, :);\nannotation_struct.N = numel(annotation_struct.names);\n\n% save('./MAT/training.mat', 'image');\nsave('./MAT/TRN.mat', 'annotation_struct', 'indices');\n\n% 20% of images will form validating set\nvalidating = indices_perm(1:per20); indices = validating;\nindices_perm(1:per20) = [];\n% save validating set\n% image = tmp_image(validating);\nannotation_struct.bbox = tmp_as.bbox(validating, :);\nannotation_struct.names = tmp_as.names(validating);\nannotation_struct.eye_r = tmp_as.eye_r(validating, :);\nannotation_struct.eye_l = tmp_as.eye_l(validating, :);\nannotation_struct.canthus_rr = tmp_as.canthus_rr(validating, :);\nannotation_struct.canthus_rl = tmp_as.canthus_rl(validating, :);\nannotation_struct.canthus_lr = tmp_as.canthus_lr(validating, :);\nannotation_struct.canthus_ll = tmp_as.canthus_ll(validating, :);\nannotation_struct.mouth = tmp_as.mouth(validating, :);\nannotation_struct.mouth_corner_r = tmp_as.mouth_corner_r(validating, :);\nannotation_struct.mouth_corner_l = tmp_as.mouth_corner_l(validating, :);\nannotation_struct.nose = tmp_as.nose(validating, :);\nannotation_struct.N = numel(annotation_struct.names);\n% save('./MAT/validating.mat', 'image');\nsave('./MAT/VAL.mat', 'annotation_struct', 'indices');\n\n% 20% (the rest) of images will form testing set\ntesting = indices_perm; indices = testing;\n% save testing set\n% image = tmp_image(testing);\nannotation_struct.bbox = tmp_as.bbox(testing, :);\nannotation_struct.names = tmp_as.names(testing);\nannotation_struct.eye_r = tmp_as.eye_r(testing, :);\nannotation_struct.eye_l = tmp_as.eye_l(testing, :);\nannotation_struct.canthus_rr = tmp_as.canthus_rr(testing, :);\nannotation_struct.canthus_rl = tmp_as.canthus_rl(testing, :);\nannotation_struct.canthus_lr = tmp_as.canthus_lr(testing, :);\nannotation_struct.canthus_ll = tmp_as.canthus_ll(testing, :);\nannotation_struct.mouth = tmp_as.mouth(testing, :);\nannotation_struct.mouth_corner_r = tmp_as.mouth_corner_r(testing, :);\nannotation_struct.mouth_corner_l = tmp_as.mouth_corner_l(testing, :);\nannotation_struct.nose = tmp_as.nose(testing, :);\nannotation_struct.N = numel(annotation_struct.names);\n% save('./MAT/testing.mat', 'image');\nsave('./MAT/TST.mat', 'annotation_struct', 'indices');\n\n%% Timestamp\n\nfprintf(1,'Finished on %s\\n\\n', datestr(now));", "meta": {"author": "uricamic", "repo": "flandmark", "sha": "ecf122f93f73504fe7d8faccca525c6b1e98fdcd", "save_path": "github-repos/MATLAB/uricamic-flandmark", "path": "github-repos/MATLAB/uricamic-flandmark/flandmark-ecf122f93f73504fe7d8faccca525c6b1e98fdcd/learning/code/dbDivision.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3465371412493564}}
{"text": "% cart2topo() - convert xyz-cartesian channel coordinates \n% to polar topoplot() coordinates. Input data\n% are points on a sphere centered at (0,0,0)\n% or at optional input 'center'. This function\n% is now DEPRECATED! See Important warning below.\n%\n% Usage: >> [th r] = cart2topo(xyz); % 3-column [x y z] position data\n% >> [th r] = cart2topo(x,y,z); % separate x,y,z vectors\n% >> [th r x y z] = cart2topo(xyz,'key', 'val', ...); \n% >> [th r x y z] = cart2topo(x,y,z,'key', 'val', ...); \n%\n% Optional inputs:\n% 'center' = [X Y Z] use a known sphere center {Default: [0 0 0]}\n% 'squeeze' = plotting squeeze factor (0[default]->1). -1 -> optimize\n% the squeeze factor automatically so that maximum radius is 0.5. \n% 'optim' = [0|1] find the best-fitting sphere center minimizing the\n% standard deviation of the radius values.\n% 'gui' = ['on'|'off'] pops up a gui for optional arguments. \n% Default is off.\n%\n% Example: >> [th r] = cart2topo(xyz,[1 0 4]);\n%\n% Notes: topoplot() does not plot channels with radius>0.5\n% Shrink radii to within this range to plot all channels.\n% [x y z] are returned after the optimization of the center\n% and optionally squeezing r towards it by factor 'squeeze'\n%\n% Important: \n% DEPRECATED: cart2topo() should NOT be used if elevation angle is less than 0 \n% (for electrodes below zero plane) since then it returns INNACURATE results. \n% SUBSTITUTE: Use cart2topo = cart2sph() -> sph2topo().\n%\n% Authors: Scott Makeig, Luca Finelli & Arnaud Delorme SCCN/INC/UCSD,\n% La Jolla, 11/1999-03/2002 \n%\n% See also: topo2sph(), sph2topo(), chancenter()\n\n% Copyright (C) 11/1999 Scott Makeig, SCCN/INC/UCSD, scott@sccn.ucsd.edu\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% 3-16-00 improved help message -sm\n% 1-25-02 put spherror subfunction inside cart2topo -ad\n% 1-25-02 help pops-up if no arguments -ad\n% 01-25-02 reformated help & license -ad \n% 02-13-02 now center fitting works, need spherror outside cart2topo -lf\n% 02-14-02 radii are squeezed of squeeze in to fit topoplot circle -lf\n% 03-31-02 center fitting is optional\n% 04-01-02 automatic squeeze calculation -ad & sm\n \nfunction [th,r,xx,yy,zz] = cart2topo(x,varargin)\n\nif nargin<1\n help cart2topo\n return;\nend;\nif nargin >= 2\n\tif ~ischar(varargin{1})\n\t\ty = varargin{1};\n\t\tz = varargin{2};\n\t\tvarargin = varargin(3:end);\n\tend;\nend;\nif exist('y') ~= 1 \n\tif size(x,2)==3 % separate 3-column data\n\t\tz = x(:,3);\n\t\ty = x(:,2);\n\t\tx = x(:,1);\n\telse\n\t\terror('Insufficient data in first argument');\n\tend\nend;\n\ng = [];\nif ~isempty(varargin)\n try, g = struct(varargin{:}); \n catch, error('Argument error in the {''param'', value} sequence'); end; \nend;\n\ntry, g.optim; catch, g.optim = 0; end;\ntry, g.squeeze; catch, g.squeeze = 0; end;\ntry, g.center; catch, g.center = [0 0 0]; end;\ntry, g.gui; catch, g.gui = 'off'; end;\n\nif g.squeeze>1\n fprintf('Warning: Squeeze must be less than 1.\\n');\n return\nend\n\nif ~isempty(g.center) & size(g.center,2) ~= 3\n fprintf('Warning: Center must be [x y z].\\n');\n return\nend\n\n% convert to columns\nx = -x(:); % minus os for consistency between measures\ny = -y(:);\nz = z(:);\n\nif any(z < 0)\n disp('WARNING: some electrodes lie below the z=0 plane, result may be innacurate')\n disp(' Instead use cart2sph() then sph2topo().')\nend;\nif strcmp(g.gui, 'on')\n\t[x y z newcenter] = chancenter(x, y, z, [], 1);\nelse \n\tif g.optim == 1\n\t\t[x y z newcenter] = chancenter(x, y, z, []);\n\telse\n\t\t[x y z newcenter] = chancenter(x, y, z, g.center);\n\tend;\nend;\nradius = (sqrt(x.^2+y.^2+z.^2)); % assume xyz values are on a sphere\nxx=-x; yy=-y; zz=z;\nx = x./radius; % make radius 1\ny = y./radius;\nz = z./radius;\n\nr = x; th=x;\n\nfor n=1:size(x,1)\n if x(n)==0 & y(n)==0\n r(n) = 0;\n else\n r(n) = pi/2-atan(z(n)./sqrt(x(n).^2+y(n).^2));\n end\nend\n\nr = r/pi; % scale r to max 0.500\nif g.squeeze < 0\n g.squeeze = 1 - 0.5/max(r); %(2*max(r)-1)/(2*rmax);\n fprintf('Electrodes will be squeezed together by %2.3g to show all\\n', g.squeeze);\nend;\nr = r-g.squeeze*r; % squeeze electrodes in squeeze*100% to have all inside\n\nfor n=1:size(x,1)\n if abs(y(n))<1e-6\n if x(n)>0\n th(n) = -90;\n else % x(n) <= 0\n th(n) = 90;\n end\n else\n th(n) = atan(x(n)./y(n))*180/pi+90;\n if y(n)<0\n th(n) = th(n)+180;\n end\n end\n if th(n)>180 \n th(n) = th(n)-360;\n end\n if th(n)<-180 \n th(n) = th(n)+360;\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/functions/sigprocfunc/cart2topo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3465371412493564}}
{"text": "function [priormeans,posteriormeans,covmatrix,rbfposteriormeans,rbfcovmatrix] = gpnddisimPredict(model,predtimes,predict_rna,with_obsnoise);\n\n% GPASIMPREDICT Compute predictions (means and a covariance matrix)\n% of POL2 and RNA values for the GPASIM model.\n%\n% FORMAT\n%---------------------------------\n% DESC computes predictions for the asynchronous Gaussian\n% process single input motif model.\n%\n% ARG model : the model for which the gradient is computed.\n%\n% ARG pol2times : the time points where predictions for POL2 are needed\n%\n% ARG rnatime : the time points where predictions for RNA are needed\n%\n% RETURN means : the predicted mean values, first the POL2\n% predictions and then the RNA predictions.\n%\n% RETURN covmatrix : the covariance matrix between the\n% predictions; for example, the diagonal values are the variances\n% of each prediction.\n%---------------------------------\n%\n% SEEALSO : gpasimCreate\n%\n% COPYRIGHT : Jaakko Peltonen, 2011\n\n% GPASIMPREDICT\n\n\n%predtimes\n%pause\n\nif nargin < 4,\n with_obsnoise = 1;\nend\n\nnumGenes=model.numGenes;\nif predict_rna==0,\n numGenes=0;\nend;\n\n\n% compute prior means \nif iscell(predtimes)==0,\n pol2priormeans=ones(size(predtimes,1),1)*model.simMean;\nelse\n pol2priormeans=ones(size(predtimes{1},1),1)*model.simMean;\nend;\n%model.pol2mean;\n\nif numGenes>0,\n % Mean for the mRNA is nonconstant over time and depends on the\n % B,D,S parameters and on the POL2 mean\n Bj=model.B(1);\n Dj=model.D(1);\n Sj=model.S(1);\n if model.use_disimstartmean==1,\n disimStartMean=model.disimStartMean(1);\n end; \nend;\n \nif numGenes>0,\n % compute the RNA mean curve\n% if model.use_disimstartmean==1,\n% rnapriormeans=(Bj+model.simMean*Sj)/Dj+(disimStartMean-(Bj+model.simMean*Sj)/Dj)*exp(Dj*(-predtimes));\n% else \n% rnapriormeans=(Bj+model.simMean*Sj)/Dj*ones(size(predtimes)); \n% end;\n\n rnapriormeans=[];\n tempind1=1;\n for k=1:numGenes,\n if iscell(predtimes)==0,\n nt=length(predtimes);\n else\n nt=length(predtimes{k+1});\n end;\n\n rnapriormeans=[rnapriormeans;nan*ones(nt,1)];\n if (model.use_disimstartmean==1),\n if iscell(predtimes)==0,\n tempt=predtimes;\n else\n tempt=predtimes{k+1};\n end;\n delayedt=tempt-model.delay(k);\n\n I=find(delayedt<0);\n delayedt(I)=0;\n rnapriormeans(tempind1:tempind1+nt-1)=...\n model.disimStartMean(k)*exp(model.D(k)*(-tempt)) ...\n +(model.B(k)/model.D(k))*(1-exp(-model.D(k)*tempt)) ...\n +(model.simMean*model.S(k)/model.D(k))*(1-exp(-model.D(k)*delayedt));\n else\n if iscell(predtimes)==0,\n tempt=predtimes;\n else\n tempt=predtimes{k+1};\n end;\n delayedt=tempt-model.delay(k);\n I=find(delayedt<0);\n delayedt(I)=0;\n rnapriormeans(tempind1:tempind1+nt-1)=...\n ((model.B(k)+model.simMean*model.S(k))/model.D(k))*exp(model.D(k)*(-tempt))...\n +((model.B(k)+model.simMean*model.S(k))/model.D(k))*(1-exp(-model.D(k)*delayedt));\n end;\n tempind1=tempind1+nt;\n end;\n %size(rnapriormeans)\n %size(pol2priormeans)\nend;\n\n \nif 1,\nif with_obsnoise,\n % This version of K_new does include observation noise\n K_new=kernCompute(model.kern, predtimes);\nelse\n % This version of K_new does not include observation noise\n K_new=kernCompute(model.kern, predtimes, predtimes);\nend\n\npredmodeltimes=model.t;\nif (iscell(predtimes)==1) && (iscell(model.t)==0),\n predmodeltimes={model.t,model.t};\nend;\nif (iscell(predtimes)==0) && (iscell(model.t)==1),\n predtimes={predtimes,predtimes};\nend;\n\nK_new_old=kernCompute(model.kern, predtimes, predmodeltimes);\nK_old=model.K;\nK_old_new=K_new_old';\nend;\n\n%K_old\n%pause\n\n\n\nif 0,\nK_old_ndsim=ndsimKernCompute(model.kern.comp{1}.comp{1},model.t);\nK_old_nddisim=nddisimKernCompute(model.kern.comp{1}.comp{2},model.t);\nK_old_nddisimXndsim=nddisimXndsimKernCompute(model.kern.comp{1}.comp{2},model.kern.comp{1}.comp{1},model.t);\nK_old=[K_old_ndsim K_old_nddisimXndsim';K_old_nddisimXndsim K_old_nddisim];\nK_old=real(K_old);\n\nK_new_ndsim=ndsimKernCompute(model.kern.comp{1}.comp{1},predtimes);\nK_new_nddisim=nddisimKernCompute(model.kern.comp{1}.comp{2},predtimes);\nK_new_nddisimXndsim=nddisimXndsimKernCompute(model.kern.comp{1}.comp{2},model.kern.comp{1}.comp{1},predtimes);\nK_new=[K_new_ndsim K_new_nddisimXndsim';K_new_nddisimXndsim K_new_nddisim];\nK_new=real(K_new);\n\nK_new_old_ndsim=ndsimKernCompute(model.kern.comp{1}.comp{1},predtimes,model.t);\nK_new_old_nddisim=nddisimKernCompute(model.kern.comp{1}.comp{2},predtimes,model.t);\nK_new_old_ndsimXnddisim=nddisimXndsimKernCompute(model.kern.comp{1}.comp{2},model.kern.comp{1}.comp{1},model.t,predtimes)';\nK_new_old_nddisimXndsim=nddisimXndsimKernCompute(model.kern.comp{1}.comp{2},model.kern.comp{1}.comp{1},predtimes,model.t);\nK_new_old=[K_new_old_ndsim K_new_old_ndsimXnddisim;K_new_old_nddisimXndsim K_new_old_nddisim];\nK_new_old=real(K_new_old);\n\nK_old_new=K_new_old';\n\nnoisekern_new=kernCompute(model.kern.comp{2}, predtimes);\nnoisekern_old=kernCompute(model.kern.comp{2}, model.t);\nK_old=K_old+noisekern_old;\nK_new=K_new+noisekern_new;\nend;\n\ntempm=model.m;\n\n% If we do not want to predict using RNA observations, throw out kernel parts related to RNA\nif numGenes==0,\n if iscell(model.t)==0,\n ot=length(model.t);\n nt=length(predtimes);\n else\n % ot=0;\n % nt=0;\n % for k=1:length(model.t),\n % ot=ot+size(model.t{k},1);\n % nt=nt+size(predtimes{k},1);\n % end;\n ot=length(model.t{1});\n nt=length(predtimes{1});\n end;\n K_old=K_old(1:ot,1:ot);\n K_new_old=K_new_old(1:nt,1:ot);\n K_old_new=K_old_new(1:ot,1:nt);\n K_new=K_new(1:nt,1:nt);\n tempm=tempm(1:ot);\nend;\n\n\nif numGenes>0,\n priormeans=[pol2priormeans;rnapriormeans];\nelse\n priormeans=pol2priormeans;\nend;\n\n%predict_rna\n%K_old\n%K_new_old\n%pause\n%figure; imagesc(K_old);\n%pause\n\nposteriormeans=priormeans+K_new_old*(K_old\\tempm);\n%covmatrix=K_new-K_new_old*inv(K_old)*K_old_new;\n\ncovmatrix=K_new-K_new_old*(K_old\\K_old_new);\nif(min(diag(covmatrix))<0),\n % Try omitting the first row and column of the kernel\n % since it might be all zeroes\n\n if iscell(model.t)==0,\n ot_pol2=length(model.t);\n ot_rna=length(model.t);\n nt_pol2=length(predtimes);\n nt_rna=length(predtimes);\n else\n ot_pol2=size(model.t{1},1);\n ot_rna=size(model.t{2},1);\n nt_pol2=size(predtimes{1},1);\n nt_rna=size(predtimes{2},1);\n end;\n\n if (numGenes>0),\n okentries=[(2:ot_pol2) (ot_pol2+2:ot_pol2+ot_rna)];\n else\n okentries=[2:ot_pol2];\n end;\n \n K_old=K_old(okentries,okentries); \n K_new_old=K_new_old(:,okentries);\n K_old_new=K_old_new(okentries,:);\n covmatrix=K_new-K_new_old*(K_old\\K_old_new);\nend;\n\n\n\nif 0,\n % Compute predictions for the driving RBF-kernel GP; only valid for\n % the SIM-DISIM model.\n\n\n % extract RBF transforms settings from DISIM part of the SIM-DISIM kernel\n disimkern=model.kern.comp{1}.comp{2};\n if isfield(disimkern, 'options') ...\n && isfield(disimkern.options, 'isNegativeS') ...\n && kern.options.isNegativeS,\n error('DISIM kern uses negative variance, cannot decide transform settings for RBF-SIM-DISIM prediction');\n else\n rbftransformsettings{1}=disimkern.transforms(1).transformsettings; % setting for inverse width\n rbftransformsettings{2}=[0 10]; % setting for RBF variance, not\n % used in GPNDDISIM model\n end\n \n\n % create a RBF kernel to match the settings in the NDSIM-NDDISIM model \n rbfkern=kernCreate(predtimes,'rbf');\n rbfkern=kernExpandParamTransformSettings(rbfkern,rbftransformsettings);\n %[rbfpars,rbfnams]=kernExtractParam(rbfkern);\n [modelpars,modelnams]=gpnddisimExtractParam(model);\n % modelpars\n % modelnams\n % pause\n fprintf(1,'Calling gpdisimExpandParam\\n');\n model=gpnddisimExpandParam(model,modelpars);\n fprintf(1,'Calling gpdisimExpandParam done\\n');\n\n \n rbfpar_inversewidth=modelpars(1); % assumes that inverse width is parameter 1 in the NDSIM-NDDISIM model\n rbfpar_variance=sigmoidabTransform(1, 'xtoa', rbftransformsettings{2});\n rbfpars(1)=rbfpar_inversewidth;\n rbfpars(2)=rbfpar_variance;\n rbfkern=kernExpandParam(rbfkern,rbfpars);\n% rbfkern\n% rbftransformsettings\n\n % create fake SIM and DISIM kernels corresponding to the NDSIM\n % and NDDISIM kernels... this is just a quick hack\n \n\n K_rbf=kernCompute(rbfkern,predtimes);\n K_rbf_sim=simXrbfKernCompute(model.kern.comp{1}.comp{1},rbfkern,model.t,predtimes)';\n K_rbf_disim=disimXrbfKernCompute(model.kern.comp{1}.comp{2},rbfkern,model.t,predtimes)';\n K_rbf_old=[K_rbf_sim K_rbf_disim];\n K_old_rbf=K_rbf_old';\n %size(K_rbf_old)\n %size(K_old)\n %size(model.m)\n \n K_old=model.K;\n rbfposteriormeans=0+K_rbf_old*(K_old\\model.m);\n rbfcovmatrix=K_rbf-K_rbf_old*inv(K_old)*K_old_rbf;\n\n \n% rbfposteriormeans=real(rbfposteriormeans);\n% rbfcovmatrix=real(rbfcovmatrix);\nelse\n rbfposteriormeans=[];\n rbfcovmatrix=[];\nend;\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/gpsim/gpnddisimPredict.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3465371412493564}}
{"text": "function [] = analyzeParVariation(logprefix, signalname, signalname_ref)\n%\n% Author: Thomas Herrmann Date: 22-10-2020\n% \n% Description:\n% extracts log data from all Simulink simulation logs and displays in one\n% plot. Purpose of this script is the tuning of the TMPC algorithm.\n% \n% Input:\n% logprefix: Prefix of all log files from simulation\n% signalname: name of signal to be compared\n% signalname_ref: name of reference signal\n%\n%% Algorithm\n\n% Get all log files with specific prefix\nF = dir([logprefix, '*.*']);\n% Allocate legend\nlgd = struct();\nF_data_struct = struct();\n\nfigure; hold on; grid on;\nlegend('-DynamicLegend');\n\n\nfor i = 1:length(F)\n % Get data from log file\n data_tmp = load(F(i).name);\n \n % get file identifier with specific parameter set\n fname = strrep(...\n strrep(F(i).name,[logprefix, '_'],''), ...\n '.mat', '');\n \n % append to struct for later use\n F_data_struct.(fname) = getfield(data_tmp.debug, signalname);\n \n % plot different paramter set signals over s coordinate\n plot(data_tmp.debug.debug_mvdc_path_matching_debug_ActualTrajPoint_s_glob_m.Data, ...\n F_data_struct.(fname).Data, ...\n 'DisplayName', fname);\n \n set(0, 'DefaultLegendInterpreter', 'none')\n \nend\n\nsignal_ref = getfield(data_tmp.debug, signalname_ref);\nplot(data_tmp.debug.debug_mvdc_path_matching_debug_ActualTrajPoint_s_glob_m.Data, ...\n signal_ref.Data, ...\n 'DisplayName', 'ref');\nset(0, 'DefaultLegendInterpreter', 'none')\nxlabel('s in m'); ylabel('v in mps');\n\nend", "meta": {"author": "TUMFTM", "repo": "mod_vehicle_dynamics_control", "sha": "48b12705b72740b0c1574b0da2eab66fe0c75127", "save_path": "github-repos/MATLAB/TUMFTM-mod_vehicle_dynamics_control", "path": "github-repos/MATLAB/TUMFTM-mod_vehicle_dynamics_control/mod_vehicle_dynamics_control-48b12705b72740b0c1574b0da2eab66fe0c75127/scripts/ExtractLogFiles/analyzeParVariation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3464639096279216}}
{"text": "function varargout = test_smooth( f, N, DOM )\n% TEST_SMOOTH Runs diagnostic checks on a TFOCS smooth function object.\n% TEST_SMOOTH( F )\n% tests whether the function handle F works as a TFOCS smooth\n% function object.\n%\n% Requirements: f = F(X) must return the value of the function at X.\n% [f,g] = F(X) must return the value, f, and the gradient, g.\n%\n% For an example, see SMOOTH_QUAD.M\n% \n% TEST_SMOOTH( F, N )\n% specifies the size of the domain space. If N is a scalar,\n% then the domain space is the set of N x 1 vectors.\n% If N is a matrix of the form [n1, n2], the the domain\n% space is the set of n1 x n2 matrices.\n%\n% TEST_SMOOTH( ..., DOM )\n% specifies the domain of F. DOM can be of the form [a,b]\n% which signifies the 1D set (a,b).\n%\n% OK = TEST_SMOOTH(...)\n% returns \"true\" if all tests are passed, and \"false\" otherwise.\n%\n% See also private/tfocs_smooth, smooth_huber\n\n\nOK = false;\nPLOT = true;\n\nerror(nargchk(1,3,nargin));\n\nif ~isa(f,'function_handle')\n fail('TFOCS smooth function must be a FUNCTION HANDLE');\n return; \nend\nfprintf('== Testing the smooth function %s ==\\n', func2str(f) );\n\nFORCE_N = false; % always require a vector input\nif nargin < 2 || isempty(N), N = 10;\nelse FORCE_N = true; \nend\nif nargin < 3 || isempty(DOM), DOM = [-1,1]; end\n\na = DOM(1); b = DOM(2);\n\nx = (a+b)/2;\nfprintf('Testing scalar inputs... \\n');\ntry \n vi = f(x);\ncatch\n fail('TFOCS smooth function failed to return a function value');\n return;\nend\nif isinf(vi)\n fail('TFOCS smooth function tester: default domain is invalid. Please specify valid domain');\n return;\nend\nfprintf('\\t\\t\\t\\t...passed. \\n');\n\n% Now, also ask for the gradient\nfprintf('Testing gradient output... \\n');\ntry \n [vi,gi] = f(x);\ncatch\n fail('TFOCS smooth function failed to return a derivative value');\n return;\nend\nfprintf('\\t\\t\\t\\t...passed. \\n');\n\n% Now, try a vector\nif isscalar(N)\n x = repmat(x,N,1);\nelse\n x = repmat(x,N(1),N(2));\n % if a > 0, assume we want a PSD matrix:\n if a >= 0\n x = ones(N(1),N(2)) + eye(N(1),N(2) );\n end\nend\nfprintf('Testing vector inputs... \\n');\ntry \n [vi,gi] = f(x);\ncatch\n fail('TFOCS smooth function failed when supplied a vector input');\n return;\nend\nfprintf('\\t\\t\\t\\t...passed. \\n');\n\n\n\n% 1D example. Does not require function to be vectorized\nn = 100; % number of grid points\nh = (b-a)/n;\ngrid = (a+h/2):h:(b-h/2);\n\nv = zeros(size(grid));\ng = zeros(size(grid));\nfirst = @(x) x(1);\nfor i = 1:length(grid)\n v(i) = f(grid(i));\n if isinf(v(i))\n g(i) = v(i);\n else\n [v(i),gi] = f(grid(i));\n g(i) = first(gi);\n end\nend\n\nif PLOT\n figure;\n clf;\n plot(grid,v,'.-');\n hold all\n plot(grid,g,'.-');\n legend('function','derivative');\n% title(func2str(f),'interpreter','none');\n line([a,b], 0*[1,1],'color','k' )\n if a < 0 && b > 0\n line( 0*[1,1], get(gca,'ylim'),'color','k' );\n end\nend\n\nOK = true;\n\nif nargout > 0\n varargout{1} = OK;\nend\n\ndisp('Test passed succesfully.');\n\n\n\n\nfunction fail(str)\n disp('Test failed. Reason:');\n disp(str);\n\n\n% TFOCS v1.3 by Stephen Becker, Emmanuel Candes, and Michael Grant.\n% Copyright 2013 California Institute of Technology and CVX Research.\n% See the file LICENSE for full license information.\n", "meta": {"author": "cvxr", "repo": "TFOCS", "sha": "164ada20401cd445930673e42bb3d2a5489f2030", "save_path": "github-repos/MATLAB/cvxr-TFOCS", "path": "github-repos/MATLAB/cvxr-TFOCS/TFOCS-164ada20401cd445930673e42bb3d2a5489f2030/test_smooth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.34646389915554776}}
{"text": "function g = indexardKernGradient(kern, x, varargin)\n\n% INDEXARDKERNGRADIENT Gradient of INDEXARD kernel's parameters.\n% FORMAT\n% DESC computes the gradient of functions with respect to the\n% index ard based covariance function\n% kernel's parameters. As well as the kernel structure and the\n% input positions, the user provides a matrix PARTIAL which gives\n% the partial derivatives of the function with respect to the\n% relevant elements of the kernel matrix. \n% ARG kern : the kernel structure for which the gradients are being\n% computed.\n% ARG x : the input locations for which the gradients are being\n% computed. \n% ARG partial : matrix of partial derivatives of the function of\n% interest with respect to the kernel matrix. The argument takes\n% the form of a square matrix of dimension numData, where numData is\n% the number of rows in X.\n% RETURN g : gradients of the function of interest with respect to\n% the kernel parameters. The ordering of the vector should match\n% that provided by the function kernExtractParam.\n%\n% FORMAT\n% DESC computes the derivatives as above, but input locations are\n% now provided in two matrices associated with rows and columns of\n% the kernel matrix. \n% ARG kern : the kernel structure for which the gradients are being\n% computed.\n% ARG x1 : the input locations associated with the rows of the\n% kernel matrix.\n% ARG x2 : the input locations associated with the columns of the\n% kernel matrix.\n% ARG partial : matrix of partial derivatives of the function of\n% interest with respect to the kernel matrix. The matrix should\n% have the same number of rows as X1 and the same number of columns\n% as X2 has rows.\n% RETURN g : gradients of the function of interest with respect to\n% the kernel parameters.\n%\n% SEEALSO indexardKernParamInit, kernGradient, indexardKernDiagGradient, kernGradX\n%\n% COPYRIGHT : Neil D. Lawrence, 2011\n\n% KERN\n\n g = zeros(1, length(kern.indices));\n covGrad = varargin{end};\n if nargin < 4\n x2 = x;\n else\n x2 = varargin{1};\n end\n for i = 1:length(kern.indices);\n g(i) = sparse(round(x)==kern.indices(i))'*covGrad*sparse(round(x2)==kern.indices(i));\n end \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/indexardKernGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3464638956647564}}
{"text": "function hm=plotsurf(node,face,varargin)\n%\n% hm=plotsurf(node,face,opt)\n%\n% plot 3D surface meshes (2d manifold) or polylines (1d manifold)\n% \n% author: Qianqian Fang \n%\n% input: \n% node: node coordinates, dimension (nn,3); if node has a \n% 4th column, it will be used to set the color at each node.\n% face: triangular surface face list; if face has a 4th column,\n% it will be used to separate the surface into \n% sub-surfaces and display them in different colors;\n% face can be a cell array, each element of the array represents\n% a polyhedral facet of the mesh, if an element is an array with\n% two array subelements, the first one is the node index, the\n% second one is a scalar as the group id of the facet.\n% opt: additional options for the plotting, see plotmesh\n%\n% output:\n% hm: handle or handles (vector) to the plotted surfaces\n%\n% example:\n%\n% h=plotsurf(node,face);\n% h=plotsurf(node,face,'facecolor','r');\n% h=plotsurf(node,edges,'linestyle','-','linewidth',2,'color','r');\n%\n% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)\n%\n\nrngstate = rand ('state');\n\nif(nargin>=2)\n randseed=hex2dec('623F9A9E'); % \"U+623F U+9A9E\"\n if(isoctavemesh) randseed=randseed+3; end\n if(~isempty(getvarfrom({'caller','base'},'ISO2MESH_RANDSEED')))\n randseed=getvarfrom({'caller','base'},'ISO2MESH_RANDSEED');\n end\n rand('state',randseed);\n\n if(iscell(face))\n sc=sparse(10,3); % face colormap\n sc(1:10,:)=rand(3,10)';\n len=length(face);\n newsurf=cell(1);\n % reorganizing each labeled surface into a new cell\n for i=1:len\n fc=face{i};\n if(iscell(fc) && length(fc)>=2)\n if(fc{2}+1>10)\n sc(fc{2}+1,:)=rand(1,3);\n end\n if(fc{2}+1>length(newsurf))\n newsurf{fc{2}+1}={};\n end\n newsurf{fc{2}+1}{end+1}=fc{1};\n else % unlabeled facet is tagged by 0\n if(iscell(fc))\n newsurf{1}{end+1}=cell2mat(fc);\n else\n newsurf{1}{end+1}=fc;\n end\n end\n end\n hold on;\n\th=[];\n newlen=length(newsurf);\n\n for i=1:newlen\n if(isempty(newsurf{i})); continue; end\n try \n subface=cell2mat(newsurf{i}')';\n if(size(subface,1)>1 && ismatrix(subface))\n subface=subface';\n end\n h=[h patch('Vertices',node,'Faces',subface,'facecolor',sc(i,:),varargin{:})];\n catch\n for j=1:length(newsurf{i})\n h=[h patch('Vertices',node,'Faces',newsurf{i}{j},'facecolor',sc(i,:),varargin{:})];\n end\n end\n end\n else\n if(size(face,2)==4)\n tag=face(:,4);\n\t\ttypes=unique(tag);\n hold on;\n\t\th=[];\n\t for i=1:length(types)\n if(size(node,2)==3)\n h=[h plotasurf(node,face(tag==types(i),1:3),'facecolor',rand(3,1),varargin{:})];\n else\n h=[h plotasurf(node,face(tag==types(i),1:3),varargin{:})];\n end\n end\n else\n h=plotasurf(node,face,varargin{:});\n end\n end\nend \nif(~isempty(h)) \n axis equal;\n if(all(get(gca,'view')==[0 90]))\n view(3);\n end\nend\nif(~isempty(h) && nargout>=1)\n hm=h;\nend\n\nrand ('state',rngstate);\n\n%-------------------------------------------------------------------------\nfunction hh=plotasurf(node,face,varargin)\nisoct=isoctavemesh;\nif(size(face,2)<=2)\n h=plotedges(node,face,varargin{:});\nelse\n if(size(node,2)==4)\n\tif(isoct && ~exist('trisurf','file'))\n\t h=trimesh(face(:,1:3),node(:,1),node(:,2),node(:,3),node(:,4),'edgecolor','k',varargin{:});\n\telse\n\t h=trisurf(face(:,1:3),node(:,1),node(:,2),node(:,3),node(:,4),varargin{:});\n\tend\n else\n\tif(isoct && ~exist('trisurf','file'))\n\t h=trimesh(face(:,1:3),node(:,1),node(:,2),node(:,3),'edgecolor','k',varargin{:});\n\telse\n\t h=trisurf(face(:,1:3),node(:,1),node(:,2),node(:,3),varargin{:});\n end\n end\nend\nif(exist('h','var')) hh=h; end\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/plotsurf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.3464626613856565}}
{"text": "function C = cell_add(A,B,a,b)\n\n% cell_add - add two cell arrays\n%\n% C = cell_add(A,B,a,b);\n%\n% C{i} = a*A{i} + b*B{i};\n%\n% Copyright (c) 2008 Gabriel Peyre\n\n\nif nargin<3\n a = 1;\nend\nif nargin<4\n b = 1;\nend\n\nif iscell(A)\n if length(A)~=length(B)\n error('A and B must be of the same size');\n end\n for i=1:length(A)\n C{i} = cell_add(A{i},B{i},a,b);\n end\n return;\nend\n\nC = a*A + b*B;", "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_misc/cell_add.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.34646265258178166}}
{"text": "function minimize( varargin )\n\n%MINIMIZE Specifiies a convex (or affine) objective to be maximized.\n\ncvx_problem = evalin( 'caller', 'cvx_problem', '[]' );\nif isempty( cvx_problem ) || ~isa( cvx_problem, 'cvxprob' ),\n error( 'A cvx problem does not exist in this scope.' );\nend\nif ~isempty( cvx_problem.direction ),\n if isequal( cvx_problem.direction, 'find' ),\n error( 'Objective functions cannot be added to sets.' );\n else\n error( 'An objective function has already been supplied.' );\n end\nend\n\nif nargin < 1,\n error( 'Objective expression missing.' );\nelseif iscellstr( varargin ),\n arg = evalin( 'caller', sprintf( '%s ', varargin{:} ) );\nelseif nargin > 1,\n error( 'Too many input arguments.' );\nelse\n arg = varargin{1};\nend\n\nif ~isa( arg, 'cvx' ) && ~isa( arg, 'double' ) && ~isa( arg, 'sparse' ),\n error( 'Cannot accept an objective of type ''%s''.', class( arg ) );\nend\npersistent remap\nif isempty( remap ),\n remap = cvx_remap( 'convex', 'log-convex' );\nend\nvx = remap( cvx_classify( arg ) );\nif ~all( vx ),\n error( 'Disciplined convex programming error:\\n Cannot minimize a(n) %s expression.', cvx_class(arg(vx==0),false,true) );\nend\n\nnewobj( cvx_problem, 'minimize', arg );\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/keywords/minimize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.34646265258178166}}
{"text": "classdef blockCoeff\n%BLOCKCOEFF Class to convert linear operator to derivative coefficents.\n% This class is not intended to be called directly by the end user.\n%\n% See also LINOP, CHEBOP, CHEBOPPREF.\n \n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Developer notes\n%\n% This class converts a linBlock object into a list of coefficients for the\n% (descending) powers of the derivative in the operator. \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %% CLASS PROPERTIES:\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n properties ( Access = public )\n coeffs = [];\n domain\n pref = chebfunpref;\n end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %% CLASS CONSTRUCTOR:\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n methods ( Access = public, Static = false )\n \n function A = blockCoeff(varargin)\n % When called with no arguments, the returned object causes the\n % block's stack to be evaluated with these methods to produce\n % coefficients.\n if ( isempty(varargin{1}) )\n pref = cheboppref;\n A.domain = pref.domain;\n return\n \n % Calling the constructor with a linBlock argument initiates the\n % process of evaluating the stack with a dummy object of this class.\n elseif ( isa(varargin{1}, 'linBlock') )\n L = varargin{1};\n dummy = blockCoeff([]);\n dummy.domain = L.domain;\n if ( nargin == 2 )\n dummy.pref = varargin{2};\n end\n A = L.stack(dummy);\n\n % If the constructor is called with data, just make a regular object\n % out of it. \n else\n f = varargin{1};\n if ( ~iscell(f) )\n f = {f};\n end\n A.coeffs = f;\n A.domain = varargin{2};\n if ( nargin == 3 )\n A.pref = varargin{3};\n end\n end\n end\n end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %% OTHER BASIC CONSTRUCTORS:\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n methods ( Access = public, Static = false )\n \n % These are the basic constructors.\n \n function I = eye(A)\n I = blockCoeff(chebfun(1, A.domain, A.pref), A.domain);\n end\n \n function I = zeros(A)\n I = blockCoeff(chebfun(0, A.domain, A.pref), A.domain);\n end\n \n function F = mult(A, f)\n F = blockCoeff(f, A.domain);\n end\n \n function C = cumsum(A, m)\n error('CHEBFUN:BLOCKCOEFF:cumsum:notSupported', ...\n 'Conversion of integration to coefficients is not supported.')\n end\n \n function D = diff(A, order)\n \n if ( nargin < 2 )\n order = 1;\n end\n \n if ( ~isempty(A.coeffs) )\n % This syntax is used by the mtimes method to differentiate\n % an existing operator.\n D = A;\n else\n % Initialize with an identity. \n D = eye(A);\n end\n \n % Differentiate the requested number of times.\n c = D.coeffs;\n for d = 1:order\n m = numel(c);\n c = c([1, 1:m]);\n for k = 2:m\n c{k} = diff(c{k}) + c{k+1};\n end\n c{m+1} = diff(c{m+1});\n end\n D = blockCoeff(c, A.domain);\n \n end\n \n function S = sum(A)\n error('CHEBFUN:BLOCKCOEFF:sum:notSupported', ...\n 'Conversion of integration to coefficients is not supported.')\n end\n \n function E = feval(A, location, direction)\n error('CHEBFUN:BLOCKCOEFF:feval:notSupported', ...\n 'Conversion of evaluation to coefficients is not supported.')\n end\n \n function F = inner(f)\n error('CHEBFUN:BLOCKCOEFF:inner:notSupported', ...\n 'Conversion of inner product to coefficients is not supported.')\n end\n \n end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %% CLASS METHODS:\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n methods ( Access = public, Static = false )\n \n function C = mtimes(A, B)\n \n if ( isnumeric(A) )\n % Allow multiplying a BLOCKCOEFF with a scalar.\n c = B.coeffs;\n for k = 1:numel(B.coeffs)\n c{k} = A*c{k};\n end\n \n % Create the result.\n C = blockCoeff(c, B.domain);\n return\n elseif ( isnumeric(B) )\n C = mtimes(B, A);\n return\n end\n \n if ( isempty(A.coeffs) || isempty(B.coeffs) )\n C = blockCoeff([]);\n return\n end\n \n % Initialize constant term of A times the coeffs of B.\n c = B.coeffs;\n for k = 1:numel(B.coeffs)\n c{k} = A.coeffs{end}.*c{k};\n end\n \n % Do a convolution-style multiplication for the rest of A.\n if ( numel(A.coeffs) > 1 )\n z = {0*c{1}}; % an appropriate zero chebfun\n end\n for j = 1:numel(A.coeffs)-1\n B = diff(B); % differentiate this operator\n c = [z, c];\n for k = 1:numel(B.coeffs)\n c{k} = c{k} + A.coeffs{end-j}.*B.coeffs{k};\n end\n end\n \n % Create the result.\n C = blockCoeff(c, A.domain);\n end\n \n function C = plus(A, B)\n sA = numel(A.coeffs);\n sB = numel(B.coeffs);\n \n % Empty operand returns empty result. \n if ( (sA == 0) || (sB == 0) )\n C = blockCoeff([]);\n return\n end\n \n % Get to same length.\n if ( sA < sB )\n z = {0*A.coeffs{1}};\n A.coeffs = [repmat(z, 1, sB-sA), A.coeffs];\n sA = sB;\n elseif ( sB < sA )\n z = {0*B.coeffs{1}};\n B.coeffs = [repmat(z, 1, sA-sB), B.coeffs];\n end\n \n % Do the work.\n c = cell(1, sA);\n for k = 1:sA\n c{k} = A.coeffs{k} + B.coeffs{k};\n end\n C = blockCoeff(c, A.domain);\n end\n \n function A = uminus(A)\n A.coeffs = cellfun(@uminus, A.coeffs, 'uniform', false);\n end\n \n function A = uplus(A)\n end\n \n end\n \nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@blockCoeff/blockCoeff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.34646265258178166}}
{"text": "function [ y2, m2, d2, f2 ] = ymdf_inc_islamic ( y1, m1, d1, f1, days )\n\n%*****************************************************************************80\n%\n%% YMDF_INC_ISLAMIC increments an Islamic YMDF date by DAYS days.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 April 2103\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer Y1, M1, D1, real F1,\n% the YMDF date.\n%\n% Input, real DAYS, the number of days to advance the date.\n%\n% Output, integer Y2, M2, D2, real F2,\n% the incremented YMDF date.\n%\n\n%\n% Copy the parameters.\n%\n y2 = y1;\n m2 = m1;\n d2 = d1;\n f2 = f1 + days;\n%\n% Check the parameters.\n%\n [ y2, m2, d2, f2, ierror ] = ymdf_check_islamic ( y2, m2, d2, f2 );\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_inc_islamic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.3464626525817816}}
{"text": "function a = uplus(a)\n%UPLUS Implements +a for intervals\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, improved performance\n%\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/uplus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.3464626437779067}}
{"text": "%%\n% Calculates b based on time using Mc and plots it - called from\n% cumulative window\n%%\n\n\nreport_this_filefun(mfilename('fullpath'));\n\n\ninter = 50;\nincr = 10;\n\n\n%%\n% set step_cat as a dummy variable so that newt2 can be reassigned\n% for use in mcperc_ca3. newt2 is reset at end.\n%%\n\nstep_cat = newt2;\nbv2 = [];\nbv3 = [] ;\nme = [];\nbvm = [];\nctr = 0;\ni=1;\nNmin=50;\n%% b=newt2; %% initialization for bvalca3.m\nday_start=0;\nday_end=0;\n\ninpr1 = 5;\n\nnibt = 200;\nwin_step = 200;\nfor ind = 1:win_step:length(step_cat)-win_step\n newt2 = step_cat(ind:ind+nibt,:);\n\n\n %%\n % calculation based on best combination of 90% and 95% probability -- default\n %%\n\n % elseif inpr1 == 5\n mcperc_ca3;\n if isnan(Mc95) == 0 \n magco = Mc95;\n elseif isnan(Mc90) == 0 \n magco = Mc90;\n else\n [bv magco stan av me mer me2, pr] = bvalca3(newt2,1,1);\n end\n l = newt2.Magnitude >= magco-0.05;\n if length(newt2(l,6)) <= Nmin\n % disp(['%%Warning --bwithtimc--%% less than 50 events in step ']);\n end\n [ntl,ntw] = size(newt2(l,:));\n if ntl <= 1\n disp('%%ERROR --bwithtimc--%% Not enough data to plot');\n newt2 = step_cat;\n return\n end\n [mea bv stand, av] = bmemag(newt2(l,:));\n\n\n\n\n days = (max(newt2.Date)-min(newt2.Date))*365.0;\n\n bvm = [bvm; bv step_cat(ind,3) step_cat(ind+nibt,3) magco days ind ind+nibt av];\nend %% end of for loop!!\n%end\n\n\n[bvml,bvmw] = size(bvm);\nif bvml <= 1\n disp('%%ERROR --bwithtimc--%% Not enough data to calculate Mc');\n newt2 = step_cat;\n return\nend\nif ind + win_step < length(step_cat)\n newt2 = step_cat(ind+win_step+1:length(step_cat),:);\n %%\n % calculation based on best combination of 90% and 95% probability -- default\n %%\n\n if inpr1 == 5\n mcperc_ca3;\n if isnan(Mc95) == 0 \n magco = Mc95;\n elseif isnan(Mc90) == 0 \n magco = Mc90;\n else\n [bv magco stan av me mer me2, pr] = bvalca3(newt2,1,1);\n end\n l = newt2.Magnitude >= magco-0.05;\n if length(newt2(l,6)) <= Nmin\n % disp(['%%Warning --bwithtimc--%% less than 50 events in step ']);\n end\n [ntl,ntw] = size(newt2(l,:));\n if ntl <= 1\n disp('%%ERROR --bwithtimc--%% Not enough data to plot');\n newt2 = step_cat;\n return\n end\n [mea bv stand, av] = bmemag(newt2(l,:));\n\n end\nend\nbvm = [bvm; bv step_cat(ind+win_step,3) step_cat(length(step_cat),3) magco days ind ind+nibt av];\n\n%bvm(length(bvm)+1,:) = bvm(ind,:)\nnewt2 = step_cat;\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/pvals/bwithtimc_nogui.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.5, "lm_q1q2_score": 0.34632099156736806}}
{"text": "%Voice Based Biometric System\n%By Ambavi K. Patel.\n\n\nfunction mfcc3=melcep(mel1,powspc1,noc1,fsize1,nwin1)\nmfcc1(1:noc1,1:nwin1)=0;\nfor j=1:nwin1\n n=floor(fsize1/2);\n mfcc1(:,j)=dct(log(mel1*abs(powspc1(1:n,j).^2)));\n %converting the power-spectrum to a melfrequency spectrum &taking the logarithm of that spectrum and by computing its inverse using\n %discrete cosine transform \nend;\nmfcc2(1:13,1:nwin1)=0;\nmfcc2(1:13,1:nwin1)=mfcc1(3:15,1:nwin1);\nmfcc3=nanclr(mfcc2);\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/31328-voice-based-biometric-system/MFCC_MLPBPN/melcep.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3463209852227794}}
{"text": "function [ new_input_args ] = reorient_chipper_args( symmetry, datasize, varargin)\n%REORIENT_CHIPPER_ARGS Applies a transform to the chipper indexing\n%\n% This function does nothing but transform the arguments into a chipper\n% function based on the symmetry specified.\n%\n% A chipper function is a simplified function of a file reader. It takes\n% only three arguments: [minIndexInDimension1 maxIndexInDimension1],\n% [minIndexInDimension2 maxIndexInDimension2], [subsampleInDimension1,\n% subsampleInDimension2]. All other information such as the file handle\n% and other auxilliary information must be contained within the chipper\n% function.\n%\n% The SYMMETRY parameter is used to perform symmetry operations on the\n% imported image data. A combination of horizontal mirroring (hm), vertical\n% mirroring (vm) and transpose(tr) is used to accomplish the symmetry\n% operations. The 'symmetry' input parameter is defined as [ hm vm tr ], where\n% each of the elements can be either 0 or 1 to indicate whether to apply a\n% transformation or not.\n%\n% [ 0 0 0 ] - default setting; successive pixels on disk are interpreted\n% to fill the first dimension in a MATLAB array (vertical, if\n% viewed in imagesc/imshow without any reorienting)\n% [ 1 0 1 ] - 90 degrees CCW from [ 0 0 0 ]\n% [ 0 1 1 ] - 90 degrees CW from [ 0 0 0 ]\n% [ 1 1 0 ] - 180 degrees from [ 0 0 0 ]\n%\n% [ 0 0 1 ] - transpose of [ 0 0 0 ];\n% [ 0 1 0 ] - 90 degrees CCW from [ 0 0 1 ]\n% [ 1 0 0 ] - 90 degrees CW from [ 0 0 1 ]\n% [ 1 1 1 ] - 180 degrees from [ 0 0 1 ]\n%\n% Written by: Wade Schwartzkopf, NGA/IDT\n%\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED ///\n% //////////////////////////////////////////\n\nif symmetry(3)\n new_input_args={};\n if(nargin>=3), new_input_args{2}=varargin{1}; end;\n if(nargin>=4), new_input_args{1}=varargin{2}; end\n if(nargin>=5), new_input_args{3}=varargin{3}(end:-1:1); end;\nelse\n new_input_args=varargin;\nend\nif symmetry(1)\n if(nargin>=3)\n new_input_args{1}=double(datasize(1))-new_input_args{1}(end:-1:1)+1;\n % The double around datasize allows this to work on empty arguments.\n end\nend\nif symmetry(2)\n if(nargin>=4)\n new_input_args{2}=double(datasize(2))-new_input_args{2}(end:-1:1)+1;\n end\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/IO/complex/generic/reorient_chipper_args.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.63341026367784, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3463095570113092}}
{"text": "function outn=eq(x,y)\n\nprecAndSize\n\nfor ii=1:max(ex,ey)\n imag=false;\n if ex==1\n [xrval,xival]=getVals(x,1);\n [yrval,yival]=getVals(y,ii);\n elseif ey==1\n [xrval,xival]=getVals(x,ii);\n [yrval,yival]=getVals(y,1);\n else\n [xrval,xival]=getVals(x,ii);\n [yrval,yival]=getVals(y,ii);\n end \n outn(ii)=mpfr_eq(precision,xrval,yrval);\n if outn(ii)==0, outn(ii)=1; else, outn(ii)=0; end\nend % for ii=1:max(ex,\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/external/analysis/mptoolbox/@mp/eq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.34630954944428927}}
{"text": "function I = eye(disc)\n%EYE Identity operator for VALSDISCRETIZATION discretization.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nn = disc.dimension;\nI = eye(sum(n));\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/@valsDiscretization/eye.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.34630954944428927}}
{"text": "function [ekg_RSlinB_am_ELF, ekg_RSlinB_bw_ELF, ekg_RSlinB_fm_ELF] = ELF_is(ekg_RSlinB_am, ekg_RSlinB_bw, ekg_RSlinB_fm, up)\n%ELF eliminates very low frequencies from resampled respiratory\n\n\nfor rel_var_name_no = 1 : length(up.al.options.FMe)\n% temp = strfind(rel_var_names{rel_var_name_no},'_');\n% start_el = temp(1); clear temp\n% eval(['save_name = ''' curr_sig, up.paths.filenames.elim_vlf2, rel_var_names{rel_var_name_no}(start_el:end) ''';']); clear start_el\n% exist_log = check_exists(savepath, save_name);\n% if exist_log\n% continue\n% end\n \n %% Load relevant data\n rel_name = ['ekg_RSlinB_' up.al.options.FMe{rel_var_name_no} ];\n %loadpath = [up.paths.data_save_folder, num2str(subj), up.paths.filenames.int_respSigs];\n %load(loadpath, rel_name);\n eval(['old_data = ' rel_name ';']);\n \n %% Eliminate VLFs\n data.hpfilt.t = old_data.t;\n try\n data.hpfilt.v = elim_vlfs(old_data, up);\n catch\n % if there aren't enough points to use the filter, simply carry forward the previous data\n data.hpfilt.v = old_data.v;\n end\n data.hpfilt.fs = old_data.fs;\n %eval(['save_name = ' rel_name '_ELF']);\n save_name = [rel_name '_ELF'];\n eval([save_name ' = data.hpfilt;']);\n \n %% Save processed data\n %save_or_append_data\nend\n\nend\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/Respiration_Tools/Algorithms/extract_resp_sig/feat_based_extraction/ELF_is.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3462784765937602}}
{"text": "function [n,ind]=my_histcounts(X,edges,normalization)\npersistent old_matlab\nif isempty(old_matlab)\n old_matlab=verLessThan('matlab','8.4');\nend\nif old_matlab\n %We make histc behave like histcounts\n [n,ind]=histc(X,edges);\n ind(ind==length(n))=length(n)-1;\n n(end-1)=n(end-1)+n(end);\n n(end)=[];\n \n switch normalization\n case 'probability'\n n=n./sum(n);\n case 'count'\n otherwise\n warning('Other types of normalization are not supported on older Matlab versions')\n end\nelse\n [n, ~, ind]=histcounts(X,edges,'Normalization',normalization);\nend\nend\n\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/private/my_histcounts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.3462784684960045}}
{"text": "function [M_final,shifts,template,options,col_shift] = normcorre(Y,options,template)\n\n% online motion correction through DFT subpixel registration\n% Based on the dftregistration.m function from Manuel Guizar and Jim Fienup\n\n% INPUTS\n% Y: Input data, can be already loaded in memory as a 3D\n% tensor, a memory mapped file, or a pointer to a tiff stack\n% options: options structure for motion correction (optional, rigid registration is performed if not provided)\n% template: provide template (optional)\n\n% OUTPUTS\n% M_final: motion corrected data\n% shifts: originally calculated shifts\n% template: calculated template\n% options: options structure (if modified)\n% col_shift: relative shift due to bi-directional scanning\n\n%% first determine filetype\n\nnd = 2 + (options.d3 > 1); %max(length(sizY)-1,2); % determine whether imaging is 2d or 3d\n\nif isa(Y,'char')\n [~,~,ext] = fileparts(Y);\n ext = ext(2:end);\n if strcmpi(ext,'tif') || strcmpi(ext,'tiff')\n tiffInfo = imfinfo(Y);\n filetype = 'tif';\n T = length(tiffInfo);\n if nd == 3\n sizY = [tiffInfo(1).Height,tiffInfo(1).Width,T,1];\n else\n sizY = [tiffInfo(1).Height,tiffInfo(1).Width,T];\n end\n elseif strcmpi(ext,'mat')\n filetype = 'mem';\n Y = matfile(Y,'Writable',true);\n details = whos(Y);\n var_sizes = [details.bytes];\n [~,var_ind] = max(var_sizes);\n var_name = details(var_ind).name;\n sizY = size(Y,var_name);\n elseif strcmpi(ext,'hdf5') || strcmpi(ext,'h5')\n filetype = 'hdf5';\n fileinfo = hdf5info(Y);\n sizY = fileinfo.GroupHierarchy.Datasets.Dims;\n end \nelseif isobject(Y)\n filetype = 'mem';\n var_name = 'Y';\n sizY = size(Y,var_name);\nelse % array loaded in memory\n filetype = 'mat';\n Y = single(Y);\n sizY = size(Y); \nend\n\nif length(sizY) == nd\n T = 1;\nelse\n T = sizY(nd+1);\nend\nsizY = sizY(1:nd);\n\n%% set default parameters if not present\n\nif ~exist('options','var') || isempty(options) \n options = NoRMCorreSetParms('d1',sizY(1),'d2',sizY(2));\n if nd > 2; options.d3 = sizY(3); end\nend\n\noptions.bin_width = min(options.bin_width,T+1);\noptions.mem_batch_size = min(options.mem_batch_size,T);\noptions.buffer_width = min(options.buffer_width,ceil(T/options.bin_width));\noptions.init_batch = min(options.init_batch,T);\n\nmemmap = options.memmap;\ngrid_size = options.grid_size; \nmot_uf = options.mot_uf;\nmin_patch_size = options.min_patch_size;\noverlap_pre = options.overlap_pre;\noverlap_post = options.overlap_post;\nupd_template = options.upd_template;\nbin_width = options.bin_width;\nbuffer_width = options.buffer_width;\nmax_dev = options.max_dev;\ninit_batch = options.init_batch;\nus_fac = options.us_fac;\nmethod = options.method;\nplot_flag = options.plot_flag*(nd==2);\nfilename = options.mem_filename;\nuse_parallel = options.use_parallel;\nmake_avi = options.make_avi;\nname = options.name;\nfr = options.fr;\niter = options.iter;\nadd_value = options.add_value;\nmax_shift = options.max_shift;\nprint_msg = options.print_msg;\nif strcmpi(options.boundary,'nan')\n fill_value = NaN;\nelse\n fill_value = add_value;\nend\n \n\n%% first check for offset due to bi-directional scanning\n\nif options.correct_bidir && isempty(options.col_shift)\n col_shift = correct_bidirectional_offset(Y,options.nFrames,options.bidir_us);\nelseif ~isempty(options.col_shift)\n col_shift = options.col_shift;\nelse\n col_shift = 0;\nend \noptions.col_shift = col_shift;\nif col_shift\n if print_msg; fprintf('Offset %1.1d pixels due to bidirectional scanning detected. \\n',col_shift); end\n if strcmpi(options.shifts_method,'fft')\n options.shifts_method = 'cubic';\n if print_msg; fprintf('Cubic shifts will be applied. \\n'); end\n end\nend\n%% read initial batch and compute template\ninit_batch = min(T,init_batch);\ninterval = ceil(T/2-init_batch/2+1):floor(T/2+init_batch/2);\nif exist('template','var')\n init_batch = min(init_batch,1);\nend\nswitch filetype\n case 'tif'\n Y_temp = read_file(Y,interval(1),init_batch,[],tiffInfo);\n case 'hdf5'\n Y_temp = read_file(Y,interval(1),init_batch); \n case 'mem'\n if nd == 2; Y_temp = Y.(var_name)(:,:,interval); elseif nd == 3; Y_temp = Y.(var_name)(:,:,:,interval); end\n case 'mat'\n if nd == 2; Y_temp = Y(:,:,interval); elseif nd == 3; Y_temp = Y(:,:,:,interval); end\nend\n\ndata_type = class(Y_temp);\nY_temp = single(Y_temp);\n\nif nargin < 3 || isempty(template)\n if print_msg; fprintf('Registering the first %i frames just to obtain a good template....',init_batch); end\n template_in = median(Y_temp,nd+1)+add_value;\n fftTemp = fftn(template_in);\n for t = 1:size(Y_temp,nd+1)\n if nd == 2\n [~,Greg] = dftregistration_min_max(fftTemp,fftn(Y_temp(:,:,t)),us_fac,-max_shift,max_shift,options.phase_flag);\n end\n if nd == 3\n [~,Greg] = dftregistration_min_max_3d(fftTemp,fftn(Y_temp(:,:,:,t)),us_fac,-max_shift,max_shift,options.phase_flag); \n end\n M_temp = real(ifftn(Greg));\n template_in = template_in*(t-1)/t + M_temp/t;\n end\n template_in = template_in + add_value;\n if print_msg; fprintf('..done. \\n'); end\nelse\n template_in = single(template + add_value);\nend\n\n[d1,d2,d3,~] = size(Y_temp);\nif nd == 2; d3 = 1; end\n%% setup grids for patches\n\n[xx_s,xx_f,yy_s,yy_f,zz_s,zz_f,xx_us,xx_uf,yy_us,yy_uf,zz_us,zz_uf] = construct_grid(grid_size,mot_uf,d1,d2,d3,min_patch_size);\nshifts = struct('shifts',cell(T,1),'shifts_up',cell(T,1),'diff',cell(T,1));\ntemp_cell = mat2cell_ov(template_in,xx_us,xx_uf,yy_us,yy_uf,zz_us,zz_uf,overlap_post,sizY);\n\n%% precompute some quantities that are used repetitively for template matching and applying shifts\nNr = cell(size(temp_cell));\nNc = cell(size(temp_cell));\nNp = cell(size(temp_cell));\nBs = cell(size(temp_cell));\nfor i = 1:length(xx_us)\n for j = 1:length(yy_us)\n for k = 1:length(zz_us)\n [nr,nc,np] = size(temp_cell{i,j,k});\n nr = ifftshift(-fix(nr/2):ceil(nr/2)-1);\n nc = ifftshift(-fix(nc/2):ceil(nc/2)-1);\n np = ifftshift(-fix(np/2):ceil(np/2)-1);\n [Nc{i,j,k},Nr{i,j,k},Np{i,j,k}] = meshgrid(nc,nr,np);\n extended_grid = [max(xx_us(i)-overlap_post(1),1),min(xx_uf(i)+overlap_post(1),d1),max(yy_us(j)-overlap_post(2),1),min(yy_uf(j)+overlap_post(2),d2),max(zz_us(k)-overlap_post(3),1),min(zz_uf(k)+overlap_post(3),d3)]; \n Bs{i,j,k} = permute(construct_weights([xx_us(i),xx_uf(i),yy_us(j),yy_uf(j),zz_us(k),zz_uf(k)],extended_grid),[2,1,3]); \n end\n end\nend\nif nd == 2; Np = cellfun(@(x) 0,Nr,'un',0); end\n\n%%\n%maxNumCompThreads(2);\ntemplate = mat2cell_ov(template_in,xx_s,xx_f,yy_s,yy_f,zz_s,zz_f,overlap_pre,sizY);\ntemp_mat = template_in;\nfftTemp = cellfun(@fftn,template,'un',0);\nfftTempMat = fftn(temp_mat);\nif nd == 2; buffer = mat2cell_ov(zeros(d1,d2,bin_width,'single'),xx_s,xx_f,yy_s,yy_f,zz_s,zz_f,overlap_pre,sizY); end\nif nd == 3; buffer = mat2cell_ov(zeros(d1,d2,d3,bin_width,'single'),xx_s,xx_f,yy_s,yy_f,zz_s,zz_f,overlap_pre,sizY); end\n\n\nif ~strcmpi(options.output_type,'mat')\n %options.mem_batch_size = min(round(options.mem_batch_size/bin_width)*bin_width,T);\n if nd == 2; mem_buffer = zeros(d1,d2,options.mem_batch_size,'single'); end\n if nd == 3; mem_buffer = zeros(d1,d2,d3,options.mem_batch_size,'single'); end\nend\n\nswitch lower(options.output_type)\n case 'mat'\n M_final = zeros([sizY,T],data_type);\n case 'memmap'\n M_final = matfile(filename,'Writable',true);\n if nd == 2; M_final.Y(d1,d2,T) = zeros(1,data_type); end\n if nd == 3; M_final.Y(d1,d2,d3,T) = zeros(1,data_type); end\n M_final.Yr(d1*d2*d3,T) = zeros(1,data_type); \n case {'hdf5','h5'}\n if exist(options.h5_filename,'file')\n [pathstr,fname,ext] = fileparts(options.h5_filename); \n new_filename = fullfile(pathstr,[fname,'_',datestr(now,30),ext]);\n warning_msg = ['File ',options.h5_filename,'already exists. Saving motion corrected file as',new_filename]; \n warning('%s',warning_msg);\n options.h5_filename = new_filename;\n end\n M_final = options.h5_filename;\n if nd == 2\n h5create(options.h5_filename,['/',options.h5_groupname],[d1,d2,Inf],'Chunksize',[d1,d2,options.mem_batch_size],'Datatype',data_type);\n elseif nd == 3\n h5create(options.h5_filename,['/',options.h5_groupname],[d1,d2,d3,Inf],'Chunksize',[d1,d2,d3,options.mem_batch_size],'Datatype',data_type);\n end\n case {'tif','tiff'}\n M_final = options.tiff_filename;\n opts_tiff.append = true;\n opts_tiff.big = true;\n if nd == 3\n error('Saving volumetric tiff stacks is currently not supported. Use a different filetype');\n end \n otherwise\n error('This filetype is currently not supported')\nend \n\n%%\nif plot_flag\n if make_avi\n vidObj = VideoWriter(name);\n set(vidObj,'FrameRate',fr);\n open(vidObj);\n end\n if strcmpi(filetype,'mat')\n nnY = quantile(Y(:),0.005);\n mmY = quantile(Y(:),0.995);\n else\n nnY = quantile(Y_temp(:),0.005);\n mmY = quantile(Y_temp(:),0.995);\n end\n fig = figure;\n screensize = get(0,'Screensize' );\n fac = min(min((screensize(3:4)-200)./[d2,d1]),10);\n set(gcf, 'PaperUnits', 'points', 'Units', 'points');\n set(gcf, 'Position', round([100 100 fac*d2 fac*d1]));\nend\ncnt_buf = 0;\nif print_msg; fprintf('Template initialization complete. Now registering all the frames with new template. \\n'); end\n%%\nprevstr = [];\nfor it = 1:iter\n if it < iter; plot_flag = 0; else plot_flag = options.plot_flag; end\n for t = 1:T\n switch filetype\n case 'tif'\n Yt = single(imread(Y,'Index',t,'Info',tiffInfo));\n case 'hdf5'\n Yt = single(h5read(Y,'/mov',[ones(1,nd),t],[sizY(1:nd),1]));\n case 'mem'\n if nd == 2; Yt = single(Y.(var_name)(:,:,t)); end\n if nd == 3; Yt = single(Y.(var_name)(:,:,:,t)); end\n case 'mat'\n if nd == 2; Yt = single(Y(:,:,t)); end\n if nd == 3; Yt = single(Y(:,:,:,t)); end\n end \n minY = min(Yt(:));\n maxY = max(Yt(:));\n Yt = Yt + add_value;\n ind = rem(t,bin_width) + bin_width*(rem(t,bin_width)==0);\n Yc = mat2cell_ov(Yt,xx_s,xx_f,yy_s,yy_f,zz_s,zz_f,overlap_pre,sizY);\n fftY = cellfun(@fftn, Yc, 'un',0);\n \n M_fin = cell(length(xx_us),length(yy_us),length(zz_us)); %zeros(size(Y_temp));\n shifts_temp = zeros(length(xx_s),length(yy_s),length(zz_s),nd); \n diff_temp = zeros(length(xx_s),length(yy_s),length(zz_s));\n if numel(M_fin) > 1 \n if nd == 2; out_rig = dftregistration_min_max(fftTempMat,fftn(Yt),us_fac,-max_shift,max_shift,options.phase_flag); lb = out_rig(3:4); ub = out_rig(3:4); end\n if nd == 3; out_rig = dftregistration_min_max_3d(fftTempMat,fftn(Yt),1,-max_shift,max_shift,options.phase_flag); lb = out_rig(3:5); ub = out_rig(3:5); end\n else\n lb = -max_shift(1,nd);\n ub = max_shift(1,nd);\n max_dev = 0*max_dev;\n end\n if ~use_parallel\n for i = 1:length(xx_s)\n for j = 1:length(yy_s) \n for k = 1:length(zz_s)\n if nd == 2\n %[output,Greg] = dftregistration_max(fftTemp{i,j,k},fftY{i,j,k},us_fac,max_shift); \n [output,Greg] = dftregistration_min_max(fftTemp{i,j,k},fftY{i,j,k},us_fac,lb-max_dev(1:2),ub+max_dev(1:2),options.phase_flag); \n elseif nd == 3\n %[output,Greg] = dftregistration_max_3d(fftTemp{i,j,k},fftY{i,j,k},us_fac,max_shift);\n [output,Greg] = dftregistration_min_max_3d(fftTemp{i,j,k},fftY{i,j,k},us_fac,lb-max_dev,ub+max_dev,options.phase_flag); \n shifts_temp(i,j,k,3) = output(5);\n end\n M_temp = real(ifftn(Greg));\n M_temp = remove_boundaries(M_temp,output(3:end),'copy',template{i,j,k});\n if nd == 2; buffer{i,j,k}(:,:,ind) = M_temp; end \n if nd == 3; buffer{i,j,k}(:,:,:,ind) = M_temp; end \n shifts_temp(i,j,k,1) = output(3);\n shifts_temp(i,j,k,2) = output(4); \n diff_temp(i,j,k) = output(2);\n if all([length(xx_s),length(yy_s),length(zz_s)] == 1)\n M_fin{i,j,k} = remove_boundaries(M_temp,output(3:end),options.boundary,template{i,j,k},add_value);\n end \n end\n end\n end \n else\n Mt2 = cell(length(xx_s)*length(yy_s)*length(zz_s),1); \n shifts_cell = cell(length(xx_s)*length(yy_s)*length(zz_s),1); \n diff_cell = cell(length(xx_s)*length(yy_s)*length(zz_s),1); \n for ii = length(xx_s)*length(yy_s)*length(zz_s):-1:1\n [i,j,k] = ind2sub([length(xx_s),length(yy_s),length(zz_s)],ii);\n if nd == 2; future_results(ii) = parfeval(@dftregistration_min_max,2,fftTemp{i,j,k},fftY{i,j,k},us_fac,lb-max_dev(1:2),ub+max_dev(1:2),options.phase_flag); end\n if nd == 3; future_results(ii) = parfeval(@dftregistration_min_max_3d,2,fftTemp{i,j,k},fftY{i,j,k},us_fac,lb-max_dev,ub+max_dev,options.phase_flag); end\n end\n for i = 1:length(xx_s)*length(yy_s)*length(zz_s)\n [ii,output,Greg] = fetchNext(future_results);\n M_temp = real(ifftn(Greg));\n Mt2{ii} = M_temp;\n shifts_cell{ii} = output(3:end);\n diff_cell{ii} = output(2);\n end\n% parfor ii = 1:length(xx_s)*length(yy_s)*length(zz_s)\n% [i,j,k] = ind2sub([length(xx_s),length(yy_s),length(zz_s)],ii);\n% %if nd == 2; [output,Greg] = dftregistration_max(fftTemp{i,j,k},fftY{i,j,k},us_fac,max_shift); end\n% %if nd == 3; [output,Greg] = dftregistration_max_3d(fftTemp{i,j,k},fftY{i,j,k},us_fac,max_shift); end\n% if nd == 2; [output,Greg] = dftregistration_min_max(fftTemp{i,j,k},fftY{i,j,k},us_fac,lb-max_dev(1:2),ub+max_dev(1:2),options.phase_flag); end\n% if nd == 3; [output,Greg] = dftregistration_min_max_3d(fftTemp{i,j,k},fftY{i,j,k},us_fac,lb-max_dev,ub+max_dev,options.phase_flag); end \n% M_temp = real(ifftn(Greg));\n% Mt2{ii} = M_temp;\n% shifts_cell{ii} = output(3:end);\n% diff_cell{ii} = output(2);\n% end\n for ii = 1:length(xx_s)*length(yy_s)*length(zz_s)\n [i,j,k] = ind2sub([length(xx_s),length(yy_s),length(zz_s)],ii);\n if nd == 2; buffer{i,j,k}(:,:,ind) = Mt2{ii}; end\n if nd == 3; buffer{i,j,k}(:,:,:,ind) = Mt2{ii}; end\n if mot_uf == 1\n M_fin{i,j,k} = Mt2{ii};\n end\n shifts_temp(i,j,k,:) = shifts_cell{ii};\n diff_temp(i,j,k) = diff_cell{ii};\n end \n end \n shifts(t).shifts = shifts_temp;\n shifts(t).diff = diff_temp;\n \n switch lower(options.shifts_method)\n case 'fft'\n if any([length(xx_s),length(yy_s),length(zz_s)] > 1)\n if ~isfield(options,'shifts_method'); options.shifts_method = 'FFT'; end \n if mot_uf(3) > 1 \n do = [length(xx_us),length(yy_us),length(zz_us)]./[length(xx_s),length(yy_s),length(zz_s)];\n ds = [length(xx_s),length(yy_s),length(zz_s)];\n dim = [length(xx_us),length(yy_us),length(zz_us)];\n [Xq,Yq,Zq] = meshgrid(linspace((1+1/do(2))/2,ds(2)+(1-1/do(2))/2,dim(2)),linspace((1+1/do(1))/2,ds(1)+(1-1/do(1))/2,dim(1)),linspace((1+1/do(3))/2,ds(3)+(1-1/do(3))/2,dim(3)));\n %tform = affine3d(diag([mot_uf(:);1]));\n %tform = affine3d(diag([mot_uf([2,1,3])';1]));\n %diff_up = imwarp(diff_temp,tform,'OutputView',imref3d([length(xx_uf),length(yy_uf),length(zz_uf)]));\n %diff_up = imwarp(diff_temp,tform,'OutputView',imref3d([length(xx_uf),length(yy_uf),length(zz_uf)]),'SmoothEdges',true);\n diff_up = interp3(diff_temp,Xq,Yq,Zq,'makima');\n shifts_up = zeros([size(diff_up),3]);\n %for dm = 1:3; shifts_up(:,:,:,dm) = imwarp(shifts_temp(:,:,:,dm),tform,'OutputView',imref3d([length(xx_uf),length(yy_uf),length(zz_uf)]),'SmoothEdges',true); end\n for dm = 1:3; shifts_up(:,:,:,dm) = interp3(shifts_temp(:,:,:,dm),Xq,Yq,Zq,'makima'); end\n else\n shifts_up = imresize(shifts_temp,[length(xx_uf),length(yy_uf)]);\n diff_up = imresize(diff_temp,[length(xx_uf),length(yy_uf)]);\n end\n\n shifts(t).shifts_up = shifts_up;\n shifts(t).diff = diff_up;\n for i = 1:length(xx_uf)\n for j = 1:length(yy_uf)\n for k = 1:length(zz_uf)\n extended_grid = [max(xx_us(i)-overlap_post(1),1),min(xx_uf(i)+overlap_post(1),d1),max(yy_us(j)-overlap_post(2),1),min(yy_uf(j)+overlap_post(2),d2),max(zz_us(k)-overlap_post(3),1),min(zz_uf(k)+overlap_post(3),d3)];\n I_temp = Yt(extended_grid(1):extended_grid(2),extended_grid(3):extended_grid(4),extended_grid(5):extended_grid(6));\n M_fin{i,j,k} = shift_reconstruct(I_temp,shifts_up(i,j,k,:),diff_up(i,j,k),us_fac,Nr{i,j,k},Nc{i,j,k},Np{i,j,k},options.boundary,add_value); \n %M_fin{i,j,k} = shift_reconstruct2(I_temp,shifts_up(i,j,k,:),'bilinear',diff_up(i,j,k),us_fac,Nr{i,j,k},Nc{i,j,k},Np{i,j,k},options.boundary,add_value);\n end\n end\n end \n else\n shifts_up = shifts_temp;\n shifts(t).shifts_up = shifts(t).shifts;\n end\n gx = max(abs(reshape(diff(shifts_up,[],1),[],1)));\n gy = max(abs(reshape(diff(shifts_up,[],2),[],1)));\n gz = max(abs(reshape(diff(shifts_up,[],3),[],1)));\n flag_interp = max([gx;gy;gz;0])<0.5; % detect possible smearing\n\n if flag_interp \n Mf = cell2mat_ov_sum(M_fin,xx_us,xx_uf,yy_us,yy_uf,zz_us,zz_uf,overlap_post,sizY,Bs) - add_value;\n else \n Mf = cell2mat_ov(M_fin,xx_us,xx_uf,yy_us,yy_uf,zz_us,zz_uf,overlap_post,sizY) - add_value;\n end \n \n otherwise\n shifts(t).shifts_up = shifts(t).shifts;\n if nd == 3 \n shifts_up = zeros([options.d1,options.d2,options.d3,3]);\n do = size(shifts_up)./size(shifts_temp);\n ds = size(shifts_temp);\n dim = [options.d1,options.d2,options.d3];\n if (0)\n [Xq,Yq,Zq] = meshgrid(linspace(1,ds(2),dim(2)),linspace(1,ds(1),dim(1)),linspace(1,ds(3),dim(3)));\n else\n [Xq,Yq,Zq] = meshgrid(linspace((1+1/do(2))/2,ds(2)+(1-1/do(2))/2,dim(2)),linspace((1+1/do(1))/2,ds(1)+(1-1/do(1))/2,dim(1)),linspace((1+1/do(3))/2,ds(3)+(1-1/do(3))/2,dim(3)));\n Xq(Xq<1)=1; Xq(Xq>dim(2))=dim(2);\n Yq(Yq<1)=1; Yq(Yq>dim(1))=dim(1);\n Zq(Zq<1)=1; Zq(Zq>dim(3))=dim(3);\n end\n if numel(shifts_temp) > 3\n for dm = 1:3; shifts_up(:,:,:,dm) = interp3(shifts_temp(:,:,:,dm),Xq,Yq,Zq,'makima'); end\n %tform = affine3d(diag([do([2,1,3])';1]));\n %for dm = 1:3; shifts_up(:,:,:,dm) = imwarp(shifts_temp(:,:,:,dm),tform,'OutputView',imref3d([options.d1,options.d2,options.d3]),'SmoothEdges',true); end\n else\n for dm = 1:3; shifts_up(:,:,:,dm) = shifts_temp(dm); end\n end\n shifts_up(2:2:end,:,:,2) = shifts_up(2:2:end,:,:,2) + col_shift;\n Mf = imwarp(Yt,-cat(4,shifts_up(:,:,:,2),shifts_up(:,:,:,1),shifts_up(:,:,:,3)),options.shifts_method,'FillValues',fill_value); \n else\n shifts_up = imresize(shifts_temp,[options.d1,options.d2]);\n shifts_up(2:2:end,:,2) = shifts_up(2:2:end,:,2) + col_shift;\n Mf = imwarp(Yt,-cat(3,shifts_up(:,:,2),shifts_up(:,:,1)),options.shifts_method,'FillValues',fill_value); \n end \n \n Mf(MfmaxY) = maxY; \n end \n \n if ~strcmpi(options.output_type,'mat')\n rem_mem = rem(t,options.mem_batch_size);\n if rem_mem == 0; rem_mem = options.mem_batch_size; end \n if nd == 2; mem_buffer(:,:,rem_mem) = cast(Mf,data_type); end\n if nd == 3; mem_buffer(:,:,:,rem_mem) = cast(Mf,data_type); end\n end\n switch lower(options.output_type)\n case 'mat'\n if nd == 2; M_final(:,:,t) = cast(Mf,data_type); end\n if nd == 3; M_final(:,:,:,t) = cast(Mf,data_type); end\n case 'memmap'\n if rem_mem == options.mem_batch_size || t == T\n if nd == 2; M_final.Y(:,:,t-rem_mem+1:t) = mem_buffer(:,:,1:rem_mem); end\n if nd == 3; M_final.Y(:,:,:,t-rem_mem+1:t) = mem_buffer(:,:,:,1:rem_mem); end\n M_final.Yr(:,t-rem_mem+1:t) = reshape(mem_buffer(1:d1*d2*d3*rem_mem),d1*d2*d3,rem_mem);\n end \n case {'hdf5','h5'}\n if rem_mem == options.mem_batch_size || t == T\n if nd == 2; h5write(options.h5_filename,['/',options.h5_groupname],mem_buffer(:,:,1:rem_mem),[ones(1,nd),t-rem_mem+1],[sizY(1:nd),rem_mem]); end\n if nd == 3; h5write(options.h5_filename,['/',options.h5_groupname],mem_buffer(:,:,:,1:rem_mem),[ones(1,nd),t-rem_mem+1],[sizY(1:nd),rem_mem]); end\n end\n case {'tif','tiff'}\n if rem_mem == options.mem_batch_size || t == T\n saveastiff(cast(mem_buffer(:,:,1:rem_mem),data_type),options.tiff_filename,opts_tiff);\n end \n end \n \n if mod(t,bin_width) == 0 && upd_template\n if print_msg\n str=[num2str(t), ' out of ', num2str(T), ' frames registered, iteration ', num2str(it), ' out of ', num2str(iter), '..'];\n refreshdisp(str, prevstr, t);\n prevstr=str; \n %fprintf('%i out of %i frames registered, iteration %i out of %i \\n',t,T,it,iter)\n end\n cnt_buf = cnt_buf + 1; \n if strcmpi(method{2},'mean')\n new_temp = cellfun(@(x) nanmean(x,nd+1), buffer, 'UniformOutput',false);\n elseif strcmpi(method{2},'median');\n new_temp = cellfun(@(x) nanmedian(x,nd+1), buffer, 'UniformOutput', false);\n end\n if strcmpi(method{1},'mean')\n cnt = t/bin_width + 1;\n template = cellfun(@plus, cellfun(@(x) x*(cnt-1)/cnt, template,'un',0), cellfun(@(x) x*1/cnt, new_temp,'un',0), 'un',0);\n elseif strcmpi(method{1},'median');\n if cnt_buf <= buffer_width\n if nd == 2; buffer_med(:,:,cnt_buf) = cell2mat_ov(new_temp,xx_s,xx_f,yy_s,yy_f,zz_s,zz_f,overlap_pre,sizY); end\n if nd == 3; buffer_med(:,:,:,cnt_buf) = cell2mat_ov(new_temp,xx_s,xx_f,yy_s,yy_f,zz_s,zz_f,overlap_pre,sizY); end\n else\n buffer_med = circshift(buffer_med,[zeros(1,nd),-1]);\n if nd == 2; buffer_med(:,:,buffer_width) = cell2mat_ov(new_temp,xx_s,xx_f,yy_s,yy_f,zz_s,zz_f,overlap_pre,sizY); end\n if nd == 3; buffer_med(:,:,:,buffer_width) = cell2mat_ov(new_temp,xx_s,xx_f,yy_s,yy_f,zz_s,zz_f,overlap_pre,sizY); end\n end\n template = mat2cell_ov(nanmedian(buffer_med,nd+1),xx_s,xx_f,yy_s,yy_f,zz_s,zz_f,overlap_pre,sizY);\n end\n fftTemp = cellfun(@fftn, template, 'un',0);\n temp_mat = cell2mat_ov(template,xx_s,xx_f,yy_s,yy_f,zz_s,zz_f,overlap_pre,sizY);\n fftTempMat = fftn(temp_mat);\n end \n \n if plot_flag && mod(t,1) == 0\n subplot(221); imagesc(Yt-add_value,[nnY,mmY]); title('Raw data','fontweight','bold','fontsize',14); \n xlabel(sprintf('Frame %i out of %i',t,T),'fontweight','bold','fontsize',14); set(gca,'Xtick',[],'Ytick',[]);\n subplot(222); imagesc(Mf,[nnY,mmY]); title('Motion Corrected','fontweight','bold','fontsize',14); colormap('bone'); axis off;\n subplot(223); quiver(shifts_up(:,:,:,1),shifts_up(:,:,:,2),'Autoscale','off'); title('Motion vector field','fontweight','bold','fontsize',14); axis off;\n subplot(224); imagesc(cell2mat_ov(template,xx_s,xx_f,yy_s,yy_f,zz_s,zz_f,overlap_pre,sizY)-add_value,[nnY,mmY]); title('Matching Template','fontweight','bold','fontsize',14); axis off\n drawnow;\n if make_avi \n currFrame = getframe(fig);\n writeVideo(vidObj,currFrame); \n end\n end \n end\n\nif print_msg; fprintf('\\n'); end\n \nif it == iter\n template = cellfun(@(x) x - add_value,template,'un',0);\n template = cell2mat_ov(template,xx_s,xx_f,yy_s,yy_f,zz_s,zz_f,overlap_pre,sizY);\nend\nif memmap\n M_final.shifts = shifts;\n M_final.template = template;\nend\n\nif make_avi && plot_flag\n close(vidObj);\nend\nmaxNumCompThreads('automatic');\nif print_msg; fprintf('done. \\n'); end\nend", "meta": {"author": "flatironinstitute", "repo": "NoRMCorre", "sha": "1b39f82f9673d51cdf9b38d3419b62bf06cf7196", "save_path": "github-repos/MATLAB/flatironinstitute-NoRMCorre", "path": "github-repos/MATLAB/flatironinstitute-NoRMCorre/NoRMCorre-1b39f82f9673d51cdf9b38d3419b62bf06cf7196/normcorre.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.34620227597876374}}
{"text": "function D = spm_eeg_contrast(S)\n% Compute contrasts over trials or trial types\n% FORMAT D = spm_eeg_contrast(S)\n%\n% S - optional input struct\n% fields of S:\n% D - filename of EEG mat-file with epoched data\n% c - contrast matrix, each row computes a contrast of the data\n% label - cell array of labels for the contrasts, the same size as\n% number of rows in c\n% weighted - flag whether average should be weighted by number of\n% replications (yes (1), no (0))\n% prefix - prefix for the output file [default: 'w']\n%\n% Output:\n% D - EEG data struct (also written to disk)\n%__________________________________________________________________________\n%\n% spm_eeg_contrast computes contrasts of data, over epochs of data. The\n% input is a single MEEG file. The argument c must have dimensions\n% Ncontrasts X Nepochs, where Ncontrasts is the number of contrasts and\n% Nepochs the number of epochs, i.e. each row of c contains one contrast\n% vector. The output is a M/EEG file with Ncontrasts epochs. The typical\n% use is to compute, for display purposes, contrasts like the difference or\n% interaction between trial types in channel space.\n%__________________________________________________________________________\n% Copyright (C) 2008-2017 Wellcome Trust Centre for Neuroimaging\n\n% Stefan Kiebel, Rik Henson\n% $Id: spm_eeg_contrast.m 7132 2017-07-10 16:22:58Z guillaume $\n\nSVNrev = '$Rev: 7132 $';\n\n%-Startup\n%--------------------------------------------------------------------------\nspm('FnBanner', mfilename, SVNrev);\nspm('FigName','M/EEG Contrast'); spm('Pointer','Watch');\n\n%-Get MEEG object\n%--------------------------------------------------------------------------\nif ~isfield(S, 'prefix'), S.prefix = 'w'; end\nif ~isfield(S, 'weighted'), S.weighted = 0; end\n\nif ~(isfield(S, 'c') && isfield(S, 'label') && numel(S.label)==size(S.c, 1))\n error('Invalid contrast specification.');\nend\n\nD = spm_eeg_load(S.D);\n \n%-Compute contrasts\n%--------------------------------------------------------------------------\n\nc = S.c;\nNcontrasts = size(c, 1);\n\n% Pad with zeros as in the contrast manager\nif size(c, 2) ~= D.ntrials\n error('The number of columns in the contrast matrix does not match the number of trials.');\nend\n\nif ~isempty(D.repl)\n weighted = S.weighted;\nelse\n weighted = 0;\nend\n\nif strncmp(D.transformtype, 'TF', 2)\n Dnew = clone(D, [S.prefix fname(D)], [D.nchannels D.nfrequencies D.nsamples Ncontrasts]);\nelse\n Dnew = clone(D, [S.prefix fname(D)],[D.nchannels D.nsamples Ncontrasts]);\nend\n\nspm_progress_bar('Init', Ncontrasts, 'Contrasts computed');\nif Ncontrasts > 100, Ibar = floor(linspace(1, Ncontrasts, 100));\nelse Ibar = 1:Ncontrasts; end\n\nfor i = 1:Ncontrasts\n\n if weighted\n p = find(c(i,:) == 1);\n if ~isempty(p)\n r = D.repl(p);\n c(i,p) = r/sum(r);\n end\n\n p = find(c(i,:) == -1);\n if ~isempty(p)\n r = D.repl(p);\n c(i,p) = -r/sum(r);\n end\n end\n\n disp(['Contrast ', mat2str(i),': ', mat2str(c(i,:),3)])\n\n if strncmp(D.transformtype, 'TF', 2)\n d = zeros(D.nchannels, D.nfrequencies, D.nsamples);\n\n for j = 1:D.nchannels\n for f = 1:D.nfrequencies\n d(j, f, :) = c(i,:) * spm_squeeze(D(j, f, :, :), [1 2 4])';\n end\n end\n\n Dnew(1:Dnew.nchannels, 1:D.nfrequencies, 1:Dnew.nsamples, i) = d;\n\n else\n\n d = zeros(D.nchannels, D.nsamples);\n\n for j = 1:D.nchannels\n d(j, :) = c(i,:) * squeeze(D(j, :, :))';\n end\n\n Dnew(1:Dnew.nchannels, 1:Dnew.nsamples, i) = d;\n end\n \n newrepl(i) = sum(D.repl(find(c(i,:)~=0)));\n\n if any(Ibar == i), spm_progress_bar('Set', i); end\n\nend\n\nspm_progress_bar('Clear');\n\n%-\n%--------------------------------------------------------------------------\nDnew = conditions(Dnew, ':', S.label);\nDnew = trialonset(Dnew, ':', []);\nDnew = trialtag(Dnew, ':', []);\nDnew = badtrials(Dnew, ':', 0);\nDnew = repl(Dnew, ':', newrepl);\nDnew = type(Dnew, 'evoked');\n\n% remove previous source reconsructions\nif isfield(Dnew,'inv')\n Dnew = rmfield(Dnew,'inv');\nend\n\n%-Save new M/EEG data\n%--------------------------------------------------------------------------\nD = Dnew;\nD = D.history('spm_eeg_contrast', S);\nsave(D);\n\n%-Cleanup\n%--------------------------------------------------------------------------\nspm('FigName','M/EEG Contrast: done'); spm('Pointer','Arrow');\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_eeg_contrast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.34620226997429693}}
{"text": "% std_stat() - compute statistics for ERP/spectral traces or ERSP/ITC images\n% of a component or channel cluster in a STUDY. \n% Usage:\n% >> std_stat( data, 'key', 'val', ...)\n% Inputs:\n% data - [cell array] mean data for each subject group and/or data\n% condition. For example, to compute mean ERPs statistics from a \n% STUDY for epochs of 800 frames in two conditions from three \n% groups of 12 subjects:\n%\n% >> data = { [800x12] [800x12] [800x12];... % 3 groups, cond 1\n% [800x12] [800x12] [800x12] }; % 3 groups, cond 2\n% >> pcond = std_stat(data, 'condstats', 'on');\n%\n% By default, parametric statistics are computed across subjects \n% in the three groups. See below and >> help statcond \n% for more information about the statistical computations.\n%\n% Statistics options:\n% 'groupstats' - ['on'|'off'] Compute (or not) statistics across groups.\n% {default: 'off'}\n% 'condstats' - ['on'|'off'] Compute (or not) statistics across groups.\n% {default: 'off'}\n% 'statistics' - ['param'|'perm'] Type of statistics to use: 'param' for\n% parametric; 'perm' for permutations {default: 'param'}\n% 'naccu' - [integer] Number of surrogate averges fo accumulate when \n% computing permutation-based statistics. For example, to\n% test p<0.01 use naccu>=200; for p<0.001, use naccu>=2000. \n% If a non-NaN 'threshold' is set (see below) and 'naccu' \n% is too low, it will be automatically increased. This \n% keyword available only from the command line {default:500}\n% 'threshold' - [NaN|p-value] threshold for computing p-value. In this \n% function, it is only used to compute naccu above. NaN\n% means that no threshold has been set. \n% 'mcorrect' - ['none'|'fdr'] apply correcting for multiple comparisons.\n%\n% Outputs:\n% pcond - [cell] condition pvalues or mask (0 or 1). One element per group.\n% pgroup - [cell] group pvalues or mask (0 or 1). One element per condition.\n% pinter - [cell] three elements, condition pvalues (group pooled),\n% group pvalues (condition pooled) and interaction pvalues.\n%\n% Author: Arnaud Delorme, CERCO, CNRS, 2006-\n% \n% See also: statcond()\n\n% 'statmode' - ['subjects'|'trials'] standard statistics are \n% 'subjects' where the statistics is performed accross\n% the mean ERSP (or ITC) of single subjects. For 'trials'\n% statistics, the single-trial data epochs of all subjects\n% are pooled together. This requires that they were\n% saved on disk using option 'savetrials', 'on' at the time\n% of computation. Note that these single-trial data\n% may use several GB of disk space and that computation \n% of 'trials' statistics requires a lot of RAM.\n\nfunction [pcond, pgroup, pinter] = std_stat(data, varargin)\n\npgroup = {};\npcond = {};\npinter = {};\nif nargin < 1\n help std_stat;\n return;\nend;\n\n% decode inputs\n% -------------\nopt = {};\nif nargin > 1\n if isstruct(varargin{1})\n g = struct(varargin{2:end});\n if isfield(g, 'condstats'), varargin{1} = rmfield(varargin{1}, 'condstats'); end;\n if isfield(g, 'groupstats'), varargin{1} = rmfield(varargin{1}, 'groupstats'); end;\n tmpparams = fieldnames(varargin{1}); tmpparams = tmpparams';\n tmpparams(2,:) = struct2cell(varargin{1});\n varargin = { tmpparams{:} varargin{2:end} };\n end;\nend;\nopt = finputcheck( varargin, { 'threshold' 'real' [] NaN;\n 'mcorrect' 'string' { 'none' 'fdr' } 'none';\n 'naccu' 'integer' [] [];\n 'groupstats' 'string' { 'on' 'off' } 'off';\n 'paired' 'cell' { 'on' 'off' } { 'on' 'on' };\n 'condstats' 'string' { 'on' 'off' } 'off';\n 'statistics' 'string' { 'param' 'perm' 'bootstrap' } 'param' }, ...\n 'std_stat', 'ignore');\n\nif isstr(opt), error(opt); end;\nif ~isnan(opt.threshold(1)) && isempty(opt.naccu), opt.naccu = 1/opt.threshold(end)*2; end;\nif any(any(cellfun('size', data, 2)==1)), opt.groupstats = 'off'; opt.condstats = 'off'; end;\nif strcmpi(opt.mcorrect, 'fdr'), opt.naccu = opt.naccu*20; end;\nif isempty(opt.naccu), opt.naccu = 2000; end;\nif strcmpi(opt.statistics, 'param') && ~isreal(data{1})\n fprintf('*** Cannot use parametric statistics for single-trial ITC significance ***\\n');\n return;\nend;\nnc = size(data,1);\nng = size(data,2);\n\n% compute significance mask\n% --------------------------\nif strcmpi(opt.condstats, 'on') && nc > 1\n for g = 1:ng\n [F df pval] = statcond(data(:,g), 'mode', opt.statistics, 'naccu', opt.naccu, 'paired', opt.paired{1}); \n pcond{g} = squeeze(pval);\n end;\nelse\n pcond = {};\nend;\nif strcmpi(opt.groupstats, 'on') && ng > 1\n for c = 1:nc\n [F df pval] = statcond(data(c,:), 'mode', opt.statistics, 'naccu', opt.naccu, 'paired', opt.paired{2}); \n pgroup{c} = squeeze(pval);\n end;\nelse\n pgroup = {};\nend;\nif ( strcmpi(opt.groupstats, 'on') && strcmpi(opt.condstats, 'on') ) & ng > 1 & nc > 1\n opt.paired = sort(opt.paired); % put 'off' first if present\n [F df pval] = statcond(data, 'mode', opt.statistics, 'naccu', opt.naccu, 'paired', opt.paired{1});\n for index = 1:length(pval)\n pinter{index} = squeeze(pval{index});\n end;\nelse\n pinter = {};\nend;\n\nif ~isempty(opt.groupstats) || ~isempty(opt.condstats) \n if strcmpi(opt.mcorrect, 'fdr'), \n disp('Applying FDR correction for multiple comparisons');\n for ind = 1:length(pcond), pcond{ind} = fdr( pcond{ind} ); end;\n for ind = 1:length(pgroup), pgroup{ind} = fdr( pgroup{ind} ); end;\n if ~isempty(pinter), \n pinter{1} = fdr(pinter{1}); \n pinter{2} = fdr(pinter{2}); \n pinter{3} = fdr(pinter{3}); \n end;\n end;\n if ~isnan(opt.threshold)\n for ind = 1:length(pcond), pcond{ind} = applythreshold(pcond{ind}, opt.threshold); end;\n for ind = 1:length(pgroup), pgroup{ind} = applythreshold(pgroup{ind}, opt.threshold); end;\n for ind = 1:length(pinter), pinter{ind} = applythreshold(pinter{ind}, opt.threshold); end;\n end;\nend;\n\nfunction newdata = applythreshold(data, threshold)\n threshold = sort(threshold);\n newdata = zeros(size(data));\n for index = 1:length(threshold)\n inds = data < threshold(index);\n data(inds) = 1;\n newdata(inds) = length(threshold)-index+1;\n end;\n \n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/functions/studyfunc/std_stat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.34620226997429693}}
{"text": "function gammaM = createGammaDose(doseNum1,doseNum2,strNum,doseAgreement,...\n distAgreement,thresholdPercentMax,maxDistanceFactor,doseDiffMethod,planC)\n% function gammaM = createGammaDose(doseNum1,doseNum2,strNum,...\n% doseAgreement,distAgreement,thresholdPercentMax,maxDistanceFactor,doseDiffMethod,planC);\n%\n% This function creates and adds a gamma dose to planC.\n% 3D Gamma is calculated between doseNum1 and doseNum2.\n% dosePercent is the dose criteria based on max(doseNum1). \n% doseAgreement = max(doseNum1)*dosePercent/100;\n% distAgreement is in cm.\n%\n% APA, 04/26/2012\n\nif ~exist('planC','var')\n global planC\nend\n \nindexS = planC{end};\n\n% Prepare inputs for gamma calculation\nassocScan = getDoseAssociatedScan(doseNum1,planC);\nif isempty(assocScan)\n assocScan = 1;\nend\n[newXgrid, newYgrid, newZgrid, doseArray1, doseArray2, interpMask3M] = ...\n prepareDosesForGamma(doseNum1,doseNum2,strNum,assocScan,planC);\n\ndeltaX = abs(newXgrid(2) - newXgrid(1));\ndeltaY = abs(newYgrid(2) - newYgrid(1));\ndeltaZ = abs(newZgrid(2) - newZgrid(1));\n\nif doseDiffMethod == 1\n doseAgreement = doseAgreement*max(planC{indexS.dose}(doseNum1).doseArray(:))/100;\nend\n\nthresholdAbsolute = thresholdPercentMax*max(planC{indexS.dose}(doseNum1).doseArray(:))/100;\n\nmaxCalcDistance = distAgreement * maxDistanceFactor;\n\ngammaM = gammaDose3d(doseArray1, doseArray2, interpMask3M, ...\n [deltaX deltaY deltaZ], doseAgreement, distAgreement, ...\n maxCalcDistance, thresholdAbsolute, doseDiffMethod);\n\n% Assume doses within the filter threshold pass gamma\n%gammaM(isnan(gammaM)) = 0;\n\nnewDoseNum = length(planC{indexS.dose}) + 1;\n\n%Remove old caching info.\nplanC{indexS.dose}(newDoseNum).cachedMask = [];\nplanC{indexS.dose}(newDoseNum).cachedColor = [];\nplanC{indexS.dose}(newDoseNum).cachedTime = [];\n\n%Set coordinates.\nplanC{indexS.dose}(newDoseNum).sizeOfDimension1 = length(newXgrid);\nplanC{indexS.dose}(newDoseNum).sizeOfDimension2 = length(newYgrid);\nplanC{indexS.dose}(newDoseNum).sizeOfDimension3 = length(newZgrid);\nplanC{indexS.dose}(newDoseNum).horizontalGridInterval = newXgrid(2)-newXgrid(1);\nplanC{indexS.dose}(newDoseNum).verticalGridInterval = newYgrid(2)-newYgrid(1);\nplanC{indexS.dose}(newDoseNum).depthGridInterval = newZgrid(2)-newZgrid(1);\nplanC{indexS.dose}(newDoseNum).coord1OFFirstPoint = newXgrid(1);\nplanC{indexS.dose}(newDoseNum).coord2OFFirstPoint = newYgrid(1);\nplanC{indexS.dose}(newDoseNum).coord3OfFirstPoint = newZgrid(1);\nplanC{indexS.dose}(newDoseNum).zValues = newZgrid;\nplanC{indexS.dose}(newDoseNum).doseUnits = 'Gy';\nplanC{indexS.dose}(newDoseNum).doseArray = gammaM;\nplanC{indexS.dose}(newDoseNum).doseUID = createUID('dose');\nstrName = planC{indexS.structures}(strNum).structureName;\nplanC{indexS.dose}(newDoseNum).fractionGroupID = ['Gamma_',...\n num2str(doseAgreement),'%_',num2str(distAgreement*10),'mm','_',strName];\n\n%Switch to new dose\nsliceCallBack('selectDose', num2str(newDoseNum));\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/createGammaDose.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.34605806647690246}}
{"text": "function [ consumption ] = infer_consumption(result, evaluation_and_training_days, usage_duration, appliance, setup)\n\n %% infer consumption from average consumption of corresponding appliance\n num_measurements = size(evaluation_and_training_days{1},1) * 86400 / setup.granularity;\n consumption = zeros(1, num_measurements);\n\n %% Fridge, Freezer, TV, Stereo\n if strcmp(appliance, 'Fridge') == 1 ...\n || strcmp(appliance, 'Freezer') == 1 ...\n || strcmp(appliance, 'TV') == 1 ...\n || strcmp(appliance, 'Stereo') == 1\n \n warning('off');\n training_days = evaluation_and_training_days{2};\n [avg_runtime, plug_events] = get_average_runtime_from_plug_data(appliance, training_days, setup);\n average_power = get_average_power_from_plug_data(appliance, training_days, setup, plug_events);\n %% HERE\n\n times = result.events(:,1);\n on_events = result.events(:,3) > 0;\n times_on_events = times(on_events);\n times_off_events = times(~on_events); \n events_to_skip = [];\n for i = 1:length(times)\n if any(events_to_skip == i)\n continue;\n end\n % is on event\n % on event: check if off_event is within runtime\n % yes: on_event:off_event, increase by off_event\n % no: on_event:on_event+runtime, increase by runtime [ check boundaries ]\n if on_events(i) == 1\n switch_on = times(i);\n potential_off_events = times_off_events > switch_on & times_off_events < switch_on + avg_runtime;\n if any(potential_off_events)\n off_idx = min(find(potential_off_events));\n switch_off = times_off_events(off_idx);\n consumption(switch_on:switch_off) = average_power;\n % skip off event\n idx_off_event = find(times == switch_off);\n events_to_skip = [events_to_skip, i:idx_off_event];\n else\n if switch_on + avg_runtime <= num_measurements\n consumption(switch_on:switch_on+avg_runtime) = average_power;\n else\n consumption(switch_on:end) = average_power;\n end\n end\n % off event: check if on_event is within runtime\n % yes: on_event:off_event;\n % [ not possible, this case is handled above ]\n % no: off_event-runtime:off_event [ check boundaries ]\n else\n switch_off = times(i);\n if switch_off - avg_runtime >= 1\n consumption(switch_off-avg_runtime:switch_off) = average_power;\n else\n consumption(1:switch_off) = average_power;\n end\n end\n end\n warning('on');\n \n \n \n \n \n \n \n elseif strcmp(appliance, 'Dishwasher') == 1\n for times = result.usage_times_start\n average_power = 1000; %1 kWh\n consumption(times:times+usage_duration-1) = average_power / usage_duration * 3600;\n end\n \n elseif strcmp(appliance, 'Water kettle') == 1\n average_power = 1800;\n times = result.events(:,1)\n on_events = result.events(:,3) > 0\n times_on_events = times(on_events);\n times_off_events = times(~on_events);\n\n for i = 1:length(times_on_events)\n switch_on = times_on_events(i);\n potential_off_events = times_off_events > switch_on & times_off_events < switch_on + usage_duration;\n if any(potential_off_events)\n switch_off = times_off_events(max(find(potential_off_events)));\n consumption(switch_on:switch_off) = average_power;\n end\n end\n\n else\n error('Determining consumption for appliance %s not implemented yet');\n end\nend", "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/algorithms/weiss_alg/appliances/infer_consumption.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.34605806159836067}}
{"text": "function [x,p] = getLastState(stage,colloc,stageVars)\nN = stage.N;\nnx = stage.nx;\nni = colloc.num_i;\nnu = stage.nu;\nnp = stage.np;\n\n[X_indizes, ~, ~, P_indizes, ~] = ocl.simultaneous.indizes(N, nx, ni, nu, np);\nx = stageVars(X_indizes(:,end));\np = stageVars(P_indizes(:,end));\n\n", "meta": {"author": "OpenOCL", "repo": "OpenOCL", "sha": "348fc31929791ddc8ed15a15733cf060a2e4674c", "save_path": "github-repos/MATLAB/OpenOCL-OpenOCL", "path": "github-repos/MATLAB/OpenOCL-OpenOCL/OpenOCL-348fc31929791ddc8ed15a15733cf060a2e4674c/+ocl/+simultaneous/getLastState.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6113819874558604, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.34605353698504737}}
{"text": "function counts = numNeighbors(grains)\n% returns the number of neighboring grains\n%\n% Input\n% grains - @grain2d\n%\n% Output\n% counts - number of neighbors per grain\n%\n\n% get list of neighbouring grains\npairs = grains.neighbors('full');\n\n% get the number of neighbours per grain\nng = max(grains.id);\ncountIds = full(sparse(pairs(pairs<=ng),1,1,ng,1));\n\n% rearange with respect to grain order\ncounts = countIds(grains.id);\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/EBSDAnalysis/@grain2d/numNeighbors.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6113819874558604, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.34605353698504737}}
{"text": "function x = pad2minsize(x, minsize, v)\n% PAD2MINSIZE pads INPUT with given VALUE so that both spatial sizes are at least MINSIZE.\n%\n% X = pad2minsize(X, MINSIZE, V)\n% Default minimum image size MINSIZE is 70. \n% Default padding value V is 0.\n\n\tif ~exist('v'), v = 0; end\n\tif ~exist('minsize'), minsize = 70; end\n\tx = padarray(x, [max(minsize-size(x,1), 0), max(minsize-size(x,2), 0)], v, 'post');", "meta": {"author": "filipradenovic", "repo": "cnnimageretrieval", "sha": "93a7391a2f8b13ff189d0c6131b95e0363542659", "save_path": "github-repos/MATLAB/filipradenovic-cnnimageretrieval", "path": "github-repos/MATLAB/filipradenovic-cnnimageretrieval/cnnimageretrieval-93a7391a2f8b13ff189d0c6131b95e0363542659/utils/pad2minsize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.34600581309835327}}
{"text": "function visualizeHOG(w)\n% Visualize HOG features/weights.\n% visualizeHOG(w)\n\n% AUTORIGHTS\n% -------------------------------------------------------\n% Copyright (C) 2011-2012 Ross Girshick\n% Copyright (C) 2008, 2009, 2010 Pedro Felzenszwalb, Ross Girshick\n% Copyright (C) 2007 Pedro Felzenszwalb, Deva Ramanan\n% \n% This file is part of the voc-releaseX code\n% (http://people.cs.uchicago.edu/~rbg/latent/)\n% and is available under the terms of an MIT-like license\n% provided in COPYING. Please retain this notice and\n% COPYING if you use this file (or a portion of it) in\n% your project.\n% -------------------------------------------------------\n\n% Make pictures of positive and negative weights\nbs = 20;\nw = w(:,:,1:9);\nscale = max(max(w(:)),max(-w(:)));\npos = HOGpicture(w, bs) * 255/scale;\nneg = HOGpicture(-w, bs) * 255/scale;\n\n% Put pictures together and draw\nbuff = 10;\npos = padarray(pos, [buff buff], 128, 'both');\nif min(w(:)) < 0\n neg = padarray(neg, [buff buff], 128, 'both');\n im = uint8([pos; neg]);\nelse\n im = uint8(pos);\nend\nimagesc(im); \ncolormap gray;\naxis equal;\naxis off;\n", "meta": {"author": "rbgirshick", "repo": "voc-dpm", "sha": "c0b88564bd668bcc6216bbffe96cb061613be768", "save_path": "github-repos/MATLAB/rbgirshick-voc-dpm", "path": "github-repos/MATLAB/rbgirshick-voc-dpm/voc-dpm-c0b88564bd668bcc6216bbffe96cb061613be768/vis/visualizeHOG.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3460058095032025}}
{"text": "2*((x - x2)*((x - x1)^2 + (y - y1)^2)*(-r12^2 + (r11 -\n ((x - x1)^2 + (y - y1)^2)^(1/2))^2 + (z - z1)^2)*(-r22^2 + (y - \n y2)^2 + (r21 - ((x - x2)^2 + (z - z2)^2)^(1/2))^2) + (x - \n x2)*((x - x1)^2 + (y - y1)^2)*(-r12^2 + (r11 - \n ((x - x1)^2 + (y - y1)^2)^(1/2))^2 + (z - z1)^2)*(-r21 + \n ((x - x2)^2 + (z - z2)^2)^(1/2))*((x - x2)^2 + (z - \n z2)^2)^(1/2) + (x - x1)*(-r11 + \n ((x - x1)^2 + (y - y1)^2)^(1/2))*((x - x1)^2 + (y - \n y1)^2)^(1/2)*(-r22^2 + (y - y2)^2 + (r21 - \n ((x - x2)^2 + (z - z2)^2)^(1/2))^2)*((x - x2)^2 + (z - \n z2)^2) + (x - x1)*(-r12^2 + (r11 - ((x - x1)^2 + (y - y1)^2)^(1/2))^2 +\n (z - z1)^2)*(-r22^2 + (y - y2)^2 + (r21 - \n ((x - x2)^2 + (z - z2)^2)^(1/2))^(2))*((x - x2)^2 + (z - z2)^2));\n\n\n2*(((x - x1)^2 + (y - y1)^2)*(y - \n y2)*(-r12^2 + (r11 - ((x - x1)^2 + (y - y1)^2)^(1/2))^2 +\n (z - z1)^2) + (-r11 + ((x - x1)^2 + (y - y1)^2)^(1/2))*\n ((x - x1)^2 + (y - y1)^2)^(1/2)*(y - y1)*(-r22^2 +\n (y - y2)^2 + (r21 - ((x - x2)^2 + (z - z2)^2)^(1/2))^2) +\n (y - y1)*(-r12^2 + (r11 - ((x - x1)^2 + (y - y1)^2)^(1/2))^2 +\n (z - z1)^2)*(-r22^2 + (y - y2)^2 + (r21 - \n ((x - x2)^2 + (z - z2)^2)^(1/2))^2))*((x - x2)^2 + (z - z2)^2);\n\n2*((x - x1)^2 + (y - y1)^2)*((z - z1)*(-r22^2 + (y - y2)^2 +\n (r21 - ((x - x2)^2 + (z - z2)^2)^(1/2))^2)*((x - x2)^2 +\n (z - z2)^2) + (-r12^2 + (r11 - ((x - x1)^2 + (y - y1)^2)^(1/2))^2 +\n (z - z1)^2)*(-r22^2 + (y - y2)^2 + (r21 - ((x - x2)^2 + (z - z2)^2)^(1/2))^2)*\n (z - z2) + (-r12^2 + (r11 - ((x - x1)^2 + (y - y1)^2)^(1/2))^2+ \n (z - z1)^2)*(-r21 + ((x - x2)^2 + (z - z2)^2)^(1/2))*\n ((x - x2)^2 + (z - z2)^2)^(1/2)*(z - z2));", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/IVEM/ExampleFun/TextFD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.34592666006271156}}
{"text": "function testFinalModelsAerts_HN_Old(pathExperiments,nExp,fSetNames)\n% - paramCells: One cell of parameters for each fSet\n% - nameCells: One cell of names for each fSet\n\nstartpath = pwd;\nnFset = numel(fSetNames);\nfor exp = 1:nExp\n cd(fullfile(pathExperiments,['Experiment',num2str(exp)])), pathExperiment = pwd;\n load('training'), load('testing')\n nameOutcomes = fieldnames(training); nOutcomes = numel(nameOutcomes); \n cd('AertsSign'), pathFinalModels = pwd;\n for o = 1:nOutcomes\n for f = 1:nFset\n results = []; results = struct;\n cd(fullfile(pathFinalModels,nameOutcomes{o},fSetNames{f}))\n load('finalModel'), load('coeff'), load('response'), order = 4;\n results.model.Name = finalModel.Name; results.model.coeff = coeff; results.model.order = order;\n results.trainData.data = finalModel.Data; results.trainData.response = response; results.trainData.outcome = training.(nameOutcomes{o}).outcome;\n \n % TESTING MODEL\n outcome = testing.(nameOutcomes{o}).outcome;\n resp = zeros(numel(outcome),1);\n data = zeros(numel(outcome),order);\n for n = 1:order\n data(:,n) = testing.(nameOutcomes{o}).sign.(fSetNames{f})(:,n);\n resp = resp + coeff(n)*data(:,n);\n end\n resp = resp + coeff(end);\n results.testData.data = data; results.testData.response = resp; results.testData.outcome = outcome;\n [AUC,sensitivity,specificity,accuracy] = calcPerformMetrics(resp,outcome,0);\n results.AUC = AUC;\n results.Sensitivity = sensitivity;\n results.Specificity = specificity;\n results.Accuracy = accuracy;\n cd(pathExperiment), save(['testResultsAerts_',fSetNames{f},'_',nameOutcomes{o}],'results')\n end\n end\nend\n\ncd(startpath)\nend", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/HN_study/Functions/MULTIVARIABLE_MODELING/testFinalModelsAerts_HN_Old.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3458206285736102}}
{"text": "\n\nfunction one_result=seg_eva_gen_result_from_con_mat(one_con_mat, exclude_class_idxes)\n\n class_num=size(one_con_mat, 1);\n\n accuracy_classes=zeros(class_num, 1);\n inter_union_score_classes=zeros(class_num, 1);\n \n if nargin<2\n exclude_class_idxes=[];\n end\n \n valid_gt_class_sel=true(class_num, 1);\n \n global_pos_num=0;\n global_predict_num=0;\n \n for c_idx=1:class_num\n \n one_true_pos_num=one_con_mat(c_idx,c_idx);\n one_gt_pos_num=sum(one_con_mat(c_idx,:));\n one_predict_pos_num=sum(one_con_mat(:, c_idx));\n \n global_pos_num=global_pos_num+one_true_pos_num;\n global_predict_num=global_predict_num+one_predict_pos_num;\n \n if one_gt_pos_num>0\n one_accuracy=one_true_pos_num/(one_gt_pos_num+eps);\n one_inter_union_score=one_true_pos_num/...\n (one_gt_pos_num+one_predict_pos_num-one_true_pos_num+eps);\n \n accuracy_classes(c_idx)=one_accuracy;\n inter_union_score_classes(c_idx)=one_inter_union_score;\n else\n valid_gt_class_sel(c_idx)=false;\n end\n \n end\n \n \n valid_class_sel=true(class_num, 1);\n valid_class_sel(exclude_class_idxes)=false;\n valid_class_sel=valid_class_sel & valid_gt_class_sel;\n \n accuracy_per_class=mean(accuracy_classes(valid_class_sel));\n inter_union_score_per_class=mean(inter_union_score_classes(valid_class_sel));\n accuracy_global=global_pos_num/global_predict_num;\n \n one_result.confusion_mat=one_con_mat; \n one_result.class_num=class_num;\n \n one_result.accuracy_global=accuracy_global;\n one_result.accuracy_per_class=accuracy_per_class;\n one_result.inter_union_score_per_class=inter_union_score_per_class;\n one_result.accuracy_classes=accuracy_classes;\n one_result.inter_union_score_classes=inter_union_score_classes;\n \n one_result.valid_class_num=nnz(valid_class_sel);\n one_result.valid_class_idxes=find(valid_class_sel);\n one_result.exclude_class_idxes=exclude_class_idxes;\n\nend\n\n\n", "meta": {"author": "guosheng", "repo": "refinenet", "sha": "0d62007bd60ba983d48acaee6ee29988c7171a91", "save_path": "github-repos/MATLAB/guosheng-refinenet", "path": "github-repos/MATLAB/guosheng-refinenet/refinenet-0d62007bd60ba983d48acaee6ee29988c7171a91/main/seg_eva_gen_result_from_con_mat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3458206285736102}}
{"text": "function ffmsh_2d_data_print ( title, v_num, e_num, t_num, v_xy, v_l, e_v, ...\n e_l, t_v, t_l )\n\n%*****************************************************************************80\n%\n%% FFMSH_2D_DATA_PRINT prints FFMSH data.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 December 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string TITLE, a title.\n%\n% Input, integer V_NUM, the number of vertices.\n%\n% Input, integer E_NUM, the number of boundary edges.\n%\n% Input, integer T_NUM, the number of triangles.\n%\n% Input, real V_XY(2,V_NUM), vertex coordinates.\n%\n% Input, integer V_L(V_NUM), vertex labels.\n%\n% Input, integer E_V(2,E_NUM), edge vertices.\n%\n% Input, integer E_L(E_NUM), vertex labels.\n%\n% Input, integer T_V(3,T_NUM), triangle vertices.\n%\n% Input, integer T_L(T_NUM), triangle labels.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, '%s\\n', title );\n \n i4vec_print ( v_num, v_l, ' Vertex labels:' );\n r8mat_transpose_print ( 2, v_num, v_xy, ' Vertex coordinates:' );\n i4vec_print ( e_num, e_l, ' Edge labels:' );\n i4mat_transpose_print ( 2, e_num, e_v, ' Edge vertices:' );\n i4vec_print ( t_num, t_l, ' Triangle labels:' );\n i4mat_transpose_print ( 3, t_num, t_v, ' Triangle vertices:' );\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/freefem++_msh_io/ffmsh_2d_data_print.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5117166047041655, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.3457999638712781}}
{"text": "function test_suite = test_createBasisTransform3d\n%TEST_CREATEBASISTRANSFORM3D Test case for the file createBasisTransform3d\n%\n% Test case for the file createBasisTransform3d\n\n% Example\n% test_createBasisTransform3d\n%\n% See also\n%\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2011-10-13, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011 INRA - Cepia Software Platform.\n\ntest_suite = functiontests(localfunctions); \n\nfunction test_Translate(testCase) %#ok<*DEFNU>\n% Basic test to check the function runs\n\np1 = [3 4 5];\np2 = [10 20 30];\nbasis1 = [p1 1 0 0 0 1 0];\nbasis2 = [p2 1 0 0 0 1 0];\n\ndp = p1-p2;\nexp = [eye(3) dp' ; 0 0 0 1];\n\ntrans = createBasisTransform3d(basis1, basis2);\ntestCase.assertEqual(exp, trans, 'AbsTol', .01);\n\n\nfunction test_TransformPointTranslation(testCase) %#ok<*DEFNU>\n% Basic test to check the function runs\n\n% two bases with different origins and same directions\nbasis1 = [0 0 0 1 0 0 0 1 0];\nbasis2 = [10 20 30 1 0 0 0 1 0];\n\ntrans = createBasisTransform3d(basis1, basis2);\n\n% pt1 = [0 0 0];\n% pt1T = transformPoint3d(pt1, trans);\n% exp1 = [0 0 0];\n% testCase.assertEqual(exp1, pt1T, 'AbsTol', .01);\n\npt2 = [10 20 30];\npt2T = transformPoint3d(pt2, trans);\nexp2 = [0 0 0];\ntestCase.assertEqual(exp2, pt2T, 'AbsTol', .01);\n\n\n\n\nfunction test_Rotate(testCase) %#ok<*DEFNU>\n% Basic test to check the function runs\n\np1 = [3 4 5];\nbasis1 = [p1 1 0 0 0 1 0];\nbasis2 = [p1 0 1 0 -1 0 0];\n\ntrans = createBasisTransform3d(basis1, basis2);\n\n% restrict the test to the linear part\nexp = [0 1 0; -1 0 0; 0 0 1];\ntestCase.assertEqual(exp, trans(1:3, 1:3), 'AbsTol', .01);\n\n\n\nfunction test_TransformedPoints(testCase) %#ok<*DEFNU>\n% test a combination of translation and axis permutation\n\n% origin basis\nbasis1 = [10 10 10 1 0 0 0 1 0];\n% translation and permutation\nbasis2 = [0 0 0 0 1 0 0 0 1];\n\ntrans = createBasisTransform3d(basis1, basis2);\n\npt1 = [0 0 0];\npt1T = transformPoint3d(pt1, trans);\n\nexp1 = [10 10 10];\ntestCase.assertEqual(exp1, pt1T, '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/geom3d/test_createBasisTransform3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.345799963871278}}
{"text": "function varargout = plotcoeffs(f, varargin)\n%PLOTCOEFFS Display coefficients of the columns, rows and tubes of a\n% CHEBFUN3 object.\n%\n% See also CHEBFUN/PLOTCOEFFS and CHEBFUN2/PLOTCOEFFS.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Empty check.\nif ( isempty(f) )\n varargout = { [] }; \n return\nend\n\n% Store the hold state of the current axis:\nholdState = ishold;\n\n% Get low rank representation of f:\n[~, fCols, fRows, fTubes] = tucker(f);\n\n% PLOTCOEFFS of cols:\nax1 = subplot(1, 3, 1);\nplotcoeffs(fCols, varargin{:}); \nylim1 = ylim(gca);\n% Remove labels from 1D plotcoeff: \nxlabel(gca, '')\nylabel(gca, 'Magnitude of coefficient') \ntitle('Cols') \n\n% PLOTCOEFFS of rows:\nax2 = subplot(1, 3, 2);\nplotcoeffs(fRows, varargin{:}); \nylim2 = ylim(gca);\n% Put an xlabel only for the plot in the middle:\nif isa(f.cols.funs{1}.onefun,'trigtech')\n xlabel(gca, 'Wave number')\nelse\n xlabel(gca, 'Degree of Chebyshev polynomial')\nend\nylabel(' ')\ntitle('Rows')\n\n% PLOTCOEFFS of tubes:\nax3 = subplot(1, 3, 3);\nplotcoeffs(fTubes, varargin{:}); \nylim3 = ylim(gca);\nxlabel(' ')\nylabel(' ')\ntitle('Tubes')\n\n% Find a proper ylim for all the three subplots:\nyLims = [ylim1; ylim2; ylim3];\nylimNew = [min(yLims(:, 1)), max(yLims(:, 2))];\n\n% Set the ylim of the plots again to be similar.\nylim(ax1, ylimNew);\nylim(ax2, ylimNew);\nylim(ax3, ylimNew);\n\n% Return hold state to what it was before:\nif ( ~holdState )\n hold off\nend\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebfun3/plotcoeffs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.3457999638712779}}
{"text": "function test_ft_plot_patch\n\n% MEM 1gb\n% WALLTIME 00:10:00\n% DEPENDENCY ft_plot_patch\n\nhdat = [1:10 10:-1:1];\nvdat = rand(1,10);\nvdat = [vdat vdat(end:-1:1)+1];\nft_plot_patch(hdat, vdat)\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_plot_patch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.34578793835137167}}
{"text": "function as_m_i(A)\n%\n% Generates of the data used in 'as_m'. Data are stored in global\n% variables.\n%\n% Calling sequence:\n%\n% as_m_i(A)\n%\n% Input:\n%\n% A real, symmetric matrix.\n%\n% \n% LYAPACK 1.0 (Thilo Penzl, May 1999)\n\nif nargin~=1\n error('Wrong number of input arguments.');\nend\n\nif norm(A-A','fro')~=0\n error('A is not symmetric!');\nend\n\nglobal LP_A\n\nLP_A = A;\n\n\n\n\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/21-lyapack/lyapack/usfs/as_m_i.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.34578793835137156}}
{"text": "classdef TestCopyMakeBorder\n %TestCopyMakeBorder\n\n methods (Static)\n function test_1\n src = imread(fullfile(mexopencv.root(),'test','img001.jpg'));\n [h,w,~] = size(src);\n border = [10, 20, 30, 40];\n types = {'Default', 'Reflect', 'Reflect101', 'Replicate', 'Wrap'};\n for i=1:numel(types)\n dst = cv.copyMakeBorder(src, border, 'BorderType',types{i});\n\n [hh,ww,~] = size(dst);\n assert(hh == (h+border(1)+border(2)));\n assert(ww == (w+border(3)+border(4)));\n assert(ndims(src) == ndims(dst));\n\n src2 = dst((1:h)+border(1), (1:w)+border(3), :);\n assert(isequal(src2, src));\n end\n end\n\n function test_2\n src = magic(5);\n dst = cv.copyMakeBorder(src, [1 2 3 4], ...\n 'BorderType','Constant', 'Value',0);\n end\n\n function test_3\n src = magic(5);\n dst = cv.copyMakeBorder(src, 1, 2, 3, 4);\n dst = cv.copyMakeBorder(src, [1 2 3 4]);\n end\n\n function test_error_argnum\n try\n cv.copyMakeBorder();\n throw('UnitTest:Fail');\n catch e\n assert(strcmp(e.identifier,'mexopencv:error'));\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/TestCopyMakeBorder.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.6150878555160666, "lm_q1q2_score": 0.34578792932758096}}
{"text": "function test_bug1998\n\n% WALLTIME 00:10:00\n% MEM 2gb\n% DEPENDENCY ft_preprocessing ft_read_data read_neuralynx_ncs\n\n% this bug is detailled on http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=1998\n% and the workaround is explained on http://www.fieldtriptoolbox.org/getting_started/neuralynx?discontinuous_recordings\n\ncd(dccnpath('/home/common/matlab/fieldtrip/data/test/bug1998'));\n\n% start with normal preprocessing of a single channel\ncfg = [];\ncfg.dataset = 'CSC1.Ncs';\ndata = ft_preprocessing(cfg);\n\n% Warning: discontinuous recording, predicted number of timestamps and observed number of timestamps differ by 1693523717.00\n% Please consult the wiki on http://www.fieldtriptoolbox.org/getting_started/neuralynx?discontinuous_recordings\n% > In fileio/private/read_neuralynx_ncs at 94\n% In ft_read_header at 1196\n% In ft_preprocessing at 394\n%\n%\n% >> disp(data)\n% hdr: [1x1 struct]\n% label: {'CSC1'}\n% time: {[1x12902912 double]}\n% trial: {[1x12902912 double]}\n% fsample: 1893\n% sampleinfo: [1 12902912]\n% cfg: [1x1 struct]\n\nfigure\nplot(data.time{1})\nxlabel('sample number')\nylabel('time (s)')\n\nts = ft_read_data(cfg.dataset, 'timestamp', 'true'); % raw timestamps\nts = double(ts); % convert from uint64 into double\n\nfigure\nplot(ts)\nxlabel('sample number')\nylabel('timestamp (a.u.)')\n\n% determine the actual timestamps per sample and interpolate the data\ndts = median(diff(ts));\ntsinterp = ts(1):dts:ts(end);\ndatinterp = interp1(ts, data.trial{1}, tsinterp);\n\n% you can use NaN to replace the data in the gaps\ngaps = find(diff(ts)>2*dts); % skips at least a sample\nfor igap = 1:length(gaps)\n sel = tsinterp < ts(gaps(igap)+1) & tsinterp > ts(gaps(igap));\n datinterp(:,sel) = NaN;\nend\n\n% update the FieldTrip data structure\ndata.trial{1} = datinterp;\ndata.time{1} = (tsinterp - ts(1)) / (data.hdr.Fs .* dts);\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_bug1998.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3457769592371696}}
{"text": "function [g1, g2] = simXsimKernDiagGradient(simKern1, simKern2, t, covDiag)\n\n% SIMXSIMKERNDIAGGRADIENT Gradient for the diagonal between two SIM kernels.\n% FORMAT\n% DESC computes cross gradient of parameters in the diagonal of a cross \n% kernel between two sim kernels for the multiple output kernel. \n% ARG simKern1 : the kernel structure associated with the first SIM\n% kernel.\n% ARG simKern2 : the kernel structure associated with the second SIM\n% kernel.\n% ARG t : inputs for which kernel is to be computed.\n% ARG covDiag : gradient of the objective function with respect to\n% the elements of the cross kernel matrix.\n% RETURN g1 : gradient of the parameters of the first kernel, for\n% ordering see simKernExtractParam.\n% RETURN g2 : gradient of the parameters of the second kernel, for\n% ordering see simKernExtractParam.\n%\n% SEEALSO : simXsimKernDiagCompute.m, simKernParamInit, simKernExtractParam\n%\n% COPYRIGHT : Mauricio A. Alvarez, 2010\n\n% KERN\n\n\nif size(t, 2) > 1\n error('Input can only have one column');\nend\n\nif simKern1.inverseWidth ~= simKern2.inverseWidth\n error('Kernels cannot be cross combined if they have different inverse widths.')\nend\n% The normalisation in the SIM kernel arises from the use of the normalised\n% version of the RBF kernel. Hence, both have to be normalised or not.\nif ~isfield(simKern1, 'isNormalised')\n isSim1Normalised = false;\nelse\n isSim1Normalised = simKern1.isNormalised;\nend\nif ~isfield(simKern2, 'isNormalised')\n isSim2Normalised = false;\nelse\n isSim2Normalised = simKern2.isNormalised;\nend\nif isSim1Normalised ~= isSim2Normalised\n error('Both SIM kernels have to be either normalised or not.');\nend\n\nsigma = sqrt(2/simKern1.inverseWidth);\n\nif (~simKern1.isStationary || ~ simKern2.isStationary)\n [h1, dh1_dD1, dh1_dD2, dh1_dsigma] = ...\n simXsimComputeDiagH(t, simKern1.decay, simKern2.decay, simKern1.delay, simKern2.delay, sigma);\nelse\n [h1, dh1_dD1, dh1_dD2, dh1_dsigma] = ...\n simXsimComputeDiagHStat(t, simKern1.decay, simKern2.decay, simKern1.delay, simKern2.delay, sigma);\nend\n\n% Avoid making the expensive call twice unless really necessary\nif ((simKern1.decay == simKern2.decay) && (simKern1.delay == simKern2.delay)),\n h2 = h1;\n dh2_dD2 = dh1_dD1;\n dh2_dD1 = dh1_dD2;\n dh2_dsigma = dh1_dsigma;\nelseif (~simKern1.isStationary) || (~simKern2.isStationary)\n [h2, dh2_dD2, dh2_dD1, dh2_dsigma] = ...\n simXsimComputeDiagH(t, simKern2.decay, simKern1.decay, simKern2.delay, simKern1.delay, sigma);\nelse\n [h2, dh2_dD2, dh2_dD1, dh2_dsigma] = ...\n simXsimComputeDiagHStat(t, simKern2.decay, simKern1.decay, simKern2.delay, simKern1.delay, sigma);\nend\n\ndK_dsigma = dh1_dsigma + dh2_dsigma;\n\n\nif isfield(simKern1, 'isVarS') && (simKern1.isVarS)\n K = 0.5 * (h1 + h2);\n if ~isSim1Normalised\n K = sqrt(pi) * K;\n dk_dD1 = (sum(covDiag.*dh1_dD1) + sum(covDiag.*dh2_dD1))*0.5*sqrt(pi)*sigma;\n dk_dD2 = (sum(covDiag.*dh1_dD2) + sum(covDiag.*dh2_dD2))*0.5*sqrt(pi)*sigma;\n dk_dsigma = sum(covDiag.*(dK_dsigma*0.5*sqrt(pi)*sigma + K));\n else\n dk_dD1 = (sum(covDiag.*dh1_dD1) + sum(covDiag.*dh2_dD1))*0.5;\n dk_dD2 = (sum(covDiag.*dh1_dD2) + sum(covDiag.*dh2_dD2))*0.5;\n dk_dsigma = 0.5 * sum(covDiag.*dK_dsigma);\n end\n dk_dinvWidth = -0.5*sqrt(2)/(simKern1.inverseWidth* ...\n sqrt(simKern1.inverseWidth))*dk_dsigma;\n % only pass the gradient with respect to the inverse width to one\n % of the gradient vectors ... otherwise it is counted twice.\n g1 = real([dk_dD1 dk_dinvWidth]);\n g2 = real([dk_dD2 0]);\nelse\n if isfield(simKern1, 'isNegativeS') && (simKern1.isNegativeS == true)\n C1 = simKern1.sensitivity;\n C2 = simKern2.sensitivity;\n else\n C1 = sqrt(simKern1.variance);\n C2 = sqrt(simKern2.variance);\n end\n K = 0.5 * (h1 + h2);\n var2 = C1*C2;\n if ~isSim1Normalised\n K = sqrt(pi) * K;\n dk_dD1 = (sum(covDiag.*dh1_dD1) + sum(covDiag.*dh2_dD1))*0.5*sqrt(pi)*sigma*var2;\n dk_dD2 = (sum(covDiag.*dh1_dD2) + sum(covDiag.*dh2_dD2))*0.5*sqrt(pi)*sigma*var2;\n dk_dsigma = sum(covDiag.*(dK_dsigma*0.5*sqrt(pi)*sigma + K))*var2;\n dk_dC1 = sigma * C2 * sum(covDiag.*K);\n dk_dC2 = sigma * C1 * sum(covDiag.*K);\n else\n dk_dD1 = (sum(covDiag.*dh1_dD1) + sum(covDiag.*dh2_dD1))*0.5*var2;\n dk_dD2 = (sum(covDiag.*dh1_dD2) + sum(covDiag.*dh2_dD2))*0.5*var2;\n dk_dsigma = 0.5 * var2 * sum(covDiag.*dK_dsigma);\n dk_dC1 = C2 * sum(covDiag.*K);\n dk_dC2 = C1 * sum(covDiag.*K);\n end\n if isfield(simKern1, 'isNegativeS') && simKern1.isNegativeS\n dk_dSim1Variance = dk_dC1;\n else\n dk_dSim1Variance = dk_dC1*0.5/C1;\n end\n if isfield(simKern2, 'isNegativeS') && simKern2.isNegativeS\n dk_dSim2Variance = dk_dC2;\n else\n dk_dSim2Variance = dk_dC2*0.5/C2;\n end\n dk_dinvWidth = -0.5*sqrt(2)/(simKern1.inverseWidth* ...\n sqrt(simKern1.inverseWidth))*dk_dsigma;\n % only pass the gradient with respect to the inverse width to one\n % of the gradient vectors ... otherwise it is counted twice.\n g1 = real([dk_dD1 dk_dinvWidth dk_dSim1Variance]);\n g2 = real([dk_dD2 0 dk_dSim2Variance]);\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/simXsimKernDiagGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.34577695310633993}}
{"text": "function x= rectwin(N)\n% Function RECTWIN(N) creates the N-point Rectangular window.\n\n\nx(1 : N)=ones(1, N);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/43601-harmonic-wavelet-based-isar-imaging/Codes/B-727/rectwin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.34569498001524973}}
{"text": "function p06_story ( )\n\n%*****************************************************************************80\n%\n%% P06_STORY prints the \"story\" for problem p06.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 August 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Carl DeBoor, John Rice,\n% Least-squares cubic spline approximation II - variable knots.\n% Technical Report CSD TR 21,\n% Purdue University, Lafayette, Indiana, 1968.\n%\n% Carl DeBoor,\n% A Practical Guide to Splines,\n% Springer, 2001,\n% ISBN: 0387953663,\n% LC: QA1.A647.v27.\n%\n% Parameters:\n%\n% None\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The data is due to deBoor and Rice.\\n' );\n fprintf ( 1, ' The data represents a temperature dependent property of titanium.\\n' );\n fprintf ( 1, ' The data has been used extensively as an example in spline\\n' );\n fprintf ( 1, ' approximation with variably-spaced knots.\\n' );\n fprintf ( 1, ' DeBoor considers two sets of knots:\\n' );\n fprintf ( 1, ' (595,675,755,835,915,995,1075)\\n' );\n fprintf ( 1, ' and\\n' );\n fprintf ( 1, ' (595,725,850,910,975,1040,1075).\\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_interp/p06_story.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.345654166284816}}
{"text": "Network UNet {\n\tLayer CONV1_1 {\n\t\tType: CONV\n\t\tDimensions { K: 64, C:1, R: 3, S: 3, Y: 572, X: 572 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(64,64) C;\n\t\t\tTemporalMap(7,7) R;\n\t\t\tTemporalMap(7,7) S;\n\t\t\tTemporalMap(7,1) Y;\n\t\t\tTemporalMap(7,1) X;\t\n\t\t\tCluster(64, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t}\n\t}\n\n\tLayer CONV1_2 {\n\t\tType: CONV\n\t\tDimensions { K: 64, C: 64, R: 3, S: 3, Y: 570, X: 570 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(64,64) C;\n\t\t\tTemporalMap(3,3) R;\n\t\t\tTemporalMap(3,3) S;\n\t\t\tTemporalMap(3,1) Y;\n\t\t\tTemporalMap(3,1) X;\t\n\t\t\tCluster(64, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t}\n\t}\n\n\tLayer CONV2_1 {\n\t\tType: CONV\n\t\tDimensions { K: 128, C: 64, R: 3, S: 3, Y: 284, X: 284 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(64,64) C;\n\t\t\tTemporalMap(3,3) R;\n\t\t\tTemporalMap(3,3) S;\n\t\t\tTemporalMap(3,1) Y;\n\t\t\tTemporalMap(3,1) X;\t\n\t\t\tCluster(64, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t}\n\t}\n\n\tLayer CONV2_2 {\n\t\tType: CONV\n\t\tDimensions { K: 128, C: 128, R: 3, S: 3, Y: 282, X: 282 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(64,64) C;\n\t\t\tTemporalMap(3,3) R;\n\t\t\tTemporalMap(3,3) S;\n\t\t\tTemporalMap(3,1) Y;\n\t\t\tTemporalMap(3,1) X;\t\n\t\t\tCluster(64, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t}\n\t}\n\n\tLayer CONV3_1 {\n\t\tType: CONV\n\t\tDimensions { K: 256, C: 128, R: 3, S: 3, Y: 140, X: 140 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(64,64) C;\n\t\t\tTemporalMap(3,3) R;\n\t\t\tTemporalMap(3,3) S;\n\t\t\tTemporalMap(3,1) Y;\n\t\t\tTemporalMap(3,1) X;\t\n\t\t\tCluster(64, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t}\n\t}\n\n\n\tLayer CONV3_2 {\n\t\tType: CONV\n\t\tDimensions { K: 256, C: 256, R: 3, S: 3, Y: 138, X: 138 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(64,64) C;\n\t\t\tTemporalMap(3,3) R;\n\t\t\tTemporalMap(3,3) S;\n\t\t\tTemporalMap(3,1) Y;\n\t\t\tTemporalMap(3,1) X;\t\n\t\t\tCluster(64, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t}\n\t}\n\n\tLayer CONV4_1 {\n\t\tType: CONV\n\t\tDimensions { K: 512, C: 256, R: 3, S: 3, Y: 68, X: 68 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(64,64) C;\n\t\t\tTemporalMap(3,3) R;\n\t\t\tTemporalMap(3,3) S;\n\t\t\tTemporalMap(3,1) Y;\n\t\t\tTemporalMap(3,1) X;\t\n\t\t\tCluster(64, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t}\n\t}\n\n\n\tLayer CONV4_2 {\n\t\tType: CONV\n\t\tDimensions { K: 512, C: 512, R: 3, S: 3, Y: 66, X: 66 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(64,64) C;\n\t\t\tTemporalMap(3,3) R;\n\t\t\tTemporalMap(3,3) S;\n\t\t\tTemporalMap(3,1) Y;\n\t\t\tTemporalMap(3,1) X;\t\n\t\t\tCluster(64, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t}\n\t}\n\n\tLayer CONV5_1 {\n\t\tType: CONV\n\t\tDimensions { K: 1024, C: 512, R: 3, S: 3, Y: 32, X: 32 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(64,64) C;\n\t\t\tTemporalMap(3,3) R;\n\t\t\tTemporalMap(3,3) S;\n\t\t\tTemporalMap(3,1) Y;\n\t\t\tTemporalMap(3,1) X;\t\n\t\t\tCluster(64, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t}\n\t}\n\n\n\tLayer CONV5_2 {\n\t\tType: CONV\n\t\tDimensions { K: 1024, C: 1024, R: 3, S: 3, Y: 30, X: 30 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(64,64) C;\n\t\t\tTemporalMap(3,3) R;\n\t\t\tTemporalMap(3,3) S;\n\t\t\tTemporalMap(3,1) Y;\n\t\t\tTemporalMap(3,1) X;\t\n\t\t\tCluster(64, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t}\n\t}\n\n\tLayer TRCONV1 {\n\t\tType: TRCONV\n\t\tDimensions { K: 512, C: 1024, R: 2, S: 2, Y: 28, X: 28 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(64,64) C;\n\t\t\tTemporalMap(2,2) R;\n\t\t\tTemporalMap(2,2) S;\n\t\t\tTemporalMap(2,1) Y;\n\t\t\tTemporalMap(2,1) X;\t\n\t\t\tCluster(64, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t}\n\t}\n\n\n\tLayer CONV4_3 {\n\t\tType: CONV\n\t\tDimensions { K: 512, C: 1024, R: 3, S: 3, Y: 56, X: 56 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(64,64) C;\n\t\t\tTemporalMap(3,3) R;\n\t\t\tTemporalMap(3,3) S;\n\t\t\tTemporalMap(3,1) Y;\n\t\t\tTemporalMap(3,1) X;\t\n\t\t\tCluster(64, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t}\n\t}\n\n\tLayer CONV4_4 {\n\t\tType: CONV\n\t\tDimensions { K: 512, C: 512, R: 3, S: 3, Y: 54, X: 54 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(64,64) C;\n\t\t\tTemporalMap(3,3) R;\n\t\t\tTemporalMap(3,3) S;\n\t\t\tTemporalMap(3,1) Y;\n\t\t\tTemporalMap(3,1) X;\t\n\t\t\tCluster(64, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t}\n\t}\n\n\tLayer TRCONV2 {\n\t\tType: TRCONV\n\t\tDimensions { K: 512, C: 512, R: 2, S: 2, Y: 52, X: 52 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(64,64) C;\n\t\t\tTemporalMap(2,2) R;\n\t\t\tTemporalMap(2,2) S;\n\t\t\tTemporalMap(2,1) Y;\n\t\t\tTemporalMap(2,1) X;\t\n\t\t\tCluster(64, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t}\n\t}\n\n\tLayer CONV3_3 {\n\t\tType: CONV\n\t\tDimensions { K: 256, C: 512, R: 3, S: 3, Y: 104, X: 104 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(64,64) C;\n\t\t\tTemporalMap(3,3) R;\n\t\t\tTemporalMap(3,3) S;\n\t\t\tTemporalMap(3,1) Y;\n\t\t\tTemporalMap(3,1) X;\t\n\t\t\tCluster(64, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t}\n\t}\n\n\n\tLayer CONV3_4 {\n\t\tType: CONV\n\t\tDimensions { K: 256, C: 256, R: 3, S: 3, Y: 102, X: 102 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(64,64) C;\n\t\t\tTemporalMap(3,3) R;\n\t\t\tTemporalMap(3,3) S;\n\t\t\tTemporalMap(3,1) Y;\n\t\t\tTemporalMap(3,1) X;\t\n\t\t\tCluster(64, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t}\n\t}\n\n\tLayer TRCONV3 {\n\t\tType: TRCONV\n\t\tDimensions { K: 128, C: 256, R: 2, S: 2, Y: 100, X: 100 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(64,64) C;\n\t\t\tTemporalMap(2,2) R;\n\t\t\tTemporalMap(2,2) S;\n\t\t\tTemporalMap(2,1) Y;\n\t\t\tTemporalMap(2,1) X;\t\n\t\t\tCluster(64, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t}\n\t}\n\n\n\tLayer CONV2_3 {\n\t\tType: CONV\n\t\tDimensions { K: 128, C: 256, R: 3, S: 3, Y: 200, X: 200 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(64,64) C;\n\t\t\tTemporalMap(3,3) R;\n\t\t\tTemporalMap(3,3) S;\n\t\t\tTemporalMap(3,1) Y;\n\t\t\tTemporalMap(3,1) X;\t\n\t\t\tCluster(64, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t}\n\t}\n\n\tLayer CONV2_4 {\n\t\tType: CONV\n\t\tDimensions { K: 128, C: 128, R: 3, S: 3, Y: 198, X: 198 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(64,64) C;\n\t\t\tTemporalMap(3,3) R;\n\t\t\tTemporalMap(3,3) S;\n\t\t\tTemporalMap(3,1) Y;\n\t\t\tTemporalMap(3,1) X;\t\n\t\t\tCluster(64, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t}\n\t}\n\n\tLayer TRCONV4 {\n\t\tType: TRCONV\n\t\tDimensions { K: 64, C: 128, R: 2, S: 2, Y: 196, X: 196 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(64,64) C;\n\t\t\tTemporalMap(2,2) R;\n\t\t\tTemporalMap(2,2) S;\n\t\t\tTemporalMap(2,1) Y;\n\t\t\tTemporalMap(2,1) X;\t\n\t\t\tCluster(64, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t}\n\t}\n\n\tLayer CONV1_3 {\n\t\tType: CONV\n\t\tDimensions { K: 64, C: 128, R: 3, S: 3, Y: 392, X: 392 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(64,64) C;\n\t\t\tTemporalMap(3,3) R;\n\t\t\tTemporalMap(3,3) S;\n\t\t\tTemporalMap(3,1) Y;\n\t\t\tTemporalMap(3,1) X;\t\n\t\t\tCluster(64, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t}\n\t}\n\n\n\tLayer CONV1_4 {\n\t\tType: CONV\n\t\tDimensions { K: 64, C: 64, R: 3, S: 3, Y: 390, X: 390 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(64,64) C;\n\t\t\tTemporalMap(3,3) R;\n\t\t\tTemporalMap(3,3) S;\n\t\t\tTemporalMap(3,1) Y;\n\t\t\tTemporalMap(3,1) X;\t\n\t\t\tCluster(64, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t}\n\t}\n\n\tLayer CONV1_5 {\n\t\tType: CONV\n\t\tDimensions { K: 2, C: 64, R: 1, S: 1, Y: 388, X: 388 }\n\t\tDataflow {\n\t\t\tSpatialMap(1,1) K;\n\t\t\tTemporalMap(64,64) C;\n\t\t\tTemporalMap(1,1) R;\n\t\t\tTemporalMap(1,1) S;\n\t\t\tTemporalMap(1,1) Y;\n\t\t\tTemporalMap(1,1) X;\t\n\t\t\tCluster(64, P);\n\t\t\tSpatialMap(1,1) C;\n\t\t}\n\t}\n}\n\n// Accelerator {\n// PE { NumPEs: 128; VectorWidth: 4; MultPrecision: INT8, AddPrecision: INT16 }\n// Buffer { GlobalL2: 2048, LocalL1: 64}\n// NoC {Bandwidth: 64; AvgLatency: 2}\n// }\n", "meta": {"author": "maestro-project", "repo": "maestro", "sha": "4eb08d17c87caf1ee3f3a351b10eb9b8ef70dd87", "save_path": "github-repos/MATLAB/maestro-project-maestro", "path": "github-repos/MATLAB/maestro-project-maestro/maestro-4eb08d17c87caf1ee3f3a351b10eb9b8ef70dd87/data/mapping/UNet_kcp_ws.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.34565416304968805}}
{"text": "function LU = getbounds(F,avoidequalitybounds,LU)\n\nK.f = 0;\nK.l = 0;\nL = [];\nU = [];\nif nargin < 3\n LU = yalmip('getbounds',1:yalmip('nvars'));\nend\nbinary = yalmip('binvariables');\nLU(binary,1) = 0;\nLU(binary,2) = 1;\nF = flatten(F);\nsimplex = [];\nis_interval = is(F,'interval');\nfor i = 1:length(F.LMIid)\n if F.clauses{i}.type == 2\n X = F.clauses{i}.data;\n AB = getbase(X);\n K.l = prod(size(X));\n variables = getvariables(X);\n if is_interval(i)\n [lb,ub,cand_rows] = find_lp_bounds_interval(AB,K);\n else\n [lb,ub,cand_rows] = find_lp_bounds(AB,K); \n end\n LU(variables,1) = max([lb LU(variables,1)]')';\n LU(variables,2) = min([ub LU(variables,2)]')'; \n elseif F.clauses{i}.type == 55\n X = F.clauses{i}.data;X = X(:);\n AB = getbase(X);\n K.l = prod(size(X));\n variables = getvariables(X);\n if is_interval(i)\n [lb,ub,cand_rows] = find_lp_bounds_interval(AB,K);\n else\n [lb,ub,cand_rows] = find_lp_bounds(AB,K); \n end\n LU(variables,1) = max([lb LU(variables,1)]')';\n LU(variables,2) = min([ub LU(variables,2)]')'; \n \n elseif F.clauses{i}.type == 3 && (nargin==1 || (nargin > 1 && isempty(avoidequalitybounds)))\n % FIX : Extract from equalities and binary constraints\n X = F.clauses{i}.data;\n AB = getbase(X);\n if size(AB,1)==1 && (AB(1) > 0) && all(AB(2:end)<0)\n % Save this simplex sum a_ix_i == b for later\n % and extract when as many variables as possible have been\n % fixed. Common in portfolio models\n simplex = [simplex i];\n end\n AB = [AB;-AB];\n K.l = 2*prod(size(X));\n variables = getvariables(X);\n if is_interval(i)\n [lb,ub,cand_rows] = find_lp_bounds_interval(AB,K);\n else\n [lb,ub,cand_rows] = find_lp_bounds(AB,K); \n end\n LU(variables,1) = max([lb LU(variables,1)]')';\n LU(variables,2) = min([ub LU(variables,2)]')';\n end\nend\n\nsemicont = yalmip('semicontvariables');\nif ~isempty(semicont)\n for i = 1:length(semicont)\n if LU(semicont(i),1) > 0\n LU(semicont(i),1) = 0;\n end\n if LU(semicont(i),2) < 0\n LU(semicont(i),2) = 0;\n end\n end\nend\n\n% Go through the simplex models with as much bounded as possible\nfor i = simplex\n X = F.clauses{i}.data;\n AB = getbase(X);\n variables = getvariables(X);\n if all(LU(variables,1)>=0)\n simplex_bound = AB(1)./(-AB(2:end));\n LU(variables,2) = min([simplex_bound(:) LU(variables,2)]')';\n end\nend\n\n% Try to bound some nonlinear terms\n% FIX: complete code\n[mt,variable_type] = yalmip('monomtable');\nquadratic = find(variable_type == 2);\nif ~isempty(quadratic)\n M = mt(quadratic,:);\n [ii,jj,kk] = find(M);\n LU(quadratic,1) = max([LU(quadratic,1) zeros(length(quadratic),1)],[],2); \n LU(quadratic,2) = max([LU(quadratic,1).^2 LU(quadratic,2).^2],[],2);\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/getbounds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.34565416304968805}}
{"text": "function Obs = projectLmk(Rob,Sen,Lmk,Obs,Opt)\n\n% PROJECTLMK Project landmark estimate into sensor's measurement space.\n% Obs = PROJECTLMK(Rob,Sen,Lmk,Obs) projects the landmark Lmk into sensor\n% Sen mounted on robot Rob, and updates the information of the\n% observation structure Obs. The observation model is determined from\n% Sen.type and Lmk.type. It is an error if no model exists for the chosen\n% Sen-Lmk pair.\n%\n% The updated fields in Obs are:\n% .sid % sensor ID\n% .lid % landmark ID\n% .ltype % landmark type\n% .vis % flag: true if landmark is visible\n% .meas.R % measurement noise cov. matrix\n% .exp.e % expectation's mean\n% .exp.E % expectation's covariances matrix\n% .exp.um % expectation's uncertainty measure\n% .Jac.E_r % Jacobian wrt robot frame\n% .Jac.E_s % Jacobian wrt sensor frame\n% .Jac.E_l % Jacobian wrt landmark state\n%\n% See also OBSERVEKNOWNLMKS.\n\n% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\nglobal Map\n\n% PREVIOUS TASKS\n% get landmark range and mean\nlr = Lmk.state.r ; % lmk range in Map\nswitch Map.type\n case 'ekf'\n l = Map.x(lr); % lmk mean\n case 'graph'\n l = Lmk.state.x; % lmk mean\n otherwise\n error('??? Unknown Map type ''%s''.',Map.type)\nend\n\n% PROJECTION FUNCTION\n% explore all sensor and landmark types\nswitch Sen.type\n\n case {'pinHole'} % camera pinHole\n\n switch Lmk.type\n\n case {'eucPnt'} % euclidean point\n\n % Point3D --> pixel -(value and Jacobians)-\n [e, depth, E_rf, E_sf, E_k, E_d, E_l] = ...\n projEucPntIntoPinHoleOnRob( ...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n Sen.par.d, ...\n l) ;\n\n vis = isVisible(e,depth,Sen.par.imSize);\n\n case {'idpPnt'} % inverse depth point\n\n % IDP --> pixel -(value and Jacobians)-\n [e, depth, E_rf, E_sf, E_k, E_d, E_l] = ...\n projIdpPntIntoPinHoleOnRob( ...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n Sen.par.d, ...\n l) ;\n\n vis = isVisible(e,depth,Sen.par.imSize);\n\n case {'hmgPnt'} % euclidean point\n\n % Point3D --> pixel -(value and Jacobians)-\n [e, depth, E_rf, E_sf, E_k, E_d, E_l] = ...\n projHmgPntIntoPinHoleOnRob( ...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n Sen.par.d, ...\n l) ;\n\n vis = isVisible(e,depth,Sen.par.imSize);\n \n case {'ahmPnt'}\n\n % Point3D --> pixel -(value and Jacobians)-\n [e, depth, E_rf, E_sf, E_k, E_d, E_l] = ...\n projAhmPntIntoPinHoleOnRob( ...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n Sen.par.d, ...\n l);\n\n vis = isVisible(e,depth,Sen.par.imSize);\n\n case {'fhmPnt'}\n\n % Point3D --> pixel -(value and Jacobians)-\n [e, depth, E_rf, E_sf, E_k, E_d, E_l] = ...\n projFhmPntIntoPinHoleOnRob( ...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n Sen.par.d, ...\n l);\n\n vis = isVisible(e,depth,Sen.par.imSize);\n\n case {'plkLin'}\n\n % Plucker line --> homogeneous line (value and Jacs)\n [e, v, E_rf, E_sf, E_k, E_l] = ...\n projPlkLinIntoPinHoleOnRob( ...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n l); % expectation e is a homogeneous line\n \n % normalize wrt director vector e(1:2):\n ine12 = 1/norm(e(1:2));\n e = e * ine12;\n E_rf = E_rf * ine12;\n E_sf = E_sf * ine12;\n % E_k = E_k * ine12;\n E_l = E_l * ine12;\n\n % 3d Segment from Plucker line and abscissas\n [si,SI_l] = pluckerSegment(l,[Lmk.par.endp.t]);\n\n % projected segment\n [s, d, S_rf, S_sf, S_k, S_si] = projSegLinIntoPinHoleOnRob(...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n si); \n \n % segment visibility\n [s,vis] = visibleSegment(s,d,Sen.par.imSize);\n \n case 'aplLin'\n \n % Anchored Plucker line --> homogeneous line (value and Jacs)\n [e, v, E_rf, E_sf, E_k, E_l] = ...\n projAplLinIntoPinHoleOnRob( ...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n l); % expectation e is a homogeneous line\n\n % normalize wrt director vector e(1:2):\n ine12 = 1/norm(e(1:2));\n e = e * ine12;\n E_rf = E_rf * ine12;\n E_sf = E_sf * ine12;\n % E_k = E_k * ine12;\n E_l = E_l * ine12;\n\n % 3d Segment from Plucker line and abscissas\n [si,SI_l] = aPluckerSegment(l,[Lmk.par.endp.t]);\n\n % projected segment\n [s, d, S_rf, S_sf, S_k, S_si] = projSegLinIntoPinHoleOnRob(...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n si); \n \n % segment visibility\n [s,vis] = visibleSegment(s,d,Sen.par.imSize);\n \n \n case 'idpLin'\n \n % IDP line --> homogeneous line (value and Jacs)\n [s, v, S_rf, S_sf, S_k, S_l] = ...\n projIdpLinIntoPinHoleOnRob( ...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n l); % expectation s is a 2d segment\n [e, E_s] = seg2hmgLin(s); % expectation e is a homogeneous line\n E_rf = E_s*S_rf;\n E_sf = E_s*S_sf;\n E_l = E_s*S_l;\n\n % normalize wrt director vector e(1:2):\n ine12 = 1/norm(e(1:2));\n e = e * ine12;\n E_rf = E_rf * ine12;\n E_sf = E_sf * ine12;\n % E_k = E_k * ine12;\n E_l = E_l * ine12;\n\n % 3d Segment from Plucker line and abscissas\n [si,SI_l] = idpLinSegment(l,[Lmk.par.endp.t]);\n\n % projected segment\n [s, d, S_rf, S_sf, S_k, S_si] = projSegLinIntoPinHoleOnRob(...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n si); \n \n % segment visibility\n [s,vis] = visibleSegment(s,d,Sen.par.imSize,0,Opt.obs.lines.minLength);\n\n case 'hmgLin'\n \n % HMG line --> homogeneous line (value and Jacs)\n [s, v, S_rf, S_sf, S_k, S_l] = ...\n projHmgLinIntoPinHoleOnRob( ...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n l); % expectation s is a 2d segment\n [e, E_s] = seg2hmgLin(s); % expectation e is a homogeneous line\n E_rf = E_s*S_rf;\n E_sf = E_s*S_sf;\n E_l = E_s*S_l;\n\n % normalize wrt director vector e(1:2):\n ine12 = 1/norm(e(1:2));\n e = e * ine12;\n E_rf = E_rf * ine12;\n E_sf = E_sf * ine12;\n % E_k = E_k * ine12;\n E_l = E_l * ine12;\n\n % 3d Segment from Plucker line and abscissas\n [si,SI_l] = hmgLinSegment(l,[Lmk.par.endp.t]);\n\n % projected segment\n [s, d, S_rf, S_sf, S_k, S_si] = projSegLinIntoPinHoleOnRob(...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n si); \n \n % segment visibility\n [s,vis] = visibleSegment(s,d,Sen.par.imSize,0,Opt.obs.lines.minLength);\n\n case 'ahmLin'\n \n % AHM line --> homogeneous line (value and Jacs)\n [s, v, S_rf, S_sf, S_k, S_l] = ...\n projAhmLinIntoPinHoleOnRob( ...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n l); % expectation s is a 2d segment\n [e, E_s] = seg2hmgLin(s); % expectation e is a homogeneous line\n E_rf = E_s*S_rf;\n E_sf = E_s*S_sf;\n E_l = E_s*S_l;\n\n % normalize wrt director vector e(1:2):\n ine12 = 1/norm(e(1:2));\n e = e * ine12;\n E_rf = E_rf * ine12;\n E_sf = E_sf * ine12;\n % E_k = E_k * ine12;\n E_l = E_l * ine12;\n\n % 3d Segment from Plucker line and abscissas\n [si,SI_l] = ahmLinSegment(l,[Lmk.par.endp.t]);\n\n % projected segment\n [s, d, S_rf, S_sf, S_k, S_si] = projSegLinIntoPinHoleOnRob(...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n si); \n \n % segment visibility\n [s,vis] = visibleSegment(s,d,Sen.par.imSize,0,Opt.obs.lines.minLength);\n\n \n otherwise % unknown landmark type for pin hole sensor\n error('??? Unknown landmark type ''%s'' for sensor ''%s''.', Lmk.type, Sen.type);\n\n end\n \n \n case 'pinHoleDepth' % Pin hole sensor with depth information\n switch Lmk.type\n case 'eucPnt'\n \n % Point3D --> pixel+depth -(value and Jacobians)-\n [e, E_rf, E_sf, E_k, E_d, E_l] = ...\n projEucPntIntoPhdOnRob( ...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n Sen.par.d, ...\n l) ;\n \n vis = isVisible(e(1:2,:),e(3,:),Sen.par.imSize);\n \n otherwise\n error('??? Unknown landmark type ''%s'' for sensor ''%s''.',Lmk.type,Sen.type);\n end\n \n case {'omniCam'} % Omnidirectional camera\n \n switch Lmk.type\n\n case {'eucPnt'} % euclidean point\n\n % Point3D --> pixel -(value and Jacobians)-\n [e, depth, E_rf, E_sf, E_k, E_d, E_l] = ...\n projEucPntIntoOmniCamOnRob( ...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n Sen.par.d, ...\n l) ;\n\n vis = isVisible(e,depth,Sen.par.imSize);\n \n case {'ahmPnt'}\n\n % Point3D --> pixel -(value and Jacobians)-\n [e, depth, E_rf, E_sf, E_k, E_d, E_l] = ...\n projAhmPntIntoOmniCamOnRob( ...\n Rob.frame, ...\n Sen.frame, ...\n Sen.par.k, ...\n Sen.par.d, ...\n l);\n\n vis = isVisible(e,depth,Sen.par.imSize);\n \n otherwise % unknown landmark type for pin hole sensor\n error('??? Unknown landmark type ''%s'' for sensor ''%s''.',Lmk.type,Sen.type);\n \n end\n \n \n \n otherwise % unknown Sensor type\n error('??? Unknown sensor type ''%s''.',Sen.type);\n\nend % sensor type\n\n\n% COVARIANCES\nif strcmp(Map.type,'ekf')\n\n % Rob-Sen-Lmk range and Jacobian\n if Sen.frameInMap\n rslr = [Rob.frame.r ; Sen.frame.r ; lr]; % range of robot, sensor, and landmark\n E_rsl = [E_rf E_sf E_l];\n else\n rslr = [Rob.frame.r ; lr]; % range of robot and landmark\n E_rsl = [E_rf E_l];\n end\n \n % Expectation covariances matrix\n E = E_rsl*Map.P(rslr,rslr)*E_rsl' ;\n\nelse\n E = [];\nend\n\n% Other parameters\nswitch Lmk.type(4:6)\n case 'Lin'\n % for lines, project endpoints with covariances:\n\n % compute endpoints\n Obs.par.endp(1).e = s(1:2);\n Obs.par.endp(2).e = s(3:4);\n\n if Map.type == 'ekf'\n % Rob-Sen-Lmk Jacobian of projected segment\n if Sen.frameInMap\n S_rsl = [S_rf S_sf S_si*SI_l];\n else\n S_rsl = [S_rf S_si*SI_l];\n end\n % compute covariances\n S = S_rsl*Map.P(rslr,rslr)*S_rsl'; % segment covariance\n Obs.par.endp(1).E = S(1:2,1:2);\n Obs.par.endp(2).E = S(3:4,3:4);\n end\n \nend\n\n\n% UPDATE OBS STRUCTURE\nObs.sid = Sen.id ;\nObs.lid = Lmk.id ;\nObs.ltype = Lmk.type ;\nObs.vis = vis ;\nObs.exp.e = e ;\nObs.exp.E = E ;\nObs.exp.um = det(E); % uncertainty measure proportional to ellipsoid area\nObs.Jac.E_r = E_rf;\nObs.Jac.E_s = E_sf;\nObs.Jac.E_l = E_l;\n\n\n\n% ========== End of function - Start GPL license ==========\n\n\n% # START GPL LICENSE\n\n%---------------------------------------------------------------------\n%\n% This file is part of SLAMTB, a SLAM toolbox for Matlab.\n%\n% SLAMTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% SLAMTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with SLAMTB. If not, see .\n%\n%---------------------------------------------------------------------\n\n% SLAMTB is Copyright:\n% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,\n% Copyright (c) 2010-2013, Joan Sola,\n% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,\n% SLAMTB is Copyright 2009 \n% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol\n% @ LAAS-CNRS.\n% See on top of this file for its particular copyright.\n\n% # END GPL LICENSE\n\n", "meta": {"author": "joansola", "repo": "slamtb", "sha": "b4767f6bf38bceed205abb85f1aed12422c9a972", "save_path": "github-repos/MATLAB/joansola-slamtb", "path": "github-repos/MATLAB/joansola-slamtb/slamtb-b4767f6bf38bceed205abb85f1aed12422c9a972/InterfaceLevel/projectLmk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.3456189986090583}}
{"text": "% batch run full-clustering on all fish, sweep param with 2-fold CV\n\ndata_masterdir = GetCurrentDataDir();\n\n% range_fish = [5,6,7];\n% M_ClusGroup = [2,2,2,2];\n% M_Cluster = [1,1,1,1];\nrange_fish = 8:9;\n% M_ClusGroup = 2;\n% M_Cluster = 3;\nM_stim = 1;\n% M_fish_set = [1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2];\n\n%%\nM_param = 5:5:100;%0.3:0.1:0.8;\n\nParam_nClus = zeros(length(M_param),length(range_fish));\nParam_CVscore = zeros(length(M_param),length(range_fish));\nParam_CVscore_raw = cell(length(M_param),length(range_fish));\n\n% thres_split = M_param(k_param);\n% setappdata(hfig,'thres_split',thres_split);\n\nfor k_fish = 1:length(range_fish),\n i_fish = range_fish(k_fish);\n disp(i_fish);\n LoadFullFish(hfig,i_fish,0);\n absIX = getappdata(hfig,'absIX');\n \n %% partitions for CV\n timelists = getappdata(hfig,'timelists');\n timelists_names = getappdata(hfig,'timelists_names');\n periods = getappdata(hfig,'periods');\n if length(periods)>1,\n timelistsCV = cell(length(M_stim),2);\n \n k_stim = 1;\n% for k_stim = 1:length(M_stim),\n i_stim = M_stim(k_stim);\n TL = timelists{i_stim};\n period = periods(i_stim);\n nrep = size(TL,2)/periods(i_stim); % integer\n n = floor(nrep/2);\n timelistsCV{k_stim,1} = TL(1):TL(n*period);\n timelistsCV{k_stim,2} = TL(1+n*period):TL(2*n*period);\n% end\n end\n \n for k_param = 1:length(M_param),\n numK2 = M_param(k_param);\n \n Score = zeros(1,2);%(length(M_stim),2);\n %%\n NumClus = zeros(1,2);\n CIX = cell(1,2);\n GIX = cell(1,2);\n for k = 1:2, % CV halves\n i_ClusGroup = 2;\n i_Cluster = k+4;\n [cIX,gIX] = LoadCluster_Direct(i_fish,i_ClusGroup,i_Cluster,absIX);\n \n tIX = timelistsCV{k_stim,k};\n M_0 = GetTimeIndexedData_Default_Direct(hfig,[],tIX,'isAllCells');\n\n isWkmeans = 0;\n [cIX,gIX] = AutoClustering(cIX,gIX,absIX,i_fish,M_0,isWkmeans,numK2);\n\n NumClus(k) = length(unique(gIX));\n CIX{k} = cIX;\n GIX{k} = gIX;\n end\n % plot cell-matching figure\n Score(1) = HungarianCV(NumClus(1),NumClus(2),CIX{1},CIX{2},GIX{1},GIX{2});% true,timelists_names{i_stim});\n Score(2) = HungarianCV(NumClus(2),NumClus(1),CIX{2},CIX{1},GIX{2},GIX{1});% true,timelists_names{i_stim});\n Param_CVscore(k_param,k_fish) = mean(Score);\n Param_CVscore_raw{k_param,k_fish} = Score;\n \n nClus1 = length(unique(GIX{1}));\n nClus2 = length(unique(GIX{2}));\n Param_nClus(k_param,k_fish) = mean([nClus1,nClus2]); \n\n end\nend\n\n%%\nfigure;\nsubplot(2,1,1)\nplot(M_param*20,Param_nClus)\n% legend('Fish8','Fish9');\nxlabel('total k for kmeans')\nylabel('# of auto-clusters')\nsubplot(2,1,2)\nplot(M_param*20,Param_CVscore)\nylim([0,1])\nlegend('Fish8','Fish9');\nxlabel('total k for kmeans')\nylabel('CV (overlapping cell %)')", "meta": {"author": "xiuyechen", "repo": "FishExplorer", "sha": "c61392cf0835480d64fc03c15f1992935fdc7106", "save_path": "github-repos/MATLAB/xiuyechen-FishExplorer", "path": "github-repos/MATLAB/xiuyechen-FishExplorer/FishExplorer-c61392cf0835480d64fc03c15f1992935fdc7106/figure scripts/Clustering/sweep cluster thresholds/Batch_autoclustering_sweepnumK2_CVhalves.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.34557283698135094}}
{"text": "function [x,pca_x,pca_coeff] = preprocess(x)\n [pca_coeff,pca_x,latent] = pca(x);\nend", "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/preprocess.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3455593105600228}}
{"text": "filename='Chair_Tetrahedra';\n ptype = 'MACRO';\nmethod = 'SIMPALL';\nmaterialType = 'ISOTROPIC';\ninitial_case = 'holes';\ncost = {'compliance'};\nweights = [1];\nconstraint = {'volume'};\noptimizer = 'HAMILTON-JACOBI'; incrementFactor = 1;\nfilterType = 'P1';\nline_search_initiator = 'STANDARD';\n\nHJiter0 = 1;\ne2 = 100;\nN_holes = [24 11 11];\nR_holes = 0.4;\nphase_holes = [0 0 0];\nnsteps = 5;\n\nVfrac_final = 0.2;\nPerimeter_target = 1;\noptimality_final = 1e-3;\nconstr_final =1e-3;\n\nVfrac_initial = 0.4;\noptimality_initial = 5e-2;\nconstr_initial = 5e-2;\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/Chair/ChairTetrahedra_Case_5_1_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.3455246590704838}}
{"text": "function [res min_cs] = tracking_dp(dres, c_en, c_ex, c_ij, betta, thr_cost, max_it, nms_in_loop)\n\nif ~exist('max_it')\n max_it = 1e5;\nend\nif ~exist('thr_cost')\n thr_cost = 0;\nend\n\nthr_nms = 0.5;\n\ndnum = length(dres.x);\n\ndres.c = betta - dres.r;\n\ndres.dp_c = [];\ndres.dp_link = [];\ndres.orig = [];\n\nmin_c = -inf;\nit = 0;\nk = 0;\ninds_all = zeros(1,1e5);\nid_s = zeros(1,1e5);\nredo_nodes = [1:dnum]';\nwhile (min_c < thr_cost) && (it < max_it)\n it = it+1;\n \n dres.dp_c(redo_nodes,1) = dres.c(redo_nodes) + c_en;\n dres.dp_link(redo_nodes,1) = 0;\n dres.orig(redo_nodes,1) = redo_nodes;\n \n for ii=1:length(redo_nodes)\n i = redo_nodes(ii);\n f2 = dres.nei(i).inds;\n if isempty(f2)\n continue\n end\n \n [min_cost j] = min(c_ij + dres.c(i) + dres.dp_c(f2));\n min_link = f2(j);\n if dres.dp_c(i,1) > min_cost\n dres.dp_c(i,1) = min_cost;\n dres.dp_link(i,1) = min_link;\n dres.orig(i,1) = dres.orig(min_link);\n end\n end\n \n [min_c ind] = min(dres.dp_c + c_ex);\n \n inds = zeros(dnum,1);\n \n k1 = 0;\n while ind~=0\n k1 = k1+1;\n inds(k1) = ind;\n ind = dres.dp_link(ind);\n end\n inds = inds(1:k1);\n \n inds_all(k+1:k+length(inds)) = inds;\n id_s(k+1:k+length(inds)) = it;\n k = k+length(inds);\n \n if nms_in_loop\n supp_inds = nms_aggressive(dres, inds, thr_nms);\n origs = unique(dres.orig(supp_inds));\n redo_nodes = find(ismember(dres.orig, origs));\n else\n supp_inds = inds;\n origs = inds(end);\n redo_nodes = find(dres.orig == origs);\n end\n redo_nodes = setdiff(redo_nodes, supp_inds);\n dres.dp_c(supp_inds) = inf;\n dres.c(supp_inds) = inf;\n\n min_cs(it) = min_c;\nend\ninds_all = inds_all(1:k);\nid_s = id_s(1:k);\n\nres = sub(dres, inds_all);\nres.id = id_s';\n\n", "meta": {"author": "yuxng", "repo": "MDP_Tracking", "sha": "2f452a1f7204b6e3344925b8eaf39db1c7eecf2c", "save_path": "github-repos/MATLAB/yuxng-MDP_Tracking", "path": "github-repos/MATLAB/yuxng-MDP_Tracking/MDP_Tracking-2f452a1f7204b6e3344925b8eaf39db1c7eecf2c/3rd_party/DP_NMS/tracking_dp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.34548181972574316}}
{"text": "function Z = jacobiansparsityfromnonlinear(model,includeLinear)\n\nif nargin == 1\n % IPOPT appends linear constraints, and that sparsity structure should\n % thus be included. KNITRO does not append linears to the structure\n includeLinear = 1;\nend\n\nm = length(model.lb);\nallA=[model.Anonlinineq];\nif any(model.K.q)\n top = startofSOCPCone(model.K);\n allQ = [];\n for i = 1:length(model.K.q)\n allQ = [allQ;any(model.F_struc(top:top+model.K.q(i)-1,2:end))];\n top = top + model.K.q(i);\n end\n allA = [allA;allQ];\nend\nif any(model.K.e)\n top = startofEXPCone(model.K);\n allQ = [];\n for i = 1:(model.K.e)\n allQ = [allQ;any(model.F_struc(top:top+3-1,2:end))];\n top = top + 3;\n end\n allA = [allA;allQ];\nend\nif any(model.K.p)\n top = startofPOWCone(model.K);\n allQ = [];\n for i = 1:length(model.K.p)\n allQ = [allQ;any(model.F_struc(top:top+model.K.p(i)-1,2:end))];\n top = top + model.K.p(i);\n end\n allA = [allA;allQ];\nend\nif any(model.K.s)\n top = startofSDPCone(model.K);\n allQ = [];\n for i = 1:length(model.K.s)\n s = any(model.F_struc(top:top+model.K.s(i)^2-1,2:end));\n allQ = [allQ;repmat(s,model.K.s(i),1)];\n top = top + model.K.s(i)^2;\n end\n allA = [allA;allQ];\nend\n\nallA = [allA;model.Anonlineq];\ndepends = allA | allA;\nif length(model.linearindicies) == size(allA,2)\n % It is linear + possibly linear cone\n jacobianstructure = double(depends);\nelse\n jacobianstructure = spalloc(size(allA,1),m,0);\n for i = 1:size(depends,1)\n vars = find(depends(i,:)); \n [ii,vars] = find(model.deppattern(vars,:));\n vars = unique(vars);\n s = size(jacobianstructure,1);\n if 0\n [~,loc] = ismember(vars,model.linearindicies);\n jacobianstructure(i,find(loc)) = 1;\n else\n for j = 1:length(vars)\n jacobianstructure(i,find(vars(j) == model.linearindicies)) = 1;\n end\n end\n end\nend\nif includeLinear\n allA=[model.A; model.Aeq];\n depends = allA | allA;\n jacobianstructure = [jacobianstructure;depends];\nend\nZ = sparse(jacobianstructure);\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/jacobiansparsityfromnonlinear.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.34548181972574316}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% A heuristic way to further refine the output windows\n%\n% For each small output window, we run our method on the\n% this ROI again and extract the output that has the \n% largest IOU with the orignal window for replacement.\n%\n% NMS is further applied to remove duplicate windows.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction res = refineWin(I, res, net, param)\n\nimsz = [size(I,1) size(I,2)];\nparam.lambda = 0.05;\nfor i = 1:size(res,2)\n bb = res(:,i);\n bbArea = (bb(3)-bb(1))*(bb(4)-bb(2));\n % only refine small windows\n if bbArea < 0.125*imsz(1)*imsz(2)\n margin = (bb(3)-bb(1)+bb(4)-bb(2))*0.2;\n bb = round(expandROI(bb, imsz, margin));\n Itmp = I(bb(2):bb(4), bb(1):bb(3) , :);\n [Ptmp, Stmp] = getProposals(Itmp, net, param);\n restmp = propOpt(Ptmp, Stmp, param);\n if ~isempty(restmp)\n restmp = getROIBBox(restmp, bb);\n [~,ii] = max(getIOUFloat(restmp', res(:,i)));\n res(:,i) = restmp(:,ii);\n end\n end\nend\nres = doNMS(res, 0.5);\n\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/SOD-master/code/propOpt/refineWin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.34545841762160556}}
{"text": "function [aw,ae,ap,su]=abc\n\nglobal dx n2 ta tb\nwarning off\nb=n2*(dx^2);\n\ni=1; \naw(i)=0;\nae(i)=1;\nsu(i)=b*ta+2*tb;\nsp(i)=-b-2;\nap(i)=aw(i)+ae(i)-sp(i);\n\n\ni=2;\naw(i)=1;\nae(i)=1;\nsu(i)=b*ta;\nsp(i)=-b;\nap(i)=aw(i)+ae(i)-sp(i);\n\ni=3;\naw(i)=1;\nae(i)=0;\nsu(i)=b*ta;\nsp(i)=-b;\nap(i)=aw(i)+ae(i)-sp(i);", "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/7004-jacobbi-gauss-seidel-sor-in-cfd/abc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.34534177441419006}}
{"text": "function u = sqr(a)\n%SQR Slope square sqr(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 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 = sqr(a.r);\n indexc = 1:INTLAB_SLOPE.NUMVAR;\n indexr = 2:INTLAB_SLOPE.NUMVAR+1;\n u.s = a.s .* (a.r(:,indexc)+a.r(:,indexr));\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/sqr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3453368188016341}}
{"text": "function [saveampname]=ps_load_mean_amp()\n%PS_LOAD_MEAN_AMP Load mean_amp file into a matlab workspace\n%\n% Andy Hooper, June 2006\n%\n% ======================================================================\n% 02/2010 AH: Reduce memory needs by reading in chunks\n% 11/2010 AH: Do amplitude merge here instead of ps_merge_patches.m \n% 11/2010 MA: Fix when length(amp_bit) returns zero at the end\n% ======================================================================\n\nif exist('patch.in','file')\n patch=load('patch.in');\n width=patch(2)-patch(1)+1;\nelse\n widthname='width.txt';\n if ~exist(widthname,'file')\n widthname= ['../',widthname];\n end\n width=load(widthname);\nend\n\nampname=['./mean_amp.flt'];\nsaveampname=['./amp_mean.mat'];\n\nif ~exist(ampname,'file')\n ampname=['../mean_amp.flt'];\n saveampname=['../amp_mean.mat'];\nend\n\nif ~exist(ampname,'file')\n ampname=['./mean_amp.flt'];\n saveampname=['./amp_mean.mat'];\n fprintf(' Merging mean amplitude files\\n')\n widthname='width.txt';\n if ~exist(widthname,'file')\n widthname= ['../',widthname];\n end\n width=load(widthname);\n amp=zeros(width,1,'single');\n\n if exist('./patch.list','file')\n dirname=struct;\n fid=fopen('patch.list','r');\n i=0;\n while feof(fid)==0\n i=i+1;\n dirname(i).name=fgetl(fid);\n end\n fclose(fid);\n else\n dirname=dir('PATCH_*');\n end\n n_patch=length(dirname);\n for i=1:n_patch\n if ~isempty(dirname(i).name)\n cd(dirname(i).name);\n if exist('./mean_amp.flt','file') \n pxy=load('patch.in');\n fid=fopen('mean_amp.flt');\n amp(pxy(1):pxy(2),pxy(3):pxy(4))=fread(fid,[pxy(2)-pxy(1)+1,inf],'float=>single');\n fclose(fid);\n end \n cd ..\n end\n end\n\n fid=fopen('./mean_amp.flt','w');\n fwrite(fid,amp,'float');\n fclose(fid);\n clear amp\n \n%error('Cannot find mean_amp.flt in this directory or parent')\nend\n\namp_high=[];\namp_low=[];\nfid=fopen(ampname,'r');\nwhile ~feof(fid) % first read through\n amp_bit=fread(fid,[width,1000],'float');\n amp_bit(isnan(amp_bit))=1;\n amp_bit=sort(amp_bit(:));\n if length(amp_bit)==0 % MA fix\n break % length(amp_bit) returns zero at the end\n end\n amp_high=[amp_high;amp_bit(round(length(amp_bit)*0.91):end)];\n amp_low=[amp_low;amp_bit(round(length(amp_bit)*0.01):end)];\nend\nfclose(fid);\n\namp_low=min(amp_low);\namp_high=sort(amp_high);\namp_min=min(amp_low);\namp_max=log(amp_high(ceil(length(amp_high)/2))-amp_min);\nclear amp_high amp_low\n\nfid=fopen(ampname,'r');\namp_mean=[];\nwhile ~feof(fid) % second read through\n amp_bit=fread(fid,[width,1000],'float');\n amp_bit=amp_bit'-amp_min;\n amp_bit(amp_bit<1)=1;\n amp_bit=log(amp_bit);\n amp_bit(isnan(amp_bit))=0;\n amp_bit(amp_bit>amp_max)=amp_max;\n amp_bit=uint8(amp_bit*255/amp_max);\n amp_mean=[amp_mean;amp_bit];\n if length(amp_bit)==0 % MA fix\n break\n end\nend\n\nsave(saveampname,'amp_mean');\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/ps_load_mean_amp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3453368116980983}}
{"text": "function result = applyToNonNan(data,func)\n% Apply the given function columnwise to all non NaN values in the given\n% data.\n%\n% USAGE:\n%\n% result = applyToNonNan(data,func)\n%\n% INPUTS:\n% data: Matrix of data (individuals x variables)\n% func: function handle that takes an vector of data and\n% computes single value result.\n%\n% OUTPUTS:\n%\n% result: A Vector of with dimensions (size(data,2) x 1) where\n% the supplied function was applied to all columns\n% ignoring NaN values.\n\nresult = zeros(1,size(data,2));\n\nfor i = 1:size(data,2)\n result(i) = func(data(~isnan(data(:,i)),i));\nend", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/base/utilities/applyToNonNan.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.3453368116980983}}
{"text": "function calcAllFeatureSets_HN(pathSet,training,pathMINE,param,setSize,alpha,delta,nBoot,seed,batchNum)\n% -------------------------------------------------------------------------\n% function calcAllFeatureSets_HN(pathExperiment,trainingStruct,pathMINE,setSize,alpha,delta,nBoot,batchNum)\n% -------------------------------------------------------------------------\n% DESCRIPTION: \n% This function computes feature set reduction for a given feature set type \n% and for all experiments with different degrees of freedom. See ref. [1,2] \n% for more details.\n% -------------------------------------------------------------------------\n% REFERENCES:\n% [1] Vallieres, M. et al. (2015). FDG-PET/CT radiomics models for the \n% early prediction of different tumour outcomes in head and neck cancer.\n% The Journal of Nuclear Medicine, aa(bb), xxx-yyy. \n% doi:\n% [2] 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. pathSet: Full path to the Feature Set folder of the corresponding experiment.\n% --> Ex: '/myProject/WORKSPACE/COHORT-BASED-RESULTS/Experiment1/FSET'\n% 2. training: Structure defining all parameters for the given experiment \n% to perform. See masterScript_HN.m for more details.\n% 3. pathMINE: Full path to the MINE.jar executable. The executable can be\n% downloaded at: .\n% --> Ex: '/myProject/radiomics/MultivariableModeling/MINE'\n% 4. param: Cell of two strings, defining 1) The feature set type/name; and\n% 2) the outcome to model\n% 4. setSize: Size of the output feature set (typically set to 25 in ref. [1]).\n% --> Ex: 25\n% 5. alpha: Numerical values specifying the coefficient of the first part of\n% the Gain equation, as defined in ref. [1,2].\n% --> Ex: 0.5 \n% 6. delta: Numerical values specifying the coefficient of the second part \n% of the Gain equation, as defined in ref. [1,2] (third part is set\n% to 0 in this function).\n% --> Ex: 0.5\n% 7. nBoot: Number of bootstrap samples to use.\n% --> Ex: 100\n% 8. seed: Numerical number to use as seed for bootstrapping experiment\n% --> Ex: 54288\n%\n% See \n% to find computeAllNonTextureFeatures_HN.m, organizeSeparateTextures_HN.m\n% and organizeFusedTextures_HN.m. See masterScript_HN.m for a complete \n% example of how to utilize the current function.\n% -------------------------------------------------------------------------\n% OUTPUTS: Feature sets are saved in a folder named 'FSET' in the\n% corresponding folder of \"pathExperiment\"\n% -------------------------------------------------------------------------\n% AUTHOR(S): Martin Vallieres \n% -------------------------------------------------------------------------\n% HISTORY:\n% - Creation: March 2016\n%--------------------------------------------------------------------------\n% STATEMENT:\n% This file is part of , \n% a package providing MATLAB programming tools for radiomics analysis.\n% --> Copyright (C) 2015 Martin Vallieres\n%\n% This package is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This package is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this package. If not, see .\n% -------------------------------------------------------------------------\n\nstartpath = pwd;\nwarning off\nif nargin < 10\n batchNum = 1;\nend\n\nfSetName = param{1};\noutcomeName = param{2};\noutcome = training.(outcomeName).outcome;\nnonText = training.(outcomeName).nonText;\n% if strcmp(outcomeName,'Death'), nonText = rmfield(nonText,'PercentInactive'); end % Creates problem for that outcome, this needs to be solved\ntextCellsName = fieldnames(training.(outcomeName).text.(fSetName)); textCellsName(1:4) = []; % Removing 'param', 'baseline', 'freedom', 'paramName'\nnTextCell = numel(textCellsName);\ntextCells = cell(1,nTextCell);\nfor i = 1:nTextCell\n textCells{i} = training.(outcomeName).text.(fSetName).(textCellsName{i});\nend\nparamAll = training.(outcomeName).text.(fSetName).param;\nfreedomMat = training.(outcomeName).text.(fSetName).freedom;\nbaseline = training.(outcomeName).text.(fSetName).baseline;\n\nif strcmp(fSetName,'CT')\n nonText = rmfield(nonText,{'SUVmax','SUVpeak','SUVmean','aucCSH','TLG','PercentInactive','gETU'}); % These features were calculated from PET.\nend\n\ntic\nfprintf(['\\n--> COMPUTING \"',fSetName,'\" FEATURE SET FOR \"',outcomeName,'\" OUTCOME ... '])\n[fSet] = featureSetReduction_HN(pathMINE,fSetName,outcome,setSize,nonText,textCells,textCellsName,paramAll,freedomMat,baseline,alpha,delta,nBoot,seed,batchNum);\ncd(pathSet), save(['FSET_',fSetName,'_',outcomeName],'fSet')\nfprintf('DONE!\\n'), toc\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/HN_study/Functions/MULTIVARIABLE_MODELING/calcAllFeatureSets_HN.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.34526928379508376}}
{"text": "function [ polyg, Features] = getcandboxlayoutSingle( layout, vp, h, w, integData )\n% getcandoxlayout Get box layout candidates and their features.\n%\n% INPUT:\n% vp- vanishing points h,w- height width of image\n% integData - integral images for features.\n\n%OUTPUT:\n% polyg - box layout candidates, each candidate as five polygons corresponding to left/middle/right walls, floor and ceiling\n% Features -for each box layout candidate\n\n%Features:-\n%line-membership features:1:20\n%correct label confidence: 21-25\n%label entropy :26 -30\n%weighted line-memership features:31-40\n%surface label confidence :41 -75\n\n\nnumf=75;\n\nsamps=10;gtexist=0;\n% [layout]=getLayouts(vp,h,w,samps);\n\nnumL=size(layout,1);\n\nFeatures=zeros(numL,numf);\npolyg=cell(numL,5);\n\ncnt=1;quantsiz=500;\nif numL > 0\n for lay=1:size(layout,1)\n Ra=[layout(lay,1) layout(lay,2)];\n Rb=[layout(lay,3) layout(lay,4)];\n Rc=[layout(lay,5) layout(lay,6)];\n Rd=[layout(lay,7) layout(lay,8)];\n Polyg=[];\n tot_area = 0;\n \n cond1=inpolygon(vp(3,1),vp(3,2),[Ra(1); Rb(1); Rc(1); Rd(1); Ra(1)],[Ra(2); Rb(2); Rc(2); Rd(2);Ra(2)]) & ...\n ~(inpolygon(vp(2,1),vp(2,2),[Ra(1); Rb(1); Rc(1); Rd(1);Ra(1)],[Ra(2); Rb(2); Rc(2); Rd(2);Ra(2)])) & ...\n ~(inpolygon(vp(1,2),vp(1,2),[Ra(1); Rb(1); Rc(1); Rd(1);Ra(1)],[Ra(2); Rb(2); Rc(2); Rd(2);Ra(2)]));\n \n lines1=[Ra(1) Rb(1) Ra(2) Rb(2);...\n Rc(1) Rd(1) Rc(2) Rd(2);...\n Rb(1) Rc(1) Rb(2) Rc(2);...\n Ra(1) Rd(1) Ra(2) Rd(2)];\n lines2=[vp(2,1) vp(3,1) vp(2,2) vp(3,2);...\n [vp(2,1) vp(3,1) vp(2,2) vp(3,2)];...\n [vp(1,1) vp(3,1) vp(1,2) vp(3,2)];...\n [vp(1,1) vp(3,1) vp(1,2) vp(3,2)]];\n [inxs inys]=IntersectLines(lines1,lines2);\n \n cond2=inxs(1) < vp(3,1) & inxs(2) > vp(3,1) & inys(3) < vp(3,2) & inys(4) > vp(3,2);\n \n %1 floor\n [tempimg tpolyg parea]=getface(Rd,Ra,vp,w,h,0,1,0);\n Polyg{1}=[tpolyg];\n if numel(find(isnan(tpolyg))) >0\n error('debug me');\n end\n tot_area = tot_area+parea;\n \n %2 middlewall\n [tempimg tpolyg trapez parea]=getmiddlewall(Ra,Rb,Rc,Rd,vp,w,h,0,1,0);\n Polyg{2}=[tpolyg];\n if numel(find(isnan(tpolyg))) >0\n error('debug me');\n end\n tot_area = tot_area+parea;\n \n %3 right wall\n [tempimg tpolyg parea]=getface(Rc,Rd,vp,w,h,0,1,0);\n Polyg{3}=[tpolyg];\n if numel(find(isnan(tpolyg))) >0\n error('debug me');\n end\n tot_area = tot_area+parea;\n \n \n %4 left wall\n [tempimg tpolyg parea]=getface(Ra,Rb,vp,w,h,0,1,0);\n Polyg{4}=[tpolyg];\n if numel(find(isnan(tpolyg))) >0\n error('debug me');\n end\n tot_area = tot_area+parea;\n \n %5 ceiling\n [tempimg tpolyg parea]=getface(Rb,Rc,vp,w,h,0,1,0);\n Polyg{5}=[tpolyg];\n if numel(find(isnan(tpolyg))) >0\n error('debug me');\n end\n tot_area = tot_area+parea;\n cond3=(numel(Polyg{1})+numel(Polyg{2})+numel(Polyg{3})+numel(Polyg{4})+numel(Polyg{5})) > 0;\n \n % zyd new code\n if cond1 & cond2 & ~cond3\n Polyg{2} = [640 1; 640 640; 1 640; 1 1];\n cond3 = 1;\n tot_area = w*h;\n end\n \n if (tot_area/w/h)<0.8 | (tot_area/w/h) > 1.2 | ~cond1 | ~cond2 | ~cond3\n continue;\n else\n \n for f=1:5\n polyg{cnt,f}=Polyg{f};\n end\n [Polyg]=clipPolyg(Polyg,h,w);\n if numel(Polyg)>0\n % tic\n [features] =getLayoutfeats(Polyg,integData,vp,h,w,0,quantsiz);\n % toc\n end\n \n Features(cnt,:)=features;\n \n cnt=cnt+1;\n end\n \n \n end\n \n Features(cnt:end,:)=[];\n polyg(cnt:end,:)=[];\n \n if size(Features,1)~=size(polyg,1)\n disp('stop');\n keyboard;\n end\n \n \nend\nend\n\n\n\n\n\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/getcandboxlayoutSingle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.3452692837950837}}
{"text": "function VO = spm_segment(VF,PG,flags)\n% Segment an MR image into Gray, White & CSF.\n%\n% FORMAT VO = spm_segment(PF,PG,flags)\n% PF - name(s) of image(s) to segment (must have same dimensions).\n% PG - name(s) of template image(s) for realignment.\n% - or a 4x4 transformation matrix which maps from the image to\n% the set of templates.\n% flags - a structure normally based on defaults.segment\n% VO - optional output volume\n%\n% The algorithm is four step:\n%\n% 1) Determine the affine transform which best matches the image with a\n% template image. If the name of more than one image is passed, then\n% the first image is used in this step. This step is not performed if\n% no template images are specified.\n%\n% 2) Perform Cluster Analysis with a modified Mixture Model and a-priori\n% information about the likelihoods of each voxel being one of a\n% number of different tissue types. If more than one image is passed,\n% then they they are all assumed to be in register, and the voxel\n% values are fitted to multi-normal distributions.\n%\n% 3) Perform morphometric operations on the grey and white partitions\n% in order to more accurately identify brain tissue. This is then used\n% to clean up the grey and white matter segments. \n%\n% 4) If no output argument is specified, then the segmented images are\n% written to disk. The names of these images have \"_seg1\", \"_seg2\"\n% & \"_seg3\" appended to the name of the first image passed.\n%\n%_______________________________________________________________________\n% Refs:\n%\n% Ashburner J & Friston KJ (1997) Multimodal Image Coregistration and\n% Partitioning - a Unified Framework. NeuroImage 6:209-217\n%\n%_______________________________________________________________________\n%\n% The template image, and a-priori likelihood images are modified\n% versions of those kindly supplied by Alan Evans, MNI, Canada\n% (ICBM, NIH P-20 project, Principal Investigator John Mazziotta).\n%_______________________________________________________________________\n% @(#)spm_segment.m\t2.28a John Ashburner 04/04/01\n\n% Create some suitable default values\n%-----------------------------------------------------------------------\n\ndef_flags.estimate.priors = str2mat(...\n fullfile(spm('Dir'),'apriori','gray.mnc'),...\n fullfile(spm('Dir'),'apriori','white.mnc'),...\n fullfile(spm('Dir'),'apriori','csf.mnc'));\ndef_flags.estimate.reg = 0.01;\ndef_flags.estimate.cutoff = 30;\ndef_flags.estimate.samp = 3;\ndef_flags.estimate.bb = [[-88 88]' [-122 86]' [-60 95]'];\ndef_flags.estimate.affreg.smosrc = 8;\ndef_flags.estimate.affreg.regtype = 'mni';\ndef_flags.estimate.affreg.weight = '';\ndef_flags.write.cleanup = 1;\ndef_flags.write.wrt_cor = 1;\ndef_flags.graphics = 1;\n\nif nargin<3, flags = def_flags; end;\nif ~isfield(flags,'estimate'), flags.estimate = def_flags.estimate; end;\nif ~isfield(flags.estimate,'priors'), flags.estimate.priors = def_flags.estimate.priors; end;\nif ~isfield(flags.estimate,'reg'), flags.estimate.reg = def_flags.estimate.reg; end;\nif ~isfield(flags.estimate,'cutoff'), flags.estimate.cutoff = def_flags.estimate.cutoff; end;\nif ~isfield(flags.estimate,'samp'), flags.estimate.samp = def_flags.estimate.samp; end;\nif ~isfield(flags.estimate,'bb'), flags.estimate.bb = def_flags.estimate.bb; end;\nif ~isfield(flags.estimate,'affreg'), flags.estimate.affreg = def_flags.estimate.affreg; end;\nif ~isfield(flags.estimate.affreg,'smosrc'),\n\tflags.estimate.affreg.smosrc = def_flags.estimate.affreg.smosrc;\nend;\nif ~isfield(flags.estimate.affreg,'regtype'),\n\tflags.estimate.affreg.regtype = def_flags.estimate.affreg.regtype;\nend;\nif ~isfield(flags.estimate.affreg,'weight'),\n\tflags.estimate.affreg.weight = def_flags.estimate.affreg.weight;\nend;\nif ~isfield(flags,'write'), flags.write = def_flags.write; end;\nif ~isfield(flags.write,'cleanup'), flags.write.cleanup = def_flags.write.cleanup; end;\nif ~isfield(flags.write,'wrt_cor'), flags.write.wrt_cor = def_flags.write.wrt_cor; end;\nif ~isfield(flags,'graphics'), flags.graphics = def_flags.graphics; end;\n\n%-----------------------------------------------------------------------\n\nif ischar(VF), VF= spm_vol(VF); end;\n\nSP = init_sp(flags.estimate,VF,PG);\n[x1,x2,x3] = get_sampling(SP.MM,VF,flags.estimate.samp,flags.estimate.bb);\nBP = init_bp(VF, flags.estimate.cutoff, flags.estimate.reg);\nCP = init_cp(VF,x3);\nsums = zeros(8,1);\n\nfor pp=1:length(x3),\n\t[raw,msk] = get_raw(VF,x1,x2,x3(pp));\n\ts = get_sp(SP,x1,x2,x3(pp));\n\tCP = update_cp_est(CP,s,raw,msk,pp);\n\tsums = sums + reshape(sum(sum(s,1),2),8,1);\nend;\nsums = sums/sum(sums);\nCP = shake_cp(CP);\n\n[CP,BP,SP] = run_segment(CP,BP,SP,VF,sums,x1,x2,x3);\n\n%save segmentation_results.mat CP BP SP VF sums\n\n[g,w,c] = get_gwc(VF,BP,SP,CP,sums,flags.write.wrt_cor);\nif flags.write.cleanup, [g,w,c] = clean_gwc(g,w,c); end;\n\n% Create the segmented images.\n%-----------------------------------------------------------------------\n%offs = cumsum(repmat(prod(VF(1).dim(1:2)),1,VF(1).dim(3)))-prod(VF(1).dim(1:2));\n%pinfo = [repmat([1/255 0]',1,VF(1).dim(3)) ; offs];\n[pth,nm,xt] = fileparts(deblank(VF(1).fname));\nfor j=1:3,\n\ttmp = fullfile(pth,[nm '_seg' num2str(j) xt]);\n\tVO(j) = struct(...\n\t\t'fname',tmp,...\n\t\t'dim', [VF(1).dim(1:3) 2],...\n\t\t'mat', VF(1).mat,...\n\t\t'pinfo', [1/255 0 0]',...\n\t\t'descrip','Segmented image');\nend;\n\nif nargout==0,\n\tVO = spm_create_vol(VO);\n\n\tspm_progress_bar('Init',VF(1).dim(3),'Writing Segmented','planes completed');\n\tfor pp=1:VF(1).dim(3),\n\t\tVO(1) = spm_write_plane(VO(1),double(g(:,:,pp))/255,pp);\n\t\tVO(2) = spm_write_plane(VO(2),double(w(:,:,pp))/255,pp);\n\t\tVO(3) = spm_write_plane(VO(3),double(c(:,:,pp))/255,pp);\n\t\tspm_progress_bar('Set',pp);\n\tend;\n\tVO = spm_close_vol(VO);\n\tspm_progress_bar('Clear');\nend;\n\nVO(1).dat = g; VO(1).pinfo = VO(1).pinfo(1:2,:);\nVO(2).dat = w; VO(2).pinfo = VO(2).pinfo(1:2,:);\nVO(3).dat = c; VO(3).pinfo = VO(3).pinfo(1:2,:);\n\nif flags.graphics, display_graphics(VF,VO,CP.mn,CP.cv,CP.mg); end;\n\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction [y1,y2,y3] = affine_transform(x1,x2,x3,M)\n\ty1 = M(1,1)*x1 + M(1,2)*x2 + M(1,3)*x3 + M(1,4);\n\ty2 = M(2,1)*x1 + M(2,2)*x2 + M(2,3)*x3 + M(2,4);\n\ty3 = M(3,1)*x1 + M(3,2)*x2 + M(3,3)*x3 + M(3,4);\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction display_graphics(VF,VS,mn,cv,mg)\n% Do the graphics\nnb = 3;\nspm_figure('Clear','Graphics');\nfg = spm_figure('FindWin','Graphics');\nif ~isempty(fg),\n\t% Show some text\n\t%-----------------------------------------------------------------------\n\tax = axes('Position',[0.05 0.8 0.9 0.2],'Visible','off','Parent',fg);\n\ttext(0.5,0.80, 'Segmentation','FontSize',16,'FontWeight','Bold',...\n\t\t'HorizontalAlignment','center','Parent',ax);\n\n\ttext(0,0.65, ['Image: ' spm_str_manip(VF(1).fname,'k50d')],...\n\t\t'FontSize',14,'FontWeight','Bold','Parent',ax);\n\n\ttext(0,0.40, 'Means:','FontSize',12,'FontWeight','Bold','Parent',ax);\n\ttext(0,0.30, 'Std devs:' ,'FontSize',12,'FontWeight','Bold','Parent',ax);\n\ttext(0,0.20, 'N vox:','FontSize',12,'FontWeight','Bold','Parent',ax);\n\tfor j=1:nb,\n\t\ttext((j+0.5)/(nb+1),0.40, num2str(mn(1,j)),...\n\t\t\t'FontSize',12,'FontWeight','Bold',...\n\t\t\t'HorizontalAlignment','center','Parent',ax);\n\t\ttext((j+0.5)/(nb+1),0.30, num2str(sqrt(cv(1,1,j))),...\n\t\t\t'FontSize',12,'FontWeight','Bold',...\n\t\t\t'HorizontalAlignment','center','Parent',ax);\n\t\ttext((j+0.5)/(nb+1),0.20, num2str(mg(1,j)/sum(mg(1,:))),...\n\t\t\t'FontSize',12,'FontWeight','Bold',...\n\t\t\t'HorizontalAlignment','center','Parent',ax);\n\tend;\n\tif length(VF) > 1,\n\t\ttext(0,0.10,...\n\t\t'Note: only means and variances for the first image are shown',...\n\t\t'Parent',ax,'FontSize',12);\n\tend;\n\n\tM1 = VS(1).mat;\n\tM2 = VF(1).mat;\n\tfor i=1:5,\n\t\tM = spm_matrix([0 0 i*VF(1).dim(3)/6]);\n\t\timg = spm_slice_vol(VF(1),M,VF(1).dim(1:2),1);\n\t\timg(1,1) = eps;\n\t\tax = axes('Position',...\n\t\t\t[0.05 0.75*(1-i/5)+0.05 0.9/(nb+1) 0.75/5],...\n\t\t\t'Visible','off','Parent',fg);\n\t\timagesc(rot90(img), 'Parent', ax);\n\t\tset(ax,'Visible','off','DataAspectRatio',[1 1 1]);\n\n\t\tfor j=1:3,\n\t\t\timg = spm_slice_vol(VS(j),M2\\M1*M,VF(1).dim(1:2),1);\n\t\t\tax = axes('Position',...\n\t\t\t\t[0.05+j*0.9/(nb+1) 0.75*(1-i/5)+0.05 0.9/(nb+1) 0.75/5],...\n\t\t\t\t'Visible','off','Parent',fg);\n\t\t\timage(rot90(img*64), 'Parent', ax);\n\t\t\tset(ax,'Visible','off','DataAspectRatio',[1 1 1]);\n\t\tend;\n\tend;\n\n\tspm_print;\n\tdrawnow;\nend;\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction M = get_affine_mapping(VF,VG,aflags)\n\nif ~isempty(VG) & ischar(VG), VG = spm_vol(VG); end;\n\nif ~isempty(VG) & isstruct(VG),\n\t% Affine registration so that a priori images match the image to\n\t% be segmented.\n\t%-----------------------------------------------------------------------\n\n\tVFS = spm_smoothto8bit(VF(1),aflags.smosrc);\n\n\t% Scale all images approximately equally\n\t% ---------------------------------------------------------------\n\tfor i=1:length(VG),\n\t\tVG(i).pinfo(1:2,:) = VG(i).pinfo(1:2,:)/spm_global(VG(i));\n\tend;\n\tVFS(1).pinfo(1:2,:) = VFS(1).pinfo(1:2,:)/spm_global(VFS(1));\n\n\tspm_chi2_plot('Init','Affine Registration','Mean squared difference','Iteration');\n\tflags = struct('sep',aflags.smosrc, 'regtype',aflags.regtype,'WG',[],'globnorm',0,'debug',0);\n\tM = eye(4);\n\t[M,scal] = spm_affreg(VG, VFS, flags, M);\n\n\tif ~isempty(aflags.weight), flags.WG = spm_vol(aflags.weight); end;\n\n\tflags.sep = aflags.smosrc/2;\n\tM = spm_affreg(VG, VFS, flags, M,scal);\n\tspm_chi2_plot('Clear');\n\nelseif all(size(VG) == [4 4])\n\t% Assume that second argument is a matrix that will do the job\n\t%-----------------------------------------------------------------------\n\tM = VG;\nelse\n\t% Assume that image is normalized\n\t%-----------------------------------------------------------------------\n\tM = eye(4);\nend\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction [x1,x2,x3] = get_sampling(MM,VF,samp,bb1)\n% Voxels to sample during the cluster analysis\n%-----------------------------------------------------------------------\n\n% A bounding box for the brain in Talairach space.\n%bb = [ [-88 88]' [-122 86]' [-60 95]'];\n%c = [bb(1,1) bb(1,2) bb(1,3) 1\n% bb(1,1) bb(1,2) bb(2,3) 1\n% bb(1,1) bb(2,2) bb(1,3) 1\n% bb(1,1) bb(2,2) bb(2,3) 1\n% bb(2,1) bb(1,2) bb(1,3) 1\n% bb(2,1) bb(1,2) bb(2,3) 1\n% bb(2,1) bb(2,2) bb(1,3) 1\n% bb(2,1) bb(2,2) bb(2,3) 1]';\n%tc = MM\\c;\n%tc = tc(1:3,:)';\n%mx = max(tc);\n%mn = min(tc);\n%bb = [mn ; mx];\n%vx = sqrt(sum(VF(1).mat(1:3,1:3).^2));\n%samp = round(max(abs([4 4 4]./vx), [1 1 1]));\n%x1 = bb(1,1):samp(1):bb(2,1);\n%x2 = bb(1,2):samp(2):bb(2,2);\n%x3 = bb(1,3):samp(3):bb(2,3);\n%return;\n\n% A bounding box for the brain in Talairach space.\nif nargin<4, bb1 = [ [-88 88]' [-122 86]' [-60 95]']; end;\n\n% A mapping from a unit radius sphere to a hyper-ellipse\n% that is just enclosed by the bounding box in Talairach\n% space.\nM0 = [diag(diff(bb1)/2) mean(bb1)';[0 0 0 1]];\n\n% The mapping from voxels to Talairach space is MM,\n% so the ellipse in the space of the image becomes:\nM0 = MM\\M0;\n\n% So to work out the bounding box in the space of the\n% image that just encloses the hyper-ellipse.\ntmp = M0(1:3,1:3);\ntmp = diag(tmp*tmp'/diag(sqrt(diag(tmp*tmp'))));\nbb = round([M0(1:3,4)-tmp M0(1:3,4)+tmp])';\nbb = min(max(bb,[1 1 1 ; 1 1 1]),[VF(1).dim(1:3) ; VF(1).dim(1:3)]);\n\n% Want to sample about every 3mm\ntmp = sqrt(sum(VF(1).mat(1:3,1:3).^2))';\nsamp = round(max(abs(tmp.^(-1)*samp), [1 1 1]'));\n\nx1 = bb(1,1):samp(1):bb(2,1);\nx2 = bb(1,2):samp(2):bb(2,2);\nx3 = bb(1,3):samp(3):bb(2,3);\n\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction [CP,BP,SP] = run_segment(CP,BP,SP,VF,sums,x1,x2,x3)\noll = -Inf;\nspm_chi2_plot('Init','Segmenting','Log-likelihood','Iteration #');\n\nfor iter = 1:64,\n\tll= 0;\n\tfor pp = 1:length(x3), % Loop over planes\n\t\tbf = get_bp(BP,x1,x2,x3(pp));\n\t\t[raw,msk] = get_raw(VF,x1,x2,x3(pp));\n\t\ts = get_sp(SP,x1,x2,x3(pp));\n\t\tcor = bf.*raw;\n\t\t[P,ll0] = get_p(cor,msk,s,sums,CP,bf);\n\t\tll = ll + ll0;\n\t\tCP = update_cp_est(CP,P,cor,msk,pp);\n\t\tBP = update_bp_est(BP,P,cor,CP,msk,x1,x2,x3(pp));\n\tend;\n\n\tBP = update_bp(BP);\n\tif iter>1, spm_chi2_plot('Set',ll); end;\n\t%fprintf('\\t%g\\n', ll);\n\n\t% Stopping criterion\n\t%-----------------------------------------------------------------------\n\tif iter == 2,\n\t\tll2 = ll;\n\telseif iter > 2 & abs((ll-oll)/(ll-ll2)) < 0.0001\n\t\tbreak;\n\tend;\n\toll = ll;\nend;\nspm_chi2_plot('Clear');\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction BP = init_bp(VF,co,reg)\nm = length(VF);\ntmp = sqrt(sum(VF(1).mat(1:3,1:3).^2));\nBP.nbas = max(round((VF(1).dim(1:3).*tmp)/co),[1 1 1]);\nBP.B1 = spm_dctmtx(VF(1).dim(1),BP.nbas(1));\nBP.B2 = spm_dctmtx(VF(1).dim(2),BP.nbas(2));\nBP.B3 = spm_dctmtx(VF(1).dim(3),BP.nbas(3));\n\nnbas = BP.nbas;\nif prod(BP.nbas)>1,\n\t% Set up a priori covariance matrix\n\tvx = sqrt(sum(VF(1).mat(1:3,1:3).^2));\n\tkx=(pi*((1:nbas(1))'-1)*pi/vx(1)/VF(1).dim(1)*10).^2;\n\tky=(pi*((1:nbas(2))'-1)*pi/vx(2)/VF(1).dim(2)*10).^2;\n\tkz=(pi*((1:nbas(3))'-1)*pi/vx(3)/VF(1).dim(3)*10).^2;\n\n\t% Cost function based on sum of squares of 4th derivatives\n\tIC0 = (1*kron(kz.^4,kron(ky.^0,kx.^0)) +...\n\t 1*kron(kz.^0,kron(ky.^4,kx.^0)) +...\n\t 1*kron(kz.^0,kron(ky.^0,kx.^4)) +...\n\t 4*kron(kz.^3,kron(ky.^1,kx.^0)) +...\n\t 4*kron(kz.^3,kron(ky.^0,kx.^1)) +...\n\t 4*kron(kz.^1,kron(ky.^3,kx.^0)) +...\n\t 4*kron(kz.^0,kron(ky.^3,kx.^1)) +...\n\t 4*kron(kz.^1,kron(ky.^0,kx.^3)) +...\n\t 4*kron(kz.^0,kron(ky.^1,kx.^3)) +...\n\t 6*kron(kz.^2,kron(ky.^2,kx.^0)) +...\n\t 6*kron(kz.^2,kron(ky.^0,kx.^2)) +...\n\t 6*kron(kz.^0,kron(ky.^2,kx.^2)) +...\n\t 12*kron(kz.^2,kron(ky.^1,kx.^1)) +...\n\t 12*kron(kz.^1,kron(ky.^2,kx.^1)) +...\n\t 12*kron(kz.^1,kron(ky.^1,kx.^2)) )*reg;\n\n\t%IC0(1) = max(IC0);\n\tBP.IC0 = diag(IC0(2:end));\n\n\t% Initial estimate for intensity modulation field\n\tBP.T = zeros(nbas(1),nbas(2),nbas(3),length(VF));\n\t%-----------------------------------------------------------------------\nelse\n\tBP.T = zeros([1 1 1 length(VF)]);\n\tBP.IC0 = [];\nend;\nBP.Alpha = zeros(prod(BP.nbas(1:3)),prod(BP.nbas(1:3)),m);\nBP.Beta = zeros(prod(BP.nbas(1:3)),m);\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction BP = update_bp_est(BP,p,cor,CP,msk,x1,x2,x3)\nif prod(BP.nbas)<=1, return; end;\nB1 = BP.B1(x1,:);\nB2 = BP.B2(x2,:);\nB3 = BP.B3(x3,:);\nfor j=1:size(BP.Alpha,3),\n\tcr = cor(:,:,j);\n\tw1 = zeros(size(cr));\n\tw2 = zeros(size(cr));\n\tfor i=[1 2 3 4 5 6 7 8],\n\t\ttmp = p(:,:,i)*CP.cv(j,j,i)^(-1);\n\t\tw1 = w1 + tmp.*(CP.mn(j,i) - cr);\n\t\tw2 = w2 + tmp;\n\tend;\n\twt1 = 1 + cr.*w1;\n\twt2 = cr.*(cr.*w2 - w1);\n\twt1(~msk) = 0;\n\twt2(~msk) = 0;\n\n\tBP.Beta(:,j) = BP.Beta(:,j) + kron(B3',spm_krutil(wt1,B1,B2,0));\n\tBP.Alpha(:,:,j) = BP.Alpha(:,:,j) + kron(B3'*B3,spm_krutil(wt2,B1,B2,1));\nend;\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction BP = update_bp(BP)\nif prod(BP.nbas)<=1, return; end;\nfor j=1:size(BP.Alpha,3),\n\tx = BP.T(:,:,:,j);\n\tx = x(:);\n\tx = x(2:end);\n\tAlpha = BP.Alpha(2:end,2:end,j);\n\tBeta = BP.Beta(2:end,j);\n\tx = (Alpha + BP.IC0)\\(Alpha*x + Beta);\n\n\tBP.T(:,:,:,j) = reshape([0 ; x],BP.nbas(1:3));\n\tBP.Alpha = zeros(size(BP.Alpha));\n\tBP.Beta = zeros(size(BP.Beta));\nend;\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction bf = get_bp(BP,x1,x2,x3)\nbf = ones(length(x1),length(x2),size(BP.Alpha,3));\nif prod(BP.nbas)<=1, return; end;\nB1 = BP.B1(x1,:);\nB2 = BP.B2(x2,:);\nB3 = BP.B3(x3,:);\nfor i=1:size(BP.Alpha,3),\n\tt = reshape(reshape(BP.T(:,:,:,i),...\n\t\tBP.nbas(1)*BP.nbas(2),BP.nbas(3))*B3', BP.nbas(1), BP.nbas(2));\n\tbf(:,:,i) = exp(B1*t*B2');\nend;\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction [dat,msk] = get_raw(VF,x1,x2,x3)\n[X1,X2,X3] = ndgrid(x1,x2,x3);\nfor i=1:length(VF),\n\t[Y1,Y2,Y3] = affine_transform(X1,X2,X3,VF(i).mat\\VF(1).mat);\n\tdat(:,:,i) = spm_sample_vol(VF(i),Y1,Y2,Y3,1);\nend;\nmsk = all(dat,3) & all(isfinite(double(dat)),3);\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction CP = init_cp(VF,x3)\nn = 8;\nm = length(VF);\np = length(x3);\nCP.mom0 = zeros(1,n,p)+eps;\nCP.mom1 = zeros(m,n,p);\nCP.mom2 = zeros(m,m,n,p)+eps;\n\n% Occasionally the dynamic range of the images is such that many voxels\n% all have the same intensity. Adding cv0 is an attempt to improve the\n% stability of the algorithm if this occurs. The value 0.083 was obtained\n% from var(rand(1000000,1)). It prbably isn't the best way of doing\n% things, but it appears to work.\nCP.cv0 = zeros(m,m);\nfor i=1:m,\n\tif spm_type(VF(i).dim(4),'intt'),\n\t\tCP.cv0(i,i)=0.083*mean(VF(i).pinfo(1,:));\n\tend;\nend;\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction CP = shake_cp(CP)\nCP.mom0(:,5,:) = CP.mom0(:,1,:);\nCP.mom0(:,6,:) = CP.mom0(:,2,:);\nCP.mom0(:,7,:) = CP.mom0(:,3,:);\nCP.mom1(:,5,:) = CP.mom1(:,1,:);\nCP.mom1(:,6,:) = CP.mom1(:,2,:);\nCP.mom1(:,7,:) = CP.mom1(:,3,:);\nCP.mom1(:,8,:) = 0;\nCP.mom2(:,:,5,:) = CP.mom2(:,:,1,:);\nCP.mom2(:,:,6,:) = CP.mom2(:,:,2,:);\nCP.mom2(:,:,7,:) = CP.mom2(:,:,3,:);\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction CP = update_cp_est(CP,P,dat,msk,p)\nm = size(dat,3);\nd = size(P);\nP = reshape(P,[d(1)*d(2),d(3)]);\ndat = reshape(dat,[d(1)*d(2),m]);\nP(~msk(:),:) = [];\ndat(~msk(:),:) = [];\nfor i=1:size(CP.mom0,2),\n\tCP.mom0(1,i,p) = sum(P(:,i));\n\tCP.mom1(:,i,p) = sum((P(:,i)*ones(1,m)).*dat)';\n\tCP.mom2(:,:,i,p) = ((P(:,i)*ones(1,m)).*dat)'*dat;\nend;\n\nfor i=1:size(CP.mom0,2),\n\tCP.mg(1,i) = sum(CP.mom0(1,i,:),3);\n\tCP.mn(:,i) = sum(CP.mom1(:,i,:),3)/CP.mg(1,i);\n\n\ttmp = (CP.mg(1,i).*CP.mn(:,i))*CP.mn(:,i)';\n\ttmp = tmp-eye(size(tmp))*eps*10000;\n\tCP.cv(:,:,i) = (sum(CP.mom2(:,:,i,:),4) - tmp)/CP.mg(1,i) + CP.cv0;\nend;\nCP.mg = CP.mg/sum(CP.mg);\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction [p,ll] = get_p(cor,msk,s,sums,CP,bf)\nd = [size(cor) 1 1];\nn = size(CP.mg,2);\ncor = reshape(cor,d(1)*d(2),d(3));\ncor = cor(msk,:);\np = zeros(d(1)*d(2),n);\nif ~any(msk), p = reshape(p,d(1),d(2),n); ll=0; return; end;\n\nfor i=1:n,\n\tamp = 1/sqrt((2*pi)^d(3) * det(CP.cv(:,:,i)));\n\tdst = (cor-ones(size(cor,1),1)*CP.mn(:,i)')/sqrtm(CP.cv(:,:,i));\n\tdst = sum(dst.*dst,2);\n\ttmp = s(:,:,i);\n\tp(msk,i) = (amp*CP.mg(1,i)/sums(i))*exp(-0.5*dst).*tmp(msk) +eps;\nend;\nsp = sum(p,2);\nll = sum(log(sp(msk).*bf(msk)+eps));\nsp(~msk) = Inf;\nfor i=1:n, p(:,i) = p(:,i)./sp; end;\np = reshape(p,d(1),d(2),n);\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction SP = init_sp(flags,VF,PG)\nSP.VB = spm_vol(flags.priors);\nMM = get_affine_mapping(VF,PG,flags.affreg);\n%VF = spm_vol(PF);\nSP.MM = MM*VF(1).mat;\nSP.w = 0.98;\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction s = get_sp(SP,x1,x2,x3)\n[X1,X2,X3] = ndgrid(x1,x2,x3);\n[Y1,Y2,Y3] = affine_transform(X1,X2,X3,SP.VB(1).mat\\SP.MM);\nw1 = SP.w;\nw2 = (1-w1)/2;\ns = zeros([size(Y1),4]);\nfor i=1:3,\n\ts(:,:,i) = spm_sample_vol(SP.VB(i),Y1,Y2,Y3,1)*w1+w2;\nend;\ns(:,:,4:8) = repmat(abs(1-sum(s(:,:,1:3),3))/5,[1 1 5]);\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction [g,w,c] = get_gwc(VF,BP,SP,CP,sums,wc)\n\nif wc,\n\tVC = VF;\n\tfor j=1:length(VF),\n\t\t[pth,nm,xt] = fileparts(deblank(VF(j).fname));\n\t\tVC(j).fname = fullfile(pth,['m' nm xt]);\n\t\tVC(j).descrip = 'Bias corrected image';\n\tend;\n\tVC = spm_create_vol(VC);\nend;\n\nspm_progress_bar('Init',VF(1).dim(3),'Creating Segmented','planes completed');\nx1 = 1:VF(1).dim(1);\nx2 = 1:VF(1).dim(2);\nx3 = 1:VF(1).dim(3);\n\ng = uint8(0); g(VF(1).dim(1),VF(1).dim(2),VF(1).dim(3)) = 0;\nw = uint8(0); w(VF(1).dim(1),VF(1).dim(2),VF(1).dim(3)) = 0;\nc = uint8(0); c(VF(1).dim(1),VF(1).dim(2),VF(1).dim(3)) = 0;\n\nfor pp=1:length(x3),\n\tbf = get_bp(BP,x1,x2,x3(pp));\n\t[raw,msk] = get_raw(VF,x1,x2,x3(pp));\n\tcor = raw.*bf;\n\tif wc,\n\t\tfor j=1:length(VC),\n\t\t\tVC(j) = spm_write_plane(VC(j),cor(:,:,j),pp);\n\t\tend;\n\tend;\n\ts = get_sp(SP,x1,x2,x3(pp));\n\tp = get_p(cor,msk,s,sums,CP,bf);\n\tg(:,:,pp) = uint8(round(p(:,:,1)*255));\n\tw(:,:,pp) = uint8(round(p(:,:,2)*255));\n\tc(:,:,pp) = uint8(round(p(:,:,3)*255));\n\n\tspm_progress_bar('Set',pp);\nend;\nspm_progress_bar('Clear');\n\nif wc, spm_close_vol(VC); end;\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction [g,w,c] = clean_gwc(g,w,c)\nb = w;\nb(1) = w(1);\n\n% Build a 3x3x3 seperable smoothing kernel\n%-----------------------------------------------------------------------\nkx=[0.75 1 0.75];\nky=[0.75 1 0.75];\nkz=[0.75 1 0.75];\nsm=sum(kron(kron(kz,ky),kx))^(1/3);\nkx=kx/sm; ky=ky/sm; kz=kz/sm;\n\n% Erosions and conditional dilations\n%-----------------------------------------------------------------------\nniter = 32;\nspm_progress_bar('Init',niter,'Extracting Brain','Iterations completed');\nfor j=1:niter,\n\tif j>2, th=0.15; else th=0.6; end; % Dilate after two its of erosion.\n\tfor i=1:size(b,3),\n\t\tgp = double(g(:,:,i));\n\t\twp = double(w(:,:,i));\n\t\tbp = double(b(:,:,i))/255;\n\t\tbp = (bp>th).*(wp+gp);\n\t\tb(:,:,i) = uint8(round(bp));\n\tend;\n\tspm_conv_vol(b,b,kx,ky,kz,-[1 1 1]);\n\tspm_progress_bar('Set',j);\nend;\nth = 0.05;\nfor i=1:size(b,3),\n\tgp = double(g(:,:,i))/255;\n\twp = double(w(:,:,i))/255;\n\tcp = double(c(:,:,i))/255;\n\tbp = double(b(:,:,i))/255;\n\tbp = ((bp>th).*(wp+gp))>th;\n\tg(:,:,i) = uint8(round(255*gp.*bp./(gp+wp+cp+eps)));\n\tw(:,:,i) = uint8(round(255*wp.*bp./(gp+wp+cp+eps)));\n\tc(:,:,i) = uint8(round(255*(cp.*bp./(gp+wp+cp+eps)+cp.*(1-bp))));\nend;\nspm_progress_bar('Clear');\nreturn;\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/spm2/spm_segment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.34526927800385393}}
{"text": "function SR = superresolve_bicubic(slidingWindow, magFactor)\n\n SR = imresize(slidingWindow.referenceFrame, magFactor, 'bicubic');\n ", "meta": {"author": "thomas-koehler", "repo": "SupER", "sha": "d8c6f2e4b26db002ff55bc2beba18639f1d0bb49", "save_path": "github-repos/MATLAB/thomas-koehler-SupER", "path": "github-repos/MATLAB/thomas-koehler-SupER/SupER-d8c6f2e4b26db002ff55bc2beba18639f1d0bb49/matlab/algorithms/SRAlgorithms/superresolve_bicubic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3452606368749277}}
{"text": "% ==============================================================================\n%\n% Software License Agreement (BSD License)\n% Copyright (c) 2019\n% (www.aimlab.wpi.edu)\n%\n% All rights reserved.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions\n% 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\n% copyright notice, this list of conditions and the following\n% disclaimer in the documentation and/or other materials provided\n% with the distribution.\n%\n% * Neither the name of authors nor the names of its contributors may\n% be used to endorse or promote products derived from this software\n% without specific prior written permission.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n% \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n% FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n% COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n% INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n% BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n% CAUSED 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%\n% \\author: \n% \\author: \n% \\author: Adnan Munawar\n% \\version: 0.1$\n% ==============================================================================\n\nfunction [its,sizePath,run_time] = RRTstar3D(dim,segmentLength,radius,random_world,show_output,samples)\n% if samples < 4000\n% disp('ERROR! SPECIFY ATLEAST 4000 SAMPLES')\n% return\n% end\n\n% dim = 2;\n% radius =0;\n% segmentLength = 5;\n% random_world = 0;\n% n_its = 1000;\n% standard length of path segments\nif dim ==2\n start_cord = [5,5];\n goal_cord = [95,95];\n \nelse\n \n start_cord = [5,5,5];\n goal_cord = [95,95,95];\nend\n\n\n\n% create random world\nSize = 100;\nNumObstacles = 100;\n\nif random_world ==1\n world = createWorld(NumObstacles,ones(1,dim)*Size,zeros(1,dim),dim);\nelse\n [world NumObstacles] = createKnownWorld(ones(1,dim)*Size,[0;0;0],dim);\nend\n% randomly select start and end nodes\n%start_node = generateRandomNode(world,dim)\n%end_node = generateRandomNode(world,dim)\nstart_node = [start_cord,0,0,0];\nend_node = [goal_cord,0,0,0];\n% establish tree starting with the start node\ntree = start_node;\n\nnumPaths = 0;\na = clock;\n% check to see if start_node connects directly to end_node\nif ( (norm(start_node(1:dim)-end_node(1:dim))0\n draw = floor(samples/8);\n its = 0;\n for i = 1:samples\n flag = 0;\n [tree,flag] = extendTree(tree,end_node,segmentLength,radius,world,flag,dim);\n numPaths = numPaths + flag;\n its = its+1;\n \n if its == draw\n tree_1 = tree;\n elseif its == draw*2\n tree_2 = tree;\n elseif its == draw*3\n tree_3 = tree;\n elseif its == draw*4\n tree_4 = tree;\n elseif its == draw*5\n tree_5 = tree;\n elseif its == draw*6\n tree_6 = tree;\n elseif its == draw*7\n tree_7 = tree;\n elseif its == samples\n tree_8 = tree;\n end\n end\n \n else\n its = 0;\n numPaths = 0;\n flag = 0;\n while numPaths < 1,\n [tree,flag] = extendTree(tree,end_node,segmentLength,radius,world,flag,dim);\n numPaths = numPaths + flag;\n its = its+1;\n end\n end\n \nend\nnumPaths\n\n% find path with minimum cost to end_node\npath = findMinimumPath(tree,end_node,dim);\n\nb = clock;\nrun_time = 3600*(b(4)-a(4)) + 60 * (b(5)-a(5)) + (b(6) - a(6));\n\npath_1 = findMinimumPath(tree_1,end_node,dim);\n\npath_2 = findMinimumPath(tree_2,end_node,dim);\n\npath_3 = findMinimumPath(tree_3,end_node,dim);\n\npath_4 = findMinimumPath(tree_4,end_node,dim);\n\npath_5 = findMinimumPath(tree_5,end_node,dim);\n\npath_6 = findMinimumPath(tree_6,end_node,dim);\n\npath_7 = findMinimumPath(tree_7,end_node,dim);\n\npath_8 = findMinimumPath(tree_8,end_node,dim);\n\nsizePath = size(path,1);\n\n\nif show_output == 1\n \n if size(path_1, 1) > 0\n figure;\n plotExpandedTree(world,tree_1,dim);\n plotWorld(world,path_1,dim);\n else\n disp('COULD NOT FIND A CONNECTING TREE TILL 1/8th SAMPLES SO NOT DRAWING THAT PATH')\n end\n if size(path_2, 1) > 0\n figure;\n plotExpandedTree(world,tree_2,dim);\n plotWorld(world,path_2,dim);\n else\n disp('COULD NOT FIND A CONNECTING TREE TILL 2/8th SAMPLES SO NOT DRAWING THAT PATH')\n end\n if size(path_3, 1) > 0\n figure;\n plotExpandedTree(world,tree_3,dim);\n plotWorld(world,path_3,dim);\n else\n disp('COULD NOT FIND A CONNECTING TREE TILL 3/8th SAMPLES SO NOT DRAWING THAT PATH')\n end\n if size(path_4, 1) > 0\n figure;\n plotExpandedTree(world,tree_4,dim);\n plotWorld(world,path_4,dim);\n else\n disp('COULD NOT FIND A CONNECTING TREE TILL 4/8th SAMPLES SO NOT DRAWING THAT PATH')\n end\n if size(path_5, 1) > 0\n figure;\n plotExpandedTree(world,tree_5,dim);\n plotWorld(world,path_5,dim);\n else\n disp('COULD NOT FIND A CONNECTING TREE TILL 5/8th SAMPLES SO NOT DRAWING THAT PATH')\n end\n if size(path_6, 1) > 0\n figure;\n plotExpandedTree(world,tree_6,dim);\n plotWorld(world,path_6,dim);\n else\n disp('COULD NOT FIND A CONNECTING TREE TILL 6/8th SAMPLES SO NOT DRAWING THAT PATH')\n end\n if size(path_7, 1) > 0\n figure;\n plotExpandedTree(world,tree_7,dim);\n plotWorld(world,path_7,dim);\n else\n disp('COULD NOT FIND A CONNECTING TREE TILL 7/8th SAMPLES SO NOT DRAWING THAT PATH')\n end\n if size(path_8, 1) > 0\n figure;\n plotExpandedTree(world,tree_8,dim);\n plotWorld(world,path_8,dim);\n else\n disp('COULD NOT FIND A CONNECTING TREE TILL 8/8th SAMPLES SO NOT DRAWING THAT PATH')\n end\n if size(path, 1) > 0\n figure;\n plotExpandedTree(world,tree,dim);\n plotWorld(world,path,dim);\n else\n disp('COULD NOT FIND A CONNECTING TREE FOR THE SPECIFIED SAMPLES. PLEASE INCREASE THE NUMBER OF SAMPLES')\n end\nend\nend\n\n\n\n\n\nfunction world = createWorld(NumObstacles, endcorner, origincorner,dim)\n\nif dim == 2\n \n % check to make sure that the region is nonempty\n if (endcorner(1) <= origincorner(1)) | (endcorner(2) <= origincorner(2))\n disp('Not valid corner specifications!')\n world=[];\n \n % create world data structure\n else\n world.NumObstacles = NumObstacles;\n world.endcorner = endcorner;\n world.origincorner = origincorner;\n \n % create NumObstacles\n maxRadius = min(endcorner(1)- origincorner(1), endcorner(2)-origincorner(2));\n maxRadius = 5*maxRadius/NumObstacles/2;\n for i=1:NumObstacles,\n % randomly pick radius\n world.radius(i) = maxRadius*rand;\n % randomly pick center of obstacles\n cx = origincorner(1) + world.radius(i)...\n + (endcorner(1)-origincorner(1)-2*world.radius(i))*rand;\n cy = origincorner(2) + world.radius(i)...\n + (endcorner(2)-origincorner(2)-2*world.radius(i))*rand;\n world.cx(i) = cx;\n world.cy(i) = cy;\n end\n end\n \nelseif dim ==3;\n % check to make sure that the region is nonempty\n if (endcorner(1) <= origincorner(1)) || (endcorner(2) <= origincorner(2)) || (endcorner(3) <= origincorner(3))\n disp('Not valid corner specifications!')\n world=[];\n \n % create world data structure\n else\n world.NumObstacles = NumObstacles;\n world.endcorner = endcorner;\n world.origincorner = origincorner;\n \n % create NumObstacles\n bounds = [endcorner(1)- origincorner(1), endcorner(2)-origincorner(2), endcorner(3)-origincorner(3)];\n maxRadius = min(bounds);\n maxRadius = 5*maxRadius/NumObstacles;\n for i=1:NumObstacles,\n % randomly pick radius\n world.radius(i) = maxRadius*rand;\n % randomly pick center of obstacles\n cx = origincorner(1) + world.radius(i)...\n + (endcorner(1)-origincorner(1)-2*world.radius(i))*rand;\n cy = origincorner(2) + world.radius(i)...\n + (endcorner(2)-origincorner(2)-2*world.radius(i))*rand;\n cz = origincorner(2) + world.radius(i)...\n + (endcorner(2)-origincorner(2)-2*world.radius(i))*rand;\n world.cx(i) = cx;\n world.cy(i) = cy;\n world.cz(i) = cz;\n end\n end\nend\nend\n\nfunction [world NumObstacles] = createKnownWorld(endcorner, origincorner,dim)\nNumObstacles = 5;\nif dim == 2\n % check to make sure that the region is nonempty\n if (endcorner(1) <= origincorner(1)) | (endcorner(2) <= origincorner(2)),\n disp('Not valid corner specifications!')\n world=[];\n % create world data structure\n else\n world.NumObstacles = NumObstacles;\n world.endcorner = endcorner;\n world.origincorner = origincorner;\n \n % create NumObstacles\n maxRadius = 10;\n \n world.radius(1) = maxRadius;\n cx = 50;\n cy = 50;\n world.cx(1) = cx;\n world.cy(1) = cy;\n \n world.radius(2) = maxRadius;\n cx = 75;\n cy = 25;\n world.cx(2) = cx;\n world.cy(2) = cy;\n \n world.radius(3) = maxRadius;\n cx = 25;\n cy = 75;\n world.cx(3) = cx;\n world.cy(3) = cy;\n \n world.radius(4) = maxRadius;\n cx = 25;\n cy = 25;\n world.cx(4) = cx;\n world.cy(4) = cy;\n \n world.radius(5) = maxRadius;\n cx = 75;\n cy = 75;\n world.cx(5) = cx;\n world.cy(5) = cy;\n end\n \nelseif dim == 3\n \n NumObstacles = 9;\n % check to make sure that the region is nonempty\n if (endcorner(1) <= origincorner(1)) | (endcorner(2) <= origincorner(2)) | (endcorner(3) <= origincorner(3)),\n disp('Not valid corner specifications!')\n world=[];\n \n % create world data structure\n else\n world.NumObstacles = NumObstacles;\n world.endcorner = endcorner;\n world.origincorner = origincorner;\n \n % create NumObstacles\n maxRadius = 10;\n \n world.radius(1) = maxRadius;\n cx = 50;\n cy = 50;\n cz = 50;\n world.cx(1) = cx;\n world.cy(1) = cy;\n world.cz(1) = cz;\n \n world.radius(2) = maxRadius;\n cx = 25;\n cy = 25;\n cz = 25;\n world.cx(2) = cx;\n world.cy(2) = cy;\n world.cz(2) = cz;\n \n world.radius(3) = maxRadius;\n cx = 75;\n cy = 75;\n cz = 75;\n world.cx(3) = cx;\n world.cy(3) = cy;\n world.cz(3) = cz;\n \n world.radius(4) = maxRadius;\n cx = 25;\n cy = 25;\n cz = 75;\n world.cx(4) = cx;\n world.cy(4) = cy;\n world.cz(4) = cz;\n \n world.radius(5) = maxRadius;\n cx = 75;\n cy = 75;\n cz = 25;\n world.cx(5) = cx;\n world.cy(5) = cy;\n world.cz(5) = cz;\n \n world.radius(6) = maxRadius;\n cx = 25;\n cy = 75;\n cz = 25;\n world.cx(6) = cx;\n world.cy(6) = cy;\n world.cz(6) = cz;\n \n world.radius(7) = maxRadius;\n cx = 75;\n cy = 25;\n cz = 25;\n world.cx(7) = cx;\n world.cy(7) = cy;\n world.cz(7) = cz;\n \n world.radius(8) = maxRadius;\n cx = 75;\n cy = 25;\n cz = 75;\n world.cx(8) = cx;\n world.cy(8) = cy;\n world.cz(8) = cz;\n \n \n world.radius(9) = maxRadius;\n cx = 25;\n cy = 75;\n cz = 75;\n world.cx(9) = cx;\n world.cy(9) = cy;\n world.cz(9) = cz;\n end\nend\nend\n\n\n\n\n\nfunction node=generateRandomNode(world,dim)\n\nif dim ==2;\n % randomly pick configuration\n px = (world.endcorner(1)-world.origincorner(1))*rand;\n py = (world.endcorner(2)-world.origincorner(2))*rand;\n \n chi = 0;\n cost = 0;\n node = [px, py, chi, cost, 0];\n \n % check collision with obstacle\n while collision(node, node, world,dim),\n px = (world.endcorner(1)-world.origincorner(1))*rand;\n py = (world.endcorner(2)-world.origincorner(2))*rand;\n \n chi = 0;\n cost = 0;\n node = [px, py, chi, cost, 0];\n end\n \nelseif dim ==3;\n % randomly pick configuration\n px = (world.endcorner(1)-world.origincorner(1))*rand;\n py = (world.endcorner(2)-world.origincorner(2))*rand;\n pz = (world.endcorner(3)-world.origincorner(3))*rand;\n \n chi = 0;\n cost = 0;\n node = [px, py, pz, chi, cost, 0];\n \n % check collision with obstacle\n while collision(node, node, world,dim),\n px = (world.endcorner(1)-world.origincorner(1))*rand;\n py = (world.endcorner(2)-world.origincorner(2))*rand;\n pz = (world.endcorner(3)-world.origincorner(3))*rand;\n \n chi = 0;\n cost = 0;\n node = [px, py, pz, chi, cost, 0];\n end\n \nend\n\nend\n\n\n\n\n\nfunction collision_flag = collision(node, parent, world,dim)\n\ncollision_flag = 0;\n\n\nfor i=1:dim\n if (node(i)>world.endcorner(i))|(node(i)1\n size_near = size(near_idx,1);\n \n for i = 1:size_near\n if collision(new_node, tree(near_idx(i),:), world,dim)==0\n \n cost_near = tree(near_idx(i),dim+2)+line_cost(tree(near_idx(i),:),new_point,dim);\n \n if cost_near < min_cost\n min_cost = cost_near;\n min_parent_idx = near_idx(i);\n end\n \n end\n end\n end\n \n new_node = [new_point, 0 , min_cost, min_parent_idx];\n new_tree = [tree; new_node];\n new_node_idx = size(new_tree,1);\n \n if size(near_idx,1)>1\n reduced_idx = near_idx;\n for j = 1:size(reduced_idx,1)\n near_cost = new_tree(reduced_idx(j),dim+2);\n lcost = line_cost(new_tree(reduced_idx(j),:),new_point,dim);\n if near_cost > min_cost + lcost ...\n && collision(new_tree(reduced_idx(j),:),new_node,world,dim)\n before = new_tree(reduced_idx(j),dim+3)\n new_tree(reduced_idx(j),dim+3) = new_node_idx;\n after = new_tree(reduced_idx(j),dim+3)\n end\n \n end\n end\n flag1=1;\n end\nend\n\n\nif flag_chk == 0\n % check to see if new node connects directly to end_node\n if ( (norm(new_node(1:dim)-end_node(1:dim)) 0\n \n % find minimum cost last node\n [tmp,idx] = min(connectingNodes(:,dim+2));\n \n % construct lowest cost path\n path = [connectingNodes(idx,:); end_node];\n parent_node = connectingNodes(idx,dim+3);\n while parent_node>1,\n parent_node = tree(parent_node,dim+3);\n path = [tree(parent_node,:); path];\n end\n \nelse\n path = [];\nend\n\nend\n\n\nfunction plotExpandedTree(world,tree,dim)\nind = size(tree,1);\nwhile ind>0\n branch = [];\n node = tree(ind,:);\n branch = [ branch ; node ];\n parent_node = node(dim+3);\n while parent_node > 1\n cur_parent = parent_node;\n branch = [branch; tree(parent_node,:)];\n parent_node = tree(parent_node,dim+3);\n end\n ind = ind - 1;\n \n if dim == 2\n X = branch(:,1);\n Y = branch(:,2);\n \n p = plot(X,Y);\n set(p,'Color','r','LineWidth',0.5,'Marker','.','MarkerEdgeColor','g');\n hold on;\n \n elseif dim == 3\n X = branch(:,1);\n Y = branch(:,2);\n Z = branch(:,3);\n \n p = plot3(X,Y,Z);\n set(p,'Color','r','LineWidth',0.5,'Marker','.','MarkerEdgeColor','g');\n hold on;\n end\nend\nend\n\n\n\n\nfunction plotWorld(world,path,dim)\n% the first element is the north coordinate\n% the second element is the south coordinate\nif dim ==2\n \n N = 10;\n th = 0:2*pi/N:2*pi;\n axis([world.origincorner(1),world.endcorner(1),...\n world.origincorner(2), world.endcorner(2)]);\n hold on\n \n for i=1:world.NumObstacles,\n X = world.radius(i)*sin(th) + world.cx(i);\n Y = world.radius(i)*cos(th) + world.cy(i);\n fill(X,Y,'blue');\n end\n \n X = path(:,1);\n Y = path(:,2);\n p = plot(X,Y);\n \nelseif dim ==3\n axis([world.origincorner(1),world.endcorner(1),...\n world.origincorner(2), world.endcorner(2),...\n world.origincorner(3), world.endcorner(3)]);\n hold on\n \n for i=1:world.NumObstacles,\n [X Y Z] = sphere(10);\n X = (X*world.radius(i));\n Y = (Y*world.radius(i));\n Z = (Z*world.radius(i));\n surf(X+world.cx(i),Y+world.cy(i),Z+world.cz(i));\n colormap([0.5 0.2 0.3]);\n end\n \n X = path(:,1);\n Y = path(:,2);\n Z = path(:,3);\n p = plot3(X,Y,Z);\nend\nset(p,'Color','black','LineWidth',3)\nxlabel('X axis');\nylabel('Y axis');\nzlabel('Z axis');\ntitle('RRT Star Algorithm');\nend\n", "meta": {"author": "adnanmunawar", "repo": "matlab-rrt-variants", "sha": "47b2ec61b8c444a27b7ac58f7c79c1279aff5187", "save_path": "github-repos/MATLAB/adnanmunawar-matlab-rrt-variants", "path": "github-repos/MATLAB/adnanmunawar-matlab-rrt-variants/matlab-rrt-variants-47b2ec61b8c444a27b7ac58f7c79c1279aff5187/RRTstar3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3452606368749277}}
{"text": "% Anchored Neighborhood Regression for Fast Example-Based Super-Resolution\n% Example code\n%\n% March 22, 2013. Radu Timofte, VISICS @ KU Leuven\n%\n% Revised version: (includes all [1] methods)\n% October 3, 2013. Radu Timofte, CVL @ ETH Zurich\n%\n% Updated version: (adds A+ methods [2])\n% September 5, 2014. Radu Timofte, CVL @ ETH Zurich\n% %\n% Please reference to both:\n% [1] Radu Timofte, Vincent De Smet, Luc Van Gool.\n% Anchored Neighborhood Regression for Fast Example-Based Super-Resolution.\n% International Conference on Computer Vision (ICCV), 2013. \n%\n% [2] Radu Timofte, Vincent De Smet, Luc Van Gool.\n% A+: Adjusted Anchored Neighborhood Regression for Fast Super-Resolution.\n% Asian Conference on Computer Vision (ACCV), 2014. \n%\n% For any questions, email me by timofter@vision.ee.ethz.ch\n%\n\nclear; \n \np = pwd;\naddpath(fullfile(p, '/methods')); % the upscaling methods\n\naddpath(fullfile(p, '/ksvdbox')) % K-SVD dictionary training algorithm\n\naddpath(fullfile(p, '/ompbox')) % Orthogonal Matching Pursuit algorithm\n\nimgscale = 1; % the scale reference we work with\nflag = 1; % flag = 0 - only GR, ANR, A+, and bicubic methods, the other get the bicubic result by default\n % flag = 1 - all the methods are applied\n\nupscaling = 4; % the magnification factor x2, x3, x4...\n\ninput_dir = 'Set5'; % Directory with input images from Set5 image dataset\n%input_dir = 'Set14'; % Directory with input images from Set14 image dataset\n\npattern = '*.bmp'; % Pattern to process\n\ndict_sizes = [2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536];\nneighbors = [1:1:12, 16:4:32, 40:8:64, 80:16:128, 256, 512, 1024];\n%d = 7\n%for nn=1:28\n%nn= 28\n\nclusterszA = 2048; % neighborhood size for A+\n\ndisp('The experiment corresponds to the results from Table 2 in the referenced [1] and [2] papers.');\n\ndisp(['The experiment uses ' input_dir ' dataset and aims at a magnification of factor x' num2str(upscaling) '.']);\nif flag==1\n disp('All methods are employed : Bicubic, Yang et al., Zeyde et al., GR, ANR, NE+LS, NE+NNLS, NE+LLE, A+ (0.5 mil), A+, A+ (16 atoms).'); \nelse\n disp('We run only for Bicubic, GR, ANR and A+ methods, the other get the Bicubic result by default.');\nend\n\nfprintf('\\n\\n');\n\nfor d=10 %1024\n %d = 9; % 512\n %d = 8; %256\n %d = 7; %128\n %d = 6; % 64\n %d = 5; % 32\n %d=4; %16\n %d=3; %8\n %d=2; %4\n %d=1; %2\n \n tag = [input_dir '_x' num2str(upscaling) '_' num2str(dict_sizes(d)) 'atoms'];\n \n disp(['Upscaling x' num2str(upscaling) ' ' input_dir ' with Zeyde dictionary of size = ' num2str(dict_sizes(d))]);\n \n mat_file = ['conf_Zeyde_' num2str(dict_sizes(d)) '_finalx' num2str(upscaling)]; \n \n if exist([mat_file '.mat'],'file')\n disp(['Load trained dictionary...' mat_file]);\n load(mat_file, 'conf');\n else \n disp(['Training dictionary of size ' num2str(dict_sizes(d)) ' using Zeyde approach...']);\n % Simulation settings\n conf.scale = upscaling; % scale-up factor\n conf.level = 1; % # of scale-ups to perform\n conf.window = [3 3]; % low-res. window size\n conf.border = [1 1]; % border of the image (to ignore)\n\n % High-pass filters for feature extraction (defined for upsampled low-res.)\n conf.upsample_factor = upscaling; % upsample low-res. into mid-res.\n O = zeros(1, conf.upsample_factor-1);\n G = [1 O -1]; % Gradient\n L = [1 O -2 O 1]/2; % Laplacian\n conf.filters = {G, G.', L, L.'}; % 2D versions\n conf.interpolate_kernel = 'bicubic';\n\n conf.overlap = [1 1]; % partial overlap (for faster training)\n if upscaling <= 2\n conf.overlap = [1 1]; % partial overlap (for faster training)\n end\n \n startt = tic;\n conf = learn_dict(conf, load_images(... \n glob('CVPR08-SR/Data/Training', '*.bmp') ...\n ), dict_sizes(d)); \n conf.overlap = conf.window - [1 1]; % full overlap scheme (for better reconstruction) \n conf.trainingtime = toc(startt);\n toc(startt)\n \n save(mat_file, 'conf'); \n \n % train call \n end\n \n if dict_sizes(d) < 1024\n lambda = 0.01;\n elseif dict_sizes(d) < 2048\n lambda = 0.1;\n elseif dict_sizes(d) < 8192\n lambda = 1;\n else\n lambda = 5;\n end\n \n %% GR\n if dict_sizes(d) < 10000\n conf.ProjM = inv(conf.dict_lores'*conf.dict_lores+lambda*eye(size(conf.dict_lores,2)))*conf.dict_lores'; \n conf.PP = (1+lambda)*conf.dict_hires*conf.ProjM;\n else\n % here should be an approximation\n conf.PP = zeros(size(conf.dict_hires,1), size(conf.V_pca,2));\n conf.ProjM = [];\n end\n \n conf.filenames = glob(input_dir, pattern); % Cell array \n \n conf.desc = {'Original', 'Bicubic', 'Yang et al.', ...\n 'Zeyde et al.', 'Our GR', 'Our ANR', ...\n 'NE+LS','NE+NNLS','NE+LLE','Our A+ (0.5mil)','Our A+', 'Our A+ (16atoms)'};\n conf.results = {};\n \n %conf.points = [1:10:size(conf.dict_lores,2)];\n conf.points = [1:1:size(conf.dict_lores,2)];\n \n conf.pointslo = conf.dict_lores(:,conf.points);\n conf.pointsloPCA = conf.pointslo'*conf.V_pca';\n \n % precompute for ANR the anchored neighborhoods and the projection matrices for\n % the dictionary \n \n conf.PPs = []; \n if size(conf.dict_lores,2) < 40\n clustersz = size(conf.dict_lores,2);\n else\n clustersz = 40;\n end\n D = abs(conf.pointslo'*conf.dict_lores); \n \n for i = 1:length(conf.points)\n [vals idx] = sort(D(i,:), 'descend');\n if (clustersz >= size(conf.dict_lores,2)/2)\n conf.PPs{i} = conf.PP;\n else\n Lo = conf.dict_lores(:, idx(1:clustersz)); \n conf.PPs{i} = 1.01*conf.dict_hires(:,idx(1:clustersz))*inv(Lo'*Lo+0.01*eye(size(Lo,2)))*Lo'; \n end\n end \n \n ANR_PPs = conf.PPs; % store the ANR regressors\n \n save([tag '_' mat_file '_ANR_projections_imgscale_' num2str(imgscale)],'conf');\n \n %% A+ computing the regressors\n Aplus_PPs = [];\n \n fname = ['Aplus_x' num2str(upscaling) '_' num2str(dict_sizes(d)) 'atoms' num2str(clusterszA) 'nn_5mil.mat'];\n \n if exist(fname,'file')\n load(fname);\n else\n %%\n disp('Compute A+ regressors');\n ttime = tic;\n tic\n [plores phires] = collectSamplesScales(conf, load_images(... \n glob('CVPR08-SR/Data/Training', '*.bmp')), 12, 0.98); \n\n if size(plores,2) > 5000000 \n plores = plores(:,1:5000000);\n phires = phires(:,1:5000000);\n end\n number_samples = size(plores,2);\n \n % l2 normalize LR patches, and scale the corresponding HR patches\n l2 = sum(plores.^2).^0.5+eps;\n l2n = repmat(l2,size(plores,1),1); \n l2(l2<0.1) = 1;\n plores = plores./l2n;\n phires = phires./repmat(l2,size(phires,1),1);\n clear l2\n clear l2n\n\n llambda = 0.1;\n\n for i = 1:size(conf.dict_lores,2)\n D = pdist2(single(plores'),single(conf.dict_lores(:,i)'));\n [~, idx] = sort(D); \n Lo = plores(:, idx(1:clusterszA)); \n Hi = phires(:, idx(1:clusterszA));\n Aplus_PPs{i} = Hi*inv(Lo'*Lo+llambda*eye(size(Lo,2)))*Lo'; \n%Aplus_PPs{i} = Hi*(inv(Lo*Lo'+llambda*eye(size(Lo,1)))*Lo)'; \n end \n clear plores\n clear phires\n \n ttime = toc(ttime); \n save(fname,'Aplus_PPs','ttime', 'number_samples'); \n toc\n end \n \n \n \n %% A+ (0.5mil) computing the regressors with 0.5 milion training samples\n Aplus05_PPs = []; \n \n fname = ['Aplus_x' num2str(upscaling) '_' num2str(dict_sizes(d)) 'atoms' num2str(clusterszA) 'nn_05mil.mat']; \n \n if exist(fname,'file')\n load(fname);\n else\n %%\n disp('Compute A+ (0.5 mil) regressors');\n ttime = tic;\n tic\n [plores phires] = collectSamplesScales(conf, load_images(... \n glob('CVPR08-SR/Data/Training', '*.bmp')), 1,1); \n\n if size(plores,2) > 500000 \n plores = plores(:,1:500000);\n phires = phires(:,1:500000);\n end\n number_samples = size(plores,2);\n \n % l2 normalize LR patches, and scale the corresponding HR patches\n l2 = sum(plores.^2).^0.5+eps;\n l2n = repmat(l2,size(plores,1),1); \n l2(l2<0.1) = 1;\n plores = plores./l2n;\n phires = phires./repmat(l2,size(phires,1),1);\n clear l2\n clear l2n\n\n llambda = 0.1;\n\n for i = 1:size(conf.dict_lores,2)\n D = pdist2(single(plores'),single(conf.dict_lores(:,i)'));\n [~, idx] = sort(D); \n Lo = plores(:, idx(1:clusterszA)); \n Hi = phires(:, idx(1:clusterszA));\n Aplus05_PPs{i} = Hi*inv(Lo'*Lo+llambda*eye(size(Lo,2)))*Lo'; \n end \n clear plores\n clear phires\n \n ttime = toc(ttime); \n save(fname,'Aplus05_PPs','ttime', 'number_samples'); \n toc\n end \n \n %% load the A+ (16 atoms) for comparison results\n conf16 = []; \n fname = ['Aplus_x' num2str(upscaling) '_16atoms' num2str(clusterszA) 'nn_05mil.mat'];\n fnamec = ['Set14_x' num2str(upscaling) '_16atoms_conf_Zeyde_16_finalx' num2str(upscaling) '_ANR_projections_imgscale_' num2str(imgscale) '.mat']; \n if exist(fname,'file') && exist(fnamec,'file')\n kk = load(fnamec);\n conf16 = kk.conf; \n kk = load(fname); \n conf16.PPs = kk.Aplus05_PPs;\n clear kk\n end\n %% \n conf.result_dirImages = qmkdir([input_dir '/results_' tag]);\n conf.result_dirImagesRGB = qmkdir([input_dir '/results_' tag 'RGB']);\n conf.result_dir = qmkdir(['Results-' datestr(now, 'YYYY-mm-dd_HH-MM-SS')]);\n conf.result_dirRGB = qmkdir(['ResultsRGB-' datestr(now, 'YYYY-mm-dd_HH-MM-SS')]);\n \n %%\n t = cputime; \n \n conf.countedtime = zeros(numel(conf.desc),numel(conf.filenames));\n \n res =[];\n for i = 1:numel(conf.filenames)\n f = conf.filenames{i};\n [p, n, x] = fileparts(f);\n [img, imgCB, imgCR] = load_images({f}); \n if imgscale<1\n img = resize(img, imgscale, conf.interpolate_kernel);\n imgCB = resize(imgCB, imgscale, conf.interpolate_kernel);\n imgCR = resize(imgCR, imgscale, conf.interpolate_kernel);\n end\n sz = size(img{1});\n \n fprintf('%d/%d\\t\"%s\" [%d x %d]\\n', i, numel(conf.filenames), f, sz(1), sz(2));\n \n img = modcrop(img, conf.scale^conf.level);\n imgCB = modcrop(imgCB, conf.scale^conf.level);\n imgCR = modcrop(imgCR, conf.scale^conf.level);\n\n low = resize(img, 1/conf.scale^conf.level, conf.interpolate_kernel);\n if ~isempty(imgCB{1})\n lowCB = resize(imgCB, 1/conf.scale^conf.level, conf.interpolate_kernel);\n lowCR = resize(imgCR, 1/conf.scale^conf.level, conf.interpolate_kernel);\n end\n \n interpolated = resize(low, conf.scale^conf.level, conf.interpolate_kernel);\n if ~isempty(imgCB{1})\n interpolatedCB = resize(lowCB, conf.scale^conf.level, conf.interpolate_kernel); \n interpolatedCR = resize(lowCR, conf.scale^conf.level, conf.interpolate_kernel); \n end\n \n res{1} = interpolated;\n \n if (flag == 1) && (dict_sizes(d) == 1024) && (upscaling==3)\n startt = tic;\n res{2} = {yima(low{1}, upscaling)}; \n toc(startt)\n conf.countedtime(2,i) = toc(startt);\n else\n res{2} = interpolated;\n end\n \n if (flag == 1)\n startt = tic;\n res{3} = scaleup_Zeyde(conf, low);\n toc(startt)\n conf.countedtime(3,i) = toc(startt); \n else\n res{3} = interpolated;\n end\n \n %if flag == 1\n startt = tic;\n res{4} = scaleup_GR(conf, low);\n toc(startt)\n conf.countedtime(4,i) = toc(startt); \n %else\n %res{4} = interpolated;\n %end\n \n startt = tic;\n conf.PPs = ANR_PPs;\n res{5} = scaleup_ANR(conf, low);\n toc(startt)\n conf.countedtime(5,i) = toc(startt); \n \n if flag == 1\n startt = tic;\n if 12 < dict_sizes(d)\n res{6} = scaleup_NE_LS(conf, low, 12);\n else\n res{6} = scaleup_NE_LS(conf, low, dict_sizes(d));\n end\n toc(startt)\n conf.countedtime(6,i) = toc(startt); \n else\n res{6} = interpolated;\n end\n \n if flag == 1\n startt = tic;\n if 24 < dict_sizes(d)\n res{7} = scaleup_NE_NNLS(conf, low, 24);\n else\n res{7} = scaleup_NE_NNLS(conf, low, dict_sizes(d));\n end\n toc(startt)\n conf.countedtime(7,i) = toc(startt); \n else\n res{7} = interpolated;\n end\n \n if flag == 1\n startt = tic;\n if 24 < dict_sizes(d)\n res{8} = scaleup_NE_LLE(conf, low, 24);\n else\n res{8} = scaleup_NE_LLE(conf, low, dict_sizes(d));\n end\n toc(startt)\n conf.countedtime(8,i) = toc(startt); \n else\n res{8} = interpolated;\n end\n \n % A+ (0.5 mil)\n if flag == 1 && ~isempty(Aplus05_PPs)\n fprintf('A+ (0.5mil)\\n');\n conf.PPs = Aplus05_PPs;\n startt = tic;\n res{9} = scaleup_ANR(conf, low);\n toc(startt)\n conf.countedtime(9,i) = toc(startt); \n else\n res{9} = interpolated;\n end\n \n % A+\n if ~isempty(Aplus_PPs)\n fprintf('A+\\n');\n conf.PPs = Aplus_PPs;\n startt = tic;\n res{10} = scaleup_ANR(conf, low);\n toc(startt)\n conf.countedtime(10,i) = toc(startt); \n else\n res{10} = interpolated;\n end \n % A+ 16atoms\n if flag == 1 && ~isempty(conf16)\n fprintf('A+ 16atoms\\n');\n startt = tic;\n res{11} = scaleup_ANR(conf16, low);\n toc(startt)\n conf.countedtime(11,i) = toc(startt); \n else\n res{11} = interpolated;\n end\n \n result = cat(3, img{1}, interpolated{1}, res{2}{1}, res{3}{1}, ...\n res{4}{1}, res{5}{1}, res{6}{1}, res{7}{1}, res{8}{1}, ...\n res{9}{1}, res{10}{1}, res{11}{1});\n \n result = shave(uint8(result * 255), conf.border * conf.scale);\n \n if ~isempty(imgCB{1})\n resultCB = interpolatedCB{1};\n resultCR = interpolatedCR{1}; \n resultCB = shave(uint8(resultCB * 255), conf.border * conf.scale);\n resultCR = shave(uint8(resultCR * 255), conf.border * conf.scale);\n end\n\n conf.results{i} = {};\n for j = 1:numel(conf.desc) \n conf.results{i}{j} = fullfile(conf.result_dirImages, [n sprintf('[%d-%s]', j, conf.desc{j}) x]); \n imwrite(result(:, :, j), conf.results{i}{j});\n\n conf.resultsRGB{i}{j} = fullfile(conf.result_dirImagesRGB, [n sprintf('[%d-%s]', j, conf.desc{j}) x]);\n if ~isempty(imgCB{1})\n rgbImg = cat(3,result(:,:,j),resultCB,resultCR);\n rgbImg = ycbcr2rgb(rgbImg);\n else\n rgbImg = cat(3,result(:,:,j),result(:,:,j),result(:,:,j));\n end\n \n imwrite(rgbImg, conf.resultsRGB{i}{j});\n end \n conf.filenames{i} = f;\n end \n conf.duration = cputime - t;\n\n % Test performance\n scores = run_comparison(conf);\n process_scores_Tex(conf, scores,length(conf.filenames));\n \n run_comparisonRGB(conf); % provides color images and HTML summary\n %% \n save([tag '_' mat_file '_results_imgscale_' num2str(imgscale)],'conf','scores');\nend\n%\n", "meta": {"author": "thomas-koehler", "repo": "SupER", "sha": "d8c6f2e4b26db002ff55bc2beba18639f1d0bb49", "save_path": "github-repos/MATLAB/thomas-koehler-SupER", "path": "github-repos/MATLAB/thomas-koehler-SupER/SupER-d8c6f2e4b26db002ff55bc2beba18639f1d0bb49/matlab/algorithms/SRAlgorithms/Aplus/go_run_Set5_x4_Aplus1024.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.34526062436109695}}
{"text": "function [U,G,I,J] = remove_small_components(V,F,varargin)\n % REMOVE_SMALL_COMPONENTS\n %\n % [U,G,I,J] = remove_small_components(V,F)\n %\n % Inputs:\n % V #V by 3 list of vertex positions\n % F #F by 3 list of face indices into rows of V\n % Optional:\n % 'Tol' followed by minimum volume (or surface area) to use OR the word\n % 'max' to keep only biggest component {0.0001*total_vol}\n % 'Volumetric' followed by whether to use volume or surface area\n % Outputs:\n % U #U by 3 list of vertex positions\n % G #G by 3 list of face indices into rows of U\n % I #V by 1 list of indices such that: G = I(F)\n % J #G by 1 list of indices into F\n %\n\n tol = [];\n volumetric = true;\n % Map of parameter names to variable names\n params_to_variables = containers.Map( ...\n {'Tol','Volumetric'}, {'tol','volumetric'});\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\n if isempty(tol)\n if volumetric\n [~,total] = centroid(V,F);\n else\n total = sum(doublearea(V,F))*0.5;\n end\n tol = 0.0001*total;\n end\n\n\n [~,C] = connected_components(F);\n nc = max(C);\n val = zeros(nc,1);\n for i = 1:nc\n Fi = F(C==i,:);\n if volumetric\n [~,val(i)] = centroid(V,Fi);\n else\n val(i) = 0.5*sum(doublearea(V,Fi));\n end\n end\n\n if isnumeric(tol)\n J = find(ismember(C,find(val>tol)));\n else \n assert(strcmp(tol,'max'));\n [~,max_c] = max(val);\n J = find(C==max_c);\n end\n F = F(J,:);\n [U,I] = remove_unreferenced(V,F);\n G = I(F);\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/remove_small_components.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3451353147904489}}
{"text": "function problem = getDefaultOptions(problem)\n% problem = getDefaultOptions(problem)\n%\n% This function fills in any blank entries in the problem.options struct.\n% It is designed to be called from inside of optimTraj.m, and not by the\n% user.\n%\n\n%%%% Top-level default options:\nOPT.method = 'trapezoid';\nOPT.verbose = 2;\nOPT.defaultAccuracy = 'medium';\n\n\n%%%% Basic setup\n\n% ensure that options is not empty\nif ~isfield(problem,'options')\n problem.options.method = OPT.method;\nend\nopt = problem.options;\n\n% Loop over each options struct and fill in top-level options\nfor i=1:length(opt)\n if ~isfield(opt(i),'method')\n opt(i).method = OPT.method;\n elseif isempty(opt(i).method)\n opt(i).method = OPT.method;\n end\n if ~isfield(opt(i),'verbose')\n opt(i).verbose = OPT.verbose;\n elseif isempty(opt(i).verbose)\n opt(i).verbose = OPT.verbose;\n end\n if ~isfield(opt(i),'defaultAccuracy')\n opt(i).defaultAccuracy = OPT.defaultAccuracy;\n elseif isempty(opt(i).defaultAccuracy)\n opt(i).defaultAccuracy = OPT.defaultAccuracy;\n end\nend\n\n% Figure out basic problem size:\nnState = size(problem.guess.state,1);\nnControl = size(problem.guess.control,1);\n\n% Loop over opt and fill in nlpOpt struct:\nfor i=1:length(opt)\n switch opt(i).verbose\n case 0\n NLP_display = 'notify';\n case 1\n NLP_display = 'final-detailed';\n case 2\n NLP_display = 'iter';\n case 3\n NLP_display = 'iter-detailed';\n otherwise\n error('Invalid value for options.verbose');\n end\n switch opt(i).defaultAccuracy\n case 'low'\n OPT.nlpOpt = optimset(...\n 'Display',NLP_display,...\n 'TolFun',1e-4,...\n 'MaxIter',200,...\n 'MaxFunEvals',1e4*(nState+nControl));\n case 'medium'\n OPT.nlpOpt = optimset(...\n 'Display',NLP_display,...\n 'TolFun',1e-6,...\n 'MaxIter',400,...\n 'MaxFunEvals',5e4*(nState+nControl));\n case 'high'\n OPT.nlpOpt = optimset(...\n 'Display',NLP_display,...\n 'TolFun',1e-8,...\n 'MaxIter',800,...\n 'MaxFunEvals',1e5*(nState+nControl));\n otherwise\n error('Invalid value for options.defaultAccuracy')\n end\n if isfield(opt(i),'nlpOpt')\n if isstruct(opt(i).nlpOpt) && ~isempty(opt(i).nlpOpt)\n names = fieldnames(opt(i).nlpOpt);\n for j=1:length(names)\n if ~isfield(OPT.nlpOpt,names{j})\n disp(['WARNING: options.nlpOpt.' names{j} ' is not a valid option']);\n else\n OPT.nlpOpt.(names{j}) = opt(i).nlpOpt.(names{j});\n end\n end\n end\n end\n opt(i).nlpOpt = OPT.nlpOpt;\nend\n\n% Check ChebFun dependency:\nmissingChebFun = false;\nfor i=1:length(opt)\nif strcmp(opt(i).method,'chebyshev')\ntry\n chebpts(3); %Test call to chebfun\ncatch ME %#ok\n missingChebFun = true;\n opt(i).method = 'trapezoid'; %Force default method\nend\nend\nend\nif missingChebFun\n warning('''chebyshev'' method requires the Chebfun toolbox');\n disp(' --> Install Chebfun toolbox: (http://www.chebfun.org/)');\n disp(' --> Running with default method instead (''trapezoid'')');\nend\n\n% Fill in method-specific paramters:\nfor i=1:length(opt)\n OPT_method = opt(i).method;\n switch OPT_method\n case 'trapezoid'\n OPT.trapezoid = defaults_trapezoid(opt(i).defaultAccuracy);\n case 'hermiteSimpson'\n OPT.hermiteSimpson = defaults_hermiteSimpson(opt(i).defaultAccuracy);\n case 'chebyshev'\n OPT.chebyshev = defaults_chebyshev(opt(i).defaultAccuracy);\n case 'multiCheb'\n OPT.multiCheb = defaults_multiCheb(opt(i).defaultAccuracy);\n case 'rungeKutta'\n OPT.rungeKutta = defaults_rungeKutta(opt(i).defaultAccuracy);\n case 'gpops'\n OPT.gpops = defaults_gpops(opt(i).defaultAccuracy);\n otherwise\n error('Invalid value for options.method');\n end\n if isfield(opt(i),OPT_method)\n if isstruct(opt(i).(OPT_method)) && ~isempty(opt(i).(OPT_method))\n names = fieldnames(opt(i).(OPT_method));\n for j=1:length(names)\n if ~isfield(OPT.(OPT_method),names{j})\n disp(['WARNING: options.' OPT_method '.' names{j} ' is not a valid option']);\n else\n OPT.(OPT_method).(names{j}) = opt(i).(OPT_method).(names{j});\n end\n end\n end\n end\n opt(i).(OPT_method) = OPT.(OPT_method);\nend\n\nproblem.options = opt;\nend\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n% Method-specific parameters %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n\n\nfunction OPT_trapezoid = defaults_trapezoid(accuracy)\n\nswitch accuracy\n case 'low'\n OPT_trapezoid.nGrid = 12;\n case 'medium'\n OPT_trapezoid.nGrid = 30;\n case 'high'\n OPT_trapezoid.nGrid = 60;\n otherwise\n error('Invalid value for options.defaultAccuracy')\nend\n\nOPT_trapezoid.adaptiveDerivativeCheck = 'off';\n\nend\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n\n\nfunction OPT_hermiteSimpson = defaults_hermiteSimpson(accuracy)\n\nswitch accuracy\n case 'low'\n OPT_hermiteSimpson.nSegment = 10;\n case 'medium'\n OPT_hermiteSimpson.nSegment = 20;\n case 'high'\n OPT_hermiteSimpson.nSegment = 40;\n otherwise\n error('Invalid value for options.defaultAccuracy')\nend\n\nOPT_hermiteSimpson.adaptiveDerivativeCheck = 'off';\n\nend\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n\n\nfunction OPT_chebyshev = defaults_chebyshev(accuracy)\n\nswitch accuracy\n case 'low'\n OPT_chebyshev.nColPts = 9;\n case 'medium'\n OPT_chebyshev.nColPts = 13;\n case 'high'\n OPT_chebyshev.nColPts = 23;\n otherwise\n error('Invalid value for options.defaultAccuracy')\nend\n\nend\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n\nfunction OPT_multiCheb = defaults_multiCheb(accuracy)\n\nswitch accuracy\n case 'low'\n OPT_multiCheb.nColPts = 6;\n OPT_multiCheb.nSegment = 3;\n case 'medium'\n OPT_multiCheb.nColPts = 8;\n OPT_multiCheb.nSegment = 6;\n case 'high'\n OPT_multiCheb.nColPts = 8;\n OPT_multiCheb.nSegment = 12;\n otherwise\n error('Invalid value for options.defaultAccuracy')\nend\n\nend\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n\n\nfunction OPT_rungeKutta = defaults_rungeKutta(accuracy)\n\nswitch accuracy\n case 'low'\n OPT_rungeKutta.nSegment = 10;\n OPT_rungeKutta.nSubStep = 2;\n case 'medium'\n OPT_rungeKutta.nSegment = 20;\n OPT_rungeKutta.nSubStep = 2;\n case 'high'\n OPT_rungeKutta.nSegment = 20;\n OPT_rungeKutta.nSubStep = 4;\n otherwise\n error('Invalid value for options.defaultAccuracy')\nend\n\nOPT_rungeKutta.adaptiveDerivativeCheck = 'off';\n\nend\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n\nfunction OPT_gpops = defaults_gpops(accuracy)\n\nOPT_gpops.bounds.phase.integral.lower = -inf;\nOPT_gpops.bounds.phase.integral.upper = inf;\nOPT_gpops.guess.phase.integral = 0;\n\nOPT_gpops.name = 'OptimTraj_GPOPS';\nOPT_gpops.auxdata = [];\nOPT_gpops.nlp.solver = 'ipopt'; % {'ipopt','snopt'}\nOPT_gpops.derivatives.dependencies = 'full'; %\ufffdfull\ufffd, \ufffdsparse\ufffd or \ufffdsparseNaN\ufffd\nOPT_gpops.derivatives.supplier = 'sparseCD'; %'sparseCD'; %'adigator'\nOPT_gpops.derivatives.derivativelevel = 'first'; %'second';\nOPT_gpops.mesh.method = 'hp-PattersonRao';\nOPT_gpops.method = 'RPM-Integration';\nOPT_gpops.mesh.phase.colpoints = 10*ones(1,10);\nOPT_gpops.mesh.phase.fraction = ones(1,10)/10;\nOPT_gpops.scales.method = 'none'; % { 'none' , automatic-hybridUpdate' , 'automatic-bounds';\n\nswitch accuracy\n case 'low'\n OPT_gpops.mesh.tolerance = 1e-2;\n OPT_gpops.mesh.maxiterations = 0;\n case 'medium'\n OPT_gpops.mesh.tolerance = 1e-3;\n OPT_gpops.mesh.maxiterations = 1; \n case 'high'\n OPT_gpops.mesh.tolerance = 1e-4;\n OPT_gpops.mesh.maxiterations = 3;\n otherwise\n error('Invalid value for options.defaultAccuracy')\nend\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/getDefaultOptions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3451353147904489}}
{"text": "function obj = updateTernaryPlotPro(obj, ternaryIndex)\n\n %-AXIS INDEX-%\n axIndex = obj.getAxisIndex(obj.State.Plot(ternaryIndex).AssociatedAxis);\n\n %-GET DATA STRUCTURES-%\n ternaryData = get(obj.State.Plot(ternaryIndex).Handle);\n axisData = get(obj.State.Plot(ternaryIndex).AssociatedAxis);\n figureData = get(obj.State.Figure.Handle);\n\n %-CHECK FOR MULTIPLE AXES-%\n [xsource, ysource] = findSourceAxis(obj, axIndex);\n\n %=========================================================================%\n %\n %-UPDATE TRACE PLOT-%\n %\n %=========================================================================%\n\n %-get plot data-%\n xData = ternaryData.XData;\n yData = ternaryData.YData;\n\n %-------------------------------------------------------------------------%\n\n %-set trace-%\n for t = 1:size(xData,2)\n\n %-------------------------------------------------------------------------%\n\n %-get new ternaryIndex-%\n if t > 1\n obj.PlotOptions.nPlots = obj.PlotOptions.nPlots + 1;\n ternaryIndex = obj.PlotOptions.nPlots;\n end\n\n %-------------------------------------------------------------------------%\n\n %-trace type-%\n obj.data{ternaryIndex}.type = 'scatterternary';\n obj.data{ternaryIndex}.subplot = sprintf('ternary%d', xsource+1);\n\n %-------------------------------------------------------------------------%\n\n %-set mode and properties for trace-%\n if ~strcmpi('none', ternaryData.Marker) && ~strcmpi('none', ternaryData.LineStyle)\n obj.data{ternaryIndex}.mode = 'lines+markers';\n obj.data{ternaryIndex}.marker = extractPatchMarker(ternaryData);\n\n elseif ~strcmpi('none', ternaryData.Marker)\n obj.data{ternaryIndex}.mode = 'markers';\n obj.data{ternaryIndex}.marker = extractPatchMarker(ternaryData);\n\n elseif ~strcmpi('none', ternaryData.LineStyle)\n obj.data{ternaryIndex}.mode = 'lines';\n obj.data{ternaryIndex}.line = extractPatchLine(ternaryData);\n\n else\n obj.data{ternaryIndex}.mode = 'none';\n end\n\n %-------------------------------------------------------------------------%\n\n %-convert from cartesian coordinates to trenary points-%\n yTernData = yData(:,t); yTernData(end+1) = yData(1,t);\n xTernData = xData(:,t); xTernData(end+1) = xData(1,t);\n\n aData = yTernData/sin(deg2rad(60));\n bData = 1 - xTernData - yTernData*cot(deg2rad(60));\n\n %-------------------------------------------------------------------------%\n\n %-set plot data-%\n obj.data{ternaryIndex}.a = aData;\n obj.data{ternaryIndex}.b = bData;\n\n %-------------------------------------------------------------------------%\n\n %-some trace properties-%\n obj.data{ternaryIndex}.name = ternaryData.DisplayName;\n obj.data{ternaryIndex}.showscale = false;\n obj.data{ternaryIndex}.visible = strcmp(ternaryData.Visible,'on');\n\n %-trace coloring-%\n faceColor = ternaryData.FaceColor;\n\n if isnumeric(faceColor)\n fillColor = sprintf('rgb(%f,%f,%f)', 255*faceColor);\n\n else\n cMap = figureData.Colormap;\n nColors = size(cMap,1);\n\n switch faceColor\n \n case 'none'\n fillColor = 'rgba(0,0,0,0)';\n \n case {'flat', 'interp'}\n\n switch ternaryData.CDataMapping\n\n case 'scaled'\n cMin = axisData.CLim(1);\n cMax = axisData.CLim(2);\n\n if strcmpi(faceColor, 'flat')\n cData = ternaryData.ZData(1,t);\n elseif strcmpi(faceColor, 'interp')\n cData = max(ternaryData.ZData(:,t));\n end\n\n cData = max(min(cData, cMax), cMin);\n cData = (cData - cMin)/diff(axisData.CLim);\n cData = 1 + floor( cData*(nColors-1) );\n\n fillColor = sprintf('rgb(%f,%f,%f)', 255*cMap(cData,:));\n\n case 'direct'\n fillColor = sprintf('rgb(%f,%f,%f)', 255*cMap(ternary(1,t),:));\n end\n end\n end\n \n obj.data{ternaryIndex}.fillcolor = fillColor;\n obj.data{ternaryIndex}.fill = 'toself';\n\n %---------------------------------------------------------------------%\n\n %-trace legend-%\n obj.data{ternaryIndex}.showlegend = false;\n\n %-------------------------------------------------------------------------%\n end\n\n %=========================================================================%\n %\n %-UPDATE TERNARY AXES-%\n %\n %=========================================================================%\n\n %-set domain plot-%\n xo = axisData.Position(1);\n yo = axisData.Position(2);\n w = axisData.Position(3);\n h = axisData.Position(4);\n\n ternary.domain.x = min([xo xo + w],1);\n ternary.domain.y = min([yo yo + h],1);\n\n %-----------------------------------------------------------------------------%\n\n %-label settings-%\n l = 1; t = 1;\n labelLetter = {'b', 'a', 'c'};\n\n for n = 1:length(axisData.Children)\n if strcmpi(axisData.Children(n).Type, 'text')\n stringText = axisData.Children(n).String;\n\n if any(isletter(stringText))\n labelIndex(l) = n;\n l = l + 1;\n else\n tickIndex(t) = n;\n t = t + 1;\n end\n end\n end\n\n for l = 1:length(labelIndex)\n n = labelIndex(l);\n patterText = sprintf('ternary.%saxis.title', labelLetter{l});\n\n labelText = axisData.Children(n).String;\n labelFontColor = sprintf('rgb(%f,%f,%f)', axisData.Children(n).Color);\n labelFontSize = 1.5 * axisData.Children(n).FontSize;\n labelFontFamily = matlab2plotlyfont(axisData.Children(n).FontName);\n\n eval(sprintf('%s.text = labelText;', patterText));\n eval(sprintf('%s.font.color = labelFontColor;', patterText));\n eval(sprintf('%s.font.size = labelFontColor;', patterText));\n eval(sprintf('%s.font.family = labelFontFamily;', patterText));\n end\n\n %-----------------------------------------------------------------------------%\n\n %-tick settings-%\n t0 = tickIndex(1); t1 = tickIndex(2);\n tick0 = str2num(axisData.Children(t0).String);\n tick1 = str2num(axisData.Children(t1).String);\n dtick = tick1 - tick0;\n\n tickFontColor = sprintf('rgb(%f,%f,%f)', axisData.Children(t0).Color);\n tickFontSize = 1.0 * axisData.Children(t0).FontSize;\n tickFontFamily = matlab2plotlyfont(axisData.Children(t0).FontName);\n\n for l = 1:3\n patterText = sprintf('ternary.%saxis', labelLetter{l});\n\n eval(sprintf('%s.tick0 = tick0;', patterText));\n eval(sprintf('%s.dtick = dtick;', patterText));\n eval(sprintf('%s.tickfont.color = tickFontColor;', patterText));\n eval(sprintf('%s.tickfont.size = tickFontSize;', patterText));\n eval(sprintf('%s.tickfont.family = tickFontFamily;', patterText));\n end\n\n %-----------------------------------------------------------------------------%\n\n %-set ternary axes to layout-%\n obj.layout = setfield(obj.layout, sprintf('ternary%d', xsource+1), ternary);\n\n %-----------------------------------------------------------------------------%\n\n obj.PlotlyDefaults.isTernary = true;\n\n %-----------------------------------------------------------------------------%\nend\n\nfunction rad = deg2rad(deg)\n rad = deg / 180 * pi;\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/updateTernaryPlotPro.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593171945416, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.34513530702380757}}
{"text": "function DEM = spm_MDP_DEM(DEM,demi,O,o)\n% auxiliary (link) function for mixed hierarchical (MDP/DEM) models\n% FORMAT DEM = spm_MDP_DEM(DEM,demi,O,o)\n%\n% DEM - DEM structure\n% demi - mapping from discrete outcomes to hidden causes\n% demi.C - cell array of true causes for each combination of outcomes\n% the appropriate array is then placed in DEM.C\n% demi.U - cell array of hidden causes for each combination of outcomes\n% the Bayesian model average is placed in DEM.U\n% O{g} - cell array of priors over discrete outcomes\n% o(g x 1) - vector of true outcomes\n%\n% completes the following fields:\n% DEM.X{g} - posterior probability over g models and t times\n%\n% This routine performs a Bayesian model comparison using (DEM) Bayesian\n% filtering and places the results in fields of the DEM structure; so that\n% MDP schemes can pick them up as likelihood terms in the next hierarchical\n% level. The outcomes of the (discrete) MDP scheme at the superordinate\n% level specify the hidden causes at the current level. These enter as\n% Bayesian model averages of the continuous causes. The resulting\n% posterior over hidden causes then furnishes the posterior over outcomes\n% using Bayesian model reduction, based on the free energy accumulated\n% (integrated) over time. This free energy is supplemented with the prior\n% over discrete outcomes; thereby constituting a posterior over outcomes.\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: spm_MDP_DEM.m 7560 2019-03-29 14:39:38Z thomas $\n\n\n% evaluate true values and priors over causes given discrete states\n%--------------------------------------------------------------------------\npo = spm_cross(O);\nind = num2cell(o);\nDEM.C = demi.C{ind{:}};\nDEM.U = 0;\nfor i = 1:size(po,1)\n for j = 1:size(po,2)\n for k = 1:size(po,3)\n DEM.U = DEM.U + demi.U{i,j,k}*po(i,j,k);\n end\n end\nend\n\n% integrate system to generate data\n%--------------------------------------------------------------------------\nDEM.db = 0;\nDEM = spm_ADEM(DEM);\n\n% posterior probability over discrete states models\n%==========================================================================\nnv = size(DEM.U,1);\nnt = size(DEM.U,2);\nic = (1:nv) + size(DEM.qU.C{1},1) - nv;\nP = spm_zeros(po);\nfor i = 1:ndims(P)\n x{i} = ones(size(P,i),1);\nend\n\n \n% prior potential\n%--------------------------------------------------------------------------\nF = log(po);\n \n% and accumulate log evidence\n%--------------------------------------------------------------------------\nfor t = 1:nt\n \n % posteriors and priors for this time point\n %----------------------------------------------------------------------\n qE = DEM.qU.v{end}(:,t);\n qC = DEM.qU.C{t}(ic,ic);\n pE = DEM.U(:,t);\n pC = DEM.pU.C{t}(ic,ic);\n gt = t > 4;\n for i = 1:size(po,1)\n for j = 1:size(po,2)\n for k = 1:size(po,3)\n if po(i,j,k) < exp(-3)\n F(i,j,k) = - exp(64);\n else\n rE = demi.U{i,j,k}(:,t);\n F(i,j,k) = F(i,j,k) + gt*spm_log_evidence(qE,qC,pE,pC,rE,pC);\n end\n end\n end\n end\n \n % Bayesian model comparison\n %----------------------------------------------------------------------\n P(:) = spm_softmax(F(:));\n \n % marginal posteriors\n %----------------------------------------------------------------------\n for g = 1:numel(O)\n X{g}(:,t) = spm_dot(P,x,g);\n end\nend\n\n% return probability over models (i.e., outcomes at subordinate level)\n%--------------------------------------------------------------------------\nDEM.X = X;\n\n\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/spm_MDP_DEM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.34509977499637695}}
{"text": "function hrf = glm_hrf(params, tSeries, stim)\n%\n% hrf = glm_hrf(params, , );\n%\n% Returns the hemodynamic impulse response function to use for GLM\n% analyses, given the current event analysis settings. The hrf will\n% always be returned in units of MR frames.\n%\n% 'tSeries' and 'stim' are optional input arguments, which are only\n% needed if params.glmHRF==1: compute the HRF from the data and\n% selected conditions in params.snrConds.\n%\n% ras, 01/2007.\nverbose = prefsVerboseCheck;\n\nif ischar(params.glmHRF)\n hrfPath = fullfile(hrfDir, params.glmHRF);\n load(hrfPath, 'hrf', 'timeWindow', 'tr');\n% if verbose, fprintf('Loading HRF from file %s\\n', hrfPath); end\n return\nend\n\n% for the pre-defined (Boynton, SPM, Dale&Buckner) HRFs, we'll need\n% to get the time window sampled in units of MR frames, excluding pre-\n% onset periods:\nif ismember(params.glmHRF, [2 3 4])\n tr = params.framePeriod;\n maxT = max(params.timeWindow); % in secs\n t = 0:tr:maxT; % also in secs\nend\n\nswitch params.glmHRF\n case 1,\n % estimate hrf as mean time course to all stim\n if isempty(tSeries)\n errmsg = ['Need tSeries to estimate mean trial response ' ...\n '(glmHRF option 1)'];\n error(errmsg);\n end\n\n% if verbose, disp('Estimating mean trial response for GLM'); end\n tSeries = squeeze(mean(tSeries,2)); % mean across voxels\n anal = er_chopTSeries2(tSeries(:),stim,params);\n postStim = find(anal.timeWindow>=0);\n hrf = anal.meanTcs(postStim,anal.condNums>0);\n hrf = hrf(:,params.snrConds);\n if size(hrf,2) > 1\n hrf = nanmeanDims(hrf,2);\n end\n\n case 2, % boynton gamma function\n % create sub-params struct\n% if verbose, disp('Boynton & Heeger gamma HRF'); end\n [p params] = glm_getHrfParams(params);\n n = params.glmHRF_params(1);\n tau = params.glmHRF_params(2);\n delay = params.glmHRF_params(3);\n hrf = boyntonHIRF(t, n, tau, delay);\n\n case 3, % spm difference-of-gammas\n% if verbose, disp('SPM difference of gamma HRF'); end\n [p params] = glm_getHrfParams(params);\n hrf = spm_hrf(tr, p);\n\n case 4, % dale & buckner HRF\n% if verbose, disp('Dale and Buckner 2000 HRF: t^2*exp(-t)'); end\n [p params] = glm_getHrfParams(params);\n hrf = fmri_hemodyn(t, p(1), p(2));\n\n case 5, % saved HRF from file\n % choose from file\n% if verbose, disp('HRF selected from file \\n'); end\n [f p] = myUiGetFile(hrfDir, '*.mat', 'Select a saved HRF File...');\n if f==0 % user canceled\n disp('User canceled -- setting HRF to Boynton Gamma')\n params.glmHRF = 2;\n else\n params.glmHRF = f(1:end-4);\n end\n hrf = glm_hrf(params);\n % TO DO: deal w/ situations in which the HRF was\n % saved using diff't TR, time window\n\n otherwise, error('Invalid specification for params.glmHRF.')\nend\n\nreturn\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/mrBOLD/EventRelated/GLM/glm_hrf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3449910854264418}}
{"text": "% AUTHORSHIP\n% Software Developers: Rachel Finck, \n% Connor Meehan \n% Stephen Meehan \n% \n% ORIGINAL PUBLICATION\n% http://cgworkspace.cytogenie.org/GetDown2/demo/dbm.pdf\n%\n% PUBLICATION REVISIONS\n% https://static-content.springer.com/esm/art%3A10.1038%2Fs42003-019-0467-6/MediaObjects/42003_2019_467_MOESM1_ESM.pdf\n%\n% Provided by the Herzenberg Lab at Stanford University \n% License: BSD 3 clause\n%\n\nclassdef Density < handle\n \n properties(Constant)\n D=2;\n CONTOUR_LIMIT=1000;\n CONTOUR_BANDWIDTH=.014;\n DbmBandwidth='DbmBandwidth'; \n DbmBackgroundType='DbmBackgroundType'; \n DbmBackgroundFactor='DbmBackgroundFactor'; \n DbmSlopeIsSignificant='DbmSlopeIsSignificant';\n DbmM='DbmM';\n DbmNmin='DbmNmin';\n DETAILS={'most high', 'very high', 'high', ...\n 'medium', 'low', 'very low', 'adaptive', ...\n 'nearest neighbor', 'dbscan arguments'};\n \n end\n \n properties(SetAccess=private)\n opts;\n labels;\n clusterNames;\n clusterColors;\n clusterMdns;\n clusterLabels;\n backgroundFactor;\n backgroundType;\n decimals;\n notes;\n gradients;\n backGround;\n maxNbrs;\n isSlopeBig;\n isSlopeSignificant;\n debug=false;\n Z={};\n slopes=[];\n pathEnds=[];\n sigPathEnds=[];\n criticalValue=0;\n Kappa=0;\n M=0;\n N=0;\n N_min;\n mins=[];\n maxs=[];\n deltas=[];\n eventBinIdxs=[];\n fmat=[];\n wmat=[];\n phimat=[];\n rawPointers=[];\n contourH=[];\n h=[];\n L=[];\n onScale=[];\n truncated=false;\n ye=[];\n wmatVector;\n fmatVector;\n fmatVector2;\n nnVec;\n eigVec;\n nnMat; % for tool tips\n eigMat;% for tool tips\n bandWidthInput=[];\n bandwidth=[];\n xgrid;\n ygrid;\n gridAssign;\n pointersWithEvents=[];\n contourZ=[];\n pseudoZ=[];\n contourXm=[];\n contourYm=[];\n contourV=[];\n colorMap=[];\n probabilityContourPercent=0;\n isBiased=false;\n nearN=0;\n end\n \n properties\n probabilityDensity;\n pointers=[]; %with or without events\n end\n \n methods\n function yes=needToRecreate(this, options)\n yes=this.M ~= options.DbmM;\n if ~yes\n yes=this.truncated;\n end\n if ~yes\n if isfield(options, Density.DbmBandwidth)\n yes=this.bandWidthInput ~= options.DbmBandwidth;\n end\n if ~yes\n if isfield(options, Density.DbmNmin)\n yes=this.N_min~=options.DbmNmin;\n end\n end\n end\n end\n \n function [displayData, display2Event, displayWeight]=getDisplayData(this, data)\n d=Density.ToData(this.ye(1,:), this.ye(2,:), ...\n this.wmat);\n carriesWeight=d(:,3)>0;\n if nargin==1 \n displayData=d(carriesWeight, 1:2);\n displayWeight=d(carriesWeight, 3);\n if this.truncated\n e=zeros(length(this.onScale), 1);\n e(this.onScale)=this.eventBinIdxs;\n else\n e=this.eventBinIdxs;\n end\n [binIdxsWithEvents, eventIdxsForBin]=unique(e);\n binIdxsWithWeight=find(carriesWeight);\n carriesWeightAndEvents=ismember(binIdxsWithWeight, ...\n binIdxsWithEvents);\n binIdxsWithWeightAndEvents=binIdxsWithWeight(carriesWeightAndEvents);\n w2e=bsearch(binIdxsWithEvents,binIdxsWithWeightAndEvents);\n display2Event=eventIdxsForBin(w2e);\n displayData=displayData(carriesWeightAndEvents, :);\n displayWeight=displayWeight(carriesWeightAndEvents, :);\n else\n displayData=d(carriesWeight, 1:2);\n displayWeight=d(carriesWeight, 3);\n e=this.eventBinIdxs;\n [binIdxsWithEvents, eventIdxsForBin]=unique(e);\n binIdxsWithWeight=find(carriesWeight);\n mapW2E=bsearch(binIdxsWithEvents,binIdxsWithWeight);\n \n if this.truncated\n data=data(this.onScale, :);\n end\n assert( issorted( binIdxsWithEvents ) );\n assert( isempty(find(~ismember(...\n binIdxsWithEvents, binIdxsWithWeight), 1)));\n ranges=this.maxs-this.mins;\n idx2BinIdxsWithWeightAndEvents=find(ismember(...\n binIdxsWithWeight, binIdxsWithEvents));\n N=length(idx2BinIdxsWithWeightAndEvents);\n \n for i=1:N\n pick=idx2BinIdxsWithWeightAndEvents(i);\n %first re-assert the above find/ismember op\n %to make sure no parity error in RAM, ROM or CPU\n assert( ismember(binIdxsWithWeight(pick), binIdxsWithEvents));\n idx=mapW2E(pick);\n eventIdx=eventIdxsForBin( idx );\n nearestBinIdx=binIdxsWithEvents(idx);\n assert( binIdxsWithEvents(idx ) == e(eventIdx) );\n %equivalent assert without documenting meaning of each\n %index IS:\n assert(binIdxsWithEvents(mapW2E(pick) )==...\n e( eventIdxsForBin( mapW2E(pick))))\n dataAtEvent=data(eventIdx, :);\n dataAtBinIdx=displayData(pick, [1:2]);\n result=abs(dataAtEvent-dataAtBinIdx);\n %the statement below does not WORK because it produces scalar:\n % perc=result/ranges*100;\n perc=result./ranges*100;\n if max(perc)>.5\n px=String.encodeRounded(perc(1),3);\n py=String.encodeRounded(perc(2),3);\n xBin=String.encodeRounded(dataAtBinIdx(1),4);\n yBin=String.encodeRounded(dataAtBinIdx(2),4);\n xEvent=String.encodeRounded(dataAtEvent(1),4);\n yEvent=String.encodeRounded(dataAtEvent(2),4);\n [xx,yy]=Density.ToMatrixIdxs(nearestBinIdx, this.M);\n xLinSpace=String.encodeRounded(this.ye(1, xx),4);\n yLinSpace=String.encodeRounded(this.ye(2, yy),5);\n fprintf(['High gap of x=%s%% && y=%s%% between X, Y at bin #%d: [%s, %s]\\n'...\n ' && X/Y at event associated with THIS same bin: [%s, %s]\\n'], ...\n px, py, binIdxsWithEvents(idx ), xBin, yBin, xEvent, yEvent);\n assert(min(perc)<1, 'Either gap in X or gap in Y MUST be less than .25');\n \n end\n end\n \n %some bin idxs have weight without data points because they\n %are close to events that are part of density smoothing\n binIdxsWithWeightButNotEvents=find(~ismember(...\n binIdxsWithWeight, binIdxsWithEvents));\n N=length(binIdxsWithWeightButNotEvents);\n for i=1:N\n pick=binIdxsWithWeightButNotEvents(i);\n %first re-assert the above find/ismember op\n %to make sure no parity error in RAM, ROM or CPU\n assert( ~ismember(binIdxsWithWeight(pick), binIdxsWithEvents));\n idx=mapW2E(pick);\n eventIdx=eventIdxsForBin( idx );\n nearestBinIdx=binIdxsWithEvents(idx);\n assert( nearestBinIdx==e(eventIdx) );\n dataAtEvent=data(eventIdx, :);\n dataAtBinIdx=displayData(pick, [1:2]);\n result=abs(dataAtEvent-dataAtBinIdx);\n perc=result./ranges*100;\n if max(perc)>3 && Density.IsDebugging2014\n actualBinIdx=MatBasics.NthTrueInBoolVector(carriesWeight,pick);\n px=String.encodeRounded(perc(1),3);\n py=String.encodeRounded(perc(2),3);\n xBin=String.encodeRounded(dataAtBinIdx(1),4);\n yBin=String.encodeRounded(dataAtBinIdx(2),4);\n xEvent=String.encodeRounded(dataAtEvent(1),4);\n yEvent=String.encodeRounded(dataAtEvent(2),4);\n [xx,yy]=Density.ToMatrixIdxs(nearestBinIdx, this.M);\n xLinSpace=String.encodeRounded(this.ye(1, xx),4);\n yLinSpace=String.encodeRounded(this.ye(2, yy),4);\n fprintf(['High gap of x=%s%% && y=%s%% between '...\n 'X, Y at actual bin #%d: [%s, %s] && X/Y at'...\n ' event associated with nearest '...\n 'bin #%d: [%s, %s]\\n'], ...\n px, py, actualBinIdx, xBin, yBin, ...\n nearestBinIdx,xEvent, yEvent);\n if min(perc)>1\n disp('Either gap in X or gap in Y MUST be less than .25');\n end\n end\n end\n if this.truncated\n e=zeros(length(this.onScale), 1);\n e(this.onScale)=this.eventBinIdxs;\n else\n e=this.eventBinIdxs;\n end\n [binIdxsWithEvents, eventIdxsForBin]=unique(e);\n binIdxsWithWeight=find(carriesWeight);\n carriesWeightAndEvents=ismember(binIdxsWithWeight, ...\n binIdxsWithEvents);\n binIdxsWithWeightAndEvents=binIdxsWithWeight(carriesWeightAndEvents);\n w2e=bsearch(binIdxsWithEvents,binIdxsWithWeightAndEvents);\n display2Event=eventIdxsForBin(w2e);\n displayData=displayData(carriesWeightAndEvents, :);\n displayWeight=displayWeight(carriesWeightAndEvents, :);\n end\n end\n \n function clusterMat=getClusterMat(this)\n clusterMat=reshape(this.pointers, this.M, this.M);\n end\n \n function y=getY(this)\n [ygrid,xgrid]=meshgrid(this.ye(2,:), this.ye(1,:));\n y=[xgrid(:) ygrid(:)]';\n end\n \n function H=contour(this, ax, probabilityContourPercent, ...\n color, lineWidth)\n if ~isempty(this.probabilityDensity)\n H=this.probabilityDensity.drawContours(ax, ...\n probabilityContourPercent, color, lineWidth);\n return;\n end\n if isempty(this.contourZ)\n this.contourDensity;\n end\n if isempty(this.contourV) || ...\n this.probabilityContourPercent ~= probabilityContourPercent\n this.probabilityContourPercent=probabilityContourPercent;\n if probabilityContourPercent==2.4\n contourLevels=8;\n elseif probabilityContourPercent==2.2\n contourLevels=6;\n else\n contourLevels=floor(100/probabilityContourPercent);\n end\n MM=this.M^2;\n T=reshape(this.contourZ, 1,MM);\n T=sort(T);\n CT=cumsum(T);\n NT=CT/CT(end);\n this.contourV=zeros(1, contourLevels);\n if probabilityContourPercent==2.4\n numerators=[ .5/100 1/100 2/100, 4/100, 8/100, 16/100, 32/100, 64/100];\n for numerator=1:contourLevels\n idx=bsearch(NT, numerators(numerator));\n this.contourV(numerator)=T(idx);\n end\n elseif probabilityContourPercent==2.2\n numerators=[ 2/100, 4/100, 8/100, 16/100, 32/100, 64/100];\n for numerator=1:contourLevels\n idx=bsearch(NT, numerators(numerator));\n this.contourV(numerator)=T(idx);\n end\n else\n for numerator=1:contourLevels\n idx=bsearch(NT, numerator/contourLevels);\n this.contourV(numerator)=T(idx);\n end\n end\n \n end\n [~,H]=contour(ax, this.contourXm, this.contourYm, ...\n this.contourZ, this.contourV, 'k', 'color', color, ...\n 'LineStyle', '-', 'LineWidth', lineWidth);\n end\n \n function contourV=getProbabilityDensities(this, contourLevels)\n if isempty(this.contourZ)\n this.contourDensity;\n end\n MM=this.M^2;\n T=reshape(this.contourZ, 1,MM);\n T=sort(T);\n CT=cumsum(T);\n NT=CT/CT(end);\n contourV=zeros(1, contourLevels);\n for numerator=1:contourLevels\n idx=bsearch(NT, numerator/contourLevels);\n contourV(numerator)=T(idx);\n end\n end\n \n function density2D(this, data, ax, colorRangeStart, colorRangeEnd)\n if ~isempty(this.probabilityDensity)\n if nargin<5\n this.probabilityDensity.drawJetColors(ax);\n return;\n else\n this.probabilityDensity.drawColors(ax, 64, data, ...\n colorRangeStart, colorRangeEnd);\n return;\n end\n end\n if isempty(this.fmatVector2)\n this.contourDensity;\n end\n isPseudoColor=nargin<4;\n if size(data, 1)==length(this.onScale)\n data=data(this.onScale, :);\n [x1,~,x3]=unique(this.eventBinIdxs);\n else\n onScale2=MatBasics.FindOnScale(data, this.mins, this.maxs);\n data=data(onScale2, :);\n z=reshape(1:this.M^2,this.M,this.M);\n \teb=interp2(this.xgrid, this.ygrid, z',...\n data(:,1),data(:,2),'nearest'); %this associates each data point with its nearest grid point\n [x1,~,x3]=unique(eb);\n end\n if isPseudoColor\n colors=jet(128);\n N_=size(colors,1);\n if isempty(this.pseudoZ)\n try\n this.pseudoZ=this.getProbabilityDensities(N_);\n catch ex\n end\n end\n probabilityRange=this.pseudoZ;\n else\n if nargin<5 \n colors=colorRangeStart;\n else\n a1=mean(colorRangeEnd);\n a2=mean(colorRangeStart);\n if a1.75\n f=.75/m1;\n colorRangeEnd=colorRangeEnd*f;\n end\n end\n N_=32;\n colors=zeros(N_,3);\n colors(1,:)=colorRangeStart;\n colors(N_,:)=colorRangeEnd;\n gap=zeros(1,3);\n for i=1:3\n gap(i)=colorRangeEnd(i)-colorRangeStart(i);\n end\n for i=2:N_-1\n for j=1:3\n colors(i,j)=colors(1,j)+(i/N_*gap(1,j));\n end\n end\n end\n N_=length(colors);\n probabilityRange=this.getProbabilityDensities(N_);\n end\n if size(data,1)<10\n color=colors(1, :);\n plot(ax, data(:,1), data(:,2), 'd',...\n 'markersize', 2, 'MarkerEdgeColor',...\n color, 'LineStyle', 'none');\n return;\n end\n try\n colormap(colors);\n catch ex\n disp('huh');\n end\n densities=this.fmatVector2(x1);\n lookup=bsearch(probabilityRange,densities);\n eventColors=lookup(x3);\n usedColors=unique(eventColors);\n N2=length(usedColors);\n sz=size(data,1);\n if sz<10000\n marker='d';\n ms=2;\n else\n marker='.';\n ms=2;\n end\n for i=1:N2\n colorIdx=usedColors(i);\n li=eventColors==colorIdx;\n plot(ax, data(li,1), data(li,2), marker,...\n 'markersize', ms, 'MarkerEdgeColor',...\n colors(colorIdx, :), 'LineStyle', 'none');\n end\n \n end\n \n function [x, y, xIdx, yIdx, mxDns, avgDns]=getPeak(this, clue)\n bi=find(this.pointersWithEvents==clue);\n if isempty(bi)\n x=0;\n y=0;\n xIdx=0;\n yIdx=0;\n mxDns=0;\n avgDns=0;\n else\n [mxDns,mi]=max(this.fmatVector(bi));\n if nargout>5\n avgDns=median(this.fmatVector(bi));\n end\n maxIdx=bi(mi);\n [xIdx, yIdx]=ind2sub([this.M this.M], maxIdx);\n x=this.mins(1)+((xIdx-1)*this.deltas(1));\n y=this.mins(2)+((yIdx-1)*this.deltas(2));\n end\n end\n\n function [xIdx, yIdx, mxEig, avgEig]=getPeakEig(this, clue)\n bi=find(this.pointersWithEvents==clue);\n if isempty(bi)\n xIdx=0;\n yIdx=0;\n mxEig=0;\n avgEig=0;\n else\n [mxEig,mi]=max(this.eigVec(bi));\n if nargout>3\n avgEig=median(this.eigVec(bi));\n end\n maxIdx=bi(mi);\n [xIdx, yIdx]=ind2sub([this.M this.M], maxIdx);\n end\n end\n \n function binScale=toBinScale(this, value, axis)\n binScale=((value-this.mins(axis))./this.deltas(axis))+1;\n end\n \n function [xx, yy]=toData(this, x, y)\n xx=this.mins(1)+((x-1)*this.deltas(1));\n yy=this.mins(2)+((y-1)*this.deltas(2));\n end\n \n function xx=toDataScale(this, value, axis)\n xx=this.mins(axis)+((value-1)*this.deltas(axis));\n end \n function [xx,yy]=allGridData(this)\n [x,y]=ind2sub([this.M this.M], [1:this.M^2]);\n xx=this.mins(1)+((x-1)*this.deltas(1));\n yy=this.mins(2)+((y-1)*this.deltas(2));\n end\n \n function bins=getNeighborIdxs(this, bin)\n [x,y]=ind2sub([this.M this.M], bin);\n xIdxs=[];\n yIdxs=[];\n for i=-1:1\n nx=x+i;\n if nx>0 && nx<=this.M\n for j=-1:1\n if i==0&&j==0\n continue;\n end\n ny=y+j;\n if ny>0 && ny<=this.M\n xIdxs(end+1)=nx;\n yIdxs(end+1)=ny;\n end\n end\n end\n end\n bins=sub2ind([this.M this.M], xIdxs, yIdxs);\n end\n \n function f2D=get2ndDerivative(this)\n f=this.fmat;\n M_=this.M;\n fx=zeros(M_, M_);\n fy=zeros(M_, M_);\n D1=this.deltas(1);\n D2=this.deltas(2);\n for x=2:M_-1\n for y=2:M_-1\n fx(x,y)=f(x-1,y)+f(x+1,y);\n fy(x,y)=f(x,y-1)+f(x,y+1);\n end\n end\n x=1;\n %left side minus corners\n for y=2:M_-1\n fx(x,y)=f(x+1,y-1)+f(x+1,y);\n fy(x,y)=f(x,y-1)+f(x,y+1);\n end\n \n %right side minus corners\n x=M_;\n for y=2:M_-1\n fx(x,y)=f(x-1,y)+f(x-1,y-1);\n fy(x,y)=f(x,y-1)+f(x,y+1); \n end\n\n %bottom side minus corners\n y=M_;\n for x=2:M_-1\n fx(x,y)=f(x-1,y)+f(x+1,y);\n fy(x,y)=f(x,y-1)+f(x-1,y-1); \n end\n \n %top side minus corners\n y=1;\n for x=2:M_-1\n fx(x,y)=f(x-1,y)+f(x+1,y);\n fy(x,y)=f(x+1,y+1)+f(x,y+1); \n end\n\n %top left\n fx(1,1)=f(2,1)+f(2,2);\n fy(1,1)=f(2,2)+f(1,2);\n\n %bottom left\n fx(1,M_)=f(2,M_)+f(2,M_-1);\n fy(1,M_)=f(1,M_-1)+f(2, M_-1);\n\n %top right\n fx(M_,1)=f(M_-1,1)+f(M_-1,2);\n fy(M_,1)=f(M_,2)+f(M_-1, 2);\n %bottom right\n fx(M_,M_)=f(M_-1,M_)+f(M_-1,M_-1);\n fy(M_,M_)=f(M_,M_-1)+f(M_-1, M_-1);\n \n f2D=(fx-2*f)/D1 + (fy-2*f)/D2;\n\n end\n\n function numClusts=setLabels(this, labels, ...\n clusterNames, clusterColors, clusterMdns, clusterLabels)\n %this.onScale and this.eventBinIdxs defined by Constructor\n %must create pointers and pointersWithEvents\n assert(length(labels)==length(this.onScale));\n %labels=labels(this.onScale);\n u=unique(labels);\n hasZero=any(labels==0);\n if hasZero\n numClusts=length(u)-1;\n else\n numClusts=length(u);\n end\n this.labels=labels;\n this.clusterNames=clusterNames;\n this.clusterColors=clusterColors;\n this.clusterMdns=clusterMdns;\n this.clusterLabels=clusterLabels;\n end\n end\n methods(Static )\n function [density, weight, idxs, bCoords]=Get3D(data, nBins, bandWidth)\n if nargin<2\n nBins=64;\n end\n if nargin<3\n bandWidth=floor(nBins/5);\n if mod(bandWidth, 2)==0\n bandWidth=bandWidth+1;\n end\n end\n x=data(:,1);\n y=data(:,2);\n z=data(:,3);\n N=numel(x);\n xBins=linspace(min(x),max(x), nBins);\n yBins=linspace(min(y),max(y), nBins);\n zBins=linspace(min(z),max(z), nBins);\n weight=zeros(nBins, nBins, nBins);\n bCoords=[xBins' yBins' zBins'];\n if nargout>1\n idxs=zeros(N,3);\n for i=1:N\n xi=find((x(i)>=xBins), 1, 'last');\n yi=find((y(i)>=yBins), 1, 'last');\n zi=find((z(i)>=zBins), 1, 'last');\n weight(xi, yi, zi)=weight(xi, yi, zi)+1;\n idxs(i,:)=[xi, yi, zi];\n end\n else\n for i=1:N\n xi=find((x(i)>=xBins), 1, 'last');\n yi=find((y(i)>=yBins), 1, 'last');\n zi=find((z(i)>=zBins), 1, 'last');\n weight(xi, yi, zi)=weight(xi, yi, zi)+1;\n end\n end\n density=smooth3(weight, 'gaussian', bandWidth, .8);\n end\n \n function [ok, isMatLabVersion]=HasDbScan(askForDownloadIfNeeded)\n if nargin<1\n askForDownloadIfNeeded=true;\n end\n clusters=[];\n data=randi(100, 50, 3);\n try\n clusters=dbscan(data, .5, 15);\n isMatLabVersion=true;\n catch ex\n try\n isMatLabVersion=false;\n % see if DBSCAN is available\n clusters=DBSCAN(data, .5, 15);\n %YES\n catch ex\n disp('No dbscan ... before r2019a');\n if askForDownloadIfNeeded\n if ~isdeployed\n Density.DownloadDbScan;\n end\n end\n end\n end\n ok=~isempty(clusters);\n end\n \n function DownloadDbScan(where)\n if nargin<1\n where='south';\n end\n questDlg(struct('where', where, 'msg', Html.Wrap(...\n ['Neither implementation of dbscan were found'...\n '- MatLab''s dbscan (fast) requires r2019a or greater'...\n '
- DBSCAN (slower) from the MathWorks File Exchange'...\n '
' Html.WrapSmallTags([...\n '(Click Download button to get DBSCAN ' ...\n 'from MathWorks File Exchange)']) '
' ]), ...\n 'checkFnc', @(jd, answer)download(jd, answer), ...\n 'modal', false, 'pauseSecs', 0), 'Get DBSCAN?', ...\n 'Download', 'Ok', 'Download');\n function ok=download(jd, answer)\n if isequal('Download', answer)\n web(['https://www.mathworks.com/matlabcentral/'...\n 'fileexchange/52905-dbscan-clustering-algorithm']);\n msg(Html.WrapHr(['After downloading & installing be'...\n '
sure to call addpath to the DB_SCAN folder']));\n msg(Html.WrapHr(['You must restart MatLab
'...\n 'after installing for this to take effect!!']), 0);\n end\n ok=true;\n jd.dispose;\n end\n end\n \n function [epsilon, minpts]=GetDbscanParameters(detail, epsilon, minpts)\n if ~strcmpi(detail, 'dbscan arguments')\n if strcmpi(detail, 'very low')\n epsilon=3;\n minpts=15;\n elseif strcmpi(detail, 'low')\n epsilon=2;\n minpts=15;\n elseif strcmpi(detail, 'medium')\n epsilon=1.5;\n minpts=15;\n elseif strcmpi(detail, 'high')\n epsilon=1;\n minpts=15;\n elseif strcmpi(detail, 'very high')\n epsilon=.66;\n minpts=5;\n elseif strcmpi(detail, 'most high')\n epsilon=.5;\n minpts=4;\n end\n end \n end\n function [numClusters, clusterIds, density]=FindClusters(...\n data, detail, method2D, pu, epsilon, minpts, ...\n distance, mins, maxs)\n if nargin<9\n maxs=[];\n mins=[];\n if nargin<7\n distance='euclidean';\n if nargin<6\n epsilon=1;\n if nargin<5\n minpts=5;\n if nargin<5\n pu=[];\n if nargin<3\n method2D='dbm';\n if nargin<2\n detail='medium';\n end\n end\n end\n end\n end\n end\n end\n wantsDbscan=size(data,2)>2 || strcmpi(method2D, 'dbscan');\n app=BasicMap.Global;\n canNotDo=app.noDbscan || ((verLessThan('matlab', '9.6') ... \n && isdeployed)); %can't add DBSCAN to compiled runtime;\n if wantsDbscan && ~canNotDo\n if isa(pu, 'PopUp')\n pu2=pu;\n priorText=pu.label.getText;\n pu.label.setText(['Finding \"' detail ...\n '\" clusters with dbscan
']);\n elseif (islogical(pu) || isnumeric(pu)) && ~isempty(pu) && pu\n pu2=PopUp(['Finding \"' detail ...\n '\" clusters with dbscan'], 'north', ...\n 'Clustering...', false);\n else\n pu2=[];\n end\n try\n if nargout>2\n if isempty(mins)\n mins=min(data); %vector of min of each column of data\n maxs=max(data); %vector of max of each column of data\n end\n density=Density.New(data(:,1:2), detail, ...\n mins(1:2), maxs(1:2));\n end\n [epsilon, minpts]=Density.GetDbscanParameters(...\n detail, epsilon, minpts);\n if isempty(distance)\n clusterIds=dbscan(data, epsilon, minpts);\n else\n clusterIds=dbscan(data, epsilon, minpts, ...\n 'Distance', distance);\n end\n catch ex\n try\n if ~isempty(pu2)\n if ~isa(pu, 'PopUp')\n pu2.setText(Html.WrapHr(['MATLAB''s dbscan not '...\n 'available ...
using DBSCAN from'...\n 'MathWorks File Exchange.
Note that'...\n ' DBSCAN is quite slow!']));\n else\n pu.label.setText('Using 3rd party DBSCAN ...');\n end\n end\n clusterIds=DBSCAN(data, epsilon, minpts);\n catch ex\n disp(ex);\n clusterIds=[];\n if ~isdeployed && ~isempty(pu) && ~isempty(pu2)\n msg(Html.WrapHr(['Density:FindClusters '...\n 'needs dbscan
in MatLab r2019a or'...\n ' later
or a download of DBSCAN '...\n '
from MathWorks FileExchange
'...\n '
2D clustering will be done
'...\n 'instead with loss of accuracy...']), ...\n 8, 'north=+');\n Density.DownloadDbScan;\n end\n app.noDbscan=true; \n canNotDo=true;\n end\n end\n if ~isempty(pu2)\n if ~isa(pu, 'PopUp')\n pu2.close;\n else\n pu.label.setText(priorText);\n end\n end\n numClusters=sum(unique(clusterIds)>0); \n end\n if wantsDbscan && canNotDo\n wantsDbscan=false;\n warning('WARNING Shaving data to 2D....no dbscan or DBSCAN found');\n data=data(:,1:2);\n if ~isempty(mins)\n mins=mins(1:2);\n end\n if ~isempty(maxs)\n maxs=maxs(1:2);\n end\n end\n if ~wantsDbscan \n if strcmpi(detail, 'low')\n [numClusters,clusterIds, density]=...\n Density.ClusterLow(data, mins, maxs);\n elseif strcmpi(detail, 'most high')\n [numClusters, clusterIds, density]=...\n Density.ClusterMostHigh(data, mins, maxs);\n elseif strcmpi(detail, 'very high')\n [numClusters, clusterIds, density]=...\n Density.ClusterVeryHigh(data, mins, maxs);\n elseif strcmpi(detail, 'high')\n [numClusters,clusterIds, density]=...\n Density.ClusterHigh(data, mins, maxs);\n elseif strcmpi(detail, 'medium')\n [numClusters,clusterIds, density]=...\n Density.ClusterMedium(data, mins, maxs);\n elseif strcmpi(detail, 'very low')\n [numClusters,clusterIds, density]=...\n Density.ClusterVeryLow(data, mins, maxs);\n elseif strcmpi(detail, 'adaptive')\n [numClusters,clusterIds, density]=...\n Density.ClusterAdaptive(data, mins, maxs);\n elseif strcmpi(detail, 'nearest neighbor')\n [numClusters,clusterIds, density]=...\n Density.ClusterNearestN(data, mins, maxs);\n else\n warning([detail ' is not a DBM method, using medium']);\n [numClusters,clusterIds, density]=...\n Density.ClusterMedium(data, mins, maxs);\n end\n end\n end\n \n function [numClusts, clusterIds, density]=ClusterMostHigh(...\n xy, mins, maxs)\n if nargin<3\n maxs=[];\n mins=[];\n end\n [numClusts, clusterIds, density]=Density.Cluster(...\n xy, 0.95, 256, 2, .1, false, mins, maxs);\n end\n\n \n function [numClusts, clusterIds, density]=ClusterVeryHigh(...\n xy, mins, maxs)\n if nargin<3\n maxs=[];\n mins=[];\n end\n [numClusts, clusterIds, density]=Density.Cluster(...\n xy, 1.5, 256, 2, .1, false, mins, maxs);\n end\n\n function [numClusts, clusterIds, density]=ClusterHigh(...\n xy, mins, maxs)\n if nargin<3\n maxs=[];\n mins=[];\n end\n [numClusts, clusterIds, density]=Density.Cluster(...\n xy, 1.6, 256, 1, 4.3, false, mins, maxs);\n end\n\n function [numClusts, clusterIds, density]=ClusterMedium(...\n xy, mins, maxs)\n if nargin<3\n maxs=[];\n mins=[];\n end\n [numClusts, clusterIds, density]=Density.Cluster(...\n xy, 2.3, 256, 1, 4.3, false, mins, maxs);\n end\n\n function [numClusts, clusterIds, density]=ClusterLow(...\n xy, mins, maxs)\n if nargin<3\n maxs=[];\n mins=[];\n end\n [numClusts, clusterIds, density]=Density.Cluster(...\n xy, 3.2, 256, 1, 4, false, mins, maxs);\n end\n\n function [numClusts, clusterIds, density]=ClusterVeryLow(...\n xy, mins, maxs)\n if nargin<3\n maxs=[];\n mins=[];\n end\n [numClusts, clusterIds, density]=Density.Cluster(...\n xy, 4, 256, 2, 1, true, mins, maxs);\n end\n \n %This clusters EXACTLY as described in 2009 publication\n %http://cgworkspace.cytogenie.org/GetDown2/demo/dbm.pdf\n function [numClusts, clusterIds, density]=ClusterAdaptive(...\n xy, mins, maxs)\n if nargin<3\n maxs=[];\n mins=[];\n end\n [numClusts, clusterIds, density]=Density.Cluster(...\n xy, 0, 256, 4, 4.3, false, mins, maxs);\n end\n \n function [numClusts, clusterIds, density]=ClusterNearestN(...\n xy, mins, maxs)\n if nargin<3\n maxs=[];\n mins=[];\n end\n [numClusts, clusterIds, density]=Density.Cluster(...\n xy, -1, 128, 4, 4.3, false, mins, maxs);\n end\n \n function [numClusts, clusterIds, density]=Cluster(xy, ...\n bandWidth, M, backgroundType, backgroundFactor, ...\n slopeSignificance, mins, maxs)\n if nargin<8\n maxs=[];\n if nargin<7\n mins=[];\n if nargin<6\n slopeSignificance=false;\n if nargin<5\n backgroundFactor=4.3;\n if nargin<4\n backgroundType=1;\n if nargin<3\n M=256;\n if nargin<2\n bandWidth=2.3;\n end\n end\n end\n end\n end\n end\n end\n options.hWait=0;\n options.mergeSmallNeighboringClusters=1;\n options.DbmMsncPerc= 0;\n options.DbmMsncDist=2;\n options.DbmBandwidth=bandWidth;\n options.DbmM=M;\n options.DbmBackgroundFactor=backgroundFactor;\n options.DbmSlopeIsSignificant=slopeSignificance;\n options.DbmBackgroundType=backgroundType;\n options.DbmNmin=5000;\n if isempty(mins) || isempty(maxs)\n density=Density.Create(xy,options);\n else\n density=Density.CreateWithScale(xy, options,mins,maxs);\n end\n [numClusts, clusterIds]=density.clusterAnalyze(options);\n end\n end\n \n methods\n function [numClusts, eventClusterIds]=clusterAnalyze(this, options)\n this.opts=options;\n debugNewJavaMerging=false;\n if debugNewJavaMerging>0\n startTime=tic;\n end\n if isfield(options, Density.DbmBackgroundFactor)\n bgFactor=options.DbmBackgroundFactor;\n else\n bgFactor=4.3; %background threshold parameter is NOT 4.3 like paper!\n end\n if this.isBiased\n this.backgroundType=-1;\n this.isSlopeSignificant=0;\n [numClusts, eventClusterIds]=DensityBiased.ClusterAnalyze(this, bgFactor);\n return;\n end\n if isfield(options, Density.DbmSlopeIsSignificant)\n slopeIsSignificant=options.DbmSlopeIsSignificant;\n else\n slopeIsSignificant=0; %pointer-assignment threshold parameter\n end\n M_=this.M;\n MM=M_^2;\n\n if ~isfield(options,'hWait')\n title=sprintf( 'Finding clusters for %s cells', ...\n String.encodeNumber(this.N));\n options.hWait=Gui.ProgressBar(title);\n options.percentDone=0;\n options.totalPercent=1;\n elseif options.hWait==0\n options=rmfield(options, 'hWait');\n end\n \n %PUBREF=STEP 1\n sigmat = 1/(this.N*(this.N-1))*...\n convn(this.wmat,this.phimat.^2,'same') - ...\n 1/(this.N-1)*this.fmat.^2; %d-dim matrix of standard error of estimated densities\n f=this.fmatVector; %f in single vector\n sig=reshape(sigmat,1,MM); %sigmat in single vector\n if isfield(options,'hWait')\n waitbar2a(options.percentDone+(.08*options.totalPercent), options.hWait, 'Densities & stderr ');\n end\n \n dfmat=cell(1,Density.D);\n Delta=this.deltas;\n for i=1:Density.D\n PhimatD = -Delta(i)/this.h(i)^2*this.L{i}'.*this.phimat;\n %PUBREF=STEP 2.C\n dfmat{i}=1/this.N*convn(this.wmat,PhimatD,'same');\n end\n \n w=this.wmatVector;\n if ~isfield(options, Density.DbmBackgroundType)\n bgType = 2;\n bgFactor=1;\n else\n bgType=options.DbmBackgroundType;\n end\n %alpha=-1;\n stdErr=sqrt(sig);\n if ~all(this.maxs<=1) && bgType==1 \n bgFactor=4.3^2;\n bgType=4;\n end\n if bgType==4\n back = f <= bgFactor*stdErr; %points designated background\n nonBack = f > bgFactor*stdErr; %points not in the background\n elseif bgType==3 % no scatter\n %secondDerivative=0-bg_thresh;\n %silvermanSigApprox=f/(this.N*this.h(1)*this.h(2)*4*pi);\n secondDerivative=reshape(this.get2ndDerivative,1, MM);\n rightSide=bgFactor*stdErr+(.5*this.h(1)*this.h(2)*secondDerivative);\n back=f<=rightSide;\n nonBack=f>rightSide;\n \n if Density.IsDebugging\n sigma43=bgFactor*stdErr;\n halfH1H2D=.5*this.h(1)*this.h(2);\n \n vIdx=sub2ind([this.M this.M], 69, 15);\n fprintf(['@69,15 f=%f AND %f*sigma^=%f AND '...\n '0.5 h1 h2 (..)=%f! (2nd derivative=%f, '...\n 'whole rightSide=%f)\\n'], f(vIdx), bgFactor, sigma43(vIdx), ...\n halfH1H2D, secondDerivative(vIdx), rightSide(vIdx));\n vIdx=sub2ind([this.M this.M], 37, 22);\n fprintf(['@69,15 f=%f AND %f*sigma^=%f AND '...\n '0.5 h1 h2 (..)=%f! (2nd derivative=%f, '...\n 'whole rightSide=%f)\\n'], f(vIdx), bgFactor, sigma43(vIdx), ...\n halfH1H2D, secondDerivative(vIdx), rightSide(vIdx));\n end\n elseif bgType==1 % no scatter\n g=1/this.N*convn(this.wmat,this.phimat.^2,'same');% (normal density)^2 divided by plot frequency\n g=reshape(g,1,MM);\n K2=(bgFactor^2);%backgroundFactor default is 4.3\n leftSide=(this.N*(f.^3))+((K2-1)*(f.^2));\n rightSide=K2*g;\n back=leftSide<=rightSide;\n nonBack=leftSide>rightSide; \n elseif bgType==2\n if bgFactor==0\n nonBack=f>0;\n back=[];\n else\n [~, inds] = sort(f,'descend');\n prop = cumsum(w(inds))/sum(w);\n perc=bgFactor/100;\n lastPoint=find(prop >= 1 - perc, 1);\n backInds=inds(1:lastPoint);\n nonBack=zeros(1,length(f)); \n nonBack(backInds)=true(1, length(backInds)); \n nonBack = logical(nonBack);\n back = ~nonBack;\n end\n end\n this.backgroundFactor=bgFactor;\n this.backgroundType=bgType;\n \n %PUBREF = STEP 2.E\n kappa = sum(nonBack)*sum(w(nonBack))/(2*pi*this.N*prod(this.h)*sum(f(nonBack)));\n %norminv is the paper's q(x) critical value. q(.5) would be 0\n %because half the area of the curve is to the left of 0\n \n Critval=norminv([0 0.95^(1/kappa)],0,1); %norminv(x,mu,sigma)mu=mean,sigma=standard deviation\n critval=Critval(2); %q(0.095^(1/kappa))\n %% compute Pointers STEP 2 ... temporary version\n %The F matrix is STRICTLY to find the most dense of 8 neighbors\n %in the 2D neighborhood by having 81 MxM lattices that are\n %rotated so that the statement max(F,[],3) sees ONLY\n %each lattice point's 8 neighbors plus self which is 0\n %On XY plot 1-9 indices mean: \n % 1=northEast 2=north 3=northWest\n % 4=east 5=self 6=west\n % 7=southEast 8=south 9=southWest \n F=zeros([M_ M_ 9]);\n P1=reshape(1:MM,[M_ M_]);\n P=zeros([M_ M_ 9]);\n Ind=1;\n for i=-1:1\n for j=-1:1\n F(:,:,Ind)=circshift(this.fmat,[j i]); %matching up densities of neighbors\n P(:,:,Ind)=circshift(P1,[j i]); %matching up corresponding indices of neighbors\n Ind=Ind+1;\n end\n end\n \n F(end,:,[1 4 7])=nan; %don't let density at one edge switch to opposite edge\n F(:,end,[1 2 3])=nan;\n F(1,:,[3 6 9])=nan;\n F(:,1,[7 8 9])=nan;\n \n %% (07/2011 RJ) Normalize by length of distance vector to actually select steepest gradient (not in paper)\n Fcenter = cat(3, F(:,:,5), F(:,:,5), F(:,:,5), F(:,:,5));\n F(:,:,[1 3 7 9]) = Fcenter + (F(:,:,[1 3 7 9]) - Fcenter)/ sqrt(2);\n %% \n %PUBREF=STEP 2.A part 1\n [~,maxNeigh]=max(F,[],3); %find 1-9 neighbor index of where the max density is\n %vvecs are directions using e the Euclidean norm. Positive \n %direction means moving east on X axis or north on Y.\n %[northEast, north, northWest,\n % east,self,west,...\n % southEast,south,southWest]\n Dnorm=sqrt(sum(Delta.^2));\n vvecs{1}=[Delta(1)/Dnorm 0 -Delta(1)/Dnorm ...\n 1 0 -1 ...\n Delta(1)/Dnorm 0 -Delta(1)/Dnorm]; %unit vectors in rectangular grid\n vvecs{2}=[Delta(2)/Dnorm 1 Delta(2)/Dnorm ...\n 0 0 0 ...\n -Delta(2)/Dnorm -1 -Delta(2)/Dnorm];\n \n xu=vvecs{1}(maxNeigh);\n yu=vvecs{2}(maxNeigh);\n \n %PUBREF = STEP 2.B\n %positive dfmat increasing in the positive (AKA southEast) direction\n %negative dfmat decreasing in the positive (AKA southEast) direction\n Slope=xu.*dfmat{1} + yu.*dfmat{2}; %df in direction of greatest increasing density\n if slopeIsSignificant ~= 0\n d=2; \n Amat=cell(d,d);\n for i=1:d\n for j=1:d\n PhimatA=Delta(i)/this.h(i)^2*Delta(j)/this.h(j)^2*this.L{i}'.*this.L{j}'.*this.phimat.^2;\n %PUBREF=STEP 2.G\n Amat{i,j}=1/this.N*convn(this.wmat,PhimatA,'same');\n end\n end\n %Connor this is not the euclidian norm, but instead a\n %rectangular grid?\n uvecs{1}=[1/sqrt(2) 0 -1/sqrt(2) 1 0 -1 1/sqrt(2) 0 -1/sqrt(2)]; %unit vectors in square grid\n uvecs{2}=[1/sqrt(2) 1 1/sqrt(2) 0 0 0 -1/sqrt(2) -1 -1/sqrt(2)];\n \n %compute Sigma and lambda in direction of greatest increasing density\n Sigma=zeros(this.M, this.M);\n for i=1:2\n for j=1:2\n %PUBREF=STEP 2.F (Note that 1/(n - 1) is left out and then replaced in STEP 2.D)\n Sigma=Sigma+uvecs{i}(maxNeigh).*uvecs{j}(maxNeigh).*(Amat{i,j} - dfmat{i}.*dfmat{j});\n end\n end\n %PUBREF=STEP 2.D\n lambda=critval*sqrt(1/(this.N-1)*Sigma);\n if this.debug\n this.gradients=lambda;\n end\n %lambda=critval*sqrt(1./(this.N*this.fmat-1).*Sigma);\n %slopeIsSignificant=1.8;\n bigSlopes=Slope > slopeIsSignificant*lambda; %which gridpoints have sufficient increase to create a pointer\n else\n bigSlopes=Slope>0;\n end\n this.isSlopeSignificant=slopeIsSignificant;\n Pointmat=zeros(M_,M_);\n for i=1:9\n if i~=5\n %PUBREF=STEP 2.A part 2\n a=bigSlopes & maxNeigh==i; %finds max neighbors in ith direction that have \n thisP=P(:,:,i); %sufficiently large slope grid points indices in ith direction\n Pointmat(a)=thisP(a); %makes association pointers\n %disp( sprintf('neighbor# %d, %d, %d!', i, sum(a(:)), sum(thisP(:))));\n end\n end\n \n Pointers=reshape(Pointmat,[1 MM]);\n Pointers(back)=-1; %sets pointers of background gridpoints to -1\n \n %% compute Pointers STEP 3\n if isfield(options,'hWait')\n waitbar2a(options.percentDone+(.16*options.totalPercent), options.hWait, 'Significant densities ');\n end\n \n %PUBREF=STEP 3\n unassigned=find(Pointers==0); %the indices of gridpoints with no association pointers\n pointed_to=Pointers(Pointers>0); %the indices of gridpoints with association pointers into them\n pathends=intersect(unassigned,pointed_to); %the indices of pathends: they have pointers into them but no pointers out of them\n sigdens=f(pathends) >= critval*stdErr(pathends); %these pathends' densities are significant\n \n Pointers(pathends(sigdens))= -1 - pathends(sigdens); %assign these pathends pointers to dummy state representing a cluster\n insig_pathends=pathends(~sigdens); %pathends that have insignificant densities \n insig_paths=false(1,MM);\n insig_paths(insig_pathends)=true; %keeps track of gridpoints that are on paths to insig_pathends\n \n if isfield(options,'hWait')\n waitbar2a(options.percentDone+(.19*options.totalPercent), options.hWait, 'Starting gradient climbs ');\n end\n \n while ~isempty(insig_pathends)\n to_insigs=ismember(Pointers,insig_pathends); %finds gridpoints that point into insig_pathends\n insig_pathends=find(to_insigs); %updates insig_pathends to be the gridpoints that point into them\n insig_paths(to_insigs)=true; %adds gridpoints that are on paths to insig_pathends\n end\n \n Pointers(insig_paths)=-1; %sends to background all gridpoints on path to an insignificant pathend\n peaks=sum(sigdens);\n if this.debug\n this.notes=sprintf(...\n ['thresh=%d, #unassigned=%d, #pointed_to=%d, \\n'...\n '#peaks=%d, #signifPeaks=%d, kappa=%0.6f, critval=%0.6f,\\n'...\n ' #bigSlopes=%d of %d, slopeSum=%0.5f,'...\n 'neighSum=%0.0f, ptrSum1=%0.0f, ptrSum2=%0.0f\\n'...\n ' h=%0.3f/%0.3f Z=%d/%d\\n'], ...\n slopeIsSignificant, length(unassigned), length(pointed_to), ...\n length(pathends), peaks, kappa, critval, ...\n sum(bigSlopes(:)), sum(Slope(:)>0), sum(Slope(:)), ...\n sum(maxNeigh(:)), sum(P(:)), sum(Pointers), ...\n this.h(1), this.h(2), this.Z(1), this.Z(2));\n disp(this.notes);\n this.pathEnds=pathends;\n this.sigPathEnds=pathends(sigdens);\n this.slopes=Slope;\n this.isSlopeBig=bigSlopes;\n this.maxNbrs=maxNeigh;\n this.Kappa=kappa;\n this.criticalValue=critval;\n this.backGround=reshape(back, this.M, this.M);\n end\n outerLoop=0;\n neighborhood=cell(1, MM);\n possibleClusterTears=[];\n pu=[];\n changes=1;\n if debugNewJavaMerging>0\n toc(startTime);\n fprintf('MatLab density calculations completed\\n\\n');\n dlmwrite('density.txt', f, 'delimiter', ',', 'precision', 16);\n dlmwrite('pointers.txt', Pointers,'delimiter', ',','precision', 16);\n dlmwrite('stdErr.txt', stdErr, 'delimiter', ',','precision', 16);\n javaMerging=tic;\n end\n noJava=false;\n try\n javaDbm=edu.stanford.facs.swing.Dbm(M_);\n javaDbm.pointers=Pointers;\n javaDbm.density=f;\n javaDbm.stdErr=stdErr;\n if debugNewJavaMerging>0\n javaDbm.debugging=1;\n else\n javaDbm.reportChangeCount=false;\n end\n javaDbm.merge;\n catch ex\n javaDbm=[];\n noJava=true;\n debugNewJavaMerging=false;\n javaMerging=tic;\n startTime=tic;\n end\n if noJava || debugNewJavaMerging>0\n if debugNewJavaMerging>0\n save('densityBasedMerge', 'MM', 'Pointers', 'f', 'stdErr')\n end \n toc(javaMerging);\n fprintf('JAVA merging completed\\n\\n');\n matLabMerging=tic;\n while outerLoop==0 || changes>0 %PUBREF=STEP 5 handle necessary repetitions\n outerLoop=outerLoop+1;\n %PUBREF=STEP 4\n pu=reportClusterMerging(outerLoop, changes, peaks, pu, startTime);\n newPointers=Pointers;\n Dummies = find(Pointers < -1); %indices of gridpoints with pointers to dummy states representing clusters\n fDummies = f(Dummies); %densities at gridpoints that have pointers to dummy states\n numDummies = length(Dummies); %number of dummy states\n \n [~,ix]=sort(fDummies,'descend');\n newDummies=Dummies(ix); %indices of gridpoints with pointers to dummy states in order of decreasing density\n innerLoop=0;\n for i = 1:numDummies\n innerLoop=innerLoop+1;\n %make A\n A = newDummies(i);\n test=(f(newDummies(i)) - stdErr(newDummies(i)));\n if Pointers(A)>0\n % Rachel originally commented:\n %I can't remember why this is here because\n %everything in newDummies should have pointers\n %to dummy states, but I am too lazy to\n %remove it, assuming I put it here for a%\n %reason initially.\n \n % Answer to Rachel's comment is that the new\n % merging she did on 6_22_10 WILL cause this when\n % if ~isempty(starts) && any(f_starts>maxQ)\n \n continue\n end\n sizeOfA = 0;\n for k=1:MM\n newSizeOfA=length(A);\n if newSizeOfA > sizeOfA %if not all of A has had its neighbors checked yet\n if k==newSizeOfA %if checking the neighbors of the current last member of A, update sizeofA\n sizeOfA=k;\n end\n neighbors=neighborhood{A(k)};\n if isempty(neighbors)\n neighbors=this.getNeighborIdxs(A(k));\n neighborhood{A(k)}=neighbors;\n end\n A=[A neighbors(Pointers(neighbors)==0 & f(neighbors)+stdErr(neighbors)>test)];\n [~, whereInA]=unique(A, 'first'); %list of indices of unique values in AA\n A=A(sort(whereInA)); %unique values of A in order in which they originally appeared, so we don't check the same things twice\n else\n break %if all of A was checked and nothing got added to AA during the last iteration, move on\n end\n end\n \n %make B\n neighborsOfAandA=unique([cell2mat(neighborhood(A)) A]);\n B=neighborsOfAandA(Pointers(neighborsOfAandA)<-1);\n [fQ,yQ] = max(f(B));\n newPeak=Pointers(B(yQ));\n tearAble=Pointers(A(Pointers(A)<-1));\n useOldMerging=true;\n neighborsOfMaxB=neighborhood{B(yQ)};\n starts=Pointers(neighborsOfMaxB)>0;\n if ~isempty(starts)\n C=neighborsOfMaxB(starts);\n f_starts=f(C);\n if any(f_starts>fQ)\n [~,maxf]=max(f_starts);\n newPeak=Pointers(C(maxf));\n useOldMerging=false;\n end\n end\n \n if debugNewJavaMerging>0\n %A(1)=[]; %remove newDummies(i) from A\n assert(~isempty(find(B==A(1), 1)));\n if useOldMerging\n %B(yQ)=[]; %remove q from B\n debug=B(yQ);\n assert(Pointers(debug)==newPeak);\n end\n end\n \n Pointers(A)=newPeak; %create pointers from all points in AA to q: changed to Pointers(q) from q\n Pointers(B)=newPeak; %create pointers from all points in B to q: changed to Pointers(q) from q\n \n if debugNewJavaMerging>1\n checkSum=sum(Pointers);\n fprintf(['loop #%d.%d, newPeak=%d, '...\n 'A=%d, B=%d, check sum=%d\\n'], ...\n outerLoop, innerLoop, newPeak,length(A), ...\n length(B), checkSum);\n end\n \n if any(tearAble ~= newPeak)\n possibleClusterTears=[possibleClusterTears tearAble];\n end\n end\n if debugNewJavaMerging==1\n checkSum=sum(Pointers);\n fprintf('Loop #%d.%d, check sum=%d\\n', ...\n outerLoop, innerLoop, checkSum); \n end \n changes=sum(Pointers~=newPointers);\n end\n possibleClusterTears=unique(possibleClusterTears);\n if ~noJava\n try\n if isempty(javaDbm.possibleClusterTears)\n elseif any(possibleClusterTears~=javaDbm.possibleClusterTears')\n msgBox('New JAVA merging POINTER problem');\n end\n if ~isequal(Pointers, javaDbm.pointers')\n msgBox('JAVA merging POINTER problem');\n end\n catch\n end\n %% put in final clusters\n javaDbm.fixClusterTear;\n end\n if ~isempty(possibleClusterTears)\n possibleClusterTears=unique(possibleClusterTears);\n if Density.IsDebugging\n fprintf('*Possible* cluster tears ---> %s\\n', ...\n MatBasics.toString(possibleClusterTears));\n end\n [Pointers, actualClusterTears]=fixClusterTear(...\n this.M, Pointers, neighborhood, possibleClusterTears);\n if isempty(actualClusterTears)\n disp('No actual cluster tears');\n else\n nTears=sum(actualClusterTears(:,2));\n fprintf('*ACTUAL* cluster tears --> %d\\n',nTears);\n end\n if ~noJava\n if any(javaDbm.tears ~= actualClusterTears)\n disp('New java merging cluster tear problem');\n end\n if any(Pointers~=javaDbm.pointers')\n disp('New JAVA merging POINTER problem after knitting torn clusters');\n end\n end\n end\n this.pointers=Pointers; %this is to save Pointers for making vector plot later\n this.rawPointers=Pointers;\n \n fprintf('MatLab merging completed\\n\\n');\n toc(matLabMerging);\n else\n javaDbm.fixClusterTear;\n Pointers=javaDbm.pointers';\n this.pointers=Pointers; %this is to save Pointers for making vector plot later\n this.rawPointers=Pointers;\n end\n p=this.pointers>0;\n while any(p)\n this.pointers(p)=this.pointers(this.pointers(p)); %follows the path of all positive pointers until they all go to dummy states\n p=this.pointers>0;\n end\n %PUBREF = STEP 6\n this.pointers(this.pointers==-1)=0; %send background gridpoints to label 0\n \n eventClusterIds=this.pointers(this.eventBinIdxs); %assigns each original data point the dummy cluster number of its closest gridpoint\n \n clusts=unique(eventClusterIds);\n clusts=clusts(clusts~=0); %all non-background clusters \n numClusts=length(clusts);\n j=1;\n for i=clusts\n eventClusterIds(eventClusterIds==i)=j; %relabel clusters from 1 to NumClusts\n this.pointers(this.pointers==i)=j; %relabel pointers\n j=j+1;\n end\n if this.truncated\n ca=zeros(1, length(this.onScale));\n ca(this.onScale)=eventClusterIds;\n eventClusterIds=ca;\n end\n clustersWithoutEventBinIdxs=this.pointers<-1;\n if sum(clustersWithoutEventBinIdxs)>0\n if Density.IsDebugging\n fprintf('There are %d grid points with clusters but no events!', sum(clustersWithoutEventBinIdxs));\n end\n this.pointers(clustersWithoutEventBinIdxs)=0; %send background gridpoints that had clusters but no events\n end\n this.computePointersWithEvents(eventClusterIds);\n if options.mergeSmallNeighboringClusters && options.DbmMsncPerc>0\n [numClusts, eventClusterIds]=...\n mergeSmallNeighboringClusters(this, numClusts, stdErr, ...\n eventClusterIds, ...\n options.DbmMsncPerc,...\n options.DbmMsncDist);\n end\n if ~isempty(pu)\n pu.close;\n end\n end\n \n function setPointersWithEvents(this, pointersWithEvents)\n this.pointersWithEvents=pointersWithEvents;\n end\n \n function p=computePointersWithEvents(this, eventClusterIds)\n if isempty(eventClusterIds)\n this.pointersWithEvents=[];\n else\n if this.truncated\n eventClusterIds=eventClusterIds(this.onScale);\n end\n this.pointersWithEvents=zeros(1, this.M^2);\n this.pointersWithEvents(this.eventBinIdxs)=eventClusterIds;\n end\n if nargout>0\n p=this.pointers;\n end\n end\n \n function [bi,xi,yi]=toBinIdxs(this, y,x)\n xi=floor((x-this.mins(1))./this.deltas(1))+1;\n yi=floor((y-this.mins(2))./this.deltas(2));\n bi=yi*this.M+xi;\n yi=yi+1;\n end\n \n function [result, resultStr]=computeDensity(this, gridX, gridY)\n phi = @(x) 1/sqrt(2*pi)*exp(-x.^2./2);\n xN=this.Z(1)*2+1;\n yN=this.Z(2)*2+1;\n xZ=-this.Z(1):this.Z(1);\n yZ=-this.Z(2):this.Z(2);\n phiXs=phi(xZ*this.deltas(1)/this.h(1))/this.h(1);\n phiYs=phi(yZ*this.deltas(2)/this.h(2))/this.h(2);\n result=0;\n for i=1:xN\n x=gridX+xZ(i);\n phiX=phiXs(i);\n if x>0 && x<=this.M\n for j=1:yN\n y=gridY+yZ(j);\n if y>0 && y<=this.M\n Wm=this.wmat(x,y);\n num=Wm*(phiX*phiYs(j));\n result=result+num;\n end\n end\n end\n end\n result=1/this.N*result;\n if nargout>1\n resultStr=String.encodeNumber(result,4);\n end\n end\n \n function decimals=getFmatDecimals(this)\n if isempty(this.decimals)\n this.decimals=abs(floor(log10(median(this.fmat(:)))));\n if isinf(this.decimals)\n this.decimals=0;\n end\n end\n decimals=this.decimals;\n end\n \n function setOptions(this, options)\n this.opts=options;\n end\n \n function yes=hasSameOptions(this, options)\n yes=false;\n if isempty(this.opts) || isempty(options)\n return;\n end\n if options.mergeSmallNeighboringClusters==this.opts.mergeSmallNeighboringClusters\n if options.DbmMsncPerc==this.opts.DbmMsncPerc\n if options.DbmMsncDist==this.opts.DbmMsncDist\n if options.DbmBandwidth==this.opts.DbmBandwidth\n if options.DbmM==this.opts.DbmM\n if options.DbmBackgroundFactor==this.opts.DbmBackgroundFactor\n if options.DbmSlopeIsSignificant==this.opts.DbmSlopeIsSignificant\n if options.DbmBackgroundType==this.opts.DbmBackgroundType\n if options.DbmNmin==this.opts.DbmNmin\n yes=true;\n end\n end\n end\n end\n end\n end\n end\n end\n end\n end\n end\n \n \n methods(Access=private)\n function this=Density(events, options, mins_, maxs_)\n this.mins=mins_;\n this.maxs=maxs_;\n this.truncated=false;\n this.opts=options;\n M_=options.DbmM;\n if isfield(options, Density.DbmBandwidth)\n this.bandWidthInput=options.DbmBandwidth;\n this.bandwidth=this.bandWidthInput/100;\n else\n this.bandwidth=0;\n end\n this.onScale=MatBasics.FindOnScale(events, mins_, maxs_);\n cntEdge=size(events, 1)-sum(this.onScale);\n if cntEdge>0\n this.truncated=true;\n events=events(this.onScale, :);\n end\n this.M=M_;\n N_=size(events,1); %number of data points\n this.N=N_;\n d=size(events,2); %number of dimensions\n assert(d==Density.D, 'DBM is currently designed for 2 dimensions');\n MM = M_^d; %number of total gridpoints\n deltas_ = 1/(M_-1)*(maxs_-mins_); %vector of distances between neighbor grid points in each dimension\n this.deltas=deltas_;\n % ym=gridpoints(d,1:M); %list of every possible combo of 1:M\n \n this.ye=zeros(d,M_);\n pointLL=zeros(N_,d); %this will be the \"lower left\" gridpoint to each data point\n for i = 1:d\n this.ye(i,:) = linspace(mins_(i),maxs_(i),M_);\n pointLL(:,i)=floor((events(:,i)-mins_(i))./deltas_(i)) + 1;\n end\n pointLL(pointLL==M_)=M_-1; %this avoids going over grid boundary\n %% assign each data point to its closest grid point\n [this.xgrid, this.ygrid]=meshgrid(this.ye(1,:),this.ye(2,:));\n z=reshape(1:MM,M_,M_);\n this.eventBinIdxs=interp2(this.xgrid, this.ygrid,z',...\n events(:,1),events(:,2),'nearest'); %this associates each data point with its nearest grid point\n %% compute w\n Deltmat=repmat(deltas_,N_,1);\n shape=M_*ones(1,d);\n \n wmat_=zeros(M_,M_);\n for i=0:1 %number of neighboring gridpoints in d dimensions\n for j=0:1\n pointm=pointLL+repmat([j i],N_,1); %indices of ith neighboring gridpoints\n pointy=zeros(N_,d);\n for k=1:d\n pointy(:,k)=this.ye(k,pointm(:,k)); %y-values of ith neighboring gridpoints\n end\n %PUBREF=REF 2.1\n W=prod(1-(abs(events-pointy)./Deltmat),2); %contribution to w from ith neighboring gridpoint from each datapoint\n wmat_=wmat_+accumarray(pointm,W,shape); %sums contributions for ith gridpoint over data points and adds to wmat\n end\n end\n this.wmat=wmat_;\n \n %% compute f, sig, df and A\n this.h=zeros(1,d);\n this.contourH=zeros(1,d);\n this.bandwidth=DensityBiased.ConfirmBandWidth(this);\n if this.bandwidth>0\n if isfield(options, Density.DbmNmin)\n this.N_min=options.DbmNmin;\n end\n for i =1:d\n this.h(i)=this.bandwidth*(maxs_(i)-mins_(i));\n this.contourH(i)=Density.CONTOUR_BANDWIDTH *(maxs_(i)-mins_(i));\n if N_' Qc.Html(fg, scrolling, mode) '